diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 2001f24..8461007 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -34,6 +34,21 @@ jobs: - name: Install latest stable Rust toolchain run: rustup toolchain install stable --profile minimal --component clippy,rustfmt,llvm-tools-preview + - name: Set up Node.js + uses: actions/setup-node@v7 + with: + node-version: 20 + cache: npm + + - name: Install JavaScript development dependencies + run: npm ci + + - name: Install WebAssembly binding generator + uses: taiki-e/install-action@e67fa11c4b9316fa714ddf0abed07a0c3143b95b # v2.87.4 + with: + tool: wasm-bindgen-cli@0.2.127 + fallback: none + - name: Check formatting run: cargo +stable fmt --check @@ -53,10 +68,19 @@ jobs: - name: Validate standalone SVG snapshots run: python3 scripts/validate-svg.py - - name: Build pure engine for WebAssembly + - name: Build browser WebAssembly package run: | rustup target add wasm32-unknown-unknown wasm32-wasip1 --toolchain stable - cargo +stable build -p stack-engine --target wasm32-unknown-unknown --locked + npm run build:wasm + + - name: Test native and browser operation parity + run: npm test + + - name: Check browser package types + run: npm run typecheck + + - name: Verify browser package contents + run: npm run pack:check - name: Install WebAssembly test runtime uses: taiki-e/install-action@e67fa11c4b9316fa714ddf0abed07a0c3143b95b # v2.87.4 diff --git a/.gitignore b/.gitignore index b83d222..50d9aed 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,3 @@ /target/ +/node_modules/ +/packages/engine/dist/ diff --git a/Cargo.lock b/Cargo.lock index f7db460..ed65bb5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,18 +2,46 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + [[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "js-sys" +version = "0.3.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0c1080212aad755ea003d18543e8768dd432c48819efd73a7bf1e39b7a5a3a" +dependencies = [ + "cfg-if", + "wasm-bindgen", +] + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + [[package]] name = "proc-macro2" version = "1.0.107" @@ -32,6 +60,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + [[package]] name = "serde" version = "1.0.229" @@ -59,7 +93,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.4", ] [[package]] @@ -89,6 +123,17 @@ dependencies = [ "stack-theme", ] +[[package]] +name = "stack-engine-wasm" +version = "0.1.0" +dependencies = [ + "js-sys", + "serde", + "serde_json", + "stack-engine", + "wasm-bindgen", +] + [[package]] name = "stack-formatter" version = "0.1.0" @@ -106,6 +151,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.4" @@ -123,6 +179,51 @@ version = "1.0.24" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +[[package]] +name = "wasm-bindgen" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b70935747edd64d89de3efa29d73789b806c15798f8e7dca4d8ac356b50ce70" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77775f8f3f7217702089053b94958f8f54061a3f663417df76e19cbdcca29bc1" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e11d33f857dc2fb11b8bc75aee111aa9cbeb12cd9f25efd3d4c2a3dd4e235284" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 2.0.119", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.127" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef64dbcc55df09c7e5a46182d181c2cfa3e925f3da937ea764728b4bbb9dcbf" +dependencies = [ + "unicode-ident", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index fc9b344..7350cad 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,5 +1,5 @@ [workspace] -members = ["crates/stack-engine", "crates/stack-formatter"] +members = ["crates/stack-engine", "crates/stack-engine-wasm", "crates/stack-formatter"] resolver = "3" [workspace.package] @@ -9,6 +9,8 @@ license = "Apache-2.0" repository = "https://github.com/stack-sh/engine" [workspace.dependencies] +serde = { version = "=1.0.229", features = ["derive"] } +serde_json = "=1.0.151" stack-compiler = { git = "https://github.com/stack-sh/compiler.git", rev = "17a0abe9c35e641761ff08fdf59b29a42828d9fd" } stack-formatter = { path = "crates/stack-formatter" } stack-theme = { git = "https://github.com/stack-sh/theme.git", rev = "ed6c500762fc9ccffc8777172ac672a716dcd916" } diff --git a/README.md b/README.md index 4ca9ec5..b3ba84a 100644 --- a/README.md +++ b/README.md @@ -2,13 +2,13 @@ `stack-sh/engine` is the pure Rust execution engine for Stack architecture diagrams. -The workspace now provides canonical Stack source formatting, the pure `stack-engine` operation facade, deterministic theme-aware scene layout and orthogonal edge routing, and safe standalone SVG rendering. A WebAssembly adapter remains planned work. +The workspace provides canonical Stack source formatting, the pure `stack-engine` operation facade, deterministic theme-aware scene layout and orthogonal edge routing, safe standalone SVG rendering, and a typed browser WebAssembly adapter. ## Workspace - `stack-engine`: operation/output boundary, theme and icon fallback resolution, deterministic scene layout, edge routing, validation beyond the compiler stage, and standalone SVG rendering; - `stack-formatter`: comment-preserving canonical formatting for Stack source files (implemented); -- a WebAssembly adapter exposing the same pure operations to browser consumers. +- `stack-engine-wasm` and npm `@stack-sh/engine`: a thin browser adapter exposing the same pure operations and portable result model. The native CLI will link the Rust engine directly. Web clients will use the WASM adapter. Shared fixtures will verify that both targets produce equivalent diagnostics, formatted source, and SVG output. @@ -27,7 +27,14 @@ cargo test --workspace STACK_SPECIFICATION_DIR=../specification cargo test -p stack-formatter --features conformance --test conformance STACK_SPECIFICATION_DIR=../specification cargo test -p stack-engine --features conformance python3 scripts/validate-svg.py -cargo build -p stack-engine --target wasm32-unknown-unknown +rustup target add wasm32-unknown-unknown wasm32-wasip1 +cargo build -p stack-engine-wasm --target wasm32-unknown-unknown +wasm-bindgen --version +npm ci +npm run build:wasm +npm test +npm run typecheck +npm run pack:check CARGO_TARGET_WASM32_WASIP1_RUNNER=wasmtime cargo test -p stack-engine --lib --target wasm32-wasip1 cross_target_numeric_fixture cargo fmt --check cargo clippy --workspace --all-targets --all-features -- -D warnings @@ -40,6 +47,8 @@ cargo doc --workspace --no-deps The renderer emits fixed-dimension standalone SVG with embedded catalog icons, local marker references, escaped authored text, accessible title and description metadata, and no script, event handler, external URL, host font measurement, or runtime I/O. Canonical SVG snapshots are byte-stable and parsed by `scripts/validate-svg.py`; set `UPDATE_STACK_SNAPSHOTS=1` only when intentionally regenerating them. CI also executes one exact numeric geometry fixture in both the native suite and a WASI build. +The npm package exports synchronous `format`, `check`, and `render` functions after asynchronous module initialization. Each operation accepts `string | Uint8Array` and returns a specific typed result with camel-case metadata and portable diagnostics. Invalid UTF-8 remains a normal `STK1001` result. Unsupported JavaScript input types and internal operational failures throw at the adapter boundary. Shared fixtures compare complete native and WebAssembly results, including formatted source, diagnostics, SVG, and metadata. Artifact validation audits WebAssembly imports and package contents; browser consumers retain responsibility for loading the module and performing any DOM, filesystem, network, or clock work. + ## Architecture - [`docs/decisions/0001-build-the-formatter-from-compiler-models.md`](./docs/decisions/0001-build-the-formatter-from-compiler-models.md) @@ -47,6 +56,7 @@ The renderer emits fixed-dimension standalone SVG with embedded catalog icons, l - [`docs/decisions/0003-use-integer-ranked-scene-layout.md`](./docs/decisions/0003-use-integer-ranked-scene-layout.md) - [`docs/decisions/0004-route-orthogonal-edges-on-a-visibility-grid.md`](./docs/decisions/0004-route-orthogonal-edges-on-a-visibility-grid.md) - [`docs/decisions/0005-serialize-safe-standalone-svg.md`](./docs/decisions/0005-serialize-safe-standalone-svg.md) +- [`docs/decisions/0006-expose-one-typed-browser-wasm-adapter.md`](./docs/decisions/0006-expose-one-typed-browser-wasm-adapter.md) - [`docs/dependency-audit.md`](./docs/dependency-audit.md) ## Licensing diff --git a/THIRD_PARTY_LICENSES.md b/THIRD_PARTY_LICENSES.md index 5e8ea84..39da578 100644 --- a/THIRD_PARTY_LICENSES.md +++ b/THIRD_PARTY_LICENSES.md @@ -11,6 +11,10 @@ | `itoa` | `1.0.18` | MIT OR Apache-2.0 | | Transitive runtime dependency of `serde_json`. | | `memchr` | `2.8.3` | Unlicense OR MIT | | Transitive runtime dependency of `serde_json`. | | `zmij` | `1.0.23` | MIT | | Transitive runtime dependency of `serde_json`. | +| `wasm-bindgen` / `wasm-bindgen-shared` | `0.2.127` | MIT OR Apache-2.0 | | JavaScript ABI and generated glue shipped by `@stack-sh/engine`. | +| `js-sys` | `0.3.104` | MIT OR Apache-2.0 | | Typed-array input and plain JavaScript result objects; built without default features. | +| `cfg-if` | `1.0.4` | MIT OR Apache-2.0 | | Transitive runtime dependency of `wasm-bindgen` and `js-sys`. | +| `once_cell` | `1.21.4` | MIT OR Apache-2.0 | | Transitive runtime dependency of `wasm-bindgen`. | ## Build-only dependencies @@ -21,7 +25,13 @@ | `quote` | `1.0.47` | MIT OR Apache-2.0 | | Transitive procedural-macro build dependency. | | `syn` | `3.0.4` | MIT OR Apache-2.0 | | Transitive procedural-macro build dependency. | | `unicode-ident` | `1.0.24` | (MIT OR Apache-2.0) AND Unicode-3.0 | | Transitive procedural-macro build dependency. | +| `wasm-bindgen-macro` / `wasm-bindgen-macro-support` | `0.2.127` | MIT OR Apache-2.0 | | Procedural macro and support code used to build the browser adapter. | +| `bumpalo` | `3.20.3` | MIT OR Apache-2.0 | | Transitive build dependency of `wasm-bindgen-macro-support`. | +| `rustversion` | `1.0.23` | MIT OR Apache-2.0 | | Transitive build dependency of `wasm-bindgen`. | +| `syn` | `2.0.119` | MIT OR Apache-2.0 | | Transitive procedural-macro build dependency of `wasm-bindgen`. | +| `wasm-bindgen-cli` | `0.2.127` | MIT OR Apache-2.0 | | Version-matched build tool; not shipped in the npm package. | +| `typescript` | `7.0.2` | Apache-2.0 | | Type-check tool; not shipped in the npm package. | -No third-party asset is bundled in a Stack Engine distribution yet. +No third-party visual asset is bundled in a Stack Engine distribution. The npm package includes this inventory and the Apache-2.0, MIT, and Unicode-3.0 license texts required by its compiled dependency choices. Before publishing a native library, binary-derived artifact, or WASM package, this inventory must list the shipped dependencies and assets, their pinned versions, exact licenses, required license texts, attribution, modifications, and redistribution conditions. Build-only dependencies that are not shipped should be distinguished from distributed code. diff --git a/crates/stack-engine-wasm/Cargo.toml b/crates/stack-engine-wasm/Cargo.toml new file mode 100644 index 0000000..86fe670 --- /dev/null +++ b/crates/stack-engine-wasm/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "stack-engine-wasm" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +description = "Browser WebAssembly adapter for Stack diagram operations" + +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +serde.workspace = true +stack-engine = { path = "../stack-engine" } + +[target.'cfg(target_arch = "wasm32")'.dependencies] +js-sys = { version = "=0.3.104", default-features = false } +wasm-bindgen = "=0.2.127" + +[dev-dependencies] +serde_json.workspace = true + +[lints.clippy] +expect_used = "deny" +panic = "deny" +todo = "deny" +unimplemented = "deny" +unreachable = "deny" +unwrap_used = "deny" diff --git a/crates/stack-engine-wasm/examples/native-parity.rs b/crates/stack-engine-wasm/examples/native-parity.rs new file mode 100644 index 0000000..8c3e541 --- /dev/null +++ b/crates/stack-engine-wasm/examples/native-parity.rs @@ -0,0 +1,59 @@ +use std::error::Error; +use std::path::PathBuf; + +use serde::{Deserialize, Serialize}; +use stack_engine_wasm::{CheckResult, FormatResult, RenderResult}; + +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct FixtureCase { + name: String, + input: FixtureInput, +} + +#[derive(Deserialize)] +#[serde(tag = "kind", rename_all = "camelCase")] +enum FixtureInput { + String { value: String }, + Bytes { value: Vec }, +} + +impl FixtureInput { + fn bytes(&self) -> &[u8] { + match self { + Self::String { value } => value.as_bytes(), + Self::Bytes { value } => value, + } + } +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct FixtureOutput { + name: String, + format: FormatResult, + check: CheckResult, + render: RenderResult, +} + +fn main() -> Result<(), Box> { + let path = std::env::args_os() + .nth(1) + .map(PathBuf::from) + .ok_or("usage: native-parity ")?; + let cases = serde_json::from_slice::>(&std::fs::read(path)?)?; + let outputs = cases + .into_iter() + .map(|case| { + let source = case.input.bytes(); + Ok(FixtureOutput { + name: case.name, + format: stack_engine_wasm::format_bytes(source)?, + check: stack_engine_wasm::check_bytes(source)?, + render: stack_engine_wasm::render_bytes(source)?, + }) + }) + .collect::, stack_engine::OperationalError>>()?; + println!("{}", serde_json::to_string(&outputs)?); + Ok(()) +} diff --git a/crates/stack-engine-wasm/src/lib.rs b/crates/stack-engine-wasm/src/lib.rs new file mode 100644 index 0000000..64033b1 --- /dev/null +++ b/crates/stack-engine-wasm/src/lib.rs @@ -0,0 +1,567 @@ +//! Typed browser adapter for the pure Stack engine. +//! +//! The Rust helpers expose the exact serializable result model used by the +//! WebAssembly boundary. The browser exports are generated only for +//! `wasm32-unknown-unknown` and accept either a JavaScript string or +//! `Uint8Array` without introducing filesystem, network, DOM, or clock access. + +#![forbid(unsafe_code)] +#![deny(missing_docs)] + +use serde::Serialize; +use stack_engine::{Engine, OperationResult}; + +#[cfg(target_arch = "wasm32")] +use js_sys::{Array, Object, Reflect, TypeError, Uint8Array}; +#[cfg(target_arch = "wasm32")] +use wasm_bindgen::{JsCast, JsValue, prelude::wasm_bindgen}; + +/// JavaScript-facing result of the format operation. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct FormatResult { + /// Canonical source, absent after encoding, lexical, or syntax failure. + pub formatted_source: Option, + /// Ordered portable diagnostics. + pub diagnostics: Vec, + /// Engine and input provenance. + pub metadata: EngineMetadata, +} + +/// JavaScript-facing result of the check operation. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct CheckResult { + /// Ordered portable diagnostics. + pub diagnostics: Vec, + /// Engine and input provenance. + pub metadata: EngineMetadata, +} + +/// JavaScript-facing result of the render operation. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RenderResult { + /// Standalone SVG, absent whenever an error diagnostic prevents rendering. + pub svg: Option, + /// Ordered portable diagnostics. + pub diagnostics: Vec, + /// Engine and input provenance. + pub metadata: EngineMetadata, +} + +/// Version metadata attached to every operation result. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct EngineMetadata { + /// Semantic version of `stack-engine`. + pub engine_version: String, + /// Authored language version, absent when parsing cannot recover it. + pub language_version: Option, + /// Semantic version of the theme catalog. + pub theme_catalog_version: String, + /// Content revision of the theme catalog and icon bytes. + pub theme_catalog_revision: String, +} + +/// Authored Stack language version. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct LanguageVersion { + /// Major language version. + pub major: u32, + /// Minor language version. + pub minor: u32, +} + +/// Portable diagnostic shared with native engine consumers. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Diagnostic { + /// Stable Stack diagnostic identifier. + pub code: String, + /// Whether the diagnostic prevents the requested artifact. + pub severity: Severity, + /// Human-readable diagnostic description. + pub message: String, + /// Primary end-exclusive source range. + pub range: SourceRange, + /// Optional corrective guidance. + pub help: Option, + /// Other source locations involved in the diagnostic. + pub related: Vec, +} + +/// Diagnostic severity. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum Severity { + /// Prevents the requested artifact. + Error, + /// Preserves successful output while reporting actionable information. + Warning, +} + +/// Additional source context related to a diagnostic. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct RelatedInformation { + /// Description of the related source location. + pub message: String, + /// End-exclusive related source range. + pub range: SourceRange, +} + +/// End-exclusive source range. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SourceRange { + /// Inclusive source position. + pub start: SourcePosition, + /// Exclusive source position. + pub end: SourcePosition, +} + +/// One-based line and column with a zero-based UTF-8 byte offset. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct SourcePosition { + /// Zero-based UTF-8 byte offset. + pub byte_offset: u64, + /// One-based source line. + pub line: u64, + /// One-based Unicode scalar column. + pub column: u64, +} + +/// Formats caller-owned source bytes through the bundled pure engine. +pub fn format_bytes(source: &[u8]) -> OperationResult { + Engine::bundled().format(source).map(FormatResult::from) +} + +/// Checks caller-owned source bytes through the bundled pure engine. +pub fn check_bytes(source: &[u8]) -> OperationResult { + Engine::bundled().check(source).map(CheckResult::from) +} + +/// Renders caller-owned source bytes through the bundled pure engine. +pub fn render_bytes(source: &[u8]) -> OperationResult { + Engine::bundled().render(source).map(RenderResult::from) +} + +impl From for FormatResult { + fn from(output: stack_engine::FormatOutput) -> Self { + Self { + formatted_source: output.formatted_source, + diagnostics: output + .diagnostics + .into_iter() + .map(Diagnostic::from) + .collect(), + metadata: EngineMetadata::from(output.metadata), + } + } +} + +impl From for CheckResult { + fn from(output: stack_engine::CheckOutput) -> Self { + Self { + diagnostics: output + .diagnostics + .into_iter() + .map(Diagnostic::from) + .collect(), + metadata: EngineMetadata::from(output.metadata), + } + } +} + +impl From for RenderResult { + fn from(output: stack_engine::RenderOutput) -> Self { + Self { + svg: output.svg, + diagnostics: output + .diagnostics + .into_iter() + .map(Diagnostic::from) + .collect(), + metadata: EngineMetadata::from(output.metadata), + } + } +} + +impl From for EngineMetadata { + fn from(metadata: stack_engine::EngineMetadata) -> Self { + Self { + engine_version: metadata.engine_version, + language_version: metadata.language_version.map(LanguageVersion::from), + theme_catalog_version: metadata.theme_catalog_version, + theme_catalog_revision: metadata.theme_catalog_revision, + } + } +} + +impl From for LanguageVersion { + fn from(version: stack_engine::LanguageVersion) -> Self { + Self { + major: version.major, + minor: version.minor, + } + } +} + +impl From for Diagnostic { + fn from(diagnostic: stack_engine::Diagnostic) -> Self { + Self { + code: diagnostic.code, + severity: Severity::from(diagnostic.severity), + message: diagnostic.message, + range: SourceRange::from(diagnostic.range), + help: diagnostic.help, + related: diagnostic + .related + .into_iter() + .map(RelatedInformation::from) + .collect(), + } + } +} + +impl From for Severity { + fn from(severity: stack_engine::Severity) -> Self { + match severity { + stack_engine::Severity::Error => Self::Error, + stack_engine::Severity::Warning => Self::Warning, + } + } +} + +impl From for RelatedInformation { + fn from(related: stack_engine::RelatedInformation) -> Self { + Self { + message: related.message, + range: SourceRange::from(related.range), + } + } +} + +impl From for SourceRange { + fn from(range: stack_engine::SourceRange) -> Self { + Self { + start: SourcePosition::from(range.start), + end: SourcePosition::from(range.end), + } + } +} + +impl From for SourcePosition { + fn from(position: stack_engine::SourcePosition) -> Self { + Self { + byte_offset: position.byte_offset, + line: position.line, + column: position.column, + } + } +} + +#[cfg(target_arch = "wasm32")] +#[wasm_bindgen(typescript_custom_section)] +const TYPESCRIPT_TYPES: &'static str = r#" +export type StackSource = string | Uint8Array; +export type Severity = "error" | "warning"; + +export interface SourcePosition { + readonly byteOffset: number; + readonly line: number; + readonly column: number; +} + +export interface SourceRange { + readonly start: SourcePosition; + readonly end: SourcePosition; +} + +export interface RelatedInformation { + readonly message: string; + readonly range: SourceRange; +} + +export interface Diagnostic { + readonly code: string; + readonly severity: Severity; + readonly message: string; + readonly range: SourceRange; + readonly help: string | null; + readonly related: readonly RelatedInformation[]; +} + +export interface LanguageVersion { + readonly major: number; + readonly minor: number; +} + +export interface EngineMetadata { + readonly engineVersion: string; + readonly languageVersion: LanguageVersion | null; + readonly themeCatalogVersion: string; + readonly themeCatalogRevision: string; +} + +export interface FormatResult { + readonly formattedSource: string | null; + readonly diagnostics: readonly Diagnostic[]; + readonly metadata: EngineMetadata; +} + +export interface CheckResult { + readonly diagnostics: readonly Diagnostic[]; + readonly metadata: EngineMetadata; +} + +export interface RenderResult { + readonly svg: string | null; + readonly diagnostics: readonly Diagnostic[]; + readonly metadata: EngineMetadata; +} + +export function format(source: StackSource): FormatResult; +export function check(source: StackSource): CheckResult; +export function render(source: StackSource): RenderResult; +"#; + +#[cfg(target_arch = "wasm32")] +/// Formats a JavaScript string or `Uint8Array` into the typed browser result. +#[wasm_bindgen(js_name = format, skip_typescript)] +pub fn format_js(source: JsValue) -> Result { + format_bytes(&source_bytes(source)?) + .map_err(operation_error) + .and_then(format_to_js) +} + +#[cfg(target_arch = "wasm32")] +/// Checks a JavaScript string or `Uint8Array` into the typed browser result. +#[wasm_bindgen(js_name = check, skip_typescript)] +pub fn check_js(source: JsValue) -> Result { + check_bytes(&source_bytes(source)?) + .map_err(operation_error) + .and_then(check_to_js) +} + +#[cfg(target_arch = "wasm32")] +/// Renders a JavaScript string or `Uint8Array` into the typed browser result. +#[wasm_bindgen(js_name = render, skip_typescript)] +pub fn render_js(source: JsValue) -> Result { + render_bytes(&source_bytes(source)?) + .map_err(operation_error) + .and_then(render_to_js) +} + +#[cfg(target_arch = "wasm32")] +fn source_bytes(source: JsValue) -> Result, JsValue> { + if let Some(source) = source.as_string() { + return Ok(source.into_bytes()); + } + if source.is_instance_of::() { + return Ok(Uint8Array::new(&source).to_vec()); + } + Err(TypeError::new("Stack source must be a string or Uint8Array").into()) +} + +#[cfg(target_arch = "wasm32")] +fn operation_error(error: stack_engine::OperationalError) -> JsValue { + js_sys::Error::new(&error.to_string()).into() +} + +#[cfg(target_arch = "wasm32")] +fn format_to_js(result: FormatResult) -> Result { + let output = Object::new(); + set_optional_string(&output, "formattedSource", result.formatted_source)?; + set( + &output, + "diagnostics", + diagnostics_to_js(result.diagnostics)?, + )?; + set(&output, "metadata", metadata_to_js(result.metadata)?)?; + Ok(output.into()) +} + +#[cfg(target_arch = "wasm32")] +fn check_to_js(result: CheckResult) -> Result { + let output = Object::new(); + set( + &output, + "diagnostics", + diagnostics_to_js(result.diagnostics)?, + )?; + set(&output, "metadata", metadata_to_js(result.metadata)?)?; + Ok(output.into()) +} + +#[cfg(target_arch = "wasm32")] +fn render_to_js(result: RenderResult) -> Result { + let output = Object::new(); + set_optional_string(&output, "svg", result.svg)?; + set( + &output, + "diagnostics", + diagnostics_to_js(result.diagnostics)?, + )?; + set(&output, "metadata", metadata_to_js(result.metadata)?)?; + Ok(output.into()) +} + +#[cfg(target_arch = "wasm32")] +fn diagnostics_to_js(diagnostics: Vec) -> Result { + let output = Array::new(); + for diagnostic in diagnostics { + output.push(&diagnostic_to_js(diagnostic)?); + } + Ok(output.into()) +} + +#[cfg(target_arch = "wasm32")] +fn diagnostic_to_js(diagnostic: Diagnostic) -> Result { + let output = Object::new(); + set(&output, "code", diagnostic.code.into())?; + set( + &output, + "severity", + match diagnostic.severity { + Severity::Error => JsValue::from_str("error"), + Severity::Warning => JsValue::from_str("warning"), + }, + )?; + set(&output, "message", diagnostic.message.into())?; + set(&output, "range", range_to_js(diagnostic.range)?)?; + set_optional_string(&output, "help", diagnostic.help)?; + let related = Array::new(); + for information in diagnostic.related { + let item = Object::new(); + set(&item, "message", information.message.into())?; + set(&item, "range", range_to_js(information.range)?)?; + related.push(&item); + } + set(&output, "related", related.into())?; + Ok(output.into()) +} + +#[cfg(target_arch = "wasm32")] +fn metadata_to_js(metadata: EngineMetadata) -> Result { + let output = Object::new(); + set(&output, "engineVersion", metadata.engine_version.into())?; + set( + &output, + "languageVersion", + metadata + .language_version + .map_or(Ok(JsValue::NULL), |version| { + let value = Object::new(); + set(&value, "major", JsValue::from(version.major))?; + set(&value, "minor", JsValue::from(version.minor))?; + Ok::(value.into()) + })?, + )?; + set( + &output, + "themeCatalogVersion", + metadata.theme_catalog_version.into(), + )?; + set( + &output, + "themeCatalogRevision", + metadata.theme_catalog_revision.into(), + )?; + Ok(output.into()) +} + +#[cfg(target_arch = "wasm32")] +fn range_to_js(range: SourceRange) -> Result { + let output = Object::new(); + set(&output, "start", position_to_js(range.start)?)?; + set(&output, "end", position_to_js(range.end)?)?; + Ok(output.into()) +} + +#[cfg(target_arch = "wasm32")] +fn position_to_js(position: SourcePosition) -> Result { + let output = Object::new(); + set( + &output, + "byteOffset", + JsValue::from_f64(position.byte_offset as f64), + )?; + set(&output, "line", JsValue::from_f64(position.line as f64))?; + set(&output, "column", JsValue::from_f64(position.column as f64))?; + Ok(output.into()) +} + +#[cfg(target_arch = "wasm32")] +fn set_optional_string(object: &Object, name: &str, value: Option) -> Result<(), JsValue> { + set(object, name, value.map_or(JsValue::NULL, JsValue::from)) +} + +#[cfg(target_arch = "wasm32")] +fn set(object: &Object, name: &str, value: JsValue) -> Result<(), JsValue> { + Reflect::set(object, &JsValue::from_str(name), &value).map(|_| ()) +} + +#[cfg(test)] +mod tests { + use std::error::Error; + + use super::{Diagnostic, Severity, check_bytes, format_bytes, render_bytes}; + + #[test] + fn native_results_keep_operation_shapes_and_invalid_utf8() -> Result<(), Box> { + let source = b"stack 1.0 diagram \"API\" { node api \"API\" }"; + let formatted = format_bytes(source)?; + let checked = check_bytes(source)?; + let rendered = render_bytes(source)?; + assert!(formatted.formatted_source.is_some()); + assert!(checked.diagnostics.is_empty()); + assert!(rendered.svg.is_some()); + assert_eq!(formatted.metadata, checked.metadata); + assert_eq!(checked.metadata, rendered.metadata); + + for diagnostics in [ + format_bytes(b"\xff")?.diagnostics, + check_bytes(b"\xff")?.diagnostics, + render_bytes(b"\xff")?.diagnostics, + ] { + assert_eq!(diagnostics[0].code, "STK1001"); + assert_eq!(diagnostics[0].severity, Severity::Error); + } + Ok(()) + } + + #[test] + fn conversion_keeps_warning_help_and_related_information() { + let range = stack_engine::SourceRange { + start: stack_engine::SourcePosition { + byte_offset: 1, + line: 1, + column: 2, + }, + end: stack_engine::SourcePosition { + byte_offset: 4, + line: 1, + column: 5, + }, + }; + let converted = Diagnostic::from(stack_engine::Diagnostic { + code: "STK5001".to_owned(), + severity: stack_engine::Severity::Warning, + message: "fallback used".to_owned(), + range, + help: Some("install the resource".to_owned()), + related: vec![stack_engine::RelatedInformation { + message: "requested here".to_owned(), + range, + }], + }); + assert_eq!(converted.severity, Severity::Warning); + assert_eq!(converted.help.as_deref(), Some("install the resource")); + assert_eq!(converted.related[0].message, "requested here"); + assert_eq!(converted.related[0].range.start.byte_offset, 1); + } +} diff --git a/docs/decisions/0006-expose-one-typed-browser-wasm-adapter.md b/docs/decisions/0006-expose-one-typed-browser-wasm-adapter.md new file mode 100644 index 0000000..fc9e6c4 --- /dev/null +++ b/docs/decisions/0006-expose-one-typed-browser-wasm-adapter.md @@ -0,0 +1,25 @@ +# ADR-0006: Expose one typed browser WebAssembly adapter + +## Status + +Accepted + +## Context + +Browser consumers need the same formatting, checking, rendering, diagnostic ordering, and provenance as native consumers. Reimplementing any compiler or renderer stage in JavaScript would create a second contract and allow target drift. A generic `any` interface would also hide the distinction between normal Stack diagnostics and adapter misuse. + +## Decision + +Add `stack-engine-wasm` as a thin `wasm32-unknown-unknown` adapter over `stack-engine` and package its generated web bindings as `@stack-sh/engine`. Export synchronous `format`, `check`, and `render` operations after module initialization. Each operation accepts only a JavaScript `string` or `Uint8Array` and returns an operation-specific TypeScript result. Preserve nullable artifacts, ordered portable diagnostics, camel-case source positions, and engine / language / catalog metadata. + +Validate input type only at the JavaScript boundary. Pass strings as UTF-8 bytes and byte arrays unchanged to the native byte-oriented facade. Invalid Stack bytes, including invalid UTF-8, remain normal diagnostic results. Unsupported JavaScript values throw `TypeError`; engine operational failures throw `Error`. + +Keep object conversion in the adapter and all language, formatting, layout, routing, and SVG behavior in `stack-engine`. Generate web-target ECMAScript bindings with a version-matched `wasm-bindgen` library and CLI. Do not import WASI, filesystem, network, DOM, clock, random, or host-font capabilities into the WebAssembly module. + +## Consequences + +- Native and browser behavior can be compared as complete operation results over one shared fixture set. +- TypeScript consumers receive explicit input, diagnostic, metadata, and operation-result contracts instead of `any`. +- The npm artifact contains generated JavaScript glue, declarations, WebAssembly, package documentation, and the Apache-2.0 license. +- Consumers own module loading and every host interaction outside the pure operations. +- The Rust library version, `wasm-bindgen` CLI version, generated binding files, import allowlist, and package contents must be verified together before publication. diff --git a/docs/dependency-audit.md b/docs/dependency-audit.md index 15e3970..170d6b4 100644 --- a/docs/dependency-audit.md +++ b/docs/dependency-audit.md @@ -10,6 +10,8 @@ Audit date: 2026-09-03 - the workspace-local `stack-formatter` for canonical source output; - `stack-theme` at `ed6c500762fc9ccffc8777172ac672a716dcd916` for the embedded core catalog, SVG bytes, deterministic font metrics, catalog version, and catalog revision. +`stack-engine-wasm` adds `serde` for its serializable native parity model and, only on `wasm32`, version-matched `wasm-bindgen` and `js-sys` for the JavaScript ABI, typed-array input, and plain object construction. It does not use `web-sys` or a WASI target. + The resolved normal dependency graph adds only the `serde` and `serde_json` graph required by `stack-theme`. Exact versions and licenses are recorded in [`THIRD_PARTY_LICENSES.md`](../THIRD_PARTY_LICENSES.md) and pinned in `Cargo.lock`. Scene layout is implemented locally with fixed-width integer arithmetic and versioned catalog metrics. Standalone SVG serialization is also local and embeds only validated catalog icon bodies and local marker references. No third-party layout or SVG serializer, filesystem, network, asynchronous runtime, random, clock, locale, DOM, or platform-font dependency is present. ## Runtime access boundary @@ -18,6 +20,7 @@ The resolved normal dependency graph adds only the `serde` and `serde_json` grap - `stack-compiler` and `stack-formatter` operate entirely on caller-owned bytes and in-memory values. - `stack-theme` embeds catalog, schema, and SVG bytes at compile time and parses the trusted generated catalog through an in-memory singleton. - No runtime dependency discovers a path, opens a socket, reads process state, observes time, samples randomness, queries a DOM, or measures a system font. +- The generated WebAssembly imports only the audited `wasm-bindgen` object, string, array, typed-array, exception, and extern-reference glue from its sibling JavaScript module. The import validator rejects WASI and names associated with filesystem, network, DOM, clock, random, process, environment, or storage capabilities. Tests and CI may read the pinned specification checkout and invoke toolchains. Those development actions are outside the runtime library boundary. @@ -29,7 +32,12 @@ cargo metadata --format-version 1 --locked cargo test --workspace --locked STACK_SPECIFICATION_DIR=../specification cargo test -p stack-engine --features conformance --locked python3 scripts/validate-svg.py -cargo build -p stack-engine --target wasm32-unknown-unknown --locked +cargo build -p stack-engine-wasm --target wasm32-unknown-unknown --release --locked +npm ci +npm run build:wasm +npm test +npm run typecheck +npm run pack:check CARGO_TARGET_WASM32_WASIP1_RUNNER=wasmtime cargo test -p stack-engine --lib --target wasm32-wasip1 cross_target_numeric_fixture --locked cargo clippy --workspace --all-targets --all-features --locked -- -D warnings ``` diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..05baf3b --- /dev/null +++ b/package-lock.json @@ -0,0 +1,402 @@ +{ + "name": "stack-engine-workspace", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "stack-engine-workspace", + "version": "0.1.0", + "workspaces": [ + "packages/engine" + ], + "devDependencies": { + "typescript": "7.0.2" + } + }, + "node_modules/@stack-sh/engine": { + "resolved": "packages/engine", + "link": true + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "packages/engine": { + "name": "@stack-sh/engine", + "version": "0.1.0", + "license": "Apache-2.0" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..2ca8a52 --- /dev/null +++ b/package.json @@ -0,0 +1,17 @@ +{ + "name": "stack-engine-workspace", + "private": true, + "version": "0.1.0", + "workspaces": [ + "packages/engine" + ], + "scripts": { + "build:wasm": "bash scripts/build-wasm.sh", + "pack:check": "node scripts/validate-npm-pack.mjs", + "test": "node --test tests/wasm.test.mjs && node scripts/validate-wasm-package.mjs", + "typecheck": "tsc --project tsconfig.json" + }, + "devDependencies": { + "typescript": "7.0.2" + } +} diff --git a/packages/engine/LICENSE b/packages/engine/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/packages/engine/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/engine/README.md b/packages/engine/README.md new file mode 100644 index 0000000..f10fe08 --- /dev/null +++ b/packages/engine/README.md @@ -0,0 +1,17 @@ +# `@stack-sh/engine` + +Browser WebAssembly adapter for the pure Stack diagram engine. + +```js +import init, { check, format, render } from "@stack-sh/engine"; + +await init(); + +const formatted = format('stack 1.0 diagram "API" { node api "API" }'); +const checked = check(new TextEncoder().encode('stack 1.0 diagram "API" { node api "API" }')); +const rendered = render('stack 1.0 diagram "API" { node api "API" }'); +``` + +Each operation is synchronous after module initialization and accepts either a JavaScript string or `Uint8Array`. Invalid Stack source, including invalid UTF-8 bytes, returns normal portable diagnostics. A JavaScript value of any other type throws `TypeError` at the package boundary. + +The package does not read files, contact a network service, inspect the DOM, observe a clock, or measure host fonts. Consumers own module loading and all host I/O. diff --git a/packages/engine/THIRD_PARTY_LICENSES.md b/packages/engine/THIRD_PARTY_LICENSES.md new file mode 100644 index 0000000..283f3b2 --- /dev/null +++ b/packages/engine/THIRD_PARTY_LICENSES.md @@ -0,0 +1,20 @@ +# Third-party licenses + +`@stack-sh/engine` contains compiled code from these components. For dual-licensed components, this distribution selects Apache-2.0 except where another license is listed. + +| Component | Version / revision | Selected license | Source | +| --- | --- | --- | --- | +| `stack-compiler` | `17a0abe9c35e641761ff08fdf59b29a42828d9fd` | Apache-2.0 | | +| `stack-theme` | `ed6c500762fc9ccffc8777172ac672a716dcd916` | Apache-2.0 | | +| `serde` / `serde_core` | `1.0.229` | Apache-2.0 | | +| `serde_json` | `1.0.151` | Apache-2.0 | | +| `itoa` | `1.0.18` | Apache-2.0 | | +| `memchr` | `2.8.3` | MIT | | +| `zmij` | `1.0.23` | MIT | | +| `wasm-bindgen` / `wasm-bindgen-shared` | `0.2.127` | Apache-2.0 | | +| `js-sys` | `0.3.104` | Apache-2.0 | | +| `cfg-if` | `1.0.4` | Apache-2.0 | | +| `once_cell` | `1.21.4` | Apache-2.0 | | +| `unicode-ident` | `1.0.24` | Apache-2.0 AND Unicode-3.0 | | + +The Apache-2.0 text is in [`LICENSE`](./LICENSE), the MIT text is in [`licenses/MIT.txt`](./licenses/MIT.txt), and the Unicode-3.0 text is in [`licenses/Unicode-3.0.txt`](./licenses/Unicode-3.0.txt). diff --git a/packages/engine/index.d.ts b/packages/engine/index.d.ts new file mode 100644 index 0000000..47902d4 --- /dev/null +++ b/packages/engine/index.d.ts @@ -0,0 +1,2 @@ +export { default } from "./dist/stack_engine.js"; +export * from "./dist/stack_engine.js"; diff --git a/packages/engine/index.js b/packages/engine/index.js new file mode 100644 index 0000000..47902d4 --- /dev/null +++ b/packages/engine/index.js @@ -0,0 +1,2 @@ +export { default } from "./dist/stack_engine.js"; +export * from "./dist/stack_engine.js"; diff --git a/packages/engine/licenses/MIT.txt b/packages/engine/licenses/MIT.txt new file mode 100644 index 0000000..31aa793 --- /dev/null +++ b/packages/engine/licenses/MIT.txt @@ -0,0 +1,23 @@ +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/packages/engine/licenses/Unicode-3.0.txt b/packages/engine/licenses/Unicode-3.0.txt new file mode 100644 index 0000000..11f2842 --- /dev/null +++ b/packages/engine/licenses/Unicode-3.0.txt @@ -0,0 +1,39 @@ +UNICODE LICENSE V3 + +COPYRIGHT AND PERMISSION NOTICE + +Copyright © 1991-2023 Unicode, Inc. + +NOTICE TO USER: Carefully read the following legal agreement. BY +DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR +SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE +TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT +DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of data files and any associated documentation (the "Data Files") or +software and any associated documentation (the "Software") to deal in the +Data Files or Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, and/or sell +copies of the Data Files or Software, and to permit persons to whom the +Data Files or Software are furnished to do so, provided that either (a) +this copyright and permission notice appear with all copies of the Data +Files or Software, or (b) this copyright and permission notice appear in +associated Documentation. + +THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY +KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +THIRD PARTY RIGHTS. + +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE +BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, +OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, +WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, +ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA +FILES OR SOFTWARE. + +Except as contained in this notice, the name of a copyright holder shall +not be used in advertising or otherwise to promote the sale, use or other +dealings in these Data Files or Software without prior written +authorization of the copyright holder. diff --git a/packages/engine/package.json b/packages/engine/package.json new file mode 100644 index 0000000..e869446 --- /dev/null +++ b/packages/engine/package.json @@ -0,0 +1,32 @@ +{ + "name": "@stack-sh/engine", + "version": "0.1.0", + "description": "Browser WebAssembly adapter for Stack diagram operations", + "type": "module", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/stack-sh/engine.git" + }, + "sideEffects": false, + "types": "./index.d.ts", + "exports": { + ".": { + "types": "./index.d.ts", + "import": "./index.js", + "default": "./index.js" + } + }, + "files": [ + "dist", + "index.d.ts", + "index.js", + "LICENSE", + "licenses", + "README.md", + "THIRD_PARTY_LICENSES.md" + ], + "publishConfig": { + "access": "public" + } +} diff --git a/review/wasm.html b/review/wasm.html new file mode 100644 index 0000000..a286351 --- /dev/null +++ b/review/wasm.html @@ -0,0 +1,54 @@ + + + + + + Stack Engine WASM Review + + + +
+

Stack Engine WASM Review

+

Loading the browser module…

+

+    
+ + + diff --git a/scripts/build-wasm.sh b/scripts/build-wasm.sh new file mode 100644 index 0000000..d03ccc1 --- /dev/null +++ b/scripts/build-wasm.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash + +set -euo pipefail + +repository_root=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) +distribution="$repository_root/packages/engine/dist" + +if [[ "$distribution" != "$repository_root/packages/engine/dist" ]]; then + echo "refusing to clean an unexpected distribution path" >&2 + exit 1 +fi + +wasm_bindgen_version=$(wasm-bindgen --version) +if [[ "$wasm_bindgen_version" != "wasm-bindgen 0.2.127" ]]; then + echo "wasm-bindgen 0.2.127 is required" >&2 + exit 1 +fi + +rm -rf "$distribution" +mkdir -p "$distribution" + +cd "$repository_root" +cargo +stable build -p stack-engine-wasm --release --target wasm32-unknown-unknown --locked +wasm-bindgen \ + target/wasm32-unknown-unknown/release/stack_engine_wasm.wasm \ + --out-dir "$distribution" \ + --out-name stack_engine \ + --target web \ + --typescript \ + --no-demangle diff --git a/scripts/validate-npm-pack.mjs b/scripts/validate-npm-pack.mjs new file mode 100644 index 0000000..29af62c --- /dev/null +++ b/scripts/validate-npm-pack.mjs @@ -0,0 +1,30 @@ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; + +const packages = JSON.parse( + execFileSync( + "npm", + ["pack", "--dry-run", "--json", "--workspace", "@stack-sh/engine"], + { encoding: "utf8" }, + ), +); +assert.equal(packages.length, 1); +assert.equal(packages[0].name, "@stack-sh/engine"); +assert.deepEqual( + packages[0].files.map(({ path }) => path).sort(), + [ + "LICENSE", + "README.md", + "THIRD_PARTY_LICENSES.md", + "dist/stack_engine.d.ts", + "dist/stack_engine.js", + "dist/stack_engine_bg.wasm", + "dist/stack_engine_bg.wasm.d.ts", + "index.d.ts", + "index.js", + "licenses/MIT.txt", + "licenses/Unicode-3.0.txt", + "package.json", + ], +); +console.log(`validated ${packages[0].entryCount} npm package entries`); diff --git a/scripts/validate-wasm-package.mjs b/scripts/validate-wasm-package.mjs new file mode 100644 index 0000000..5ee6523 --- /dev/null +++ b/scripts/validate-wasm-package.mjs @@ -0,0 +1,50 @@ +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; + +const packageRoot = new URL("../packages/engine/", import.meta.url); +const repositoryRoot = new URL("../", import.meta.url); +const packageDocument = JSON.parse(readFileSync(new URL("package.json", packageRoot), "utf8")); +const declaration = readFileSync(new URL("dist/stack_engine.d.ts", packageRoot), "utf8"); +const glue = readFileSync(new URL("dist/stack_engine.js", packageRoot), "utf8"); +const binary = readFileSync(new URL("dist/stack_engine_bg.wasm", packageRoot)); + +assert.equal(packageDocument.name, "@stack-sh/engine"); +assert.equal(packageDocument.license, "Apache-2.0"); +assert.equal(packageDocument.exports["."].types, "./index.d.ts"); +assert.equal( + readFileSync(new URL("LICENSE", packageRoot), "utf8"), + readFileSync(new URL("LICENSE", repositoryRoot), "utf8"), +); +assert.match(declaration, /export type StackSource = string \| Uint8Array;/); +assert.match(declaration, /export function format\(source: StackSource\): FormatResult;/); +assert.match(declaration, /export function check\(source: StackSource\): CheckResult;/); +assert.match(declaration, /export function render\(source: StackSource\): RenderResult;/); + +const module = new WebAssembly.Module(binary); +const imports = WebAssembly.Module.imports(module); +const forbiddenCapability = /(fetch|xmlhttprequest|websocket|document|window|navigator|location|storage|date|performance|crypto|random|timer|timeout|interval|process|require|filesystem|wasi|path|environment|clock)/i; +for (const imported of imports) { + assert.equal(imported.module, "./stack_engine_bg.js"); + assert.match(imported.name, /^__(?:wbindgen|wbg)_/); + assert.doesNotMatch(imported.name, forbiddenCapability); +} + +const importGlueStart = glue.indexOf("function __wbg_get_imports()"); +const importGlueEnd = glue.indexOf("function addToExternrefTable0", importGlueStart); +assert.notEqual(importGlueStart, -1); +assert.notEqual(importGlueEnd, -1); +const importGlue = glue.slice(importGlueStart, importGlueEnd); +assert.doesNotMatch( + importGlue, + /\b(?:eval|Function|fetch|XMLHttpRequest|WebSocket|document|window|navigator|location|localStorage|sessionStorage|Date|performance|crypto|process|require|setTimeout|setInterval)\b/, +); +for (const requiredPrimitive of ["Array", "Error", "Object", "Reflect", "TypeError", "Uint8Array"]) { + assert.match(importGlue, new RegExp(`\\b${requiredPrimitive}\\b`)); +} + +const exports = new Set(WebAssembly.Module.exports(module).map(({ name }) => name)); +for (const operation of ["format", "check", "render"]) { + assert.ok(exports.has(operation), `missing ${operation} WebAssembly export`); +} + +console.log(`validated ${imports.length} capability-limited WebAssembly imports`); diff --git a/tests/fixtures/operation-cases.json b/tests/fixtures/operation-cases.json new file mode 100644 index 0000000..460473b --- /dev/null +++ b/tests/fixtures/operation-cases.json @@ -0,0 +1,23 @@ +[ + { + "name": "valid-string", + "input": { + "kind": "string", + "value": "stack 1.0 diagram \"API\" { node web \"Web\" edge web -> api \"HTTPS\" node api \"API\" }" + } + }, + { + "name": "warning-string", + "input": { + "kind": "string", + "value": "stack 1.0 diagram \"Fallback\" { theme neon node api \"API\" { icon \"missing\" } }" + } + }, + { + "name": "invalid-utf8-bytes", + "input": { + "kind": "bytes", + "value": [255] + } + } +] diff --git a/tests/types.test.ts b/tests/types.test.ts new file mode 100644 index 0000000..6fa2f4a --- /dev/null +++ b/tests/types.test.ts @@ -0,0 +1,27 @@ +import init, { + check, + format, + render, + type CheckResult, + type Diagnostic, + type FormatResult, + type RenderResult, + type StackSource, +} from "@stack-sh/engine"; + +const text: StackSource = 'stack 1.0 diagram "API" { node api "API" }'; +const bytes: StackSource = new TextEncoder().encode(text); + +const formatted: FormatResult = format(text); +const checked: CheckResult = check(bytes); +const rendered: RenderResult = render(text); +const diagnostic: Diagnostic | undefined = checked.diagnostics[0]; + +formatted.formattedSource?.toUpperCase(); +rendered.svg?.startsWith(" { + const source = browserInput(fixture.input); + return { + name: fixture.name, + format: format(source), + check: check(source), + render: render(source), + }; + }); +} + +test("browser exports match native engine results for shared fixtures", () => { + const native = JSON.parse( + execFileSync( + "cargo", + [ + "run", + "--quiet", + "--locked", + "-p", + "stack-engine-wasm", + "--example", + "native-parity", + "--", + fixturePath, + ], + { cwd: repositoryRoot, encoding: "utf8" }, + ), + ); + assert.deepEqual(wasmOutputs(), native); +}); + +test("invalid UTF-8 is a normal diagnostic result for every operation", () => { + const invalid = wasmOutputs().find(({ name }) => name === "invalid-utf8-bytes"); + assert.ok(invalid); + assert.equal(invalid.format.formattedSource, null); + assert.equal(invalid.render.svg, null); + for (const operation of [invalid.format, invalid.check, invalid.render]) { + assert.equal(operation.diagnostics[0].code, "STK1001"); + assert.equal(operation.diagnostics[0].severity, "error"); + assert.equal(operation.metadata.languageVersion, null); + } +}); + +test("the JavaScript boundary rejects unsupported source values consistently", () => { + for (const operation of [format, check, render]) { + assert.throws( + () => operation({ source: "not a supported boundary value" }), + { name: "TypeError", message: "Stack source must be a string or Uint8Array" }, + ); + } +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..01455ac --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "lib": ["ES2022", "DOM"], + "module": "ESNext", + "moduleResolution": "Bundler", + "noEmit": true, + "strict": true, + "target": "ES2022" + }, + "include": ["tests/types.test.ts"] +}