Skip to content

fix: $config() synthesized getType() inherited by subclasses causes node-type collision (#8640) - #8867

Merged
etrepum merged 1 commit into
mainfrom
fix-8640-config-getType-subclass-inheritance
Jul 20, 2026
Merged

etrepum merged 1 commit into
mainfrom
fix-8640-config-getType-subclass-inheritance

Conversation

@potatowagon

Copy link
Copy Markdown
Contributor

Bug

#8640 ("Port node classes to the $config() protocol") introduced a node-type collision for $config()-based subclasses, found while syncing the change into Meta's internal www codebase (D112781184). It's a sibling of #8864 (direct-clone property loss) — same root PR, different broken invariant.

What breaks

getStaticNodeConfig synthesizes a getType for any class that derives its type from $config() rather than an explicit static getType():

if (!hasOwnStaticMethod(klass, 'getType')) {
  klass.getType = () => ownNodeType;
}

That closure is assigned as an own static on the class, and it captures a hardcoded type. The problem is inheritance:

  1. A superclass is resolved first (e.g. TextNode) → TextNode.getType = () => 'text' is now an own static on TextNode.
  2. A subclass that hasn't had its own getType synthesized yet (CodeHighlightNode, HashtagNode, any TextNode/ElementNode subclass using $config()) then inherits TextNode's closure via the prototype chain.
  3. SubClass.getType() now returns the superclass's 'text' instead of its own type — without ever reaching the base LexicalNode.getType() that would resolve it correctly.

Inside createEditor, the registry is keyed by klass.getType(), so the subclass registers under the superclass's type and collides. The failure manifests as:

Create node: Type text in node TextNode does not match registered node CodeHighlightNode with the same type

Because it depends on the order classes are first resolved in a process, it's intermittent — it only bites when the superclass's getType is synthesized before the subclass is registered. That's exactly why it can pass in isolation but fail inside a larger app that creates multiple editors with overlapping node sets.

Fix

Guard the synthesized getType so it only returns the captured type when invoked on the exact class it was synthesized for. When it's inherited and invoked on a subclass, defer to the base LexicalNode.getType(), which resolves the correct type for this (and synthesizes the subclass's own guarded getType in the process):

const synthesizedForKlass = klass;
klass.getType = function (this: Klass<LexicalNode>): string {
  if (this !== synthesizedForKlass) {
    return LexicalNode.getType.call(this);
  }
  return ownNodeType;
};

No behavior change for a class read on its own; it only stops a subclass from inheriting the wrong hardcoded type. No recursion risk — the deferred base call resolves the subclass from its own $config() record and caches it.

Tests

Added two regression tests in LexicalNode.test.ts (LexicalNode.$config() without registration block):

  1. subclass static getType() is not shadowed by a superclass synthesized getType — resolves the parent FIRST (synthesizing its own-static getType), then asserts a child and a sibling still return their own $config() types, not the parent's. Fails before this change (both return the parent type), passes after.
  2. subclass static getType() resolves correctly when read before the superclass — the reverse ordering, and asserts reading the subclass first does not poison the superclass.

Verification

