Skip to content

Add init(unsafelyCopying:JSObject) on @JS struct #510

Closed

Description

@MaxDesiatov

The goal is to support the following code

import JavaScriptKit

@JS protocol JSON {
    func parse(_ message: String) throws(JSException) -> JSObject
    func serialize(_ message: JSObject) throws(JSException) -> String
}

@JSGetter(from: .global) var json: JSON

@JS struct ShoppingCart {
    var x: Int

    @JS public func toJSON() throws(JSException) -> String {
        json.serialize(self.toJSObject())
    }

    @JS static public func fromJSON(_ string: String) throws(JSException) -> ShoppingCart {
        self.init(unsafelyCopying: json.parse(string))
    }

/* Generated by ExportSwift
    init(unsafelyCopying jsObject: JSObject) {
        _ShoppingCartHelpers.lower(jsObject)
        self = bridgeJSLiftParameter()
    }

    func toJSObject() -> JSObject {
        _ShoppingCartHelpers.raise(...)
        return bridgeJSLowerReturn()
    }
*/
}

Future direction

There's an opinion that such struct should follow value semantics, for which it has to copy its property values out to Wasm linear memory out of JS. To control copying strategies we might consider adding an argument to @JS controlling this, i.e. @JS(copy: .lazy), @JS(copy: .eager).

In the long term we should also support @JS struct Foo: ~Copyable that avoids copies altogether and always gives access to backing JS object reference.

Activity

  1. changed the title [-]Make `init(unsafelyWrapping:JSObject` available on `@JS struct` declarations[/-] [+]Make `init(unsafelyWrapping:JSObject` available on `@JS struct`[/+] on Jan 22, 2026
  2. changed the title [-]Make `init(unsafelyWrapping:JSObject` available on `@JS struct`[/-] [+]Make `init(unsafelyWrapping:JSObject)` available on `@JS struct`[/+] on Jan 22, 2026
  3. changed the title [-]Make `init(unsafelyWrapping:JSObject)` available on `@JS struct`[/-] [+]Add `init(unsafelyWrapping:JSObject)` on `@JS struct`[/+] on Jan 22, 2026
  4. changed the title [-]Add `init(unsafelyWrapping:JSObject)` on `@JS struct`[/-] [+]Add `init(unsafelyCopying:JSObject)` on `@JS struct`[/+] on Jan 26, 2026
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

    documentationImprovements or additions to documentationenhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions