server-shim.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import { customElements as litCE, HTMLElement as litShimHTMLElement } from '@lit-labs/ssr-dom-shim';
  2. // Something at build time injects document.currentScript = undefined instead of
  3. // document.currentScript = null. This causes Sass build to fail because it
  4. // seems to be expecting `=== null`. This set to `undefined` doesn't seem to be
  5. // caused by Lit and only happens at build / test time, but not in dev or
  6. // preview time.
  7. if (globalThis.document) {
  8. document.currentScript = null;
  9. }
  10. if (globalThis.HTMLElement) {
  11. // Seems Astro's Element shim does nothing when `.setAttribute` is called
  12. // and subsequently `.getAttribute` is called. Causes Lit to not SSR attrs
  13. globalThis.HTMLElement = litShimHTMLElement;
  14. }
  15. // Astro seems to have a DOM shim and the only real difference that we need out
  16. // of the Lit DOM shim is that the Lit DOM shim reads
  17. // `HTMLElement.observedAttributes` which is meant to trigger
  18. // `ReactiveElement.finalize()`. So this is the only thing we will re-shim since
  19. // Lit will try to respect other global DOM shims.
  20. globalThis.customElements = litCE;
  21. const litCeDefine = customElements.define;
  22. // We need to patch customElements.define to keep track of the tagName on the
  23. // class itself so that we can transform JSX custom element class definintion to
  24. // a DSD string on the server, because there is no way to get the tagName from a
  25. // CE class otherwise. Not an issue on client:only because the browser supports
  26. // appending a class instance directly to the DOM.
  27. customElements.define = function (tagName, Ctr) {
  28. Ctr[Symbol.for('tagName')] = tagName;
  29. return litCeDefine.call(this, tagName, Ctr);
  30. };