npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@yodaos-pkg/ink

v0.20.1

Published

Ink Web SDK for browser rendering and VFS-backed app loading

Readme

@yodaos-pkg/ink

@yodaos-pkg/ink is the browser-facing Ink SDK for third-party frontend projects.

It wraps the low-level wasm runtime and InkWebView into a stable JavaScript and TypeScript API so you can:

  • initialize the Ink wasm runtime
  • create and destroy an InkView
  • bind a canvas and forward DOM events such as keyboard and pointer input
  • open an Ink bundle directly from memory
  • parse AIX package metadata and page-backed tools from package bytes or files
  • fetch and render an Ink bundle from an HTTP VFS service

Use Cases

This package is designed for:

  • plain browser-based frontend applications
  • React applications embedding Ink inside a component
  • Vue applications embedding Ink inside a page or component
  • frontend apps that fetch Ink resources from a backend VFS service

What You Need Before Starting

Before integrating the SDK, make sure you have one of these two inputs:

  1. An in-memory bundle

    • You already have the contents of app.json, page scripts, styles, images, and other files.
    • This is a good fit when your build pipeline or backend has already prepared the bundle.
  2. A VFS service URL

    • The frontend only knows an appId and an HTTP VFS endpoint.
    • This is a good fit when assets live on the server and the browser fetches them on demand.

If you use the VFS flow, provide your own HTTP VFS endpoint on the server side.

Installation

Step 1: Install the SDK

npm install @yodaos-pkg/ink

The package exposes a native ESM entry point, so bundlers and runtimes with npm package resolution can import it directly:

import { createInkView, initInk } from '@yodaos-pkg/ink';

Browser-native ESM without a bundler

Browsers do not resolve npm package names by themselves. To use the package without a build step or an ESM transformation service, import the published ESM file from a static npm CDN. The JavaScript glue and Wasm binary are resolved relative to this URL:

<script type="module">
  import {
    createInkView,
    initInk,
  } from 'https://cdn.jsdelivr.net/npm/@yodaos-pkg/[email protected]/index.js';

  await initInk();

  const view = await createInkView({
    width: 360,
    height: 640,
    canvas: document.querySelector('canvas'),
  });
</script>

An import map can preserve the regular package specifier:

<script type="importmap">
{
  "imports": {
    "@yodaos-pkg/ink": "https://cdn.jsdelivr.net/npm/@yodaos-pkg/[email protected]/index.js"
  }
}
</script>

<script type="module">
  import { createInkView } from '@yodaos-pkg/ink';
</script>

Pin the complete package version in production so index.js, its JavaScript dependencies, and ink_web_bg.wasm always come from the same immutable release.

If you also want to use the VFS flow, prepare an HTTP endpoint that exposes:

GET /apps/:appId/manifest
GET /apps/:appId/files/:path

Core API

These are the most commonly used APIs:

renderPreviewToImageBitmap(files, options)

Renders a widget once on an internally managed offscreen surface and returns the completed frame as an ImageBitmap. The default output size is exactly 480 × 140 pixels.

const bitmap = await renderPreviewToImageBitmap(files, {
  entry: 'widgets/weather',
});

try {
  context.drawImage(bitmap, 0, 0);
} finally {
  bitmap.close();
}

Widget authors can customize the captured state with an optional synchronous or asynchronous onPreview() lifecycle hook:

export default {
  data: { city: '', temperature: 0 },

  async onPreview() {
    const weather = await loadBundledPreviewWeather();
    this.setData({ city: 'Hangzhou', temperature: weather.temperature });
  },

  onCreate() {
    this.startLiveWeatherUpdates();
  },
};

Preview rendering waits for the hook and applies its data changes before the final layout and paint. It does not run the widget's normal onCreate or onAttach lifecycle. When onPreview is absent, the initial widget data is rendered directly. Use signal to cancel preparation; callers can use AbortSignal.timeout(...) when they need a deadline.

createInkView(options)

Creates an InkView instance and initializes the wasm runtime internally.

Parameters

  • options.width: number
    • Required
    • The logical width of the Ink view
  • options.height: number
    • Required in bounded mode
    • Optional in width-constrained-auto-height mode
  • options.layoutMode?: 'bounded' | 'width-constrained-auto-height'
    • Optional
    • Defaults to bounded
    • Use width-constrained-auto-height when the host wants a fixed width and a runtime-driven height
  • options.scaleFactor?: number
    • Optional
    • The device pixel ratio, defaulting to window.devicePixelRatio
  • options.appFps?: number
    • Optional
    • Per-view app logic frame rate
    • Defaults to 60
  • options.hostPackages?: Array<{ type?: 'bundle'; files: BundleFiles } | { type: 'directory'; path: string }>
    • Optional
    • Injects host-provided packages into the runtime
    • Browser hosts should normally use bundle mounts
    • Package import names still come from each package's package.json.name
  • options.canvas?: HTMLCanvasElement
    • Optional
    • If provided, the view is automatically bound to this canvas
  • options.wasm?: InitInkOptions
    • Optional
    • Lets you customize wasm initialization
    • wasmUrl?: string | URL | Request
    • moduleOrPath?: RequestInfo | URL | Response | BufferSource | WebAssembly.Module

What it does

  • Initializes the Ink wasm runtime
  • Creates the underlying InkWebView
  • Returns the higher-level InkView wrapper
  • Automatically calls bindCanvas() if a canvas is provided
  • In auto-height mode, automatically adopts the latest runtime content height for HTML canvas surfaces

Returns

  • Promise<InkView>
    • Resolves to an InkView instance that can then call bindDomEvents(), openBundle(), and openFromVfs()

Auto-height Layout

Use layoutMode: 'width-constrained-auto-height' when the host controls width but wants Ink to drive the rendered height:

const view = await createInkView({
  width: 360,
  layoutMode: 'width-constrained-auto-height',
  scaleFactor: window.devicePixelRatio,
  appFps: 30,
  canvas,
  systemAgent: true,
});

In this mode:

  • the host still owns the constrained width
  • the SDK automatically adopts runtime-reported content height
  • browser hosts should call view.setViewport() when width or device pixel ratio changes
  • pass { resetScroll: true } only when the host explicitly wants to reset the current page scroll position during that viewport update
  • browser hosts do not need to manually apply HTML canvas height in the common case

Host Packages

Use hostPackages when the host wants to inject reusable functions or components without copying them into every app bundle:

const view = await createInkView({
  width: 360,
  height: 640,
  canvas,
  hostPackages: [
    {
      files: {
        'package.json': JSON.stringify({
          name: '@rokid/ui',
          module: './index.ts',
          ink: {
            components: {
              './card': './components/card',
            },
          },
        }),
        'index.ts': 'export const source = "host";',
        'components/card/index.ink': `
          <script def>{ "component": true }</script>
          <template><view class="rk-card" /></template>
          <style></style>
          <script setup>export default {};</script>
        `,
      },
    },
  ],
});

Apps can then consume the injected package with the package name declared in package.json:

import { source } from '@rokid/ui';
{
  "usingComponents": {
    "rk-card": "@rokid/ui/card"
  }
}

Resolution order stays local-first:

  • app node_modules wins when the app already ships the same package name
  • host packages are used only as a fallback source

configNavigatorHost(serialNumber?, platform?, arch?, languages?, region?, platformService?)

Configures global host-provided navigator metadata for subsequently created Ink views.

import { configNavigatorHost, createInkView } from '@yodaos-pkg/ink';

configNavigatorHost(
  'device-sn-from-host',
  'YodaOS Sprite',
  'aarch64',
  ['zh-CN', 'en-US'],
  'CN',
  { region: 'cn', environment: 'production', host: 'api.example.com' },
);

Browser hosts should call this before createInkView(...) when they want Ink JavaScript to observe host-provided navigator metadata:

const view = await createInkView({
  width: 360,
  height: 640,
  scaleFactor: window.devicePixelRatio,
  canvas,
});

This affects:

  • navigator.getDeviceSerialNumber()
  • navigator.userAgent
  • navigator.languages
  • navigator.language
  • navigator.region
  • navigator.platformService

Compatibility notes:

  • configNavigatorHost(...) is fully optional
  • existing createInkView({...}) calls continue to work without changes
  • systemAgent is an instance-scoped declaration and defaults to false
  • only a view created with systemAgent: true can read the configured serial number
  • when systemAgent is omitted or false, navigator.getDeviceSerialNumber() returns ''
  • blank language entries are filtered out of languages
  • when omitted, navigator.languages returns []
  • when omitted, navigator.language and navigator.region return ''
  • when omitted or empty, navigator.platformService returns null
  • navigator.language always returns navigator.languages[0]
  • when omitted, navigator.userAgent falls back to AIUI/{major.minor} Ink/{inkVersion}
  • updates only affect views created after the change and do not hot-swap existing instances

