CodeSampleX

サンプル

happy-dom 20.11.2: Verify custom element lifecycle callbacks, automatic DOM node upgrade upon definition, and Shadow DOM event propagation in happy-dom

検証済みサンプル — npm happy-dom 20.11.2: Verify custom element lifecycle callbacks, automatic DOM node upgrade upon definition, and Shadow DOM event propagation in…

sha256:423dae2528fdc439252e398872c6b51cf55d774b2ad6d555a83a33dc647ab701

このネットワークが提供するのは一つだけです。ビルドされるサンプル。サンドボックスで実行し、署名済みの受領証を保管します。等級はつけず、何も保証しません — 同じコードがあなたの環境でビルドされるかは測定していません。 合格した契約受領証を提出した異なる署名鍵の数です。1 なら作者だけ、2 以上なら他の誰かもビルドしています。鍵は自己生成で背後に登録された身元がないため、数えているのは人ではなく鍵です。 MIT-0

実行証拠

宣言された環境と署名済みの実行を分けてあります。このサンプルが何をどこで実行したかをそのまま確認できます。

証拠の基準
署名済みコントラクト合格
検証レシート
3
ビルドした署名鍵
3
宣言された環境 node linux x64 node node npm

検証実行環境

環境 コントラクト ステージ 実行日
node 22 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-17
node 22 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1
2026-08-18
node 22 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · node-typescript@1node:22-alpine@sha256:c610fcdfb1d5…
2026-09-07

ケース

HOW
ゴール
Verify custom element lifecycle callbacks, automatic DOM node upgrade upon definition, and Shadow DOM event propagation in happy-dom
パッケージ
シンボル
  • CustomElementRegistry
  • HTMLElement
  • ShadowRoot
環境
node
作成日
2026-08-17T13:15:47Z

コントラクト

  1. customElements.define registers custom element lifecycle callbacks (connectedCallback, disconnectedCallback, attributeChangedCallback) that execute synchronously upon DOM tree mutation and observed attribute modification.
  2. Defining a custom element automatically upgrades matching pre-existing elements in the active DOM tree, replacing the node and triggering connectedCallback.
  3. attachShadow creates open or closed shadow roots where mode open exposes element.shadowRoot and mode closed keeps element.shadowRoot as null.
  4. Composed events dispatched inside a shadow root bubble across the shadow boundary through light DOM ancestors to Window, populating composedPath with the shadow root, host, and document nodes.

ファイル

  • NOTES.md
  • csx.json
  • package-lock.json
  • package.json
  • test/contract.mjs

ソースアーティファクトをダウンロード (tar.gz)

ソース

NOTES.md
# Happy DOM Custom Elements and Shadow DOM Lifecycle

## Prior Search Results

A search for known solutions for `happy-dom` returned three existing samples:
- `sha256:53aeae586fae7f02414a22588d189556a779055a4c627064ec6114aee07367ef` (Happy DOM window options and HTML parsing via `document.write` vs `DOMParser`)
- `sha256:930977ea5401f145841532e344ef71bed6ed96079f8ff6f685626c41d25cb31e` (Inline script execution requiring explicit JavaScript evaluation opt-in)
- `sha256:3098b65e11bf49d14ab84c27e05ab483a1e7c1eeae701327dadd384fd3ad8cd0` (VirtualConsolePrinter console output capture and draining)

None of these existing samples verify `CustomElementRegistry`, custom element lifecycle hooks, DOM tree upgrade mechanics, or Shadow DOM composed event bubbling.

## Pinned Release

- `happy-dom@20.11.2` (current stable major)

## Observed Behaviour

1. **Custom Element Lifecycle Execution**:
   - Registering a custom element subclass extending `HTMLElement` via `customElements.define(name, constructor)` registers synchronous lifecycle callbacks.
   - Setting attributes listed in `static get observedAttributes()` invokes `attributeChangedCallback(name, oldValue, newValue)` synchronously with `null` as the old value for new attributes. Setting unobserved attributes does not trigger the callback.
   - Appending a registered custom element to the DOM tree invokes `connectedCallback` synchronously.
   - Removing the element from the DOM tree invokes `disconnectedCallback` synchronously.

2. **DOM Tree Upgrades**:
   - When elements matching a custom tag name already exist in the DOM tree before registration, calling `customElements.define` automatically upgrades the nodes in the active DOM tree to instances of the custom element class and executes `connectedCallback`.

3. **Shadow DOM Encapsulation and Event Propagation**:
   - Calling `attachShadow({ mode: 'open' })` attaches an open shadow root and exposes it on `element.shadowRoot`.
   - Calling `attachShadow({ mode: 'closed' })` attaches a closed shadow root while `element.shadowRoot` evaluates to `null`.
   - Dispatching a `CustomEvent` with `{ bubbles: true, composed: true }` inside a shadow root bubbles across the shadow boundary through the light DOM parent chain to `document` and `window`. The event's `composedPath()` contains the target button, the shadow root, the host element, and ancestor DOM nodes up to `Window`.
csx.json
{"case":{"caseId":"case:sha256:76342040f863f0e2821abe12616b0cc8c2eabca1e476049d611a3c3ee9eceb53","contract":["customElements.define registers custom element lifecycle callbacks (connectedCallback, disconnectedCallback, attributeChangedCallback) that execute synchronously upon DOM tree mutation and observed attribute modification.","Defining a custom element automatically upgrades matching pre-existing elements in the active DOM tree, replacing the node and triggering connectedCallback.","attachShadow creates open or closed shadow roots where mode open exposes element.shadowRoot and mode closed keeps element.shadowRoot as null.","Composed events dispatched inside a shadow root bubble across the shadow boundary through light DOM ancestors to Window, populating composedPath with the shadow root, host, and document nodes."],"goal":"Verify custom element lifecycle callbacks, automatic DOM node upgrade upon definition, and Shadow DOM event propagation in happy-dom","kind":"HOW","packages":["pkg:npm/happy-dom@20.11.2"],"schemaVersion":1,"symbols":["CustomElementRegistry","HTMLElement","ShadowRoot"]},"contractCommand":["node","test/contract.mjs"],"environment":{"arch":"x64","ecosystem":"npm","executionContext":"node","language":"node","os":"linux","packageManager":"npm","runtime":"node","schemaVersion":1},"license":"MIT-0","packages":["pkg:npm/happy-dom@20.11.2"],"schemaVersion":1,"symbols":["CustomElementRegistry","HTMLElement","ShadowRoot"],"verifierAdapter":"node-typescript@1"}
package-lock.json
{
  "name": "npm-happy-dom-version-depth",
  "version": "1.0.0",
  "lockfileVersion": 3,
  "requires": true,
  "packages": {
    "": {
      "name": "npm-happy-dom-version-depth",
      "version": "1.0.0",
      "license": "ISC",
      "dependencies": {
        "happy-dom": "20.11.2"
      }
    },
    "node_modules/@types/node": {
      "version": "26.2.0",
      "resolved": "https://registry.npmjs.org/@types/node/-/node-26.2.0.tgz",
      "integrity": "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg==",
      "license": "MIT",
      "dependencies": {
        "undici-types": "~8.3.0"
      }
    },
    "node_modules/@types/whatwg-mimetype": {
      "version": "3.0.2",
      "resolved": "https://registry.npmjs.org/@types/whatwg-mimetype/-/whatwg-mimetype-3.0.2.tgz",
      "integrity": "sha512-c2AKvDT8ToxLIOUlN51gTiHXflsfIFisS4pO7pDPoKouJCESkhZnEy623gwP9laCy5lnLDAw1vAzu2vM2YLOrA==",
      "license": "MIT"
    },
    "node_modules/@types/ws": {
      "version": "8.18.1",
      "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
      "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
      "license": "MIT",
      "dependencies": {
        "@types/node": "*"
      }
    },
    "node_modules/buffer-image-size": {
      "version": "0.6.4",
      "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz",
      "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==",
      "license": "MIT",
      "dependencies": {
        "@types/node": "*"
      },
      "engines": {
        "node": ">=4.0"
      }
    },
    "node_modules/entities": {
      "version": "7.0.1",
      "resolved": "https://registry.npmjs.org/entities/-/entities-7.0.1.tgz",
      "integrity": "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA==",
      "license": "BSD-2-Clause",
      "engines": {
        "node": ">=0.12"
      },
      "funding": {
        "url": "https://github.com/fb55/entities?sponsor=1"
      }
    },
    "node_modules/happy-dom": {
      "version": "20.11.2",
      "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.11.2.tgz",
      "integrity": "sha512-7MB+bJLkxu3SowAfBJbjW+c55kNz5tkR45gu2qzrxznezhLeN5YIlJbwUgSzlGc+qWoZ8Ykg71H5ezz69xixrw==",
      "license": "MIT",
      "dependencies": {
        "@types/node": ">=20.0.0",
        "@types/whatwg-mimetype": "^3.0.2",
        "@types/ws": "^8.18.1",
        "buffer-image-size": "^0.6.4",
        "entities": "^7.0.1",
        "whatwg-mimetype": "^3.0.0",
        "ws": "^8.21.0"
      },
      "engines": {
        "node": ">=20.0.0"
      }
    },
    "node_modules/undici-types": {
      "version": "8.3.0",
      "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
      "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
      "license": "MIT"
    },
    "node_modules/whatwg-mimetype": {
      "version": "3.0.0",
      "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-3.0.0.tgz",
      "integrity": "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q==",
      "license": "MIT",
      "engines": {
        "node": ">=12"
      }
    },
    "node_modules/ws": {
      "version": "8.21.3",
      "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz",
      "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==",
      "license": "MIT",
      "engines": {
        "node": ">=10.0.0"
      },
      "peerDependencies": {
        "bufferutil": "^4.0.1",
        "utf-8-validate": ">=5.0.2"
      },
      "peerDependenciesMeta": {
        "bufferutil": {
          "optional": true
        },
        "utf-8-validate": {
          "optional": true
        }
      }
    }
  }
}
package.json
{
  "name": "npm-happy-dom-version-depth",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "node test/contract.mjs"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "type": "commonjs",
  "dependencies": {
    "happy-dom": "20.11.2"
  }
}
test/contract.mjs
import { Window } from 'happy-dom';
import assert from 'node:assert/strict';

const window = new Window();
const { customElements, HTMLElement, document, CustomEvent } = window;

// 1. Custom element registration and synchronous lifecycle callbacks
{
  const lifecycleEvents = [];

  class CustomBadge extends HTMLElement {
    static get observedAttributes() {
      return ['variant', 'label'];
    }

    connectedCallback() {
      lifecycleEvents.push(`connected:${this.getAttribute('label')}`);
    }

    disconnectedCallback() {
      lifecycleEvents.push(`disconnected:${this.getAttribute('label')}`);
    }

    attributeChangedCallback(name, oldValue, newValue) {
      lifecycleEvents.push(`attr:${name}:${oldValue}->${newValue}`);
    }
  }

  customElements.define('custom-badge', CustomBadge);

  const badge = document.createElement('custom-badge');
  badge.setAttribute('label', 'New');
  badge.setAttribute('variant', 'primary');
  badge.setAttribute('unobserved', 'ignored');

  assert.deepStrictEqual(lifecycleEvents, [
    'attr:label:null->New',
    'attr:variant:null->primary'
  ]);

  document.body.appendChild(badge);
  assert.strictEqual(lifecycleEvents[lifecycleEvents.length - 1], 'connected:New');

  badge.setAttribute('variant', 'success');
  assert.strictEqual(lifecycleEvents[lifecycleEvents.length - 1], 'attr:variant:primary->success');

  document.body.removeChild(badge);
  assert.strictEqual(lifecycleEvents[lifecycleEvents.length - 1], 'disconnected:New');
}

// 2. DOM tree pre-existing elements are upgraded upon definition
{
  const upgradeLog = [];

  class UserWidget extends HTMLElement {
    connectedCallback() {
      upgradeLog.push('widget-connected');
    }
  }

  document.body.innerHTML = '<user-widget class="target"></user-widget>';
  const initialEl = document.body.firstElementChild;
  assert.strictEqual(initialEl instanceof UserWidget, false);

  customElements.define('user-widget', UserWidget);

  const upgradedEl = document.body.firstElementChild;
  assert.strictEqual(upgradedEl instanceof UserWidget, true);
  assert.strictEqual(upgradedEl === initialEl, false);
  assert.deepStrictEqual(upgradeLog, ['widget-connected']);
}

// 3. Shadow DOM encapsulation modes (open vs closed)
{
  const hostOpen = document.createElement('div');
  const shadowOpen = hostOpen.attachShadow({ mode: 'open' });
  assert.strictEqual(hostOpen.shadowRoot, shadowOpen);
  assert.strictEqual(shadowOpen.mode, 'open');

  const hostClosed = document.createElement('div');
  const shadowClosed = hostClosed.attachShadow({ mode: 'closed' });
  assert.strictEqual(hostClosed.shadowRoot, null);
  assert.strictEqual(shadowClosed.mode, 'closed');
}

// 4. Composed event propagation from Shadow DOM through light DOM to Window
{
  const host = document.createElement('div');
  const shadow = host.attachShadow({ mode: 'open' });
  const innerButton = document.createElement('button');
  shadow.appendChild(innerButton);
  document.body.appendChild(host);

  const eventBubbledTargets = [];
  window.addEventListener('user-action', () => eventBubbledTargets.push('window'));
  document.addEventListener('user-action', () => eventBubbledTargets.push('document'));
  host.addEventListener('user-action', () => eventBubbledTargets.push('host'));
  shadow.addEventListener('user-action', () => eventBubbledTargets.push('shadow'));

  let observedComposedPath = null;
  innerButton.addEventListener('user-action', (e) => {
    eventBubbledTargets.push('innerButton');
    observedComposedPath = e.composedPath();
  });

  const event = new CustomEvent('user-action', { bubbles: true, composed: true });
  innerButton.dispatchEvent(event);

  assert.deepStrictEqual(eventBubbledTargets, [
    'innerButton',
    'shadow',
    'host',
    'document',
    'window'
  ]);

  assert.strictEqual(observedComposedPath[0], innerButton);
  assert.strictEqual(observedComposedPath[1], shadow);
  assert.strictEqual(observedComposedPath[2], host);
  assert.strictEqual(observedComposedPath[3], document.body);
  assert.strictEqual(observedComposedPath[4], document.documentElement);
  assert.strictEqual(observedComposedPath[5], document);
  assert.strictEqual(observedComposedPath[6], window);
}

オリジンシーダー

csx-seed