@stencil/mock-doc 5.0.0-beta.9 → 5.0.0-rc.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.
package/dist/index.d.mts CHANGED
@@ -169,6 +169,7 @@ declare class MockShadowRoot extends MockDocumentFragment {
169
169
  private _delegatesFocus;
170
170
  private _clonable;
171
171
  private _serializable;
172
+ private _referenceTarget;
172
173
  get activeElement(): HTMLElement | null;
173
174
  get clonable(): boolean;
174
175
  set clonable(value: boolean);
@@ -180,6 +181,8 @@ declare class MockShadowRoot extends MockDocumentFragment {
180
181
  set mode(value: 'open' | 'closed');
181
182
  get pictureInPictureElement(): HTMLElement | null;
182
183
  get pointerLockElement(): HTMLElement | null;
184
+ get referenceTarget(): string | null;
185
+ set referenceTarget(value: string | null);
183
186
  get serializable(): boolean;
184
187
  set serializable(value: boolean);
185
188
  get slotAssignment(): 'named' | 'manual';
@@ -448,6 +451,18 @@ declare function cloneDocument(srcDoc: Document): Document;
448
451
  * @param win the mock window instance to update
449
452
  */
450
453
  declare function constrainTimeouts(win: MockWindow): void;
454
+ /**
455
+ * Reset a window so the same object can be used for another render, then parse `html` into its
456
+ * document.
457
+ *
458
+ * Code that captured the window's sub-objects (e.g. an SSR platform holding `win.location`,
459
+ * `win.console` or `win.document`) keeps working: those objects are kept and reset in place,
460
+ * rather than replaced. Everything else on the window - including anything a previous render
461
+ * added - is removed.
462
+ * @param win the window to reset
463
+ * @param html the HTML for the next render
464
+ */
465
+ declare function resetWindowForReuse(win: MockWindow, html: string): void;
451
466
  //#endregion
452
467
  //#region src/event.d.ts
453
468
  declare class MockEvent {
@@ -567,7 +582,7 @@ declare class MockTokenList {
567
582
  add(...tokens: string[]): void;
568
583
  remove(...tokens: string[]): void;
569
584
  contains(token: string): boolean;
570
- toggle(token: string): void;
585
+ toggle(token: string, force?: boolean): boolean;
571
586
  get length(): number;
572
587
  item(index: number): string;
573
588
  toString(): string;
@@ -617,7 +632,17 @@ declare class MockNode {
617
632
  static DOCUMENT_TYPE_NODE: number;
618
633
  static DOCUMENT_FRAGMENT_NODE: number;
619
634
  }
620
- type MockElementInternals = Record<keyof ElementInternals, null>;
635
+ /**
636
+ * Just enough of `ElementInternals` for form-associated components to run without throwing.
637
+ * There is no form, validation or accessibility tree to update, so the methods do nothing.
638
+ */
639
+ declare class MockElementInternals {
640
+ states: Set<string>;
641
+ setFormValue(): void;
642
+ setValidity(): void;
643
+ checkValidity(): boolean;
644
+ reportValidity(): boolean;
645
+ }
621
646
  declare class MockElement extends MockNode {
622
647
  __namespaceURI: string | null;
623
648
  __localName: string | null;
@@ -627,7 +652,9 @@ declare class MockElement extends MockNode {
627
652
  attachInternals(): MockElementInternals;
628
653
  constructor(ownerDocument: any, nodeName: string | null, namespaceURI?: string | null);
629
654
  addEventListener(type: string, handler: (ev?: any) => void, options?: boolean | AddEventListenerOptions): void;
630
- attachShadow(_opts: ShadowRootInit): any;
655
+ attachShadow(_opts: ShadowRootInit & {
656
+ referenceTarget?: string;
657
+ }): any;
631
658
  blur(): void;
632
659
  get localName(): string;
633
660
  get namespaceURI(): string;
@@ -691,8 +718,8 @@ declare class MockElement extends MockNode {
691
718
  insertAdjacentText(position: 'beforebegin' | 'afterbegin' | 'beforeend' | 'afterend', text: string): void;
692
719
  hasAttribute(attrName: string): boolean;
693
720
  hasAttributeNS(namespaceURI: string | null, name: string): boolean;
694
- get hidden(): boolean;
695
- set hidden(isHidden: boolean);
721
+ get hidden(): boolean | "until-found";
722
+ set hidden(isHidden: boolean | 'until-found');
696
723
  get lang(): string;
697
724
  set lang(value: string);
698
725
  get lastElementChild(): MockElement | null;
@@ -1041,4 +1068,4 @@ declare class MockResponse {
1041
1068
  clone(): MockResponse;
1042
1069
  }
1043
1070
  //#endregion
1044
- export { MockAttr, MockAttributeMap, MockComment, MockCustomEvent, MockDocument, MockElement, MockHTMLElement, MockHeaders, MockKeyboardEvent, MockMouseEvent, MockNode, MockRequest, type MockRequestInfo, type MockRequestInit, MockResponse, type MockResponseInit, MockTextNode, MockWindow, NODE_TYPES, type SerializeNodeToHtmlOptions, cloneAttributes, cloneDocument, cloneWindow, constrainTimeouts, createDocument, createFragment, parseHtmlToDocument, parseHtmlToFragment, patchWindow, resetDocument, serializeNodeToHtml, setupGlobal, teardownGlobal };
1071
+ export { MockAttr, MockAttributeMap, MockComment, MockCustomEvent, MockDocument, MockElement, MockHTMLElement, MockHeaders, MockKeyboardEvent, MockMouseEvent, MockNode, MockRequest, type MockRequestInfo, type MockRequestInit, MockResponse, type MockResponseInit, MockTextNode, MockWindow, NODE_TYPES, type SerializeNodeToHtmlOptions, cloneAttributes, cloneDocument, cloneWindow, constrainTimeouts, createDocument, createFragment, parseHtmlToDocument, parseHtmlToFragment, patchWindow, resetDocument, resetWindowForReuse, serializeNodeToHtml, setupGlobal, teardownGlobal };
package/dist/index.mjs CHANGED
@@ -21,9 +21,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
21
21
  value: mod,
22
22
  enumerable: true
23
23
  }) : target, mod));
24
- //#endregion
25
- //#region src/constants.ts
26
- const HYDRATE_ID = "s-id";
27
24
  const XML_NS = "http://www.w3.org/XML/1998/namespace";
28
25
  const XMLNS_NS = "http://www.w3.org/2000/xmlns/";
29
26
  /**
@@ -954,6 +951,11 @@ function* streamToHtml(node, opts, output) {
954
951
  yield " shadowrootserializable";
955
952
  output.currentLineWidth += 23;
956
953
  }
954
+ if ("referenceTarget" in node && typeof node.referenceTarget === "string" && node.referenceTarget) {
955
+ const referenceTargetAttr = ` shadowrootreferencetarget="${escapeString(node.referenceTarget, true)}"`;
956
+ yield referenceTargetAttr;
957
+ output.currentLineWidth += referenceTargetAttr.length;
958
+ }
957
959
  }
958
960
  const attrsLength = node.attributes.length;
959
961
  const attributes = opts.prettyHtml && attrsLength > 1 ? cloneAttributes(node.attributes, true) : node.attributes;
@@ -961,7 +963,7 @@ function* streamToHtml(node, opts, output) {
961
963
  const attr = attributes.item(i);
962
964
  const attrName = attr.name;
963
965
  if (attrName === "style") continue;
964
- if (tag === "template" && isShadowRoot && (attrName === "shadowrootmode" || attrName === "shadowrootdelegatesfocus" || attrName === "shadowrootcustomelementregistry")) continue;
966
+ if (tag === "template" && isShadowRoot && (attrName === "shadowrootmode" || attrName === "shadowrootdelegatesfocus" || attrName === "shadowrootreferencetarget" || attrName === "shadowrootcustomelementregistry")) continue;
965
967
  let attrValue = attr.value;
966
968
  if (opts.removeEmptyAttributes && attrValue === "" && REMOVE_EMPTY_ATTR.has(attrName)) continue;
967
969
  const attrNamespaceURI = attr.namespaceURI;
@@ -1041,19 +1043,7 @@ function* streamToHtml(node, opts, output) {
1041
1043
  const isWithinWhitespaceSensitiveNode = opts.newLines || (opts.indentSpaces ?? 0) > 0 ? isWithinWhitespaceSensitive(node) : false;
1042
1044
  if (!isWithinWhitespaceSensitiveNode && (opts.indentSpaces ?? 0) > 0 && ignoreTag === false) output.indent = output.indent + (opts.indentSpaces ?? 0);
1043
1045
  for (let i = 0; i < childNodeLength; i++) {
1044
- /**
1045
- * In cases where a user would pass in a declarative shadow dom of a
1046
- * Stencil component, we want to skip over the template tag as we
1047
- * will be parsing the shadow root of the component again.
1048
- *
1049
- * We know it is a hydrated Stencil component by checking if the `HYDRATE_ID`
1050
- * is set on the node.
1051
- */
1052
- const sId = node.attributes.getNamedItem(HYDRATE_ID);
1053
- if (childNodes[i].nodeName.toLowerCase() === "template" && sId) {
1054
- yield `\n${" ".repeat(output.indent)}<!--r.${sId.value}-->`;
1055
- continue;
1056
- }
1046
+ if (childNodes[i].nodeName.toLowerCase() === "template" && node.attributes.getNamedItem("s-id")) continue;
1057
1047
  yield* streamToHtml(childNodes[i], opts, output);
1058
1048
  }
1059
1049
  if (ignoreTag === false) {
@@ -1323,10 +1313,12 @@ var MockTokenList = class {
1323
1313
  token = String(token);
1324
1314
  return getItems(this.elm, this.attr).includes(token);
1325
1315
  }
1326
- toggle(token) {
1316
+ toggle(token, force) {
1327
1317
  token = String(token);
1328
- if (this.contains(token) === true) this.remove(token);
1329
- else this.add(token);
1318
+ const shouldAdd = force === void 0 ? !this.contains(token) : !!force;
1319
+ if (shouldAdd) this.add(token);
1320
+ else this.remove(token);
1321
+ return shouldAdd;
1330
1322
  }
1331
1323
  get length() {
1332
1324
  return getItems(this.elm, this.attr).length;
@@ -1553,6 +1545,21 @@ var MockNodeList = class {
1553
1545
  this.length = length;
1554
1546
  }
1555
1547
  };
1548
+ /**
1549
+ * Just enough of `ElementInternals` for form-associated components to run without throwing.
1550
+ * There is no form, validation or accessibility tree to update, so the methods do nothing.
1551
+ */
1552
+ var MockElementInternals = class {
1553
+ states = /* @__PURE__ */ new Set();
1554
+ setFormValue() {}
1555
+ setValidity() {}
1556
+ checkValidity() {
1557
+ return true;
1558
+ }
1559
+ reportValidity() {
1560
+ return true;
1561
+ }
1562
+ };
1556
1563
  var MockElement = class extends MockNode {
1557
1564
  __namespaceURI;
1558
1565
  __localName;
@@ -1560,13 +1567,7 @@ var MockElement = class extends MockNode {
1560
1567
  __shadowRoot;
1561
1568
  __style;
1562
1569
  attachInternals() {
1563
- return new Proxy({}, { get: function(_target, prop, _receiver) {
1564
- /**
1565
- * only print warning when running in a test environment
1566
- */
1567
- if ("process" in globalThis && globalThis.process.env.__STENCIL_SPEC_TESTS__) console.error(`NOTE: Property ${String(prop)} was accessed on ElementInternals, but this property is not implemented.
1568
- Testing components with ElementInternals is fully supported in e2e tests.`);
1569
- } });
1570
+ return new MockElementInternals();
1570
1571
  }
1571
1572
  constructor(ownerDocument, nodeName, namespaceURI = null) {
1572
1573
  super(ownerDocument, 1, typeof nodeName === "string" ? nodeName : null, null);
@@ -1584,6 +1585,7 @@ var MockElement = class extends MockNode {
1584
1585
  shadowRoot.delegatesFocus = _opts.delegatesFocus ?? false;
1585
1586
  shadowRoot.clonable = _opts.clonable ?? false;
1586
1587
  shadowRoot.serializable = _opts.serializable ?? false;
1588
+ shadowRoot.referenceTarget = _opts.referenceTarget ?? null;
1587
1589
  this.shadowRoot = shadowRoot;
1588
1590
  return shadowRoot;
1589
1591
  }
@@ -1824,7 +1826,8 @@ var MockElement = class extends MockNode {
1824
1826
  return this.hasAttributeNS(null, "hidden");
1825
1827
  }
1826
1828
  set hidden(isHidden) {
1827
- if (isHidden === true) this.setAttributeNS(null, "hidden", "");
1829
+ if (isHidden === "until-found") this.setAttributeNS(null, "hidden", "until-found");
1830
+ else if (isHidden === true) this.setAttributeNS(null, "hidden", "");
1828
1831
  else this.removeAttributeNS(null, "hidden");
1829
1832
  }
1830
1833
  get lang() {
@@ -4709,6 +4712,7 @@ var MockShadowRoot = class extends MockDocumentFragment {
4709
4712
  _delegatesFocus = false;
4710
4713
  _clonable = false;
4711
4714
  _serializable = false;
4715
+ _referenceTarget = null;
4712
4716
  get activeElement() {
4713
4717
  return null;
4714
4718
  }
@@ -4747,6 +4751,12 @@ var MockShadowRoot = class extends MockDocumentFragment {
4747
4751
  get pointerLockElement() {
4748
4752
  return null;
4749
4753
  }
4754
+ get referenceTarget() {
4755
+ return this._referenceTarget;
4756
+ }
4757
+ set referenceTarget(value) {
4758
+ this._referenceTarget = value;
4759
+ }
4750
4760
  get serializable() {
4751
4761
  return this._serializable;
4752
4762
  }
@@ -5267,6 +5277,77 @@ function constrainTimeouts(win) {
5267
5277
  win.__allowInterval = false;
5268
5278
  win.__maxTimeout = 0;
5269
5279
  }
5280
+ /**
5281
+ * Reset a window so the same object can be used for another render, then parse `html` into its
5282
+ * document.
5283
+ *
5284
+ * Code that captured the window's sub-objects (e.g. an SSR platform holding `win.location`,
5285
+ * `win.console` or `win.document`) keeps working: those objects are kept and reset in place,
5286
+ * rather than replaced. Everything else on the window - including anything a previous render
5287
+ * added - is removed.
5288
+ * @param win the window to reset
5289
+ * @param html the HTML for the next render
5290
+ */
5291
+ function resetWindowForReuse(win, html) {
5292
+ const retained = {
5293
+ console: win.console,
5294
+ document: win.document,
5295
+ eventCounts: win.performance.eventCounts,
5296
+ history: win.history,
5297
+ localStorage: win.localStorage,
5298
+ location: win.location,
5299
+ navigator: win.navigator,
5300
+ orientation: win.screen.orientation,
5301
+ performance: win.performance,
5302
+ screen: win.screen,
5303
+ sessionStorage: win.sessionStorage
5304
+ };
5305
+ if (win.__timeouts) win.__timeouts.forEach((timeoutId) => {
5306
+ nativeClearInterval(timeoutId);
5307
+ nativeClearTimeout(timeoutId);
5308
+ });
5309
+ resetObject(retained.console, createConsole());
5310
+ resetObject(retained.history, new MockHistory());
5311
+ resetObject(retained.location, new MockLocation());
5312
+ resetObject(retained.navigator, new MockNavigator());
5313
+ retained.localStorage.clear();
5314
+ retained.sessionStorage.clear();
5315
+ retained.eventCounts.clear();
5316
+ resetObject(retained.performance, {
5317
+ eventCounts: retained.eventCounts,
5318
+ interactionCount: 0,
5319
+ timeOrigin: Date.now()
5320
+ });
5321
+ for (const key of Reflect.ownKeys(win)) delete win[key];
5322
+ resetWindowDefaults(win);
5323
+ resetWindowDimensions(win);
5324
+ const defaultScreen = win.screen;
5325
+ resetObject(retained.orientation, defaultScreen.orientation);
5326
+ resetObject(retained.screen, {
5327
+ ...defaultScreen,
5328
+ orientation: retained.orientation
5329
+ });
5330
+ win.console = retained.console;
5331
+ win.customElements = null;
5332
+ win.document = retained.document;
5333
+ win.history = retained.history;
5334
+ win.localStorage = retained.localStorage;
5335
+ win.location = retained.location;
5336
+ win.navigator = retained.navigator;
5337
+ win.performance = retained.performance;
5338
+ win.screen = retained.screen;
5339
+ win.sessionStorage = retained.sessionStorage;
5340
+ resetDocumentForReuse(retained.document, win, html);
5341
+ }
5342
+ /**
5343
+ * Replace every own property of `target` with those of `defaults`, keeping the object itself.
5344
+ * @param target the object to reset in place
5345
+ * @param defaults the properties it should have afterwards
5346
+ */
5347
+ function resetObject(target, defaults) {
5348
+ for (const key of Reflect.ownKeys(target)) delete target[key];
5349
+ Object.assign(target, defaults);
5350
+ }
5270
5351
  function resetWindow(win) {
5271
5352
  if (win != null) {
5272
5353
  if (win.__timeouts) {
@@ -5286,11 +5367,14 @@ function resetWindow(win) {
5286
5367
  if (win.document != null) try {
5287
5368
  win.document.defaultView = win;
5288
5369
  } catch {}
5289
- win.fetch = null;
5290
- win.Headers = null;
5291
- win.Request = null;
5292
- win.Response = null;
5293
- win.FetchError = null;
5370
+ const windowDestroyed = () => {
5371
+ throw new Error("MockWindow was already destroyed");
5372
+ };
5373
+ win.fetch = windowDestroyed;
5374
+ win.Headers = windowDestroyed;
5375
+ win.Request = windowDestroyed;
5376
+ win.Response = windowDestroyed;
5377
+ win.FetchError = windowDestroyed;
5294
5378
  }
5295
5379
  }
5296
5380
  function resetWindowDimensions(win) {
@@ -5572,6 +5656,37 @@ function resetDocument(doc) {
5572
5656
  } catch {}
5573
5657
  }
5574
5658
  }
5659
+ /**
5660
+ * Reset a document so the same object can be used for another render, then parse `html` into
5661
+ * it. The document object itself is kept (code holding a reference to it stays valid), but its
5662
+ * whole element tree is replaced with freshly parsed elements - so caches keyed on elements, like
5663
+ * the runtime's applied-styles cache keyed on `<head>`, start empty.
5664
+ * @param doc the document to reset
5665
+ * @param win the window that owns the document
5666
+ * @param html the HTML to parse into the document
5667
+ */
5668
+ function resetDocumentForReuse(doc, win, html) {
5669
+ resetDocument(doc);
5670
+ for (const key of Reflect.ownKeys(doc)) if (typeof key !== "string" || !REUSABLE_DOC_KEY_KEEPERS.has(key)) delete doc[key];
5671
+ doc.defaultView = win;
5672
+ doc.documentElement = parseDocumentUtil(doc, html).documentElement;
5673
+ }
5674
+ /** Structural document properties kept by {@link resetDocumentForReuse}; everything else is per-render state. */
5675
+ const REUSABLE_DOC_KEY_KEEPERS = /* @__PURE__ */ new Set([
5676
+ "_nodeValue",
5677
+ "nodeName",
5678
+ "nodeType",
5679
+ "ownerDocument",
5680
+ "parentNode",
5681
+ "_childNodes",
5682
+ "__namespaceURI",
5683
+ "__localName",
5684
+ "defaultView",
5685
+ "cookie",
5686
+ "referrer",
5687
+ "compatMode",
5688
+ "contentType"
5689
+ ]);
5575
5690
  const DOC_KEY_KEEPERS = /* @__PURE__ */ new Set([
5576
5691
  "nodeName",
5577
5692
  "nodeType",
@@ -5610,4 +5725,4 @@ function setOwnerDocument(elm, ownerDocument) {
5610
5725
  }
5611
5726
  }
5612
5727
  //#endregion
5613
- export { MockAttr, MockAttributeMap, MockComment, MockCustomEvent, MockDocument, MockElement, MockHTMLElement, MockHeaders, MockKeyboardEvent, MockMouseEvent, MockNode, MockRequest, MockResponse, MockTextNode, MockWindow, NODE_TYPES, cloneAttributes, cloneDocument, cloneWindow, constrainTimeouts, createDocument, createFragment, parseHtmlToDocument, parseHtmlToFragment, patchWindow, resetDocument, serializeNodeToHtml, setupGlobal, teardownGlobal };
5728
+ export { MockAttr, MockAttributeMap, MockComment, MockCustomEvent, MockDocument, MockElement, MockHTMLElement, MockHeaders, MockKeyboardEvent, MockMouseEvent, MockNode, MockRequest, MockResponse, MockTextNode, MockWindow, NODE_TYPES, cloneAttributes, cloneDocument, cloneWindow, constrainTimeouts, createDocument, createFragment, parseHtmlToDocument, parseHtmlToFragment, patchWindow, resetDocument, resetWindowForReuse, serializeNodeToHtml, setupGlobal, teardownGlobal };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stencil/mock-doc",
3
- "version": "5.0.0-beta.9",
3
+ "version": "5.0.0-rc.0",
4
4
  "description": "A minimal mock DOM implementation for SSR and testing",
5
5
  "keywords": [
6
6
  "dom",
@@ -41,6 +41,9 @@
41
41
  "typescript": ">5.0.0 <7.0.0",
42
42
  "vitest": "^4.1.10"
43
43
  },
44
+ "engines": {
45
+ "node": ">=22.0.0"
46
+ },
44
47
  "volta": {
45
48
  "extends": "../../package.json"
46
49
  },