WDK logoWDK documentation

Worklet Bundler API Reference

API for @tetherto/wdk-worklet-bundler

API Reference

Package: @tetherto/wdk-worklet-bundler

This reference covers @tetherto/wdk-worklet-bundler@1.0.0-beta.17. The package requires Node.js ^22.21.0 || >=24.9.0; see installation prerequisites.

Configuration Types

WdkBundleConfig

WdkBundleConfig is the public configuration shape for wdk.config.js.

WdkBundleConfig Shape
import type { ConditionalSpecifier } from '@tetherto/wdk-worklet-bundler'

interface WdkBundleConfig {
  networks: Record<string, { package: string }>
  protocols?: Record<string, { package: string; [key: string]: unknown }>
  modules?: Record<string, {
    package: string
    factory?: string
    events?: string[]
  }>
  allowedMethods?: Record<string, {
    methods?: string[]
    protocols?: Record<string, Record<string, { methods?: string[] }>>
  }>
  allowedModuleMethods?: Record<string, { methods?: string[] }>
  preloadModules?: string[]
  transport?: 'hrpc' | 'jsonrpc'
  output?: {
    bundle?: string
    types?: string
    addons?: {
      ios?: string
      macos?: string
      android?: string
      linux?: string
      windows?: string
    }
    addonsYml?: string
  }
  options?: {
    minify?: boolean
    sourceMaps?: boolean
    targets?: string[]
    builtins?: ConditionalSpecifier[]
    linkAddons?: boolean
    swiftTarget?: string
    convertEsmToCjs?: boolean
    handleLeakCheck?: number | true
  }
}

allowedMethods is keyed by network. Its direct methods array restricts account calls, while protocols nests restrictions by protocol type and protocol name. allowedModuleMethods is keyed by generic-module name and applies to both HRPC and JSON-RPC. These inline helper shapes are present in the config declaration but are not named exports from the npm entrypoint.

Every omitted map, level, or methods field remains unrestricted. An explicit methods: [] denies every method on that exact surface. Both generated contexts receive allowedMethods and allowedModuleMethods.

Both transports support modules; use the installation example for the Pear runtime pairing and peer dependency. JSON-RPC defaults addon linking to true; HRPC defaults it to false. config.options.convertEsmToCjs defaults to false for both transports and must be enabled explicitly for targets whose Bare engine cannot load ESM.

The config declares output.types, options.minify, and options.sourceMaps, but its bundle generator does not honor those fields. Declarations are always written to ./.wdk/index.d.ts; minify and sourceMaps do not control bare-pack output (tracked in #74 and #75, respectively). ESM-to-CJS conversion minifies independently.

options.handleLeakCheck is optional and applies only to generated HRPC entrypoints. Set true to use Pear Worklet's default 1000 ms interval, or a positive number to pass as tickIntervalMs. Omit it to disable diagnostics; false, zero, negative numbers, and strings fail loadConfig() validation. The interval controls repeated sampling after an immediate suspend snapshot, not a one-time delay.

Generation checks whether the installed Pear Worklet diagnostic subpath resolves, warning and skipping it if unavailable. The helper logs through console.warn until Bare idle or resume; it does not close handles. JSON-RPC generation accepts the option but does not emit diagnostic registration.

options.builtins accepts module specifiers and conditional specifiers such as { addon: 'bare-fs' } for addons already provided by the host. Host-provided addon versions must match the host build exactly; configuration validation does not verify that match.

ResolvedConfig

ResolvedConfig extends WdkBundleConfig with absolute filesystem paths produced by loadConfig().

ResolvedConfig Additions
interface ResolvedConfig extends WdkBundleConfig {
  configPath: string
  projectRoot: string
  resolvedOutput: {
    bundle: string
    types: string
    addons: {
      ios: string
      macos: string
      android: string
      linux: string
      windows: string
    }
    addonsYml: string
  }
}

Dependency Helpers

FunctionDescriptionReturns
validateDependencies(modules, projectRoot)Resolve configured packages and report which modules are installed or missing.ValidationResult
detectPackageManager(projectRoot)Detect whether the project uses npm, yarn, or pnpm.'npm', 'yarn', or 'pnpm'
generateInstallCommand(missing, packageManager?)Build the command string used to install missing dependencies.string
installDependencies(missing, projectRoot, options?)Install missing dependencies with the detected or selected package manager.InstallResult
generateUninstallCommand(packages, packageManager?)Build the command string used to remove packages.string
uninstallDependencies(packages, projectRoot, options?)Remove packages with the detected or selected package manager.UninstallResult

validateDependencies(modules, projectRoot)

Use this helper to confirm that the packages listed in wdk.config.js are already resolvable from the host project.

Validate Missing Dependencies
import { validateDependencies } from '@tetherto/wdk-worklet-bundler'

const result = validateDependencies(
  ['@tetherto/wdk-wallet-btc', '@tetherto/pear-wrk-wdk'],
  process.cwd()
)

ValidationResult contains:

  • valid (boolean)
  • installed (ModuleInfo[])
  • missing (string[])

detectPackageManager(projectRoot)

Use this helper when you need the same package-manager detection logic that the CLI uses before install or uninstall flows.

Detect The Package Manager
import { detectPackageManager } from '@tetherto/wdk-worklet-bundler'

const packageManager = detectPackageManager(process.cwd())

generateInstallCommand(missing, packageManager?)

Build the install command string without mutating the project:

Generate An Install Command
import { generateInstallCommand } from '@tetherto/wdk-worklet-bundler'

const command = generateInstallCommand(
  ['@tetherto/wdk-wallet-btc', '@tetherto/pear-wrk-wdk'],
  'npm'
)

installDependencies(missing, projectRoot, options?)

Run the install flow from code when you want the same dependency installation behavior as generate --install.

generateUninstallCommand(packages, packageManager?)

Build the uninstall command string without mutating the project.

uninstallDependencies(packages, projectRoot, options?)

Run the uninstall flow from code and receive a structured UninstallResult.

Bundle Generation

FunctionDescriptionReturns
loadConfig(configPath?)Load, validate, and resolve a wdk.config.js file into absolute paths.Promise\<ResolvedConfig\>
generateBundle(config, options?)Generate the entrypoint, bundle, host import, and optional type output.Promise\<GenerateBundleResult\>
generateSourceFiles(config, options?)Generate the source entrypoint and related artifacts without bundling.Promise\<{ entryPath: string }\>
packBundle(options)Pack an entrypoint in memory, optionally converting ESM to CommonJS.Promise\<PackBundleResult\>
writeBundleFile(outputPath, bundle)Serialize and write a bundle, selecting its wrapper from the path.Buffer
wrapperForPath(outputPath)Select the wrapper for an output filename.BundleWrapper or null
generateEntryPoint(config, outputDir)Generate an HRPC Bare worklet entrypoint file.Promise\<string\>
generateJsonRpcEntryPoint(config, outputDir)Generate a JSON-RPC Bare worklet entrypoint file.Promise\<string\>
linkAddons(config, options?)Link bundle-header addons for the hosts selected by options.targets.Promise\<LinkAddonsResult\>
readBundle(bundlePath)Read a raw or default UTF-8-wrapped bare-pack artifact.Bundle
discoverLinkedAddons(bundle, projectRoot)Discover native addon packages and artifacts recorded in a packed bundle.LinkedAddon[]
generateAddonsYml(iosAddonsDir, swiftTarget, outputPath)Generate the BareKit Swift addon dependency file.void
generateWalletModulesCode(config)Generate the wallet-module section inserted into the entrypoint.string

loadConfig(configPath?)

loadConfig() searches for wdk.config.js when no explicit path is supplied, validates the public config shape, and resolves the output paths relative to the config file directory.

Load The Resolved Config
import { loadConfig } from '@tetherto/wdk-worklet-bundler'

const config = await loadConfig()

generateBundle(config, options?)

Use generateBundle() when you want the same bundle workflow that powers the CLI generate command.

GenerateBundleOptions supports:

  • dryRun
  • verbose
  • silent
  • skipTypes
  • skipGeneration: Reuse an existing generated entrypoint. Regenerate it after changing the entrypoint configuration.
  • deferOptionalPeers? (boolean): When omitted or true, defer missing peers marked optional during packing. The peer scan checks root, nested, scoped, and symlinked package trees before treating an optional peer as missing. Set this option to false to require absent optional imports at build time.

deferOptionalPeers is a per-run API option. It is not a WdkBundleConfig field and cannot be set in wdk.config.js.

GenerateBundleResult contains:

  • success
  • bundlePath
  • typesPath
  • bundleSize: Written byte count on success, including any output wrapper.
  • duration
  • error?
  • missingModule?
  • pack?: Packing metadata containing id, hosts, files (file count), addons (addon hrefs), and esmToCjs ({ converted, packagesPatched } or null). Check for its presence before reading it; dry runs and some failure paths omit it.

Packing and conversion failures return success: false with error; an unresolved module may also set missingModule. Check success before using the output. Unlike packBundle(), these failures are returned rather than rejected.

typesPath can reflect a configured output.types path even though the declaration file is still written to ./.wdk/index.d.ts.

Generate A Bundle Programmatically
import { generateBundle, loadConfig } from '@tetherto/wdk-worklet-bundler'

const config = await loadConfig('./wdk.config.js')
const result = await generateBundle(config, { verbose: true })

generateSourceFiles(config, options?)

Use generateSourceFiles() when you want the generated entrypoint and host import without packing or conversion. The second options argument accepts only verbose. Pass the returned entry path to packBundle() for a custom build.

packBundle(options)

Pack an existing entrypoint into an in-memory bundle. Supply an absolute entry path and packOptions with the project-root file URL and target hosts. Enable convertEsmToCjs for a CommonJS-only target; it defaults to false. minify defaults to true and applies only during conversion.

Before enabling conversion, resolve same-basename .js/.mjs collisions.

For example, pack a source entrypoint at ./worklet/index.mjs and write a CommonJS-wrapped bundle:

Pack And Write A Bundle
import path from 'node:path'
import { pathToFileURL } from 'node:url'
import { packBundle, writeBundleFile } from '@tetherto/wdk-worklet-bundler'

const projectRoot = process.cwd()
const packed = await packBundle({
  entry: path.join(projectRoot, 'worklet/index.mjs'),
  packOptions: {
    base: pathToFileURL(projectRoot).href,
    hosts: ['ios-arm64'],
    linked: true
  },
  convertEsmToCjs: true
})

writeBundleFile(
  path.join(projectRoot, '.wdk-bundle/worklet.bundle.js'),
  packed.bundle
)

This packs and writes JavaScript; link any required native addons separately before deployment. PackBundleResult contains bundle, id, hosts, addons (addon hrefs), files (file count), and esmToCjs. Conversion statistics are { converted, packagesPatched } when enabled, or null otherwise. packBundle() does not write an output file and rejects on packing or conversion errors.

For TypeScript consumers, the package exports these supporting types:

Import Packing Types
import type {
  BarePackOptions,
  ConditionalSpecifier,
  EsmToCjsStats,
  PackBundleOptions,
  PackBundleResult
} from '@tetherto/wdk-worklet-bundler'

BarePackOptions accepts bare-pack options except resolve and aliases, plus defer?: string[]. Use builtins only for modules supplied by the host. See conversion configuration for target-engine requirements and limitations.

writeBundleFile(outputPath, bundle)

Serialize the in-memory bundle and write it synchronously, creating the parent directory if needed and overwriting an existing file. The returned Buffer contains the bytes written, including the selected wrapper. Filesystem errors throw.

wrapperForPath(outputPath)

Return the wrapper selected by the output filename:

Filename suffixReturn valueFile format
.bundle.js, .bundle.cjs'cjs'CommonJS export of a UTF-8 bundle string
.bundle.mjs'mjs'ESM default export of a UTF-8 bundle string
.bundle.json'json'JSON-encoded UTF-8 bundle string
Any other suffixnullRaw bundle bytes

The exported BundleWrapper type is 'cjs' | 'mjs' | 'json'; callers must also handle null.

generateEntryPoint(config, outputDir)

Use generateEntryPoint() when you need the generated HRPC Bare entrypoint written to a chosen output directory. This path includes configured generic modules, both method-allowlist maps, module lifecycle/event wiring, and the optional handleLeakCheck diagnostic.

The HRPC entrypoint scans require.cache for every loaded bare-http1 and bare-https module, deduplicates their globalAgent objects, and invokes each agent's suspend() or resume() method. It also invokes context.moduleRuntime.suspendAll() or resumeAll() when present. Each call is fire-and-forget; synchronous throws and rejected promises are logged without stopping the other lifecycle calls.

generateJsonRpcEntryPoint(config, outputDir)

Generate the framed JSON-RPC entrypoint used by native hosts. It includes wallet, protocol, and generic-module managers plus both method-allowlist maps. It generates the same fire-and-forget HTTP-agent and module-runtime lifecycle wiring as HRPC. options.handleLeakCheck is HRPC-only, so JSON-RPC does not emit diagnostic registration.

linkAddons(config, options?)

Link the native addons recorded in an existing packed bundle. Platforms come from config.options.targets: iOS, macOS, Android, Linux, or Windows according to the host prefixes. LinkAddonsOptions supports verbose, silent, and an optional in-memory bundle. When bundle is omitted, it reads config.resolvedOutput.bundle. The result contains success, duration, platforms, addons: LinkedAddon[], and optional error.

Each selected platform's addon output directory is cleared and rewritten. Keep it dedicated to generated files. For each platform, an addon package with no prebuild directory for any selected host is skipped; this does not confirm runtime support. Unsupported host families and missing required artifacts from addons with matching prebuilds produce a failed result; a project-root or ancestor output directory is rejected. A failure can follow partial output changes. generateBundle() also returns success: false if addon linking fails.

When iOS is selected, addon linking also calls generateAddonsYml() with config.options.swiftTarget or the default target name app.

readBundle(bundlePath)

Read a bare-pack artifact synchronously and return its parsed bare-bundle Bundle. Accepts raw bundles and bare-pack's default UTF-8 CommonJS, ESM, or JSON string wrappers. A missing file or invalid bundle throws. Custom non-UTF-8 wrappers are unsupported.

discoverLinkedAddons(bundle, projectRoot)

Inspect a parsed bundle packed with --linked and return native addon packages sorted by name. projectRoot is the directory where bare-pack ran. Each LinkedAddon has name, version, absolute package dir, and artefacts, whose entries have name and family (apple, elf, or windows). An unrecognized linked-artifact name or a missing package manifest in the bundle throws. Non-linked addon hrefs, including builtin: addons supplied by the host, are ignored. This function discovers requirements; it does not link or install addons.

generateAddonsYml(iosAddonsDir, swiftTarget, outputPath)

Generate the addons.yml dependency list expected by BareKit Swift from linked iOS XCFrameworks.

generateWalletModulesCode(config)

Use generateWalletModulesCode() when you only need the generated wallet-module section for inspection or custom generator flows.

CLI Commands

The published CLI exposes these commands through wdk-worklet-bundler:

CommandDescriptionKey Options
generateGenerate a WDK bundle from configuration.--config, --install, --keep-artifacts, --dry-run, --no-types, --source-only, --skip-generation, --transport, --link-addons, --skip-link-addons, --no-defer-optional-peers, --verbose
initCreate a new wdk.config.js file.--yes
validateValidate configuration without building.--config
list-modulesList available WDK modules.--json
cleanRemove the generated .wdk folder.--yes

For the end-to-end config workflow and transport defaults, see the Worklet Bundler configuration guide.

The CLI applies --transport after loadConfig() resolves output paths. The flag changes entrypoint generation but does not recompute the default bundle filename. Set transport in wdk.config.js, or configure output.bundle explicitly when using the flag.

For older configs and custom build scripts, see addon platform migration and custom bundling migration.


Need Help?

On this page