The core mechanism was isolated in a standalone reproduction of getStaticNodeConfig + the base getType (parent-first read makes the subclass inherit the parent's () => 'text' closure; the guard fixes both orderings). The internal www reproduction (D112781184) is a DraftJS↔Lexical round-trip that creates several editors and throws the Type text ... does not match registered node CodeHighlightNode error; with this fix those conversions no longer collide.

I was not able to run the JS unit suite in my sandbox (Node 16 only; repo requires Node ≥20.19 + pnpm 10) — relying on CI here. The added tests directly encode the isolated repro.

Context

Reported by the Lexical → fbsource sync oncall. Concrete internal regressions surfaced by this collision (Meta-internal): LexicalTransformersListStart, HiringEmailLexicalEditor e2e, and MetaCRMSalesAICanvasComposer tests, all failing with the same CodeHighlightNode-registered-under-text error. See D112781184 for the full internal analysis.

Related: #8864 fixes the direct-clone property loss from the same #8640 port; this PR fixes the type-inheritance collision.

…iding node types (#8640)

The $config() protocol port (#8640) makes getStaticNodeConfig synthesize
`klass.getType = () => ownNodeType` for classes that derive their type from
$config(). That closure is assigned as an *own* static on the class.

When a superclass is resolved first (e.g. TextNode), its synthesized getType
becomes an own static on the superclass. A subclass that has not yet had its
own getType synthesized (CodeHighlightNode, HashtagNode, ...) then *inherits*
that closure through the prototype chain and returns the SUPERCLASS's hardcoded
type. In an editor this causes the subclass to register under the superclass's
type and collide with it:

  Create node: Type text in node TextNode does not match registered node
  CodeHighlightNode with the same type

This is order-dependent, so it surfaces intermittently depending on which
editors/nodes are resolved first in a process.

Fix: guard the synthesized getType so it only returns the captured type when
invoked on the exact class it was synthesized for; when inherited and invoked
on a subclass it defers to the base LexicalNode.getType(), which resolves the
correct type for `this`.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Jul 20, 2026
@etrepum
etrepum added this pull request to the merge queue Jul 20, 2026
Merged via the queue into main with commit ff28f1e Jul 20, 2026
57 of 58 checks passed
pull Bot pushed a commit to nagyist/lexical that referenced this pull request Jul 21, 2026
@etrepum etrepum mentioned this pull request Jul 29, 2026
etrepum pushed a commit to etrepum/lexical that referenced this pull request Aug 21, 2026
…d roll back a failed registration completely

## Description

Three defects in the per-class serialization machinery.

`validateOwnFields` checks that a `withField` (or `__`-prefixed accessor) names
a field the node actually has — a misspelling is silent, total loss of that
property, since nothing is ever exported and importing writes a field nothing
reads. It had two holes.

It ran against whichever compiled table its caller happened to hold, and set one
per-class "already validated" flag. A getter name and a setter name are declared
independently, so a class can carry a field-backed entry on one side only:
`withAccessors(schema, {getter: null, setter: '__lable'})` produces one on the
setter table and none on the getter table. Exporting first — which is the usual
order, autosave before paste — validated the getter table, found nothing to
check, and retired the flag, so the misspelling was never reported in either
direction. Both tables are now checked on the first pass.

It also set the flag before running the loop. What a serialization path throws
does not always reach the caller: `parseEditorState` routes it to the editor's
`onError` rather than rethrowing. So one swallowed failure marked the class
validated with every field after the failing one still unexamined. The flag is
now set after the pass completes.

Separately, `buildNodeClassRecord` injected the statics a class did not declare
(`getType`, `clone`, `importJSON`, `importDOM`) before compiling its accessor
tables, so the rollback on a failed compile could drop the cache record but not
un-mutate the class: a class whose registration failed still answered
`getType()` with a real type and still carried a live `importJSON`, while every
path through the cache re-threw. The DEV clone-arity invariant threw even
earlier, before the record existed, so no rollback ran for it at all.
Compilation now happens before injection — nothing in it reads a synthesized
static; both compile passes resolve names off `klass.prototype` and walk the
config chain — so every throw leaves the class as it was found.

Two corrections to what `c91911f5d` claimed. Its rollback was not "complete for
the first time": it was complete for the caches, which is the half described
above, and this change is what makes it complete for the class. And
`@lexical/fast-check` is affected after all — `getComposedSchemaFields` reads
through the consolidated record, so for a class whose compile throws it now
throws on every call, where the separate `composedSchemaByClass` map used to
survive the failure and answer calls 2..n. Throwing consistently is the better
behavior, but it is a change, and `composeNodeSerializationSchema` should say so
as its sibling `nodeSerializationSchema` already does.

Also: the accessor helpers take the record their callers already hold, so a
serialized node costs one cache lookup in DEV rather than two; two doc comments
described a post-failure lazy recompile that cannot happen (a failed build drops
the record, so the retry rebuilds) and now describe the window that can — a
`$config()` body that serializes a node of the class being built; the comment
recording why these caches must be weak, lost in the consolidation, is back; and
two `SYNTHESIZED_GET_TYPE` comments still pointed at `getStaticNodeConfig` for
logic that moved into `buildNodeClassRecord`, which matters because that brand is
the meta#8867 infinite-recursion guard.

## Test plan

`npx vitest run --project unit packages/lexical/src/__tests__/unit/LexicalSchema.test.ts`

### Before

```
 ❯ editor.update.discrete packages/lexical/src/__tests__/unit/LexicalSchema.test.ts:1150:43
    1148|         const node = $create(ImportOnlyFieldNode);
    1149|         for (let i = 0; i < 2; i++) {
    1150|           expect(() => node.exportJSON()).toThrow(
       |                                           ^
    1151|             'names a node field __lable that the node does not have',
    1152|           );

 Test Files  1 failed (1)
      Tests  2 failed | 72 passed (74)
```

### After

```
 Test Files  1 passed (1)
      Tests  74 passed (74)
```

Unit projects, `npx vitest run --project unit --project scripts-unit`:

```
 Test Files  265 passed (265)
      Tests  5271 passed | 1 skipped (5272)
```

Browser tests, `npx vitest run --project browser` (Chromium):

```
 Test Files  18 passed (18)
      Tests  131 passed | 1 skipped (132)
```

`npx tsc --noEmit -p .`, `npx eslint` and `npx prettier --list-different .` are
clean. Firefox and WebKit browser runs and the Playwright E2E suite were not
exercised.

This branch was successfully deployed

2 active deployments
Preview – lexical — c6bdd816 Deployed Jul 20, 2026 by vercel[bot]
Preview – lexical-playground — c6bdd816 Deployed Jul 20, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants