@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
canvasand 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:
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.
- You already have the contents of
A VFS service URL
- The frontend only knows an
appIdand an HTTP VFS endpoint. - This is a good fit when assets live on the server and the browser fetches them on demand.
- The frontend only knows an
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/inkThe 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/:pathCore 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
boundedmode - Optional in
width-constrained-auto-heightmode
- Required in
options.layoutMode?: 'bounded' | 'width-constrained-auto-height'- Optional
- Defaults to
bounded - Use
width-constrained-auto-heightwhen 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 | RequestmoduleOrPath?: RequestInfo | URL | Response | BufferSource | WebAssembly.Module
What it does
- Initializes the Ink wasm runtime
- Creates the underlying
InkWebView - Returns the higher-level
InkViewwrapper - Automatically calls
bindCanvas()if acanvasis provided - In auto-height mode, automatically adopts the latest runtime content height for HTML canvas surfaces
Returns
Promise<InkView>- Resolves to an
InkViewinstance that can then callbindDomEvents(),openBundle(), andopenFromVfs()
- Resolves to an
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_moduleswins 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.userAgentnavigator.languagesnavigator.languagenavigator.regionnavigator.platformService
Compatibility notes:
configNavigatorHost(...)is fully optional- existing
createInkView({...})calls continue to work without changes systemAgentis an instance-scoped declaration and defaults tofalse- only a view created with
systemAgent: truecan read the configured serial number - when
systemAgentis omitted orfalse,navigator.getDeviceSerialNumber()returns'' - blank language entries are filtered out of
languages - when omitted,
navigator.languagesreturns[] - when omitted,
navigator.languageandnavigator.regionreturn'' - when omitted or empty,
navigator.platformServicereturnsnull navigator.languagealways returnsnavigator.languages[0]- when omitted,
navigator.userAgentfalls back toAIUI/{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
proxyUrlis 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()orinitInk()
- A reusable interceptor for
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
windowwhen available
options.focusTarget?: HTMLElement | HTMLCanvasElement | null- Optional
- The target used for focus synchronization when
syncFocusis enabled, defaulting to the canvas
options.syncFocus?: boolean- Optional
- Controls whether DOM
focus/blurand 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/blurwhensyncFocusis 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.wakeupevent into the Ink runtime - Reaches app/page listeners as
voicewakeup/onVoiceWakeup - Automatically triggers a render request
Returns
booleantruewhen the event is not canceledfalsewhen Ink handles the event and callspreventDefault()
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
networkstatusevent
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
dataOrJsonis a string - Defaults to
'auto'
What it does
- If
dataOrJsonis a string, forwards it to the runtime with the selected format 'auto'tries one JSON document first and falls back to JSONL'jsonl'dispatches onemessageevent 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
MessageStreamobject throughonMessage(event)
Returns
InkHostMessageStream- A small host-side stream handle with
write(chunk)andclose()
- A small host-side stream handle with
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:
stringUint8ArrayArrayBufferArrayBufferView
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
fetchimplementation
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: stringmanifest: VfsManifestfiles: 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
.aixpackage bytes - A map, entry array, or plain object is treated as unpacked application files
- Binary input is treated as
Returns
AixManifest- Includes package fields such as
engine,package_id, andentries - Includes
toolsderived from the pages declared byapp.json - Includes
widgetsdeclared byapp.json, with validated.inkentries
- Includes package fields such as
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
requestAnimationFrameinternally 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
nullto 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
booleantrueafter the runtime emitslifecycle.closeRequestedfalsebefore 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/manifesthttps://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/inkStep 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
filesandappIdas 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/inkStep 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
filesas a stable reference when possible, so the view is not rebuilt on every render - If you need to switch apps, reinitialize when
appIdor a wrappingkeychanges - If the host size changes significantly, use
ResizeObserverand callview.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:
stringUint8ArrayArrayBuffer
4. When should I use openBundle() vs openFromVfs()?
- If you already have the full resource contents, use
openBundle() - If you only know the
appIdand a server endpoint, useopenFromVfs()
Local Development
Build
npm run buildTest
npm testPackage 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.