configureNetwork(options)

Configures host-controlled request interception for Ink network traffic.

Parameters

  • options.interceptor
    • Optional
    • A function that receives the outgoing request and returns an action
  • options.proxyUrl
    • Optional
    • A convenience option for rewriting requests through a proxy endpoint
  • options.targetSearchParam
    • Optional
    • The query parameter name used when proxyUrl is provided
  • options.clear
    • Optional
    • Clears the previously registered interceptor

What it does

  • Registers a global Ink request interceptor
  • Lets hosts continue, rewrite, or block outgoing requests
  • Mirrors the shape of a WebView-style request interception hook

Returns

  • void

createProxyUrlResolver(options)

Creates a request interceptor that rewrites outgoing requests to a host-managed proxy endpoint such as '/__proxy?url=...'.

Parameters

  • options.proxyUrl
    • Required
    • The proxy endpoint to call
  • options.targetSearchParam
    • Optional
    • The query parameter name that receives the original target URL

Returns

  • InkRequestInterceptor
    • A reusable interceptor for configureNetwork() or initInk()

view.bindDomEvents(options?)

Binds common DOM events to the current InkView.

Parameters

  • options.canvas?: HTMLCanvasElement
    • Optional
    • Overrides the currently bound canvas
  • options.keyboardTarget?: EventTarget | null
    • Optional
    • The keyboard event target, defaulting to window when available
  • options.focusTarget?: HTMLElement | HTMLCanvasElement | null
    • Optional
    • The target used for focus synchronization when syncFocus is enabled, defaulting to the canvas
  • options.syncFocus?: boolean
    • Optional
    • Controls whether DOM focus / blur and click-to-focus are synchronized into Ink host focus
    • Defaults to false
  • options.preventWheelDefault?: boolean
    • Optional
    • Controls whether wheel default behavior is prevented
    • Defaults to true

What it does

  • Binds pointerdown / pointermove / pointerup / pointercancel
  • Binds wheel
  • Binds keydown / keyup
  • Optionally binds focus / blur when syncFocus is enabled
  • Automatically forwards these browser events into the Ink runtime

Returns

  • () => void
    • Returns a cleanup function
    • Calling it removes every listener created by this binding call

view.dispatchVoiceWakeup(keyword, timestamp?)

Dispatches a host voice wakeup event to the current Ink app/page.

Parameters

  • keyword: string
    • Required
    • The wakeup keyword exposed to Ink as event.keyword
  • timestamp?: number
    • Optional
    • Event timestamp in milliseconds
    • Defaults to Date.now()

What it does

  • Forwards a cancelable voice.wakeup event into the Ink runtime
  • Reaches app/page listeners as voicewakeup / onVoiceWakeup
  • Automatically triggers a render request

Returns

  • boolean
    • true when the event is not canceled
    • false when Ink handles the event and calls preventDefault()

view.dispatchConnectivityEvent(status)

Dispatches a host connectivity update to the current Ink app/page.

Parameters

  • status: 'online' | 'offline'
    • Required
    • The connectivity state exposed to Ink as a networkstatus event

What it does

  • Forwards a host connectivity update into the Ink runtime
  • Reaches app/page listeners as networkstatus / onNetworkStatus
  • Automatically triggers a render request

Returns

  • InkView
    • Returns the current instance so it can be chained

view.dispatchMessageEvent(dataOrJson, origin?, lastEventId?, format?)

Dispatches a one-shot host message to the current Ink page.

Parameters

  • dataOrJson: unknown
    • Required
    • Accepts either a structured JSON-serializable value or a raw JSON string
  • origin?: string
    • Optional
    • The host-defined origin exposed as event.origin
    • Defaults to 'host'
  • lastEventId?: string
    • Optional
    • The host-defined message identifier exposed as event.lastEventId
    • Defaults to ''
  • format?: 'auto' | 'json' | 'jsonl'
    • Optional
    • Only applies when dataOrJson is a string
    • Defaults to 'auto'

What it does

  • If dataOrJson is a string, forwards it to the runtime with the selected format
  • 'auto' tries one JSON document first and falls back to JSONL
  • 'jsonl' dispatches one message event per non-empty line
  • Otherwise serializes the structured value directly
  • Dispatches the resulting payload as a DOM-style MessageEvent
  • Automatically triggers a render request

Returns

  • InkView
    • Returns the current instance so it can be chained

Throws

  • Error
    • If a string input is not valid JSON
  • TypeError
    • If a structured input cannot be serialized into JSON

view.createMessageStream(origin?, lastEventId?)

Creates a host-controlled JSON message stream for the current Ink page.

Parameters

  • origin?: string
    • Optional
    • The host-defined origin propagated to stream events
    • Defaults to 'host'
  • lastEventId?: string
    • Optional
    • The host-defined message identifier propagated to stream events
    • Defaults to ''

What it does

  • Creates a progressive JSON stream owned by the browser host
  • Lets the host call write(chunk) repeatedly
  • Lets the host call close() when the stream is complete
  • Delivers a runtime-side MessageStream object through onMessage(event)

Returns

  • InkHostMessageStream
    • A small host-side stream handle with write(chunk) and close()

InkHostMessageStream.write(chunk)

Appends the next JSON text chunk to the stream.

Parameters

  • chunk: string
    • Required
    • The next JSON text fragment to append

Throws

  • Error
    • If the stream has already been closed

InkHostMessageStream.close()

Closes the host stream.

What it does

  • Ends the stream inside the Ink runtime
  • Is safe to call more than once

view.openBundle(options)

Opens an Ink bundle that already exists in memory.

Parameters

  • options.appId: string
    • Required
    • The application ID of the Ink app to open
  • options.files: BundleFiles
    • Required
    • Supports three formats:
    • Map<string, BundleFileInput>
    • Array<[string, BundleFileInput]>
    • Record<string, BundleFileInput>
  • BundleFileInput
    • Supported input types:
    • string
    • Uint8Array
    • ArrayBuffer
    • ArrayBufferView
  • options.initialPage?: string | null
    • Optional
    • Sets the first page to open
  • options.query?: string | Record<string, unknown> | null
    • Optional
    • Initial query payload
    • If an object is provided, the SDK serializes it into JSON

What it does

  • Normalizes the file set into the bundle shape expected by the runtime
  • Calls the underlying openBundle
  • Opens the requested Ink app
  • Automatically triggers a render request

Returns

  • InkView
    • Returns the current instance so it can be chained

view.openFromVfs(options)

Fetches an Ink bundle from a remote HTTP VFS service and opens it.

Parameters

  • options.appId: string
    • Required
    • The application ID to open
  • options.baseUrl: string
    • Required
    • The VFS service base URL, for example https://example.com/ink-vfs
  • options.fetch?: typeof globalThis.fetch
    • Optional
    • Lets you provide a custom fetch implementation
  • options.signal?: AbortSignal
    • Optional
    • Used to cancel the request flow
  • options.headers?: HeadersInit
    • Optional
    • Extra request headers
  • options.requestInterceptor?: InkRequestInterceptor
    • Optional
    • Overrides the global interceptor for this VFS load only
  • options.initialPage?: string | null
    • Optional
    • Sets the first page to open
  • options.query?: string | Record<string, unknown> | null
    • Optional
    • Initial query payload

What it does

  • Fetches the VFS manifest first
  • Fetches each file listed in the manifest
  • Reconstructs the bundle in the browser
  • Applies the request interceptor when one is configured
  • Calls openBundle() automatically

Returns

  • Promise<LoadedVfsBundle>
    • Resolves to the fetched bundle data:
    • appId: string
    • manifest: VfsManifest
    • files: Map<string, Uint8Array>

parseAixManifest(source)

Parses package metadata, page-backed tools, and widgets through the same AIX core used by native hosts. Call initInk() before using this synchronous helper.

import { initInk, parseAixManifest } from '@yodaos-pkg/ink';

await initInk();

const response = await fetch('/apps/weather.aix');
const manifest = parseAixManifest(await response.arrayBuffer());

for (const tool of manifest.tools) {
  console.log(tool.function.name, tool.target);
}

For an unpacked application, pass the same BundleFiles shape accepted by openBundle():

const manifest = parseAixManifest({
  'app.json': '{"pages":["pages/weather/index"]}',
  'pages/weather/index.json': '{"description":"Show the weather"}',
});

Parameters

  • source: ArrayBuffer | ArrayBufferView | BundleFiles
    • Binary input is treated as .aix package bytes
    • A map, entry array, or plain object is treated as unpacked application files

Returns

  • AixManifest
    • Includes package fields such as engine, package_id, and entries
    • Includes tools derived from the pages declared by app.json
    • Includes widgets declared by app.json, with validated .ink entries

initInk(options)

Initializes the wasm runtime and optionally installs a host networking policy.

Parameters

  • options.wasmUrl?: string | URL | Request
    • Optional
    • Custom URL for the wasm binary
  • options.moduleOrPath?: RequestInfo | URL | Response | BufferSource | WebAssembly.Module
    • Optional
    • Custom wasm module input supported by wasm-bindgen
  • options.requestInterceptor?: InkRequestInterceptor
    • Optional
    • Installs a host request interceptor before Ink networking starts
  • options.proxyUrl?: string
    • Optional
    • Shorthand for a proxy-based interceptor

Returns

  • Promise<{ InkWebView, getInkVersion, getInkBundleVersion, parseAixManifest, satisfiesInkEngine }>
    • Resolves to the wasm bindings and host preflight helpers

view.startRendering()

Starts the continuous render loop.

Parameters

  • None

What it does

  • Enables automatic rendering mode
  • Uses requestAnimationFrame internally to keep rendering
  • Works well for animations, interaction-heavy apps, and continuously updating UIs

Returns

  • InkView
    • Returns the current instance so it can be chained

view.setOnCloseRequested(callback)

Registers a host callback for runtime-driven close requests.

Parameters

  • callback: (() => void) | null
    • Required
    • Called after Ink emits lifecycle.closeRequested
    • Pass null to clear the callback

What it does

  • Listens for close requests emitted by the Ink runtime
  • Automatically calls stopRendering() before invoking the callback
  • Lets the host destroy or replace the closed view on its own timing

Returns

  • InkView
    • Returns the current instance so it can be chained

view.isCloseRequested()

Returns whether Ink has already requested that the host close this view.

Returns

  • boolean
    • true after the runtime emits lifecycle.closeRequested
    • false before any close request, or after the host opens a new app in the same view

view.destroy()

Destroys the current InkView and releases its resources.

Parameters

  • None

What it does

  • Stops the render loop
  • Removes event listeners created by bindDomEvents()
  • Calls the underlying InkWebView.destroy()
  • Releases runtime resources held by the current view
  • Should be called by the host after a close-requested view is no longer needed

Returns

  • void

Host Message Example

Use dispatchMessageEvent() when the full payload is already available:

view.dispatchMessageEvent(
  { type: 'hello', value: 1 },
  'browser-host',
  'msg-1',
);

view.dispatchMessageEvent(
  '{"type":"hello","value":2}',
  'browser-host',
  'msg-2',
);

Inside the Ink page:

export default Page({
  onMessage(event) {
    console.log('message data:', event.data);
    console.log('origin:', event.origin);
    console.log('lastEventId:', event.lastEventId);
  },
});

Host Message Stream Example

Use createMessageStream() when JSON arrives progressively:

const stream = view.createMessageStream('browser-host', 'stream-1');
stream.write('{"delta":"hel"');
stream.write('lo"}{"done":true}');
stream.close();

Inside the Ink page:

export default Page({
  onMessage(event) {
    if (!(event.data instanceof MessageStream)) {
      return;
    }

    const stream = event.data;
    stream.addEventListener('token', (tokenEvent) => {
      console.log('token:', tokenEvent.token);
    });
    stream.addEventListener('error', (errorEvent) => {
      console.error('stream error:', errorEvent.error);
    });
    stream.addEventListener('end', () => {
      console.log('stream finished');
    });
  },
});

Plain JavaScript Integration

This is the most direct way to integrate Ink into a plain JavaScript app.

Step 1: Prepare a container element

Start with a canvas element:

<canvas id="ink-root" style="width: 375px; height: 667px;"></canvas>

Step 2: Import the SDK

import { createInkView } from '@yodaos-pkg/ink';

Step 3: Prepare the bundle files

If your assets are already available in memory, organize them as an object or a Map:

const files = {
  'app.json': JSON.stringify({
    pages: ['pages/index/index'],
  }),
  'pages/index/index.js': `
    export default {
      data: {
        title: 'Hello Ink'
      }
    };
  `,
};

Step 4: Create the view and bind the canvas

const canvas = document.getElementById('ink-root');

const view = await createInkView({
  width: canvas.clientWidth,
  height: canvas.clientHeight,
  scaleFactor: window.devicePixelRatio,
  canvas,
});

Step 5: Bind DOM events

This wires common pointer, keyboard, focus, and blur events automatically:

view.bindDomEvents();

Step 6: Open the Ink bundle

view.openBundle({
  appId: 'demo-app',
  files,
});

Step 7: Start the render loop

view.startRendering();

Step 8: Clean up when the page is destroyed

window.addEventListener('beforeunload', () => {
  view.destroy();
});

Full Plain JavaScript Example

import { createInkView } from '@yodaos-pkg/ink';

const files = {
  'app.json': JSON.stringify({
    pages: ['pages/index/index'],
  }),
  'pages/index/index.js': `
    export default {
      data: {
        title: 'Hello Ink'
      }
    };
  `,
};

const canvas = document.getElementById('ink-root');

const view = await createInkView({
  width: canvas.clientWidth,
  height: canvas.clientHeight,
  scaleFactor: window.devicePixelRatio,
  canvas,
});

view.bindDomEvents();
view.setOnCloseRequested(() => {
  if (view.isCloseRequested()) {
    view.destroy();
  }
});
view.openBundle({
  appId: 'demo-app',
  files,
});
view.startRendering();

window.addEventListener('beforeunload', () => {
  view.destroy();
});

Opening an App Through VFS

If you do not want to embed the full bundle in the browser and instead prefer to fetch resources from the server, use openFromVfs().

Step 1: Prepare an accessible VFS service

For example, the server may expose:

  • https://example.com/ink-vfs/apps/demo-app/manifest
  • https://example.com/ink-vfs/apps/demo-app/files/...

Step 2: Create the view

import { createInkView } from '@yodaos-pkg/ink';

const canvas = document.getElementById('ink-root');

const view = await createInkView({
  width: canvas.clientWidth,
  height: canvas.clientHeight,
  scaleFactor: window.devicePixelRatio,
  canvas,
});

Step 3: Open the remote app

view.bindDomEvents();
view.setOnCloseRequested(() => {
  if (view.isCloseRequested()) {
    view.destroy();
  }
});

await view.openFromVfs({
  appId: 'demo-app',
  baseUrl: 'https://example.com/ink-vfs',
});

view.startRendering();

Step 4: Release resources when done

view.destroy();

Vue.js Integration

The recommended approach is to wrap Ink inside a Vue component and manage it through onMounted and onBeforeUnmount.

Step 1: Install the dependency

npm install @yodaos-pkg/ink

Step 2: Create a Vue component

Below is a minimal InkCanvas.vue example.

Step 3: Initialize in onMounted

  • Get the canvas
  • Create the InkView
  • Bind DOM events
  • Open the bundle
  • Start rendering

Step 4: Clean up in onBeforeUnmount

  • Call view.destroy()

Full Vue Example

<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { createInkView } from '@yodaos-pkg/ink';

const props = defineProps<{
  appId: string;
  files: Record<string, string | Uint8Array>;
}>();

const canvasRef = ref<HTMLCanvasElement | null>(null);
let cleanup = () => {};

onMounted(async () => {
  const canvas = canvasRef.value;
  if (!canvas) {
    return;
  }

  const view = await createInkView({
    width: canvas.clientWidth,
    height: canvas.clientHeight,
    scaleFactor: window.devicePixelRatio,
    canvas,
  });

  view.bindDomEvents();
  view.setOnCloseRequested(() => {
    if (view.isCloseRequested()) {
      view.destroy();
    }
  });
  view.openBundle({
    appId: props.appId,
    files: props.files,
  });
  view.startRendering();

  cleanup = () => view.destroy();
});

onBeforeUnmount(() => {
  cleanup();
});
</script>

<template>
  <canvas ref="canvasRef" style="width: 375px; height: 667px;" />
</template>

Vue Integration Tips

  • Treat files and appId as component inputs
  • If the bundle changes, destroy the old view before creating a new one
  • If the component size changes, call view.setViewport() from the host layer

React.js Integration

The recommended approach is to wrap Ink in a React component and manage its lifecycle inside useEffect.

Step 1: Install the dependency

npm install @yodaos-pkg/ink

Step 2: Create a React component

The component keeps a canvas ref and creates or destroys the Ink view inside useEffect.

Step 3: Initialize inside useEffect

  • Get the canvas
  • Create the InkView
  • Bind DOM events
  • Open the bundle
  • Start rendering

Step 4: Destroy it in the effect cleanup

  • Call view.destroy()

Full React Example

import { useEffect, useRef } from 'react';
import { createInkView } from '@yodaos-pkg/ink';

type InkCanvasProps = {
  appId: string;
  files: Record<string, string | Uint8Array>;
};

export function InkCanvas({ appId, files }: InkCanvasProps) {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);

  useEffect(() => {
    let disposed = false;
    let cleanup = () => {};

    async function mount() {
      const canvas = canvasRef.current;
      if (!canvas) {
        return;
      }

      const view = await createInkView({
        width: canvas.clientWidth,
        height: canvas.clientHeight,
        scaleFactor: window.devicePixelRatio,
        canvas,
      });

      view.bindDomEvents();
      view.setOnCloseRequested(() => {
        if (view.isCloseRequested()) {
          view.destroy();
        }
      });
      view.openBundle({
        appId,
        files,
      });
      view.startRendering();

      cleanup = () => view.destroy();
      if (disposed) {
        cleanup();
      }
    }

    mount();

    return () => {
      disposed = true;
      cleanup();
    };
  }, [appId, files]);

  return <canvas ref={canvasRef} style={{ width: 375, height: 667 }} />;
}

React Integration Tips

  • Keep files as a stable reference when possible, so the view is not rebuilt on every render
  • If you need to switch apps, reinitialize when appId or a wrapping key changes
  • If the host size changes significantly, use ResizeObserver and call view.setViewport()

Frequently Asked Questions

1. The page renders, but input does not work

The usual cause is missing this step:

view.bindDomEvents();

2. Resources are still retained after the page is destroyed

Make sure you call this when the component unmounts or the page exits:

view.destroy();

3. Should bundle files be strings or binary?

Both are supported:

  • string
  • Uint8Array
  • ArrayBuffer

4. When should I use openBundle() vs openFromVfs()?

  • If you already have the full resource contents, use openBundle()
  • If you only know the appId and a server endpoint, use openFromVfs()

Local Development

Build

npm run build

Test

npm test

Package Shape

  • dist/index.js
    • SDK entry point
  • dist/pkg/*
    • wasm-bindgen output
  • dist/env.js
    • runtime import shim

Single-file generated programs

Open a complete single-page .ink source without an app.json:

view.openSource(
  { source, sourceName: 'assistant.ink', appId: 'assistant' },
  { language: 'en' },
  { initialFocus: 'focus' },
);

The source descriptor contains only source text and identity. Pass query and hostOptions as the second and third arguments, using the same launch semantics as open().

For streamed generation, write decoded text chunks and activate once:

const writer = view.startSourceStream(
  { appId: 'assistant', sourceName: 'assistant.ink' },
  { language: 'en' },
  { initialFocus: 'focus' },
);
try {
  for await (const chunk of generatedTextChunks) writer.write(chunk);
  writer.finish();
} catch (error) {
  console.error(error.phase, error.line, error.column, error.message);
  writer.abort();
}

Keep the rendering loop enabled. Generation previews static markup and complete CSS rules without running generated scripts, bindings, or custom-component code. The stream descriptor contains only appId and optional sourceName; query and hostOptions are separate arguments, as with openSource(). A successful finish() attaches the Page script to the existing page once. abort() clears a generating or failed preview; completed or stale writers cannot modify a newer application. A static source can omit its script.

Single-file programs use dynamic Host permission requests automatically. Supply hostCapabilities.permissions.request to authorize sensitive APIs; an absent authorizer denies them. Stable appId values preserve application storage. Builtin and Host-provided modules are supported without filesystem fallback. Existing directory and AIX bundles retain their usual permission policies.