Skip to content

Synchronous clone = global.structuredClone(value, transfer = []) API #793

Closed

Description

@annevk

As proposed in https://lists.w3.org/Archives/Public/public-webapps/2015AprJun/thread.html#msg251 at some point there seems to be some interest in doing this and it would expose a primitive without having to go through postMessage()/onmessage.

Is this still a good idea in 2016?

Activity

  1. added
    addition/proposal
    needs implementer interest
    on Mar 3, 2016
  2. banksJeremy commented on Dec 19, 2016

    @banksJeremy

    I think there's a lot of demand for a structuredClone() function like this. Though it may not be the best practice, realistically it is very common to have a lot of application state in ad-hoc graphs of standard data structures. I've had to implement similar cloning functions to help support that on a few different projects, and I've seen bugs from people using JSON.parse(JSON.stringify(...)) instead without considering cyclic data structures, leading to unexpected crashes later.

    A built-in feature or interface for deep cloning standard data structures is common in other dynamic languages, and is something I've seen many novices look for when starting to use JavaScript. It would be nice to have a standard that includes making this fully extensible, but as you discussed on the mailing list that is quite complicated and doesn't seem to be happening soon. Extensibility is somewhat orthogonal to exposing this existing functionality to users.

    As an outsider this appears to be relatively low-hanging fruit that many users would benefit from.

  3. added
    topic: serialize and transfer
    on Mar 28, 2017
  4. annevk commented on Jan 23, 2018

    @annevk
    MemberAuthor

    As pointed out in https://twitter.com/DasSurma/status/955484341358022657 by @surma you can already do this synchronously today by (ab)using the history API. Seems like another reason to expose this.

  5. surma commented on Jan 23, 2018

    @surma
    Contributor

    I think there is a use-case for wanting to deep-copy objects, and the structured clone algorithm comes very close to that — it would solve the vast majority of use-cases.

    The hack with the History API can be slow as there’s some cross-process communication going on.

    I also wrote an asynchronous version using MessageChannel that turned out to be faster than the History API or JSON.parse(), even for big objects:

    function structuredClone(obj) {
      return new Promise(resolve => {
        const {port1, port2} = new MessageChannel();
        port2.onmessage = ev => resolve(ev.data);
        port1.postMessage(obj);
      });
    }

    But sometime a synchronous version is very desirable.

    As an outsider this appears to be relatively low-hanging fruit that many users would benefit from.

    I agree with this.

  6. annevk commented on Jan 23, 2018

    @annevk
    MemberAuthor

    The main thing blocking this is getting interest from implementers (judging by that 2015 thread there is interest from Mozilla) and then finding someone who wants to write the specification and someone who wants to write the tests (can be the same someone).

    @ajklein @othermaciej @dstorey thoughts?

  7. surma commented on Jan 23, 2018

    @surma
    Contributor

    Maybe I'm naïve, but shouldn't specification be rather trivial, considering that the structured clone algorithm is already specified? If that is the case, I'm happy to take this as my opportunity to write my first spec bits and tests :D (Provided we get the interest bit sorted, of course)

  8. jeremyroman commented on Jan 23, 2018

    @jeremyroman
    Contributor

    I wonder if this structured clone is actually what the developer wants. For instance, structured clone does some replication of the object graph, but makes no attempt to replicate the original prototype chain, so if the author has Point objects and expects to get Point objects out, they will be disappointed. (There's not an obvious reasonable way to do this cross-realm, but perhaps that is what authors want within the realm.)

    I guess it's at least as close a match as JSON.parse(JSON.stringify(o)), though.

  9. RamIdeas commented on Jan 23, 2018

    @RamIdeas

    @jeremyroman Not entirely sure it would be a full/strict clone if you still referenced the old Point constructor in the prototype chain so this would be kind of expected, right?

  10. jeremyroman commented on Jan 23, 2018

    @jeremyroman
    Contributor

    It depends what the application is trying to do. Naively, I wouldn't blame an author for thinking this is reasonable:

    let p = new Point(3, 4);
    let p2 = clone(p);
    console.assert(p2 instanceof Point);
    

    Structured cloning necessarily clones only the things that you can kinda reasonably do across realms. I'm not sure it's a general-purpose deep clone (though I admit I'm not familiar with the ones apparently present in other dynamic languages), though it's possible that it is suitable for some author use cases.

  11. surma commented on Jan 25, 2018

    @surma
    Contributor

    though it's possible that it is suitable for some author use cases

    I’d argue it’s enough for the majority of cases, but we’d have to look into that. Types by the author have never been cloned (unless the author also wrote a custom cloning function), so I think we should expose structured clone first, before thinking about how to handle the prototype chain.

  12. othermaciej commented on Jan 25, 2018

    @othermaciej

    Tagging @cdumez and @rniwa to give WebKit thoughts on this.

  13. samal-rasmussen commented on Jan 25, 2018

    @samal-rasmussen

    Maybe we want to have two different clone variants, one that just does structural cloning and one that also clones the prototype hierarchy properly as well. Call em structualClone() and cloneWithPrototypeHierarchy() or whatever. In any case the former is basically already done, as surma mentioned, so why not? Let's go already.

  14. jeremyroman commented on Jan 25, 2018

    @jeremyroman
    Contributor

    If what's wanted is a generic way to deeply clone ECMAScript objects, maybe that's something that belongs in the ECMAScript spec (or maybe just a third-party library) rather than the HTML spec.

    On the other hand, if it's useful for authors to have semantics that match postMessage, IndexedDB, etc. (for which it's not really clear what dealing with the prototype chain would even mean), then perhaps HTML should expose the existing primitive as suggested.

  15. 34 remaining items

  16. GrosSacASac commented on Aug 20, 2019

    @GrosSacASac

    I found a tc39 proposal in the stage 0 list. It looks like it is not active anymore, could someone present it ?

    Should it be a tc39 proposal or a whatwg one ?

    What are the next steps necessary to have it implemented in browsers ?

  17. domenic commented on Aug 20, 2019

    @domenic
    Member

    This works best as a WHATWG proposal as the WHATWG is the body that specifies structured cloning.

    The next steps necessary to have it implemented in browsers are for browsers to determine that it's a high priority on their product roadmap (compared to other things they could spend engineering effort on). That is usually helped by evidence such as web developers advocating for it or showing what they're using instead. However, I think we've already reached a pretty good amount of evidence that this would be useful, so I'm not sure how to make progress on increasing the priority in browser teams' backlogs :(.

  18. rniwa commented on Aug 20, 2019

    @rniwa

    It looks like two use cases being discussed are:

    Both of these tweets are about cloning JS objects, not structured cloning, and some of the discussions explicitly mention a "proper" way of cloning JS objects.

    I'd be curious to know more concrete use cases, and whatever v0 API being proposed here would satisfy any of them.

  19. surma commented on Aug 20, 2019

    @surma
    Contributor

    Yes, I was looking at deep-cloning at the time. Standardizing/exposing structured clone seemed like a low risk and low friction first step. It behaves correct for the majority of use cases (as far as I can tell) and is already specified and implemented in most engines.

    The use-cases are mostly related to architectures relying on immutable data structures and chaining-style APIs.

  20. agm1984 commented on Sep 14, 2019

    @agm1984

    I am encountering an issue currently in Vue JS whereby I pass an Object prop from a parent to child component like this:

    Also I apologize for showing framework code, but my intent is to help establish context for a need.

    export default {
        props: {
            initialValue: {
                type: Object,
                required: false,
                default: () => ({}),
            },
        },
    
        data() {
            return {
                value: this.initialValue,
            };
        },
    };

    The initialValue reference is copied to value, which unfortunately copies the Vue getter/setter functions that exist on initialValue.

    This means if a person mutates the local state of value, Vue fires the hidden setter functions on the upstream reference and therefore breaks the component encapsulation. In this way, the data flow is not unidirectional, but it is expected behaviour simply because the reference is copied in a non-immutable fashion. Part of this is Vue's problem in my opinion. I think the framework itself should deep clone props as they enter into a component.

    This example means you can pass a reference through 100 dimensions of child components and mutate the root component's state in a way that is extremely difficult to trace by visual code analysis. I suspect countless application developers will experience some form of this issue moving forward.

    Currently, shallow cloning is not adequate as a solution because nested Objects do not have their child references broken. So in my opinion, the only viable solution is to use Lodash's cloneDeep function or equivalent.

    My described issue would be solved using structuredClone like this:

        data() {
            return {
                value: structuredClone(this.initialValue),
            };
        },

    I think browsers should natively support deep cloning ASAP, so that a third party cloning dependency can be avoided. This will save bandwidth for all parties by reducing bundle size in every library that packages some form of deep cloning in order to operate immutably.

    Personally, I like the idea of following the implementation details from node.js because it will make it easier for both node.js and browsers to benefit from continued innovations from either node.js or browsers with respect to deep cloning and immutable paradigms.

  21. krisdages commented on Dec 9, 2020

    @krisdages

    Does anyone have any suggestions on how to advocate for something like this to the browser vendors?
    What if one was to just implement it in Chromium or Firefox and try to submit it to the project?

    Or maybe standing outside headquarters chanting with a protest sign? :)

  22. jeremyroman commented on Dec 9, 2020

    @jeremyroman
    Contributor

    You'd have to follow their respective launch processes to submit it. For Chromium, that's this process.

  23. added a commit that references this issue on Jul 27, 2021
    a09e2f4
  24. added 2 commits that reference this issue on Jul 27, 2021
    0947339
    1b5099f
  25. deleted a comment from shijiexiao on Nov 2, 2021
  26. temporarily blocked shijiexiaoon Nov 2, 2021
  27. deleted a comment from shijiexiao on Nov 2, 2021
  28. added a commit that references this issue on Jun 3, 2022
    c576a74
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    addition/proposalneeds implementer interesttopic: serialize and transfer

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions