whatwg / streams

Streams Standard
https://streams.spec.whatwg.org/
Other
1.34k stars 155 forks source link

Symbol.clone to ease-out structuredClone implicit conversion #1314

Closed WebReflection closed 1 month ago

WebReflection commented 1 month ago

What problem are you trying to solve?

The complexity of cross-realms interactions is very high these days:

What solutions exist today?

None, but we historically have toJSON convention to automatically transform any class into its JSON representation. Times are different these days though, and while structuredClone works wonderfully for all its allowed types, it's impossible from a library author point of view to grant some data can cross boundaries or be cloned properly, as opposite of throwing errors.

How would you solve it?

const ref = {
  // implicitly invoked when `structuredClone(ref)` happens
  // or during the conversion / clone algorithm is applied
  [Symbol.clone]() {
    // returns any structured-clone compatible value
    return new Map(Object.entries(this));
  }
};

The algorithm should look for non primitive values to a Symbol.clone special property that should return the cloned representation of the underlying proxy, class, complex data, and so on.

For this proposal, it would be a developers concern to "reconstruct" or understand returned data, simply screening in a recursive way whatever was cloned, simplifying ad-hoc clones for API calls, or cross-proxy related use cases.

Anything else?

As library author, I could dictate how any reference the library creates could be cloned or even throw if some reference should actually never be cloned (authentication / credentials / passwords / security related things / ... and so on).

This was (wrongly) posted also in TC39 in case some extra thoughts are needed: https://es.discourse.group/t/symbol-clone-to-ease-out-structuredclone-implicit-conversion/2035

domenic commented 1 month ago

Dupe of https://github.com/whatwg/html/issues/7428 in the wrong repository.