@fossil-lang/wasm 0.3.0-alpha.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/README.md ADDED
@@ -0,0 +1,70 @@
1
+ # @fossil-lang/wasm
2
+
3
+ JS/TS wrapper around the `fossil-wasm` Rust crate's wasm-bindgen artefacts. Provides:
4
+
5
+ - `initFossilWasm({ wasmUrl })` — consumer-controlled `.wasm` URL loader (memoised).
6
+ - `tokenize(text)` — calls the Rust lexer, returns `TokenRow[]` (ADR-0030).
7
+ - `semanticLegend()` — returns the LSP semantic-tokens legend (Phase 6 plan 06-07).
8
+ - `FossilPlayground` — the Workspace API class (ADR-0024) for LSP + compile.
9
+
10
+ ## Why explicit `init({ wasmUrl })` and not auto-load?
11
+
12
+ We use `wasm-bindgen --target web` (NOT `--target bundler`). This means consumers
13
+ control the `.wasm` URL resolution — works in Vite, Next.js, Webpack, Rspack, or
14
+ plain `new URL(...)` in a Web Worker context. See `08-RESEARCH.md` Pitfall 1
15
+ (this monorepo's phase-8 research) for why `--target bundler` was rejected.
16
+
17
+ ## Consumer patterns
18
+
19
+ ### Vite host
20
+
21
+ ```typescript
22
+ import { initFossilWasm, tokenize } from '@fossil-lang/wasm';
23
+ import wasmUrl from '@fossil-lang/wasm/pkg/fossil_wasm_bg.wasm?url';
24
+
25
+ await initFossilWasm({ wasmUrl });
26
+ const tokens = tokenize('prefix ex: <https://example.org/>');
27
+ ```
28
+
29
+ ### Next.js host (in a Client Component)
30
+
31
+ ```typescript
32
+ 'use client';
33
+ import { initFossilWasm, tokenize } from '@fossil-lang/wasm';
34
+
35
+ // Put fossil_wasm_bg.wasm in public/wasm/ at build time (next.config.mjs copies it)
36
+ useEffect(() => {
37
+ void initFossilWasm({ wasmUrl: '/wasm/fossil_wasm_bg.wasm' });
38
+ }, []);
39
+ ```
40
+
41
+ ### Web Worker
42
+
43
+ ```typescript
44
+ // inside a Worker module:
45
+ import { initFossilWasm, FossilPlayground } from '@fossil-lang/wasm';
46
+ import wasmUrl from '@fossil-lang/wasm/pkg/fossil_wasm_bg.wasm?url';
47
+
48
+ await initFossilWasm({ wasmUrl });
49
+ const pg = new FossilPlayground();
50
+ ```
51
+
52
+ ## Build
53
+
54
+ ```bash
55
+ # From repo root
56
+ pnpm --filter @fossil-lang/wasm build:wasm # → packages/wasm/pkg/
57
+ pnpm --filter @fossil-lang/wasm build # = build:wasm + tsc
58
+ ```
59
+
60
+ Requires: Rust 1.90 toolchain (per `rust-toolchain.toml` at repo root) +
61
+ `wasm-bindgen-cli` 0.2.120 (`cargo install --version 0.2.120 wasm-bindgen-cli`).
62
+ Optionally `wasm-opt` (binaryen) for size reduction.
63
+
64
+ ## Source of truth
65
+
66
+ - Rust crate: `crates/fossil-wasm/`
67
+ - tokenize ADR: `decisions/0030-wasm-exported-tokenizer.md`
68
+ - Workspace API ADR: `decisions/0024-fossil-wasm-workspace-api.md`
69
+ - Distribution pattern: `decisions/0028-playground-as-react-library.md`
70
+ (this package is one of the six in the `@fossil-lang/*` family)
@@ -0,0 +1,246 @@
1
+ /**
2
+ * @fossil-lang/wasm — JS/TS wrapper around the fossil-wasm wasm-bindgen artifacts.
3
+ *
4
+ * Public API (one of the six @fossil-lang/* packages per ADR-0028):
5
+ * - {@link initFossilWasm} — consumer-controlled .wasm URL loader (memoised).
6
+ * - {@link tokenize} — calls the Rust lexer, returns TokenRow[] (ADR-0030).
7
+ * - {@link semanticLegend} — returns the LSP SemanticTokensLegend (Phase-6 06-07).
8
+ * - {@link FossilPlayground} — Workspace API class (ADR-0024) for the LSP.
9
+ *
10
+ * Consumer pattern (wasm-bindgen --target web — RESEARCH.md Pattern 3):
11
+ *
12
+ * import { initFossilWasm, tokenize } from '@fossil-lang/wasm';
13
+ * import wasmUrl from '@fossil-lang/wasm/pkg/fossil_wasm_bg.wasm?url'; // Vite
14
+ *
15
+ * await initFossilWasm({ wasmUrl });
16
+ * const tokens = tokenize('prefix ex: <https://example.org/>');
17
+ */
18
+ import { FileHandle as RawFileHandle } from '../pkg/fossil_wasm.js';
19
+ import type { TokenRow, SemanticTokensLegend } from '@fossil-lang/types';
20
+ export { initFossilWasm } from './load.js';
21
+ export type { InitFossilWasmOpts } from './load.js';
22
+ /**
23
+ * Install the LSP-over-postMessage dispatcher on the current Worker scope.
24
+ *
25
+ * Per ADR-0024 (`fossil-wasm` IS the LSP server-side) + Phase 7 plan 07-03
26
+ * (the 16-route dispatch loop). The Rust function (re-exported from
27
+ * `crates/fossil-wasm/src/lsp_worker.rs`) installs `self.onmessage` on the
28
+ * Worker scope and owns LSP JSON-RPC dispatch from that point forward —
29
+ * including per-file `textDocument/publishDiagnostics` drains (B3 fix from
30
+ * 07-03), `textDocument/semanticTokens/full` (06-07), hover, completion,
31
+ * definition, references, rename, formatting, code actions, document
32
+ * symbols, signature help.
33
+ *
34
+ * MUST be called inside a Web Worker scope, AFTER {@link initFossilWasm} has
35
+ * resolved. Calling it on the main thread is a no-op (the dispatcher needs
36
+ * `DedicatedWorkerGlobalScope.onmessage`).
37
+ *
38
+ * Consumed by `@fossil-lang/playground`'s `src/workers/lsp.worker.ts` —
39
+ * the React component's LSP Worker entry boots the WASM module then calls
40
+ * this function once.
41
+ */
42
+ export declare function start_lsp_worker(): void;
43
+ /**
44
+ * Opaque file-handle returned by {@link FossilPlayground.openFile}. Pass it
45
+ * back into the matching `updateFile` / `closeFile` / `diagnosticsFor`
46
+ * calls. JS code cannot construct one directly (the wasm-bindgen
47
+ * class has a private constructor) — that is intentional per ADR-0024:
48
+ * handles are minted only by `openFile` on the Rust side, where they index a
49
+ * `HashMap<FileHandle, SourceFile>` keyed by a `u32` newtype.
50
+ */
51
+ export type FileHandle = RawFileHandle;
52
+ /**
53
+ * Tokenize a Fossil source string. Returns the byte-range tokens from the
54
+ * canonical Rust lexer (`fossil_syntax::lexer::raw_lex`) — single grammar
55
+ * source of truth per ADR-0030.
56
+ *
57
+ * MUST be called after {@link initFossilWasm} has resolved; otherwise the
58
+ * underlying wasm-bindgen function throws (the wasm module is not yet
59
+ * instantiated).
60
+ */
61
+ export declare function tokenize(text: string): TokenRow[];
62
+ /**
63
+ * Returns the LSP `SemanticTokensLegend` (token types + modifiers list) the
64
+ * editor uses to map LSP `semanticTokens/full` response indices to highlight
65
+ * categories. Re-export of `fossil_ide::semantic_legend` (Phase-6 06-07) over
66
+ * the wasm-bindgen boundary — NO duplicate legend definition lives here.
67
+ *
68
+ * MUST be called after {@link initFossilWasm} has resolved.
69
+ */
70
+ export declare function semanticLegend(): SemanticTokensLegend;
71
+ /** Diagnostic row returned by {@link FossilPlayground.check} and
72
+ * {@link FossilPlayground.diagnosticsFor} — mirrors `fossil-wasm`'s
73
+ * `CheckRow` JSON shape (the LSP `Diagnostic` projected through
74
+ * `fossil_ide::LineIndex` for UTF-16 ranges).
75
+ */
76
+ export interface CheckRow {
77
+ uri: string;
78
+ range: {
79
+ start: {
80
+ line: number;
81
+ character: number;
82
+ };
83
+ end: {
84
+ line: number;
85
+ character: number;
86
+ };
87
+ };
88
+ severity: number;
89
+ message: string;
90
+ }
91
+ /** Stdlib classification entry returned by {@link FossilPlayground.classification}.
92
+ * `wasm_class` indicates whether a stdlib function can execute in-browser
93
+ * (`"pure_sql"`) or requires the native runtime (`"native_udf_only"`). The
94
+ * playground reads this once at startup to render `native_udf_only` functions
95
+ * as disabled (STDL-07 / SC#1 playground half).
96
+ */
97
+ export interface StdlibClass {
98
+ name: string;
99
+ wasm_class: 'pure_sql' | 'native_udf_only';
100
+ }
101
+ /**
102
+ * Canonical primitive names for inferred-descriptor columns. Must match the
103
+ * lookup table in `fossil-hir::infer::primitive_from_name` (ADR-0037). Names
104
+ * map 1:1 to the `Primitive` enum in HIR (Integer, Float, String, Bool, Date,
105
+ * DateTime, Time, GYear, AnyURI).
106
+ *
107
+ * Unknown / non-canonical strings are accepted on the wire — the Rust side
108
+ * coerces them to `String` and emits a `D-INFERRED-UNKNOWN-DATATYPE`
109
+ * diagnostic. Hosts SHOULD canonicalise their DuckDB `DESCRIBE` output to
110
+ * these names before registering.
111
+ */
112
+ export type InferredPrimitive = 'String' | 'Integer' | 'Float' | 'Bool' | 'Date' | 'DateTime' | 'Time' | 'GYear' | 'AnyURI';
113
+ /** One column from a host-introspected source. */
114
+ export interface InferredColumnJson {
115
+ name: string;
116
+ primitive: InferredPrimitive;
117
+ }
118
+ /**
119
+ * Host-introspected input schema. Produced by the playground's browser-side
120
+ * `DuckDB-WASM` `DESCRIBE read_csv_auto('<url>')` call (see plan 13-04b);
121
+ * consumed by the Rust compiler via
122
+ * {@link FossilPlayground.registerInferredDescriptor}. See ADR-0037 for the
123
+ * full architectural rationale (drop user-facing CSVW; host-side
124
+ * introspection feeds the compiler ahead of `compile()`).
125
+ */
126
+ export interface InferredDescriptorJson {
127
+ /** Source binding name (e.g. `"users"` for `users := io.csv(...)`). */
128
+ source_name: string;
129
+ /** Ordered columns — order is significant for column-position fallback. */
130
+ columns: InferredColumnJson[];
131
+ /**
132
+ * Opaque content-hash. Empty string means "let the Rust side derive a
133
+ * deterministic hash from the column tuple list" (used for Salsa keying).
134
+ * Hosts that already maintain a per-file content-hash (e.g. resolver-side)
135
+ * MAY supply it.
136
+ */
137
+ content_hash: string;
138
+ }
139
+ /**
140
+ * Workspace API class (ADR-0024). Thin TS wrapper around the wasm-bindgen
141
+ * `FossilPlayground` that exposes camelCase method names for JS idiom + better
142
+ * TS inference (the raw bindings use snake_case from the Rust impl block).
143
+ *
144
+ * One instance per browser tab / Node process — the instance owns the Salsa
145
+ * store + `Arc<OutputDescriptorKind>` for the schema slot. Subsequent
146
+ * `openFile` calls intern fresh `SourceFile` inputs under the same Salsa
147
+ * revision so `updateFile` benefits from incremental memoisation.
148
+ *
149
+ * The Phase 7 LSP Worker (07-03) drives this class via postMessage; the React
150
+ * component in `@fossil-lang/playground` (08-09) does the same via the
151
+ * WorkerTransport adapter.
152
+ *
153
+ * NOTE: {@link FileHandle} is opaque — JS cannot construct one. Callers receive
154
+ * a handle from `openFile` and pass it back to subsequent operations. The Rust
155
+ * side keeps a `HashMap<FileHandle, SourceFile>` indexed by a `u32` newtype;
156
+ * the wasm-bindgen wrapper exposes that as a class with `private constructor()`.
157
+ */
158
+ export declare class FossilPlayground {
159
+ private _inner;
160
+ constructor();
161
+ /**
162
+ * Free the underlying WASM-side Salsa store. Call when the playground is no
163
+ * longer needed (e.g. component unmount). Idempotent in spirit — subsequent
164
+ * method calls on a freed playground throw.
165
+ */
166
+ free(): void;
167
+ /**
168
+ * Return the stdlib classification manifest (STDL-07). The playground reads
169
+ * this once at startup to render `native_udf_only` functions as disabled
170
+ * with a "native-only — unavailable in the browser" tooltip.
171
+ */
172
+ classification(): StdlibClass[];
173
+ /**
174
+ * Open a file in the workspace. Returns the {@link FileHandle} subsequent
175
+ * `updateFile` / `closeFile` / `diagnosticsFor` calls key
176
+ * on. `path` is the URI / virtual path diagnostics carry back to the LSP
177
+ * client (e.g. `"file:///tmp/a.fossil"` or `"untitled:Untitled-1"`).
178
+ *
179
+ * Mirrors `ty_wasm::Workspace::open_file` (Astral). Interns a fresh
180
+ * `fossil_base::SourceFile` under the current Salsa revision.
181
+ */
182
+ openFile(path: string, contents: string): FileHandle;
183
+ /**
184
+ * Apply an edit to an open file. Mutates the SAME `SourceFile` via the
185
+ * Salsa `Setter` (`set_text`) — this BUMPS THE REVISION (ADR-0022), the
186
+ * real cancellation trigger. NO new `SourceFile` is interned, so memoised
187
+ * downstream queries (`def_map`, `typecheck_mapping`) invalidate
188
+ * incrementally instead of falling off a cliff.
189
+ */
190
+ updateFile(handle: FileHandle, contents: string): void;
191
+ /**
192
+ * Close a file in the workspace. Strict in signal: closing an unknown /
193
+ * already-closed handle throws so JS-side bugs surface loudly (mirrors
194
+ * `ty_wasm`).
195
+ */
196
+ closeFile(handle: FileHandle): void;
197
+ /**
198
+ * Workspace-wide diagnostic drain. Runs `parse → def_map →
199
+ * typecheck_mapping` across every open file and returns a flat array of
200
+ * {@link CheckRow}. The LSP Worker (07-03) republishes these grouped by URI
201
+ * as `textDocument/publishDiagnostics` notifications.
202
+ */
203
+ check(): CheckRow[];
204
+ /**
205
+ * Per-file diagnostic drain — the B3 follow-up accessor the LSP Worker uses
206
+ * for its per-file `publishDiagnostics` notifications. `check()` returns
207
+ * the workspace-wide flat array; `diagnosticsFor` returns just one file's
208
+ * rows so 07-03 can dispatch one notification per affected URI without
209
+ * partitioning the workspace array on the JS side.
210
+ */
211
+ diagnosticsFor(handle: FileHandle): CheckRow[];
212
+ /**
213
+ * Install a user-supplied ShEx schema as the active output descriptor. On
214
+ * parse failure the previously-installed descriptor is RETAINED (no
215
+ * half-applied state — same contract as `fossil-lsp::load_sibling_shex` in
216
+ * 06-09). Future `fossil-ide` feature calls (hover, completion) reading
217
+ * `HirDb::output_descriptor_kind` see the new schema atomically.
218
+ */
219
+ setTargetShex(text: string): void;
220
+ /**
221
+ * Register an {@link InferredDescriptorJson} for a source binding name
222
+ * BEFORE invoking {@link check}. The Rust compiler reads from this
223
+ * registration during forward type propagation (Phase 3 CORE-05 rewired in
224
+ * plan 13-02).
225
+ *
226
+ * The browser-side orchestration runs DuckDB-WASM
227
+ * `DESCRIBE read_csv_auto('<resolved-url>')` for each `io.csv("...")`
228
+ * reference in the source, canonicalises the columns to the
229
+ * {@link InferredPrimitive} catalog, and calls this method with the
230
+ * resulting descriptor before {@link check}. See ADR-0037 for the full
231
+ * architectural rationale.
232
+ *
233
+ * Keyed by source-binding name (e.g. `"users"` for
234
+ * `users := io.csv("...")`), NOT by URL. Idempotent — re-registering with
235
+ * the same `source_name` overwrites the previous entry.
236
+ *
237
+ * @throws Error if the descriptor JSON fails to deserialise on the Rust
238
+ * side (e.g. missing required fields). The error message includes
239
+ * the underlying serde_json diagnostic.
240
+ *
241
+ * @see ADR-0037 — drop user-facing CSVW; infer via DuckDB DESCRIBE
242
+ */
243
+ registerInferredDescriptor(descriptor: InferredDescriptorJson): void;
244
+ }
245
+ export type { TokenRow, SemanticTokensLegend } from '@fossil-lang/types';
246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.
3
+ *
4
+ * Public API (one of the six @fossil-lang/* packages per ADR-0028):
5
+ * - {@link initFossilWasm} — consumer-controlled .wasm URL loader (memoised).
6
+ * - {@link tokenize} — calls the Rust lexer, returns TokenRow[] (ADR-0030).
7
+ * - {@link semanticLegend} — returns the LSP SemanticTokensLegend (Phase-6 06-07).
8
+ * - {@link FossilPlayground} — Workspace API class (ADR-0024) for the LSP.
9
+ *
10
+ * Consumer pattern (wasm-bindgen --target web — RESEARCH.md Pattern 3):
11
+ *
12
+ * import { initFossilWasm, tokenize } from '@fossil-lang/wasm';
13
+ * import wasmUrl from '@fossil-lang/wasm/pkg/fossil_wasm_bg.wasm?url'; // Vite
14
+ *
15
+ * await initFossilWasm({ wasmUrl });
16
+ * const tokens = tokenize('prefix ex: <https://example.org/>');
17
+ */
18
+ // '../pkg/fossil_wasm.js' is a wasm-bindgen --target web output emitted by `pnpm run build:wasm`.
19
+ // Gitignored at the repo root (`packages/wasm/pkg/`) but always present at build time. The accompanying
20
+ // .d.ts is consumed via the file's `/* @ts-self-types="./fossil_wasm.d.ts" */` pragma.
21
+ import { FossilPlayground as RawFossilPlayground, FileHandle as RawFileHandle, tokenize as rawTokenize, semantic_legend as rawSemanticLegend, start_lsp_worker as rawStartLspWorker, } from '../pkg/fossil_wasm.js';
22
+ export { initFossilWasm } from './load.js';
23
+ /**
24
+ * Install the LSP-over-postMessage dispatcher on the current Worker scope.
25
+ *
26
+ * Per ADR-0024 (`fossil-wasm` IS the LSP server-side) + Phase 7 plan 07-03
27
+ * (the 16-route dispatch loop). The Rust function (re-exported from
28
+ * `crates/fossil-wasm/src/lsp_worker.rs`) installs `self.onmessage` on the
29
+ * Worker scope and owns LSP JSON-RPC dispatch from that point forward —
30
+ * including per-file `textDocument/publishDiagnostics` drains (B3 fix from
31
+ * 07-03), `textDocument/semanticTokens/full` (06-07), hover, completion,
32
+ * definition, references, rename, formatting, code actions, document
33
+ * symbols, signature help.
34
+ *
35
+ * MUST be called inside a Web Worker scope, AFTER {@link initFossilWasm} has
36
+ * resolved. Calling it on the main thread is a no-op (the dispatcher needs
37
+ * `DedicatedWorkerGlobalScope.onmessage`).
38
+ *
39
+ * Consumed by `@fossil-lang/playground`'s `src/workers/lsp.worker.ts` —
40
+ * the React component's LSP Worker entry boots the WASM module then calls
41
+ * this function once.
42
+ */
43
+ export function start_lsp_worker() {
44
+ rawStartLspWorker();
45
+ }
46
+ /**
47
+ * Tokenize a Fossil source string. Returns the byte-range tokens from the
48
+ * canonical Rust lexer (`fossil_syntax::lexer::raw_lex`) — single grammar
49
+ * source of truth per ADR-0030.
50
+ *
51
+ * MUST be called after {@link initFossilWasm} has resolved; otherwise the
52
+ * underlying wasm-bindgen function throws (the wasm module is not yet
53
+ * instantiated).
54
+ */
55
+ export function tokenize(text) {
56
+ // The wasm-bindgen wrapper returns a `JsValue` typed as `any`; the Rust side
57
+ // (crates/fossil-wasm/src/tokenize.rs) serializes `Vec<TokenRow>` via
58
+ // `serde_wasm_bindgen::to_value`, so the shape matches `{ kind, start, end }`
59
+ // exactly. Cast is safe because the Rust ↔ JS contract is enforced upstream.
60
+ return rawTokenize(text);
61
+ }
62
+ /**
63
+ * Returns the LSP `SemanticTokensLegend` (token types + modifiers list) the
64
+ * editor uses to map LSP `semanticTokens/full` response indices to highlight
65
+ * categories. Re-export of `fossil_ide::semantic_legend` (Phase-6 06-07) over
66
+ * the wasm-bindgen boundary — NO duplicate legend definition lives here.
67
+ *
68
+ * MUST be called after {@link initFossilWasm} has resolved.
69
+ */
70
+ export function semanticLegend() {
71
+ return rawSemanticLegend();
72
+ }
73
+ /**
74
+ * Workspace API class (ADR-0024). Thin TS wrapper around the wasm-bindgen
75
+ * `FossilPlayground` that exposes camelCase method names for JS idiom + better
76
+ * TS inference (the raw bindings use snake_case from the Rust impl block).
77
+ *
78
+ * One instance per browser tab / Node process — the instance owns the Salsa
79
+ * store + `Arc<OutputDescriptorKind>` for the schema slot. Subsequent
80
+ * `openFile` calls intern fresh `SourceFile` inputs under the same Salsa
81
+ * revision so `updateFile` benefits from incremental memoisation.
82
+ *
83
+ * The Phase 7 LSP Worker (07-03) drives this class via postMessage; the React
84
+ * component in `@fossil-lang/playground` (08-09) does the same via the
85
+ * WorkerTransport adapter.
86
+ *
87
+ * NOTE: {@link FileHandle} is opaque — JS cannot construct one. Callers receive
88
+ * a handle from `openFile` and pass it back to subsequent operations. The Rust
89
+ * side keeps a `HashMap<FileHandle, SourceFile>` indexed by a `u32` newtype;
90
+ * the wasm-bindgen wrapper exposes that as a class with `private constructor()`.
91
+ */
92
+ export class FossilPlayground {
93
+ _inner;
94
+ constructor() {
95
+ this._inner = new RawFossilPlayground();
96
+ }
97
+ /**
98
+ * Free the underlying WASM-side Salsa store. Call when the playground is no
99
+ * longer needed (e.g. component unmount). Idempotent in spirit — subsequent
100
+ * method calls on a freed playground throw.
101
+ */
102
+ free() {
103
+ this._inner.free();
104
+ }
105
+ /**
106
+ * Return the stdlib classification manifest (STDL-07). The playground reads
107
+ * this once at startup to render `native_udf_only` functions as disabled
108
+ * with a "native-only — unavailable in the browser" tooltip.
109
+ */
110
+ classification() {
111
+ return this._inner.classification();
112
+ }
113
+ /**
114
+ * Open a file in the workspace. Returns the {@link FileHandle} subsequent
115
+ * `updateFile` / `closeFile` / `diagnosticsFor` calls key
116
+ * on. `path` is the URI / virtual path diagnostics carry back to the LSP
117
+ * client (e.g. `"file:///tmp/a.fossil"` or `"untitled:Untitled-1"`).
118
+ *
119
+ * Mirrors `ty_wasm::Workspace::open_file` (Astral). Interns a fresh
120
+ * `fossil_base::SourceFile` under the current Salsa revision.
121
+ */
122
+ openFile(path, contents) {
123
+ return this._inner.open_file(path, contents);
124
+ }
125
+ /**
126
+ * Apply an edit to an open file. Mutates the SAME `SourceFile` via the
127
+ * Salsa `Setter` (`set_text`) — this BUMPS THE REVISION (ADR-0022), the
128
+ * real cancellation trigger. NO new `SourceFile` is interned, so memoised
129
+ * downstream queries (`def_map`, `typecheck_mapping`) invalidate
130
+ * incrementally instead of falling off a cliff.
131
+ */
132
+ updateFile(handle, contents) {
133
+ this._inner.update_file(handle, contents);
134
+ }
135
+ /**
136
+ * Close a file in the workspace. Strict in signal: closing an unknown /
137
+ * already-closed handle throws so JS-side bugs surface loudly (mirrors
138
+ * `ty_wasm`).
139
+ */
140
+ closeFile(handle) {
141
+ this._inner.close_file(handle);
142
+ }
143
+ /**
144
+ * Workspace-wide diagnostic drain. Runs `parse → def_map →
145
+ * typecheck_mapping` across every open file and returns a flat array of
146
+ * {@link CheckRow}. The LSP Worker (07-03) republishes these grouped by URI
147
+ * as `textDocument/publishDiagnostics` notifications.
148
+ */
149
+ check() {
150
+ return this._inner.check();
151
+ }
152
+ /**
153
+ * Per-file diagnostic drain — the B3 follow-up accessor the LSP Worker uses
154
+ * for its per-file `publishDiagnostics` notifications. `check()` returns
155
+ * the workspace-wide flat array; `diagnosticsFor` returns just one file's
156
+ * rows so 07-03 can dispatch one notification per affected URI without
157
+ * partitioning the workspace array on the JS side.
158
+ */
159
+ diagnosticsFor(handle) {
160
+ return this._inner.diagnostics_for(handle);
161
+ }
162
+ /**
163
+ * Install a user-supplied ShEx schema as the active output descriptor. On
164
+ * parse failure the previously-installed descriptor is RETAINED (no
165
+ * half-applied state — same contract as `fossil-lsp::load_sibling_shex` in
166
+ * 06-09). Future `fossil-ide` feature calls (hover, completion) reading
167
+ * `HirDb::output_descriptor_kind` see the new schema atomically.
168
+ */
169
+ setTargetShex(text) {
170
+ this._inner.set_target_shex(text);
171
+ }
172
+ /**
173
+ * Register an {@link InferredDescriptorJson} for a source binding name
174
+ * BEFORE invoking {@link check}. The Rust compiler reads from this
175
+ * registration during forward type propagation (Phase 3 CORE-05 rewired in
176
+ * plan 13-02).
177
+ *
178
+ * The browser-side orchestration runs DuckDB-WASM
179
+ * `DESCRIBE read_csv_auto('<resolved-url>')` for each `io.csv("...")`
180
+ * reference in the source, canonicalises the columns to the
181
+ * {@link InferredPrimitive} catalog, and calls this method with the
182
+ * resulting descriptor before {@link check}. See ADR-0037 for the full
183
+ * architectural rationale.
184
+ *
185
+ * Keyed by source-binding name (e.g. `"users"` for
186
+ * `users := io.csv("...")`), NOT by URL. Idempotent — re-registering with
187
+ * the same `source_name` overwrites the previous entry.
188
+ *
189
+ * @throws Error if the descriptor JSON fails to deserialise on the Rust
190
+ * side (e.g. missing required fields). The error message includes
191
+ * the underlying serde_json diagnostic.
192
+ *
193
+ * @see ADR-0037 — drop user-facing CSVW; infer via DuckDB DESCRIBE
194
+ */
195
+ registerInferredDescriptor(descriptor) {
196
+ // The wasm-bindgen wrapper exposes `registerInferredDescriptor(string)` —
197
+ // it accepts a JSON string. Serialise here so callers pass a typed object.
198
+ this._inner.registerInferredDescriptor(JSON.stringify(descriptor));
199
+ }
200
+ }
201
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,kGAAkG;AAClG,wGAAwG;AACxG,uFAAuF;AACvF,OAAO,EACL,gBAAgB,IAAI,mBAAmB,EACvC,UAAU,IAAI,aAAa,EAC3B,QAAQ,IAAI,WAAW,EACvB,eAAe,IAAI,iBAAiB,EACpC,gBAAgB,IAAI,iBAAiB,GACtC,MAAM,uBAAuB,CAAC;AAG/B,OAAO,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAG3C;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,UAAU,gBAAgB;IAC9B,iBAAiB,EAAE,CAAC;AACtB,CAAC;AAYD;;;;;;;;GAQG;AACH,MAAM,UAAU,QAAQ,CAAC,IAAY;IACnC,6EAA6E;IAC7E,sEAAsE;IACtE,8EAA8E;IAC9E,6EAA6E;IAC7E,OAAO,WAAW,CAAC,IAAI,CAAe,CAAC;AACzC,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,cAAc;IAC5B,OAAO,iBAAiB,EAA0B,CAAC;AACrD,CA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AAU,CAAC,CAAC,CAAC;IACrE,CAAC;CACF"}
package/dist/load.d.ts ADDED
@@ -0,0 +1,30 @@
1
+ /** Options for {@link initFossilWasm}. */
2
+ export interface InitFossilWasmOpts {
3
+ /**
4
+ * URL or path to `fossil_wasm_bg.wasm`. Consumers control resolution:
5
+ * - Vite: `import wasmUrl from '@fossil-lang/wasm/pkg/fossil_wasm_bg.wasm?url'`
6
+ * - Next.js: serve from `public/` and pass the static URL (e.g. `'/wasm/fossil_wasm_bg.wasm'`)
7
+ * - Web Worker: `new URL('@fossil-lang/wasm/pkg/fossil_wasm_bg.wasm', import.meta.url)`
8
+ * - Node test: a `file://` URL resolved from `import.meta.url`
9
+ *
10
+ * Accepts `string` (a URL string), `URL`, a `Request`, or a `Response` —
11
+ * matching `wasm-bindgen --target web`'s init signature.
12
+ */
13
+ wasmUrl: string | URL | Request | Response;
14
+ }
15
+ /**
16
+ * Boot the fossil-wasm module. MUST be awaited before calling any of
17
+ * {@link tokenize}, {@link semanticLegend}, or instantiating
18
+ * {@link FossilPlayground}. Memoised — subsequent calls return the same promise.
19
+ *
20
+ * Per 08-RESEARCH.md Pattern 3 (wasm-bindgen --target web), consumers control
21
+ * the `.wasm` URL — this avoids tying library users to a specific bundler's
22
+ * `.wasm` import magic. See `packages/wasm/README.md` for consumer patterns.
23
+ */
24
+ export declare function initFossilWasm(opts: InitFossilWasmOpts): Promise<unknown>;
25
+ /**
26
+ * For tests + hot-reload — reset the memoised promise. NOT exported from the
27
+ * package index (test-internal helper).
28
+ */
29
+ export declare function __resetForTests(): void;
30
+ //# sourceMappingURL=load.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"load.d.ts","sourceRoot":"","sources":["../src/load.ts"],"names":[],"mappings":"AAMA,0CAA0C;AAC1C,MAAM,WAAW,kBAAkB;IACjC;;;;;;;;;OASG;IACH,OAAO,EAAE,MAAM,GAAG,GAAG,GAAG,OAAO,GAAG,QAAQ,CAAC;CAC5C;AAID;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,kBAAkB,GAAG,OAAO,CAAC,OAAO,CAAC,CASzE;AAED;;;GAGG;AACH,wBAAgB,eAAe,IAAI,IAAI,CAEtC"}
package/dist/load.js ADDED
@@ -0,0 +1,33 @@
1
+ // '../pkg/fossil_wasm.js' is a wasm-bindgen --target web output emitted by `pnpm run build:wasm`.
2
+ // It is gitignored (per 08-01 .gitignore + repo .gitignore `packages/wasm/pkg/`) but always present at build time.
3
+ // The accompanying fossil_wasm.d.ts is consumed via the file's `/* @ts-self-types="./fossil_wasm.d.ts" */` pragma —
4
+ // TS 5.6 resolves the `import` to that side-channel `.d.ts` automatically (no `@ts-expect-error` needed).
5
+ import init from '../pkg/fossil_wasm.js';
6
+ let _initPromise = null;
7
+ /**
8
+ * Boot the fossil-wasm module. MUST be awaited before calling any of
9
+ * {@link tokenize}, {@link semanticLegend}, or instantiating
10
+ * {@link FossilPlayground}. Memoised — subsequent calls return the same promise.
11
+ *
12
+ * Per 08-RESEARCH.md Pattern 3 (wasm-bindgen --target web), consumers control
13
+ * the `.wasm` URL — this avoids tying library users to a specific bundler's
14
+ * `.wasm` import magic. See `packages/wasm/README.md` for consumer patterns.
15
+ */
16
+ export function initFossilWasm(opts) {
17
+ if (!_initPromise) {
18
+ // wasm-bindgen 0.2.120 init() prefers the `{ module_or_path }` object form;
19
+ // passing the URL/Request/Response/BufferSource as a positional argument
20
+ // still works but logs a deprecation warning ("pass a single object
21
+ // instead"). We use the object form to stay on the maintained path.
22
+ _initPromise = init({ module_or_path: opts.wasmUrl });
23
+ }
24
+ return _initPromise;
25
+ }
26
+ /**
27
+ * For tests + hot-reload — reset the memoised promise. NOT exported from the
28
+ * package index (test-internal helper).
29
+ */
30
+ export function __resetForTests() {
31
+ _initPromise = null;
32
+ }
33
+ //# sourceMappingURL=load.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"load.js","sourceRoot":"","sources":["../src/load.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,mHAAmH;AACnH,oHAAoH;AACpH,0GAA0G;AAC1G,OAAO,IAAI,MAAM,uBAAuB,CAAC;AAiBzC,IAAI,YAAY,GAA4B,IAAI,CAAC;AAEjD;;;;;;;;GAQG;AACH,MAAM,UAAU,cAAc,CAAC,IAAwB;IACrD,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,4EAA4E;QAC5E,yEAAyE;QACzE,oEAAoE;QACpE,oEAAoE;QACpE,YAAY,GAAG,IAAI,CAAC,EAAE,cAAc,EAAE,IAAI,CAAC,OAAgB,EAAE,CAAC,CAAC;IACjE,CAAC;IACD,OAAO,YAAY,CAAC;AACtB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,eAAe;IAC7B,YAAY,GAAG,IAAI,CAAC;AACtB,CAAC"}
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@fossil-lang/wasm",
3
+ "version": "0.3.0-alpha.1",
4
+ "description": "JS/TS wrapper around the fossil-wasm wasm-bindgen artifacts (--target web). Exposes initFossilWasm + tokenize + semanticLegend + FossilPlayground class for downstream @fossil-lang/* packages.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/kanzo-tech/fossil.git",
9
+ "directory": "packages/wasm"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "type": "module",
15
+ "main": "./dist/index.js",
16
+ "module": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js"
22
+ },
23
+ "./pkg/fossil_wasm_bg.wasm": "./pkg/fossil_wasm_bg.wasm"
24
+ },
25
+ "files": [
26
+ "dist/",
27
+ "pkg/fossil_wasm.js",
28
+ "pkg/fossil_wasm.d.ts",
29
+ "pkg/fossil_wasm_bg.wasm",
30
+ "pkg/fossil_wasm_bg.wasm.d.ts",
31
+ "README.md",
32
+ "LICENSE"
33
+ ],
34
+ "sideEffects": false,
35
+ "dependencies": {
36
+ "@fossil-lang/types": "0.3.0-alpha.1"
37
+ },
38
+ "devDependencies": {
39
+ "typescript": "^5.6.0",
40
+ "vitest": "^2.0.0"
41
+ },
42
+ "scripts": {
43
+ "build:wasm": "bash scripts/build-wasm.sh",
44
+ "build": "pnpm run build:wasm && tsc -p tsconfig.json",
45
+ "test": "vitest run",
46
+ "test:watch": "vitest",
47
+ "lint": "tsc --noEmit"
48
+ }
49
+ }