ktory-wasm 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kuchinashi Hoshikawa
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,46 @@
1
- # Temporary Holding Version
1
+ # ktory-wasm
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Run Ktory `.ktr` dialogue, choices, localized text and clock gates in a browser, Node.js, Electron or a Web game engine. The package ships an ES module, TypeScript declarations and the compiled Rust core. Installation requires no Rust toolchain or runtime dependencies.
4
+
5
+ ```sh
6
+ npm install ktory-wasm
7
+ ```
8
+
9
+ ```js
10
+ import { createKtoryWasm } from 'ktory-wasm';
11
+
12
+ const runtime = await createKtoryWasm();
13
+ const session = runtime.createSession();
14
+ try {
15
+ const menu = await session.start('#choice\n + [Open the door]\n : Welcome!');
16
+ const open = menu.choice.options.find(option => option.canSelect);
17
+ const first = await session.choice(open.id, menu.presentationId, menu.sessionId);
18
+ console.log(first.payload.content); // Welcome!
19
+ } finally {
20
+ session.dispose();
21
+ }
22
+ ```
23
+
24
+ ## Run the examples
25
+
26
+ From the project where you installed the package, run `node node_modules/ktory-wasm/examples/node.mjs`. For the browser example run `python3 -m http.server 8000 --bind 127.0.0.1` from the same directory, then open [the local example](http://127.0.0.1:8000/node_modules/ktory-wasm/examples/browser.html). Click **Continue** to advance. Its import map points at the installed browser entry.
27
+
28
+ The browser entry fetches the sibling `ktory_wasm.wasm`. When serving static files, keep `index.js`, `ktory-wasm.js` and `ktory_wasm.wasm` together. Bundlers can also emit the exported `ktory-wasm/ktory_wasm.wasm` asset and pass its URL to `createKtoryWasm(url)`. The Node ESM entry reads the installed binary from disk. Both entries accept bytes (`Uint8Array`, including a Node `Buffer`, or `ArrayBuffer`), or an HTTP(S) URL. The Node entry also accepts a `file:` URL object. In Electron use the browser entry for a sandboxed renderer and the Node entry in the main process.
29
+
30
+ ## Sessions
31
+
32
+ Create one runtime and call `createSession()` for each story instance. Session operations return promises. `start(script, primaryLocale?, entryBlock?, secondaryLocale?, conditionMode?)` starts or replaces the story. For unknown conditions the package default `0` (`AskHost`) returns `WaitingForEvaluation` and `evaluationRequests`. Answer the whole batch with `provideEvaluations(sessionId, { [requestId]: true })`, supplying actual game state. Mode `1` accepts unknown conditions for previews and mode `2` treats them as false.
33
+
34
+ - `step(presentationId, sessionId)`, `choice(optionId, presentationId, sessionId)` and `break(presentationId, sessionId)` take the identity captured when the input was offered. Keep both values with a queued event. A stale input leaves the story in place and records diagnostic kind `512`. Submitting a choice already reaches the first beat in the branch.
35
+ - Read `payload` for the current Main beat, `choice.options` for a menu, and `outputEvents` for new outputs from all tracks in delivery order. Event kinds `0` through `4` mean content, language refresh, track end, session end and snapshot restore. `recentTags`, `recentLaneTags` and `diagnostics` are rolling histories. Use `payload.text.primary` and `.secondary` for text, actual language and literal segments. Call `setLanguage` or `setSecondaryLanguage` to refresh active presentations.
36
+ - Call `advanceClocks(deltaSeconds, sessionId, sourcePositions?)` once per elapsed interval or `reportClockPosition(sourceName, position, sessionId)` for an external sample. Source positions are numeric values keyed by source name, with `null` for an unavailable sample. Read `pendingClockGates` for the threshold and `clockResetRequests` for external resets.
37
+ - `exportSnapshot()` returns a `snapshot` string. Keep it opaque. On a session with the target script loaded, `restoreSnapshot(snapshot)` returns a fresh `sessionId`, `scriptChanged` and restored outputs. Store game state, media positions and presentation timing in the host save. A pending evaluation or completed story cannot be exported.
38
+ - Before a successful start, ordinary input returns `{}`. A script load failure clears the previous story. `dispose()` releases the session and can be called repeatedly. Use a new session after disposal.
39
+
40
+ ## Lint and errors
41
+
42
+ The runtime linter is synchronous. `lint(script)` returns diagnostics, `lintWithDeclarations(script, manifest)` returns `scriptDiagnostics` and `declarationErrors`, and `lintWithProjectDeclarations(script, files)` returns `scriptDiagnostics` and `declarationDiagnostics` with a path for each manifest issue. A manifest can be JSON text or a `{ tags: … }` object. For project lint, supply a map from manifest paths to their JSON text. Each diagnostic has `code`, `message`, numeric `severity` (1 error, 2 warning, 3 information, 4 hint) and source coordinates. Positive line and column numbers are one-based.
43
+
44
+ Catch `KtoryError` and branch on `.code`. Use `.message` for display. Loader failures use `WASM_LOAD`, unexpected execution failures in the module use `WASM_RUNTIME`, and invalid JS argument serialization or project mapping uses `INVALID_ARGUMENT`. Script, session command and snapshot failures use `SESSION`. An operation on a released session uses `DISPOSED`. Ordinary script lint findings are returned as data.
45
+
46
+ See the [public type declarations](./index.d.ts) for all fields and optional arguments, and the [repository workflow](https://github.com/Kutinana/Ktory/blob/main/docs/ktory-workflow.md) for building and releasing. MIT licensed.
@@ -0,0 +1,29 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <meta charset="utf-8">
4
+ <title>Ktory browser example</title>
5
+ <p id="line" aria-live="polite"></p>
6
+ <button type="button" disabled>Continue</button>
7
+ <script type="importmap">
8
+ { "imports": { "ktory-wasm": "../index.js" } }
9
+ </script>
10
+ <script type="module">
11
+ import { createKtoryWasm } from 'ktory-wasm';
12
+
13
+ const line = document.querySelector('#line');
14
+ const button = document.querySelector('button');
15
+ const runtime = await createKtoryWasm();
16
+ const session = runtime.createSession();
17
+
18
+ function render(state) {
19
+ line.textContent = state.payload?.content ?? 'The end.';
20
+ button.disabled = state.status !== 'SuspendedAtBeat';
21
+ button.onclick = async () => {
22
+ button.disabled = true;
23
+ render(await session.step(state.presentationId, state.sessionId));
24
+ };
25
+ if (state.status === 'Completed') session.dispose();
26
+ }
27
+ render(await session.start(': The lighthouse is quiet.\n: A light appears.'));
28
+ </script>
29
+ </html>
@@ -0,0 +1,12 @@
1
+ import { createKtoryWasm } from 'ktory-wasm';
2
+
3
+ const runtime = await createKtoryWasm();
4
+ const session = runtime.createSession();
5
+ try {
6
+ const first = await session.start(': The lighthouse is quiet.\n: A light appears.');
7
+ console.log(first.payload.content);
8
+ const next = await session.step(first.presentationId, first.sessionId);
9
+ console.log(next.payload.content);
10
+ } finally {
11
+ session.dispose();
12
+ }
package/index.d.ts ADDED
@@ -0,0 +1,181 @@
1
+ // With no source, each entry loads the packaged WASM beside its ES module.
2
+ export type WasmSource = string | URL | ArrayBuffer | ArrayBufferView;
3
+ export type KtoryErrorCode = 'WASM_LOAD' | 'WASM_RUNTIME' | 'INVALID_ARGUMENT' | 'SESSION' | 'DISPOSED';
4
+ export class KtoryError extends Error {
5
+ readonly code: KtoryErrorCode;
6
+ constructor(code: KtoryErrorCode, message: string, options?: { cause?: unknown });
7
+ }
8
+ /** 0 asks the host (package default), 1 accepts unknown conditions, 2 rejects them. */
9
+ export type ConditionMode = 0 | 1 | 2;
10
+ export interface Diagnostic {
11
+ severity: 1 | 2 | 3 | 4;
12
+ code: string;
13
+ message: string;
14
+ line: number;
15
+ column: number;
16
+ endLine: number;
17
+ endColumn: number;
18
+ }
19
+ export interface Tag {
20
+ name: string;
21
+ positionalArgs: (string | number | boolean)[];
22
+ namedArgs: Record<string, string | number | boolean>;
23
+ }
24
+ export interface LocalizedValue {
25
+ content: string;
26
+ segments: { content: string; isLiteral: boolean }[] | null;
27
+ requestedLanguage: string | null;
28
+ actualLanguage: string | null;
29
+ }
30
+ export interface LocalizedText {
31
+ primary: LocalizedValue;
32
+ secondary: LocalizedValue | null;
33
+ }
34
+ export interface AutoPolicy {
35
+ enabled: boolean;
36
+ useEstimatedReadingTime: boolean;
37
+ defaultWaitSeconds: number;
38
+ }
39
+ export interface Beat {
40
+ stepId: string;
41
+ presentationId: number;
42
+ stepType: 0 | 1;
43
+ speakerId: string | null;
44
+ speakerActualLanguage: string | null;
45
+ actualLanguage: string | null;
46
+ requestedLanguage: string | null;
47
+ autoPolicy: AutoPolicy | null;
48
+ isAuto: boolean;
49
+ isNarration: boolean;
50
+ lineNumber: number;
51
+ content: string;
52
+ speaker: string | null;
53
+ text: LocalizedText;
54
+ speakerName: LocalizedText | null;
55
+ tags: Tag[];
56
+ }
57
+ export interface Choice {
58
+ presentationId: number;
59
+ tags: Tag[];
60
+ selectableCount: number;
61
+ lineNumber: number;
62
+ containerName: string;
63
+ isLoop: boolean;
64
+ options: {
65
+ id: string;
66
+ label: string;
67
+ text: LocalizedText;
68
+ canSelect: boolean;
69
+ isConsumed: boolean;
70
+ marker: string;
71
+ actualLanguage: string | null;
72
+ requestedLanguage: string | null;
73
+ tags: Tag[];
74
+ lineNumber: number;
75
+ }[];
76
+ }
77
+ export interface PresentationToken {
78
+ sessionId: string;
79
+ presentationId: number;
80
+ }
81
+ interface Presentation {
82
+ payload: Beat | null;
83
+ choice: Choice | null;
84
+ }
85
+ export interface LanePresentation extends Presentation {
86
+ laneId: string;
87
+ laneName: string;
88
+ isMain: boolean;
89
+ token: PresentationToken;
90
+ status: 0 | 1 | 2 | 3 | 4 | 7 | 8 | 9;
91
+ autoPolicy: AutoPolicy | null;
92
+ requiresInput: boolean;
93
+ }
94
+ export interface StoryOutput extends Presentation {
95
+ /** Content, language refresh, track end, session end, snapshot restore. */
96
+ kind: 0 | 1 | 2 | 3 | 4;
97
+ sequence: number;
98
+ sessionId: string;
99
+ trackId: string;
100
+ trackName: string | null;
101
+ isMain: boolean;
102
+ token: PresentationToken;
103
+ languageChange: 0 | 1 | 2;
104
+ }
105
+ export interface SessionState extends PresentationToken, Presentation {
106
+ status: 'Ready' | 'SuspendedAtBeat' | 'AwaitingChoice' | 'Completed' | 'Error'
107
+ | 'WaitingForClock' | 'WaitingForTrack' | 'WaitingForEvaluation';
108
+ activePresentations: LanePresentation[];
109
+ retainedPresentations: LanePresentation[];
110
+ outputEvents: StoryOutput[];
111
+ autoPolicy: AutoPolicy | null;
112
+ requestedLanguage: string;
113
+ secondaryLanguage: string | null;
114
+ defaultLanguage: string | null;
115
+ visitedItems: string[];
116
+ callStackDepth: number;
117
+ recentLaneTags: {
118
+ sessionId: string; laneId: string; laneName: string; isMain: boolean;
119
+ lineNumber: number; tags: Tag[]; currentPayload: Beat | null;
120
+ }[];
121
+ clocks: {
122
+ clockId: number; name: string | null; sourceName: string | null; ownerLaneId: string;
123
+ isExternal: boolean; position: number | null; declaredAtElapsedSeconds: number; lineNumber: number;
124
+ }[];
125
+ clockResetRequests: { sessionId: string; sourceName: string; clockId: number; lineNumber: number }[];
126
+ recentTags: Tag[];
127
+ diagnostics: { kind: 256 | 512; block: string; lineNumber: number; message: string; laneId: string; laneName: string }[];
128
+ pendingClockGates: {
129
+ laneId: string; laneName: string; token: PresentationToken; clockName: string | null; clockId: number;
130
+ sourceName: string | null; clockPosition: number | null; position: number; lineNumber: number;
131
+ }[];
132
+ evaluationRequests: { requestId: number; sessionId: string; expression: string; lineNumber: number; columnNumber: number }[];
133
+ snapshot: string | null;
134
+ scriptChanged: boolean | null;
135
+ }
136
+ // Input before a successful start returns an empty object.
137
+ type Turn = Promise<SessionState | { [K in keyof SessionState]?: never }>;
138
+ type Token = [expectedPresentationId?: number | null, expectedSessionId?: string | null];
139
+ export type ClockPositions = Record<string, number | null>;
140
+ type TimedInput = [...Token, deltaTime?: number, sourcePositions?: ClockPositions];
141
+ export interface KtorySession {
142
+ start(script: string, requestedLocale?: string | null, entryBlock?: string | null,
143
+ secondaryLocale?: string | null, conditionMode?: ConditionMode): Promise<SessionState>;
144
+ step(...input: TimedInput): Turn;
145
+ choice(choiceId: string, ...input: TimedInput): Turn;
146
+ break(...input: TimedInput): Turn;
147
+ setLanguage(locale: string | null, ...token: Token): Turn;
148
+ setSecondaryLanguage(locale: string | null, ...token: Token): Turn;
149
+ advanceClocks(deltaTime: number, sessionId: string, sourcePositions?: ClockPositions): Turn;
150
+ reportClockPosition(sourceName: string, position: number, sessionId: string,
151
+ deltaTime?: number, sourcePositions?: ClockPositions): Turn;
152
+ provideEvaluations(expectedSessionId: string, answers?: Record<number, boolean> | null): Promise<SessionState>;
153
+ exportSnapshot(): Promise<SessionState & { snapshot: string }>;
154
+ restoreSnapshot(snapshot: string): Promise<SessionState & { scriptChanged: boolean }>;
155
+ lint(script: string): Promise<Diagnostic[]>;
156
+ dispose(): void;
157
+ }
158
+ export interface TagDeclarations {
159
+ tags: Record<string, {
160
+ summary?: string;
161
+ openArgs?: boolean;
162
+ params?: {
163
+ name: string;
164
+ type?: 'any' | 'string' | 'number' | 'boolean';
165
+ required?: boolean;
166
+ positional?: boolean;
167
+ summary?: string;
168
+ }[];
169
+ }>;
170
+ }
171
+ export interface KtoryRuntime {
172
+ createSession(): KtorySession;
173
+ lint(script: string): Diagnostic[];
174
+ lintWithDeclarations(script: string, declarations: string | TagDeclarations | null): {
175
+ scriptDiagnostics: Diagnostic[]; declarationErrors: Diagnostic[];
176
+ };
177
+ lintWithProjectDeclarations(script: string, files: string | Record<string, string | null> | null): {
178
+ scriptDiagnostics: Diagnostic[]; declarationDiagnostics: { path: string; diagnostic: Diagnostic }[];
179
+ };
180
+ }
181
+ export function createKtoryWasm(source?: WasmSource): Promise<KtoryRuntime>;
package/index.js ADDED
@@ -0,0 +1,8 @@
1
+ import { createKtoryWasm as loadRuntime } from './ktory-wasm.js';
2
+
3
+ export { KtoryError } from './ktory-wasm.js';
4
+
5
+ // Games supply their own world state when a condition needs evaluation.
6
+ export function createKtoryWasm(source) {
7
+ return loadRuntime(source, 0);
8
+ }
package/ktory-wasm.js ADDED
@@ -0,0 +1,182 @@
1
+ const defaultWasmUrl = new URL('./ktory_wasm.wasm', import.meta.url);
2
+ const readerCatalog = './samples.json';
3
+
4
+ export class KtoryError extends Error {
5
+ constructor(code, message, options) {
6
+ super(message, options);
7
+ this.name = 'KtoryError';
8
+ this.code = code;
9
+ }
10
+ }
11
+
12
+ function serialize(value) {
13
+ try {
14
+ return JSON.stringify(value, (_key, item) => {
15
+ if (typeof item === 'number' && !Number.isFinite(item)) {
16
+ throw new TypeError('Expected a finite number.');
17
+ }
18
+ return item;
19
+ });
20
+ } catch (cause) {
21
+ throw new KtoryError('INVALID_ARGUMENT', cause.message, { cause });
22
+ }
23
+ }
24
+
25
+ async function fetchAsset(url) {
26
+ const response = await fetch(url);
27
+ if (!response.ok) throw new Error(`Could not load ${url} (HTTP ${response.status})`);
28
+ return response;
29
+ }
30
+
31
+ function declarationJson(declarations) {
32
+ return typeof declarations === 'string' ? declarations : serialize(declarations ?? null);
33
+ }
34
+
35
+ function optionalClock(deltaTime, sourcePositions) {
36
+ return deltaTime === undefined ? [] : [deltaTime, sourcePositions];
37
+ }
38
+
39
+ export async function createKtoryWasm(source = defaultWasmUrl, defaultConditionMode = 1) {
40
+ let wasm;
41
+ try {
42
+ const bytes = typeof source === 'string' || source instanceof URL
43
+ ? await (await fetchAsset(source)).arrayBuffer()
44
+ : source;
45
+ const { instance } = await WebAssembly.instantiate(bytes);
46
+ wasm = instance.exports;
47
+ if (!(wasm.memory instanceof WebAssembly.Memory) || [
48
+ 'alloc', 'dealloc', 'lint', 'lint_with_declarations', 'lint_with_project_declarations',
49
+ 'session_create', 'session_dispose', 'session_invoke',
50
+ ].some(name => typeof wasm[name] !== 'function')) {
51
+ throw new Error('Expected the Ktory WebAssembly module.');
52
+ }
53
+ } catch (cause) {
54
+ throw new KtoryError('WASM_LOAD', cause.message, { cause });
55
+ }
56
+ const encoder = new TextEncoder();
57
+ const decoder = new TextDecoder();
58
+
59
+ function invoke(name, strings, prefix = []) {
60
+ const buffers = [];
61
+ try {
62
+ for (const string of strings) {
63
+ if (typeof string !== 'string') throw new KtoryError('INVALID_ARGUMENT', 'Expected a string.');
64
+ const bytes = encoder.encode(string);
65
+ const ptr = wasm.alloc(bytes.length) >>> 0;
66
+ buffers.push([ptr, bytes.length]);
67
+ new Uint8Array(wasm.memory.buffer, ptr, bytes.length).set(bytes);
68
+ }
69
+
70
+ // The ABI packs the pointer into the low 32 bits and the length into the high 32 bits.
71
+ const packed = wasm[name](...prefix, ...buffers.flat());
72
+ const ptr = Number(packed & 0xFFFFFFFFn);
73
+ const length = Number(BigInt.asUintN(64, packed) >> 32n);
74
+ try {
75
+ const json = JSON.parse(decoder.decode(new Uint8Array(wasm.memory.buffer, ptr, length)));
76
+ if (typeof json?.error === 'string') {
77
+ const code = name === 'session_invoke' ? 'SESSION' : 'INVALID_ARGUMENT';
78
+ throw new KtoryError(code, json.error);
79
+ }
80
+ return json;
81
+ } finally {
82
+ wasm.dealloc(ptr, length);
83
+ }
84
+ } catch (cause) {
85
+ if (cause instanceof KtoryError) throw cause;
86
+ throw new KtoryError('WASM_RUNTIME', cause.message, { cause });
87
+ } finally {
88
+ for (const [ptr, length] of buffers) wasm.dealloc(ptr, length);
89
+ }
90
+ }
91
+
92
+ const runtime = {
93
+ lint(script) {
94
+ return invoke('lint', [script]);
95
+ },
96
+ lintWithDeclarations(script, declarations) {
97
+ return invoke('lint_with_declarations', [script, declarationJson(declarations)]);
98
+ },
99
+ lintWithProjectDeclarations(script, declarations) {
100
+ return invoke('lint_with_project_declarations', [script, declarationJson(declarations)]);
101
+ },
102
+ createSession() {
103
+ let handle = wasm.session_create() >>> 0;
104
+
105
+ if (!handle) throw new KtoryError('SESSION', 'Session limit reached.');
106
+
107
+ function requireHandle() {
108
+ if (!handle) throw new KtoryError('DISPOSED', 'No active session.');
109
+ }
110
+
111
+ function call(method, args = []) {
112
+ requireHandle();
113
+ return invoke('session_invoke', [serialize({ method, args })], [handle]);
114
+ }
115
+
116
+ return {
117
+ async start(script, requestedLocale = null, entryBlock = null, secondaryLocale = null, conditionMode = defaultConditionMode) {
118
+ if (![0, 1, 2].includes(conditionMode)) {
119
+ throw new KtoryError('INVALID_ARGUMENT', 'Expected condition mode 0, 1 or 2.');
120
+ }
121
+ return call('start', [script, requestedLocale, entryBlock || null, secondaryLocale, conditionMode]);
122
+ },
123
+ async step(expectedPresentationId = null, expectedSessionId = null, deltaTime, sourcePositions = {}) {
124
+ return call('step', [expectedPresentationId, expectedSessionId, ...optionalClock(deltaTime, sourcePositions)]);
125
+ },
126
+ async choice(choiceId, expectedPresentationId = null, expectedSessionId = null, deltaTime, sourcePositions = {}) {
127
+ return call('choice', [choiceId, expectedPresentationId, expectedSessionId, ...optionalClock(deltaTime, sourcePositions)]);
128
+ },
129
+ async break(expectedPresentationId = null, expectedSessionId = null, deltaTime, sourcePositions = {}) {
130
+ return call('break', [expectedPresentationId, expectedSessionId, ...optionalClock(deltaTime, sourcePositions)]);
131
+ },
132
+ async setLanguage(locale, expectedPresentationId = null, expectedSessionId = null) {
133
+ return call('setLanguage', [locale, expectedPresentationId, expectedSessionId]);
134
+ },
135
+ async setSecondaryLanguage(locale, expectedPresentationId = null, expectedSessionId = null) {
136
+ return call('setSecondaryLanguage', [locale, expectedPresentationId, expectedSessionId]);
137
+ },
138
+ async reportClockPosition(sourceName, position, sessionId, deltaTime, sourcePositions = {}) {
139
+ return call('reportClockPosition', [sourceName, position, sessionId, ...optionalClock(deltaTime, sourcePositions)]);
140
+ },
141
+ async advanceClocks(deltaTime, sessionId, sourcePositions) {
142
+ return call('advanceClocks', sourcePositions === undefined
143
+ ? [deltaTime, sessionId] : [deltaTime, sessionId, sourcePositions]);
144
+ },
145
+ async exportSnapshot() {
146
+ return call('exportSnapshot');
147
+ },
148
+ async restoreSnapshot(snapshot) {
149
+ return call('restoreSnapshot', [snapshot]);
150
+ },
151
+ async provideEvaluations(expectedSessionId, answers = null) {
152
+ return call('provideEvaluations', [expectedSessionId, answers]);
153
+ },
154
+ async lint(script) {
155
+ requireHandle();
156
+ return runtime.lint(script);
157
+ },
158
+ dispose() {
159
+ if (handle) wasm.session_dispose(handle);
160
+ handle = 0;
161
+ }
162
+ };
163
+ }
164
+ };
165
+ return runtime;
166
+ }
167
+
168
+ export async function createReaderWasm(source, samplesUrl = new URL(readerCatalog, import.meta.url)) {
169
+ const [runtime, { samples, declarations }] = await Promise.all([
170
+ createKtoryWasm(source),
171
+ fetchAsset(samplesUrl).then(response => response.json())
172
+ ]);
173
+ return {
174
+ ...runtime.createSession(),
175
+ async getSamples() {
176
+ return { ...samples };
177
+ },
178
+ async lintSample(script) {
179
+ return runtime.lintWithDeclarations(script, declarations).scriptDiagnostics;
180
+ }
181
+ };
182
+ }
Binary file
package/node.js ADDED
@@ -0,0 +1,15 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { createKtoryWasm as loadRuntime, KtoryError } from './index.js';
3
+
4
+ export { KtoryError };
5
+
6
+ export async function createKtoryWasm(source = new URL('./ktory_wasm.wasm', import.meta.url)) {
7
+ if (source instanceof URL && source.protocol === 'file:') {
8
+ try {
9
+ source = await readFile(source);
10
+ } catch (cause) {
11
+ throw new KtoryError('WASM_LOAD', cause.message, { cause });
12
+ }
13
+ }
14
+ return loadRuntime(source);
15
+ }
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "ktory-wasm",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Ktory narrative sessions and script diagnostics for JavaScript and TypeScript, powered by the Rust WebAssembly core.",
5
+ "type": "module",
6
+ "types": "./index.d.ts",
7
+ "exports": {
8
+ ".": {
9
+ "types": "./index.d.ts",
10
+ "browser": "./index.js",
11
+ "node": "./node.js",
12
+ "default": "./index.js"
13
+ },
14
+ "./ktory_wasm.wasm": "./ktory_wasm.wasm"
15
+ },
16
+ "files": [
17
+ "index.js", "node.js", "ktory-wasm.js", "index.d.ts", "ktory_wasm.wasm",
18
+ "examples", "README.md", "LICENSE"
19
+ ],
20
+ "license": "MIT",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/Kutinana/Ktory.git",
24
+ "directory": "packages/ktory-wasm"
25
+ },
26
+ "homepage": "https://ktory.ink/",
27
+ "publishConfig": { "access": "public", "registry": "https://registry.npmjs.org/" },
28
+ "scripts": { "prepack": "node ../../scripts/build-js-package.mjs" }
29
+ }