Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(hydrate): support object serialization for hydrated components #6208

Open
wants to merge 33 commits into
base: main
Choose a base branch
from

Conversation

christian-bromann
Copy link
Member

@christian-bromann christian-bromann commented Mar 18, 2025

What is the current behavior?

Stencil has only limited support for the serialization of objects in cases where you want to server side render a component. Support was given for basic objects, e.g.

renderToString(`<my-element complex-prop=${JSON.stringify({ foo: 'bar' })} />`)

But not for more complex ones like Map, Set, Infinity or symbols.

What is the new behavior?

The hydrate module now exports a serializeProperty method that can help to properly serialize a property of any type, e.g. given the following component:

import { Component, h, Prop } from '@stencil/core';

@Component({
  tag: 'complex-properties',
  shadow: true,
})
export class ComplexProperties {
  /**
   * basic object
   */
  @Prop() foo: { bar: string, loo: number[], qux: { quux: symbol } };

  /**
   * map objects
   */
  @Prop() baz: Map<string, { qux: symbol }>;

  /**
   * set objects
   */
  @Prop() quux: Set<string>;

  /**
   * infinity
   */
  @Prop() grault: typeof Infinity;

  /**
   * null
   */
  @Prop() waldo: null;


  render() {
    return <ul>
      <li>{`this.foo.bar`}: {this.foo.bar}</li>
      <li>{`this.foo.loo`}: {this.foo.loo.join(', ')}</li>
      <li>{`this.foo.qux`}: {typeof this.foo.qux.quux}</li>
      <li>{`this.baz.get('foo')`}: {typeof this.baz.get('foo')?.qux}</li>
      <li>{`this.quux.has('foo')`}: {this.quux.has('foo') ? 'true' : 'false'}</li>
      <li>{`this.grault`}: {this.grault === Infinity ? 'true' : 'false'}</li>
      <li>{`this.waldo`}: {this.waldo === null ? 'true' : 'false'}</li>
    </ul>;
  }
}

You could serialize it via:

import { renderToString, serializeProperty } from './test/wdio/hydrate/index.mjs';

const { html } = await renderToString(`<complex-properties
  foo=${serializeProperty({ bar: 123, loo: [1, 2, 3], qux: { quux: Symbol('quux') } })}
  baz=${serializeProperty(new Map([['foo', { qux: Symbol('quux') }]]))}
  quux=${serializeProperty(new Set(['foo']))}
  corge=${serializeProperty(new Set([{ foo: { bar: 'foo' } }]))}
  grault=${serializeProperty(Infinity)}
  waldo=${serializeProperty(null)}
/>`, {
  prettyHtml: true
});

Which will output:

<!doctype html>
<html class="hydrated" data-stencil-build="fi5vbicm">
  <head>
    <meta charset="utf-8">
  </head>
  <body>
    <complex-properties baz="serialized:eyJ0eXBlIjoibWFwIiwidmFsdWUiOltbeyJ0eXBlIjoic3RyaW5nIiwidmFsdWUiOiJmb28ifSx7InR5cGUiOiJvYmplY3QiLCJ2YWx1ZSI6W1sicXV4Iix7InR5cGUiOiJzeW1ib2wiLCJ2YWx1ZSI6InF1dXgifV1dfV1dfQ==" class="hydrated" corge="serialized:eyJ0eXBlIjoic2V0IiwidmFsdWUiOlt7InR5cGUiOiJvYmplY3QiLCJ2YWx1ZSI6W1siZm9vIix7InR5cGUiOiJvYmplY3QiLCJ2YWx1ZSI6W1siYmFyIix7InR5cGUiOiJzdHJpbmciLCJ2YWx1ZSI6ImZvbyJ9XV19XV19XX0=" foo="serialized:eyJ0eXBlIjoib2JqZWN0IiwidmFsdWUiOltbImJhciIseyJ0eXBlIjoibnVtYmVyIiwidmFsdWUiOjEyM31dLFsibG9vIix7InR5cGUiOiJhcnJheSIsInZhbHVlIjpbeyJ0eXBlIjoibnVtYmVyIiwidmFsdWUiOjF9LHsidHlwZSI6Im51bWJlciIsInZhbHVlIjoyfSx7InR5cGUiOiJudW1iZXIiLCJ2YWx1ZSI6M31dfV0sWyJxdXgiLHsidHlwZSI6Im9iamVjdCIsInZhbHVlIjpbWyJxdXV4Iix7InR5cGUiOiJzeW1ib2wiLCJ2YWx1ZSI6InF1dXgifV1dfV1dfQ==" grault="serialized:eyJ0eXBlIjoibnVtYmVyIiwidmFsdWUiOiJJbmZpbml0eSJ9" quux="serialized:eyJ0eXBlIjoic2V0IiwidmFsdWUiOlt7InR5cGUiOiJzdHJpbmciLCJ2YWx1ZSI6ImZvbyJ9XX0=" s-id="1" waldo="serialized:eyJ0eXBlIjoibnVsbCJ9">
      <template shadowrootmode="open">
        <ul c-id="1.0.0.0">
          <li c-id="1.1.1.0">
            <!--t.1.2.2.0-->
            this.foo.bar: 123
          </li>
          <li c-id="1.3.1.1">
            <!--t.1.4.2.0-->
            this.foo.loo: 1, 2, 3
          </li>
          <li c-id="1.5.1.2">
            <!--t.1.6.2.0-->
            this.foo.qux: symbol
          </li>
          <li c-id="1.7.1.3">
            <!--t.1.8.2.0-->
            this.baz.get('foo'): symbol
          </li>
          <li c-id="1.9.1.4">
            <!--t.1.10.2.0-->
            this.quux.has('foo'): true
          </li>
          <li c-id="1.11.1.5">
            <!--t.1.12.2.0-->
            this.grault: true
          </li>
          <li c-id="1.13.1.6">
            <!--t.1.14.2.0-->
            this.waldo: true
          </li>
        </ul>
      </template>
      <!--r.1-->
    </complex-properties>
  </body>
</html>

Documentation

wip.

Does this introduce a breaking change?

  • Yes
  • No

Testing

Added an e2e WebdriverIO test to verify if a component with complex types can be rendered and hydrated.

Other information

The implemented serialization and deserialization primitives come from the WebDriver Bidi protocol defined in 7.5.3.7. The script.LocalValue Type (https://www.w3.org/TR/webdriver-bidi/#type-script-LocalValue) where this is used to serialize complex values between a local script and a remote browser. I made an addition to parse the serialized object into a base64 string and prefixed it with serialized: to clearly identify a serialized value.

@christian-bromann christian-bromann marked this pull request as ready for review March 18, 2025 16:55
@christian-bromann christian-bromann requested a review from a team as a code owner March 18, 2025 16:55
@@ -27,7 +27,7 @@ describe('different types of decorated properties and states render on both serv
renderToString = mod.renderToString;
});

it('renders default values', async () => {
it.skip('renders default values', async () => {
Copy link
Member Author

Choose a reason for hiding this comment

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

@johnjenkins any idea why these tests are failing? It seems like something with reflected properties that is still not quite right here

@johnjenkins
Copy link
Contributor

johnjenkins commented Mar 20, 2025

A side note (perhaps tangentially related or not at all ... or just a note for documentation)

A similar result can be achieved within Stencil right now using beforeHydrate:

await renderToString(response.body, {
    beforeHydrate: (doc: Document) => {
      doc.querySelector(`my-component`).someComplexThing = new Map(...)
   },
})

It may save on payload bytes if the object in question is already being handled / serialised by the framework in question.

@christian-bromann
Copy link
Member Author

Thanks @johnjenkins for your support 🙏 I will incorporate your suggestion in the docs.

Created a dev released at @stencil/[email protected]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants