### Install Swift Toolchain and Build Project Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/Basic/README.md Installs a specific Swift WASM development snapshot toolchain and then builds the project using a provided build script. This is a prerequisite for running the project. ```sh swift sdk install https://github.com/swiftwasm/swift/releases/download/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-07-09-a/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-07-09-a-wasm32-unknown-wasi.artifactbundle.zip ./build.sh ``` -------------------------------- ### Serve Local Project with npx Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-3-2-server.txt Starts a local development server using npx to serve the built project files, typically for testing in a web browser. ```bash npx serve ``` -------------------------------- ### Serve Project Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/OffscrenCanvas/README.md Uses Node Package Execute (npx) to serve the built project files. This command typically starts a local web server, allowing you to view the OffscreenCanvas example in your browser. ```sh npx serve ``` -------------------------------- ### Serve Local Development Server Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-3-3-open.txt This command starts a local HTTP server using Node Package Execute (npx) to serve the built project files. It's commonly used for local development and testing of web applications. ```bash npx serve ``` -------------------------------- ### Install Swift Snapshot and Build Project Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/PlayBridgeJS/README.md This snippet demonstrates the commands required to install a specific Swift development snapshot for WASM and then build the project using a provided build script. It also includes a command to serve the built project using Node.js's `serve` package. ```sh swift sdk install https://github.com/swiftwasm/swift/releases/download/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-07-09-a/swift-wasm-DEVELOPMENT-SNAPSHOT-2024-07-09-a-wasm32-unknown-wasi.artifactbundle.zip ./build.sh npx serve ``` -------------------------------- ### Install Swift SDK and Build Project Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/ActorOnWebWorker/README.md This snippet installs the necessary Swift SDK for WASM and builds the project using a custom build script. It also starts a local server to host the application. ```sh ( set -eo pipefail; V="$(swiftc --version | head -n1)"; TAG="$(curl -sL "https://raw.githubusercontent.com/swiftwasm/swift-sdk-index/refs/heads/main/v1/tag-by-version.json" | jq -e -r --arg v "$V" '.[$v] | .[-1]')"; curl -sL "https://raw.githubusercontent.com/swiftwasm/swift-sdk-index/refs/heads/main/v1/builds/$TAG.json" | jq -r '.["swift-sdks"]["wasm32-unknown-wasip1-threads"] | "swift sdk install \"(.url)\" --checksum \"(.checksum)\""' | sh -x ) export SWIFT_SDK_ID=$( V="$(swiftc --version | head -n1)"; TAG="$(curl -sL "https://raw.githubusercontent.com/swiftwasm/swift-sdk-index/refs/heads/main/v1/tag-by-version.json" | jq -e -r --arg v "$V" '.[$v] | .[-1]')"; curl -sL "https://raw.githubusercontent.com/swiftwasm/swift-sdk-index/refs/heads/main/v1/builds/$TAG.json" | jq -r '.["swift-sdks"]["wasm32-unknown-wasip1-threads"]["id"]' ) ./build.sh npx serve ``` -------------------------------- ### Getting Started with JavaScriptKit Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/Basic/index.html This snippet shows the basic steps to initialize JavaScriptKit in a Swift project. It imports the necessary module and calls the init function. ```javascript import { init } from "./.build/plugins/PackageToJS/outputs/Package/index.js"; init(); ``` -------------------------------- ### Check Swift Version Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-0-2-select-sdk.txt Verifies the installed Swift compiler version. Ensure you are using a compatible version for the project. ```bash swift --version ``` -------------------------------- ### Getting Started with JavaScriptKit Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/Embedded/index.html This snippet shows the basic steps to initialize JavaScriptKit in a Swift project. It imports the necessary module and calls the init function. ```javascript import { init } from "./.build/plugins/PackageToJS/outputs/Package/index.js"; init(); ``` -------------------------------- ### Build and Serve Project Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/Multithreading/README.md This snippet shows the commands to build the project using './build.sh' and then serve the built files using 'npx serve'. ```sh ./build.sh npx serve ``` -------------------------------- ### List Available Swift SDKs Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-0-2-select-sdk.txt Lists all available Swift Software Development Kits (SDKs) on your system. This helps identify the correct SDK for WASM development. ```bash swift sdk list ``` -------------------------------- ### Install Swift SDK for WebAssembly with Threads Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/Multithreading/README.md This script automatically determines the correct Swift SDK version, fetches its details from a JSON index, and installs the 'wasm32-unknown-wasip1-threads' SDK. It also sets the SWIFT_SDK_ID environment variable. ```sh ( set -eo pipefail; V="$(swiftc --version | head -n1)"; TAG="$(curl -sL "https://raw.githubusercontent.com/swiftwasm/swift-sdk-index/refs/heads/main/v1/tag-by-version.json" | jq -e -r --arg v "$V" '.[$v] | .[-1]')"; curl -sL "https://raw.githubusercontent.com/swiftwasm/swift-sdk-index/refs/heads/main/v1/builds/$TAG.json" | jq -r '.["swift-sdks"]["wasm32-unknown-wasip1-threads"] | "swift sdk install \"(.url)\" --checksum \"(.checksum)\""' | sh -x ) export SWIFT_SDK_ID=$( V="$(swiftc --version | head -n1)"; TAG="$(curl -sL "https://raw.githubusercontent.com/swiftwasm/swift-sdk-index/refs/heads/main/v1/tag-by-version.json" | jq -e -r --arg v "$V" '.[$v] | .[-1]')"; curl -sL "https://raw.githubusercontent.com/swiftwasm/swift-sdk-index/refs/heads/main/v1/builds/$TAG.json" | jq -r '.["swift-sdks"]["wasm32-unknown-wasip1-threads"]["id"]' ) ``` -------------------------------- ### Install Swift SDK for Wasm Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/OffscrenCanvas/README.md This script automatically determines the correct Swift SDK version based on your installed Swift compiler and installs the wasm32-unknown-wasip1-threads SDK. It uses curl to fetch SDK index data and jq to parse JSON responses. ```sh ( set -eo pipefail; V="$(swiftc --version | head -n1)"; TAG="$(curl -sL "https://raw.githubusercontent.com/swiftwasm/swift-sdk-index/refs/heads/main/v1/tag-by-version.json" | jq -e -r --arg v "$V" '.[$v] | .[-1]')"; curl -sL "https://raw.githubusercontent.com/swiftwasm/swift-sdk-index/refs/heads/main/v1/builds/$TAG.json" | jq -r '.["swift-sdks"]["wasm32-unknown-wasip1-threads"] | "swift sdk install \"(.url)\" --checksum \"(.checksum)\""' | sh -x ) ``` -------------------------------- ### Serve Project Files with npx serve Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/ExportSwift/README.md Serves the project files using the 'serve' package, typically used for local development and testing of web applications. This command starts a local HTTP server, making the exported JavaScript and other project assets accessible via a browser. ```sh npx serve ``` -------------------------------- ### Build SwiftWasm Project with JavaScriptKit Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-3-3-open.txt This command builds a SwiftWasm project, linking it with JavaScriptKit support. It utilizes a specified Swift SDK ID and can optionally use a CDN for dependencies. The output is a WebAssembly binary. ```bash swift package --swift-sdk $SWIFT_SDK_ID js --use-cdn ``` -------------------------------- ### Build SwiftWasm Project with JavaScriptKit Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-3-1-build.txt This command compiles a SwiftWasm project, enabling JavaScriptKit integration. It specifies the Swift SDK to use and indicates that the JavaScript dependencies should be fetched from a CDN. The output shows the linking process and successful build completion. ```bash swift package --swift-sdk $SWIFT_SDK_ID js --use-cdn [37/37] Linking Hello.wasm Build of product 'Hello' complete! (5.16s) Packaging... ...Packaging finished ``` -------------------------------- ### Build Swift Package and Vite Assets Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Articles/Deploying-Pages.md Builds the Swift package for WebAssembly, creates a minimal HTML file, installs Vite, and builds optimized assets for deployment. ```bash swift package --swift-sdk wasm32-unknown-wasi js -c release cat < index.html EOS npm install -D vite .build/plugins/PackageToJS/outputs/Package npx vite build ``` -------------------------------- ### Install JavaScriptKit Dependencies Source: https://github.com/swiftwasm/javascriptkit/blob/main/CONTRIBUTING.md Installs the necessary dependencies for the JavaScriptKit project using the 'make bootstrap' command. This is a crucial step after cloning the repository. ```bash make bootstrap ``` -------------------------------- ### Open Local Development Server in Browser Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-3-3-open.txt This command opens the default web browser to the specified local development server address, allowing you to view and interact with your SwiftWasm application. ```bash open http://localhost:3000 ``` -------------------------------- ### Serve Project Locally Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/Basic/README.md Uses Node Package Execute (npx) to serve the project files locally, typically for development and testing purposes. ```sh npx serve ``` -------------------------------- ### Install WASM SDK for Linux Source: https://github.com/swiftwasm/javascriptkit/blob/main/CONTRIBUTING.md Installs the WebAssembly SDK for Linux users. This command assumes Swift 6.0.2 is already installed and focuses on adding the WASM SDK. ```bash ( SWIFT_SDK_TAG="swift-wasm-6.0.2-RELEASE"; SWIFT_SDK_CHECKSUM="6ffedb055cb9956395d9f435d03d53ebe9f6a8d45106b979d1b7f53358e1dcb4"; swift sdk install "https://github.com/swiftwasm/swift/releases/download/$SWIFT_SDK_TAG/$SWIFT_SDK_TAG-wasm32-unknown-wasi.artifactbundle.zip" --checksum "$SWIFT_SDK_CHECKSUM"; ) ``` -------------------------------- ### Build SwiftWasm Project with JavaScriptKit Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-3-2-server.txt Compiles a SwiftWasm project using JavaScriptKit, linking the WebAssembly output. It specifies the Swift SDK ID to be used for the build process. ```bash swift package --swift-sdk $SWIFT_SDK_ID js --use-cdn [37/37] Linking Hello.wasm Build of product 'Hello' complete! (5.16s) Packaging... ... Packaging finished ``` -------------------------------- ### WebWorker + Actor Example Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/ActorOnWebWorker/index.html Initializes the application using the 'init' function from the local bundle. This sets up the WebWorker and Actor environment for full-text search. ```javascript import { init } from "./Bundle/index.js" init(); ``` -------------------------------- ### Install OSS Swift Toolchain and WASM SDK for macOS Source: https://github.com/swiftwasm/javascriptkit/blob/main/CONTRIBUTING.md Installs a specific OSS Swift toolchain and the WebAssembly SDK for macOS users. It involves downloading a package, installing it, and then installing the SDK artifact. ```bash (SWIFT_TOOLCHAIN_CHANNEL=swift-6.0.2-release; SWIFT_TOOLCHAIN_TAG="swift-6.0.2-RELEASE"; SWIFT_SDK_TAG="swift-wasm-6.0.2-RELEASE"; SWIFT_SDK_CHECKSUM="6ffedb055cb9956395d9f435d03d53ebe9f6a8d45106b979d1b7f53358e1dcb4"; pkg=$(mktemp -d)/InstallMe.pkg; set -ex; curl -o "$pkg" "https://download.swift.org/$SWIFT_TOOLCHAIN_CHANNEL/xcode/$SWIFT_TOOLCHAIN_TAG/$SWIFT_TOOLCHAIN_TAG-osx.pkg"; installer -pkg "$pkg" -target CurrentUserHomeDirectory; export TOOLCHAINS=$(plutil -extract CFBundleIdentifier raw ~/Library/Developer/Toolchains/$SWIFT_TOOLCHAIN_TAG.xctoolchain/Info.plist); swift sdk install "https://github.com/swiftwasm/swift/releases/download/$SWIFT_SDK_TAG/$SWIFT_SDK_TAG-wasm32-unknown-wasi.artifactbundle.zip" --checksum "$SWIFT_SDK_CHECKSUM"; ) ``` -------------------------------- ### Build Project Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/OffscrenCanvas/README.md Executes the build script for the SwiftWasm project. This command compiles the Swift code and prepares the necessary assets for deployment. ```sh ./build.sh ``` -------------------------------- ### Serve and View Code Coverage Report Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/Testing/README.md Serves the generated HTML code coverage report using `npx serve`, allowing it to be viewed in a web browser. ```console npx serve .build/coverage/html ``` -------------------------------- ### Set SWIFT_SDK_ID Environment Variable Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/OffscrenCanvas/README.md This command retrieves the SDK ID for the wasm32-unknown-wasip1-threads target, which is necessary for subsequent build steps. It follows a similar logic to the SDK installation script to ensure compatibility. ```sh export SWIFT_SDK_ID=$( V="$(swiftc --version | head -n1)"; TAG="$(curl -sL "https://raw.githubusercontent.com/swiftwasm/swift-sdk-index/refs/heads/main/v1/tag-by-version.json" | jq -e -r --arg v "$V" '.[$v] | .[-1]')"; curl -sL "https://raw.githubusercontent.com/swiftwasm/swift-sdk-index/refs/heads/main/v1/builds/$TAG.json" | jq -r '.["swift-sdks"]["wasm32-unknown-wasip1-threads"]["id"]' ) ``` -------------------------------- ### Swift Version Check Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-0-1-swift-version.txt Displays the currently installed Swift compiler version. This is useful for verifying your Swift development environment. ```bash swift --version # Expected output: # Apple Swift version 6.0.3 (swift-6.0.3-RELEASE) # or # Swift version 6.0.3 (swift-6.0.3-RELEASE) ``` -------------------------------- ### Run SwiftWasm JavaScriptKit Tests Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/Testing/README.md Executes tests for Swift code compiled to WebAssembly using JavaScriptKit. This command requires disabling the sandbox and specifying the WebAssembly SDK. ```console swift package --disable-sandbox --swift-sdk wasm32-unknown-wasi js test ``` -------------------------------- ### BridgeJS Playground Configuration Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/PlayBridgeJS/index.html Configuration for the BridgeJS Playground, specifying imported modules. This example shows how to import the TypeScript module. ```json { "imports": { "typescript": "https://esm.sh/typescript@5.3.3" } } ``` -------------------------------- ### Call Exported Swift Functions from JavaScript Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Articles/Exporting-Swift-to-JavaScript.md Example of how to call the exported Swift functions (calculateTotal, formatCurrency) from JavaScript. ```javascript const total = exports.calculateTotal(19.99, 3); const formattedTotal = exports.formatCurrency(total); console.log(formattedTotal); // "$59.97" ``` -------------------------------- ### Generate HTML Code Coverage Report Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/Testing/README.md Generates an HTML report for code coverage using the `llvm-cov` tool. It requires the profile data and the compiled WebAssembly binary. ```console llvm-cov show -instr-profile=.build/plugins/PackageToJS/outputs/PackageTests/default.profdata --format=html .build/plugins/PackageToJS/outputs/PackageTests/main.wasm -o .build/coverage/html Sources ``` -------------------------------- ### Enable and Run Code Coverage for SwiftWasm Tests Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/Testing/README.md Runs SwiftWasm JavaScriptKit tests with code coverage enabled. This is the first step in generating a code coverage report. ```console swift package --disable-sandbox --swift-sdk wasm32-unknown-wasi js test --enable-code-coverage ``` -------------------------------- ### Swift Code with @JS Annotations Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Articles/Ahead-of-Time-Code-Generation.md Example Swift code demonstrating the use of `@JS` annotations for exporting functions and classes to JavaScript. ```swift import JavaScriptKit @JS public func calculateTotal(price: Double, quantity: Int) -> Double { return price * Double(quantity) } @JS class Counter { private var count = 0 @JS init() {} @JS func increment() { count += 1 } @JS func getValue() -> Int { return count } } ``` -------------------------------- ### Set Swift SDK Environment Variable Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-0-2-select-sdk.txt Sets the SWIFT_SDK_ID environment variable to the specific WASM SDK. This is crucial for the build system to locate and use the correct SDK. ```bash export SWIFT_SDK_ID=6.0.3-RELEASE-wasm32-unknown-wasi ``` -------------------------------- ### Configure Package.swift for BridgeJS Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Articles/Exporting-Swift-to-JavaScript.md Example Package.swift file to enable the experimental 'Extern' feature and add the BridgeJS plugin for exporting Swift code to JavaScript. ```swift // swift-tools-version:6.0 import PackageDescription let package = Package( name: "MyApp", dependencies: [ .package(url: "https://github.com/swiftwasm/JavaScriptKit.git", branch: "main") ], targets: [ .executableTarget( name: "MyApp", dependencies: ["JavaScriptKit"], swiftSettings: [ // This is required because the generated code depends on @_extern(wasm) .enableExperimentalFeature("Extern") ], plugins: [ // Add build plugin for processing @JS and generate Swift glue code .plugin(name: "BridgeJS", package: "JavaScriptKit") ] ) ] ) ``` -------------------------------- ### Browser Setup and Execution with JavaScriptKit Source: https://github.com/swiftwasm/javascriptkit/blob/main/Plugins/PackageToJS/Templates/test.browser.html This snippet shows the client-side JavaScript code for setting up and running a Swift WebAssembly module using JavaScriptKit. It fetches configuration, sets up logging, and initiates the Swift execution in the browser. ```javascript import { testBrowserInPage } from "./test.js"; import { MODULE_PATH } from "./instantiate.js"; import { defaultBrowserSetup /* #if USE_SHARED_MEMORY */, createDefaultWorkerFactory /* #endif */ } from './platforms/browser.js'; const logElement = document.createElement("pre"); document.body.appendChild(logElement); const processInfo = await fetch("/process-info.json").then((response) => response.json()); const options = await defaultBrowserSetup({ module: await fetch(new URL(MODULE_PATH, import.meta.url)), args: processInfo.args, onStdoutLine: (line) => { console.log(line); logElement.textContent += line + "\n"; }, onStderrLine: (line) => { console.warn(line); logElement.textContent += line + "\n"; }, /* #if USE_SHARED_MEMORY */ spawnWorker: createDefaultWorkerFactory(processInfo.preludeScript), /* #endif */ }); testBrowserInPage(options, processInfo); ``` -------------------------------- ### BridgeJS Future Work - Constructor Pattern Source: https://github.com/swiftwasm/javascriptkit/blob/main/Plugins/BridgeJS/README.md Example of a TypeScript interface with a constructor and static methods, illustrating a future feature for simplifying constructor patterns in BridgeJS. ```typescript interface Foo { someMethod(value: number): void; } interface FooConstructor { new(name: string) : Foo; anotherMethod(): number; } declare var Foo: FooConstructor; ``` -------------------------------- ### Interact with Exported Swift Class from JavaScript Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Articles/Exporting-Swift-to-JavaScript.md Example of how to import and use the exported Swift ShoppingCart class from JavaScript, including creating instances and calling its methods. ```javascript import { init } from "./.build/plugins/PackageToJS/outputs/Package/index.js"; const { exports } = await init({}); const cart = new exports.ShoppingCart(); cart.addItem("Laptop", 999.99, 1); cart.addItem("Mouse", 24.99, 2); console.log(`Items in cart: ${cart.getItemCount()}`); console.log(`Total: $${cart.getTotal().toFixed(2)}`); ``` -------------------------------- ### Build Swift Project for JavaScript Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/ExportSwift/README.md Builds the Swift project, exporting it to JavaScript. It requires the JAVASCRIPTKIT_EXPERIMENTAL_BRIDGEJS environment variable to be set and uses the Swift SDK to generate JavaScript-compatible code. The --use-cdn flag is used to fetch dependencies from a CDN. ```sh env JAVASCRIPTKIT_EXPERIMENTAL_BRIDGEJS=1 swift package --swift-sdk $SWIFT_SDK_ID js --use-cdn ``` -------------------------------- ### JavaScript Element Rotation and Initialization Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/Multithreading/index.html This snippet demonstrates rotating an HTML element using JavaScript's `setInterval` for continuous animation and initializes the application by importing and calling an `init` function from a local module. It includes basic CSS for styling the animated element. ```javascript /* CSS */ .loading-emoji { font-size: 60px; width: 60px; height: 80px; } /* JavaScript */ function rotateElement(element, speed = 2) { let degree = 0; setInterval(() => { degree = (degree + speed) % 360; element.style.transform = `rotate(${degree}deg)`; }, 20); } document.addEventListener('DOMContentLoaded', () => { const loadingCircle = document.getElementById('loading-emoji'); rotateElement(loadingCircle); }); import { init } from "./Bundle/index.js" init(); ``` -------------------------------- ### Swift JavaScript Interaction Example Source: https://github.com/swiftwasm/javascriptkit/blob/main/README.md Demonstrates how to interact with JavaScript from Swift using JavaScriptKit. This includes accessing global JavaScript objects like 'document', creating and manipulating DOM elements, and handling events using Swift closures. ```swift import JavaScriptKit // Access global JavaScript objects let document = JSObject.global.document // Create and manipulate DOM elements var div = document.createElement("div") div.innerText = "Hello from Swift!" _ = document.body.appendChild(div) // Handle events with Swift closures var button = document.createElement("button") button.innerText = "Click me" button.onclick = .object(JSClosure { _ in JSObject.global.alert!("Button clicked!") return .undefined }) _ = document.body.appendChild(button) ``` -------------------------------- ### Initialize Swift Executable Package Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-1-2-add-dependency.txt Creates a new Swift package with an executable target. This is the first step in setting up a new project. ```bash swift package init --name Hello --type executable Creating executable package: Hello Creating Package.swift Creating .gitignore Creating Sources/ Creating Sources/main.swift ``` -------------------------------- ### Default main.swift Content Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-1-1-init-package.txt The initial content of the main.swift file for a newly created executable package. This serves as the entry point for the application. ```swift print("Hello, World!") ``` -------------------------------- ### List Available Swift SDKs Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-0-1-swift-version.txt Lists all available Swift Software Development Kits (SDKs) on the system. This helps in identifying which WASM targets are supported. ```bash swift sdk list # Example output: # 6.0.3-RELEASE-wasm32-unknown-wasi ``` -------------------------------- ### Initialize Swift Executable Package Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-1-1-init-package.txt Initializes a new Swift package with an executable type. This command creates the necessary project structure, including the Package.swift manifest file, a .gitignore file, and the basic directory layout for source code. ```bash swift package init --name Hello --type executable ``` -------------------------------- ### Build and Serve Project Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/Embedded/README.md Commands to build the project using a custom script and serve it using npx. Requires a recent DEVELOPMENT-SNAPSHOT toolchain. ```sh $ ./build.sh $ npx serve ``` -------------------------------- ### TypeScript Definitions for JavaScript Imports Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Articles/Ahead-of-Time-Code-Generation.md Example TypeScript definition file (`bridge-js.d.ts`) for importing JavaScript APIs into Swift. ```typescript // Sources/MyApp/bridge-js.d.ts export function consoleLog(message: string): void; export interface Document { title: string; getElementById(id: string): HTMLElement; } export function getDocument(): Document; ``` -------------------------------- ### Default Package.swift Structure Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-1-1-init-package.txt The default Package.swift file generated for an executable package. It defines the package name, supported platforms, and the executable product. ```swift // swift-tools-version: 5.9 import PackageDescription let package = Package( name: "Hello", platforms: [ .macOS(.v10_15) // Example platform, adjust as needed ], products: [ // Products define the executables and libraries a package produces, making them visible to other packages. .executable( name: "Hello", targets: ["Hello"]), ], targets: [ // Targets are the basic building blocks of a package, defining a module or a test suite. // Targets can depend on other targets in this package and on products in packages this package depends on. .executableTarget( name: "Hello"), .testTarget( name: "HelloTests", dependencies: ["Hello"]), ]) ``` -------------------------------- ### Export Swift Functions to JavaScript Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Articles/Exporting-Swift-to-JavaScript.md Example of exporting Swift functions to JavaScript using the @JS attribute. These functions can then be called from JavaScript. ```swift import JavaScriptKit @JS public func calculateTotal(price: Double, quantity: Int) -> Double { return price * Double(quantity) } @JS public func formatCurrency(amount: Double) -> String { return "$\(String(format: \"%.2f\", amount))" } ``` -------------------------------- ### Initialize Swift Web App Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-2-2-index-html.html Initializes the Swift Web App by importing and executing the 'init' function from the javascriptkit package. This is the primary entry point for the application's JavaScript functionality. ```javascript import { init } from "./.build/plugins/PackageToJS/outputs/Package/index.js"; init(); ``` -------------------------------- ### Initialize Swift Executable Package Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-1-3-add-target-dependency.txt Initializes a new Swift executable package with a specified name. This command creates the basic file structure for a Swift project, including a Package.swift manifest, a .gitignore file, and a main.swift file within the Sources directory. ```bash swift package init --name Hello --type executable Creating executable package: Hello Creating Package.swift Creating .gitignore Creating Sources/ Creating Sources/main.swift ``` -------------------------------- ### Export Swift Class to JavaScript Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Articles/Exporting-Swift-to-JavaScript.md Example of exporting a Swift class and its methods to JavaScript using the @JS attribute. This allows creating instances and calling methods from JavaScript. ```swift import JavaScriptKit @JS class ShoppingCart { private var items: [(name: String, price: Double, quantity: Int)] = [] @JS init() {} @JS public func addItem(name: String, price: Double, quantity: Int) { items.append((name, price, quantity)) } @JS public func removeItem(atIndex index: Int) { guard index >= 0 && index < items.count else { return } items.remove(at: index) } @JS public func getTotal() -> Double { return items.reduce(0) { $0 + $1.price * Double($1.quantity) } } @JS public func getItemCount() -> Int { return items.count } // This method won't be accessible from JavaScript (no @JS) var debugDescription: String { return "Cart with \(items.count) items, total: \(getTotal())" } } ``` -------------------------------- ### JavaScript Initialization Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/OffscrenCanvas/index.html This JavaScript code initializes the application by importing and calling the 'init' function from './Bundle/index.js'. This is the main entry point for the project's JavaScript execution. ```javascript import { init } from "./Bundle/index.js" init(); ``` -------------------------------- ### GitHub Actions Workflow for Deployment Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Articles/Deploying-Pages.md A GitHub Actions workflow to automate the build and deployment of a JavaScriptKit application to GitHub Pages. It checks out code, sets up Node.js and Swiftwasm, builds the project, and uploads artifacts for deployment. ```yaml name: Deploy to GitHub Pages on: # Runs on pushes targeting the default branch push: branches: [main] # Sets the GITHUB_TOKEN permissions to allow deployment to GitHub Pages permissions: contents: read pages: write id-token: write jobs: deploy: environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} runs-on: ubuntu-latest container: swift:6.0.3 steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 20 - uses: actions/configure-pages@v4 id: pages # Install Swift SDK for WebAssembly - uses: swiftwasm/setup-swiftwasm@v2 - name: Build run: | swift package --swift-sdk wasm32-unknown-wasi js -c release npm install npx vite build --base "${{ steps.pages.outputs.base_path }}" - uses: actions/upload-pages-artifact@v3 with: path: './dist' - uses: actions/deploy-pages@v4 id: deployment ``` -------------------------------- ### TypeScript Definitions for JavaScript APIs Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Articles/Importing-TypeScript-into-Swift.md Defines JavaScript APIs in TypeScript for use with BridgeJS. Includes examples for simple functions, DOM interfaces like `Document` and `HTMLElement`, and type re-exports. ```typescript // Simple function export function consoleLog(message: string): void; // Define a subset of DOM API you want to use interface Document { // Properties title: string; readonly body: HTMLElement; // Methods getElementById(id: string): HTMLElement; createElement(tagName: string): HTMLElement; } // You can use type-level operations like `Pick` to reuse // type definitions provided by `lib.dom.d.ts`. interface HTMLElement extends Pick { appendChild(child: HTMLElement): void; // TODO: Function types on function signatures are not supported yet. // addEventListener(event: string, handler: (event: any) => void): void; } // Provide access to `document` export function getDocument(): Document; ``` -------------------------------- ### Clone JavaScriptKit Repository Source: https://github.com/swiftwasm/javascriptkit/blob/main/CONTRIBUTING.md Clones the JavaScriptKit repository and navigates into the project directory. This is the first step in setting up the development environment. ```bash git clone https://github.com/swiftwasm/JavaScriptKit.git cd JavaScriptKit ``` -------------------------------- ### Using Generated Swift Bindings in Application Code Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Articles/Importing-TypeScript-into-Swift.md Demonstrates how to use the Swift bindings generated by BridgeJS to interact with JavaScript APIs. Includes examples of calling functions, accessing properties, and manipulating the DOM. ```swift import JavaScriptKit @JS func run() { // Simple function call consoleLog("Hello from Swift!") // Get `document` let document = getDocument() // Property access document.title = "My Swift App" // Method calls let button = document.createElement("button") button.innerText = "Click Me" // TODO: Function types on function signatures are not supported yet. // buttion.addEventListener("click") { _ in // print("On click!") // } // DOM manipulation let container = document.getElementById("app") container.appendChild(button) } ``` -------------------------------- ### Add Target Dependency Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-1-3-add-target-dependency.txt Links the JavaScriptKit library to the current project's target. This command ensures that the JavaScriptKit library is available for use within the 'Hello' executable target, updating the Package.swift manifest to reflect this relationship. ```bash swift package add-target-dependency --package JavaScriptKit JavaScriptKit Hello Updating package manifest at Package.swift... done. ``` -------------------------------- ### Add JavaScriptKit Dependency Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-1-3-add-target-dependency.txt Adds the JavaScriptKit library as a dependency to the Swift package. It fetches the library from the specified Git repository and branch, updating the Package.swift manifest accordingly. ```bash swift package add-dependency https://github.com/swiftwasm/JavaScriptKit.git --branch main Updating package manifest at Package.swift... done. ``` -------------------------------- ### Add JavaScriptKit Dependency Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Tutorials/Hello-World/Resources/hello-world-1-2-add-dependency.txt Adds the JavaScriptKit library as a dependency to your Swift package. This enables interaction with JavaScript environments. ```bash swift package add-dependency https://github.com/swiftwasm/JavaScriptKit.git --branch main Updating package manifest at Package.swift... done. ``` -------------------------------- ### BridgeJS Playground Input/Output Source: https://github.com/swiftwasm/javascriptkit/blob/main/Examples/PlayBridgeJS/index.html Demonstrates the input files and expected output files for the BridgeJS Playground. It takes Swift and TypeScript definitions and generates bridged code. ```text Input: ----- Playground.swift bridge-js.d.ts Output: ------ Playground.d.ts Playground.js ImportTS.swift ExportSwift.swift ``` -------------------------------- ### Build JavaScriptKit Benchmarks Source: https://github.com/swiftwasm/javascriptkit/blob/main/Benchmarks/README.md Builds the JavaScriptKit test suite for performance benchmarks. Requires setting the JAVASCRIPTKIT_EXPERIMENTAL_BRIDGEJS environment variable and specifying the Swift SDK ID. ```bash JAVASCRIPTKIT_EXPERIMENTAL_BRIDGEJS=1 swift package --swift-sdk $SWIFT_SDK_ID js -c release ``` -------------------------------- ### Run Internal Unit Tests for PackageToJS Source: https://github.com/swiftwasm/javascriptkit/blob/main/Plugins/PackageToJS/README.md This command executes the unit tests for the PackageToJS plugin using the Swift Package Manager. Ensure you are in the correct directory before running. ```bash swift test --package-path ./Plugins/PackageToJS ``` -------------------------------- ### BridgeJS Configuration File Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Articles/Ahead-of-Time-Code-Generation.md Creates a `bridge-js.config.json` file in the SwiftPM target directory to configure BridgeJS. ```bash $ echo "{}" > Sources/MyApp/bridge-js.config.json ``` -------------------------------- ### Build Swift Package with JavaScriptKit Source: https://github.com/swiftwasm/javascriptkit/blob/main/Sources/JavaScriptKit/Documentation.docc/Articles/Ahead-of-Time-Code-Generation.md Command to build a Swift package that utilizes JavaScriptKit, specifying the SDK. ```bash swift package --swift-sdk $SWIFT_SDK_ID js ```