Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

feat(core): introduce Weirpacks (#2491)

Elijah Potter3a5cd68b1015
diff --git a/Cargo.lock b/Cargo.lock
index 84497db50..dbf289e00 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -740,7 +740,7 @@ dependencies = [
"thiserror 1.0.69",
"ug",
"yoke 0.7.5",
- "zip",
+ "zip 1.1.4",
]
[[package]]
@@ -2794,6 +2794,7 @@ dependencies = [
"unicode-blocks",
"unicode-script",
"unicode-width",
+ "zip 2.4.2",
]
[[package]]
@@ -7264,12 +7265,41 @@ dependencies = [
"thiserror 1.0.69",
]
+[[package]]
+name = "zip"
+version = "2.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fabe6324e908f85a1c52063ce7aa26b68dcb7eb6dbc83a2d148403c9bc3eba50"
+dependencies = [
+ "arbitrary",
+ "crc32fast",
+ "crossbeam-utils",
+ "displaydoc",
+ "flate2",
+ "indexmap",
+ "memchr",
+ "thiserror 2.0.18",
+ "zopfli",
+]
+
[[package]]
name = "zmij"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0f4a4e8e9dc5c62d159f04fcdbe07f4c3fb710415aab4754bf11505501e3251d"
+[[package]]
+name = "zopfli"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
+dependencies = [
+ "bumpalo",
+ "crc32fast",
+ "log",
+ "simd-adler32",
+]
+
[[package]]
name = "zstd"
version = "0.13.3"
diff --git a/harper-cli/src/lint.rs b/harper-cli/src/lint.rs
index f4e171118..53f3a0042 100644
--- a/harper-cli/src/lint.rs
+++ b/harper-cli/src/lint.rs
@@ -4,6 +4,7 @@ use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::{fs, process};
+use anyhow::Context;
use ariadne::{Color, Fmt, Label, Report, ReportKind, Source};
use hashbrown::HashMap;
use rayon::prelude::*;
@@ -12,6 +13,7 @@ use harper_core::{
linting::{Lint, LintGroup, LintGroupConfig, LintKind},
parsers::MarkdownOptions,
spell::{Dictionary, MergedDictionary, MutableDictionary},
+ weirpack::Weirpack,
{Dialect, DictWordMetadata, Document, Token, TokenKind, remove_overlaps_map},
};
@@ -34,6 +36,26 @@ fn load_dict(path: &Path) -> anyhow::Result<MutableDictionary> {
Ok(dict)
}
+fn load_weirpacks(inputs: &[SingleInput]) -> anyhow::Result<Vec<Weirpack>> {
+ let mut packs = Vec::new();
+ for input in inputs {
+ let Some(file) = input.try_as_file_ref() else {
+ anyhow::bail!(
+ "Weirpack inputs must be files, got {}",
+ input.get_identifier()
+ );
+ };
+
+ let path = file.path();
+ let bytes = fs::read(path)
+ .with_context(|| format!("Failed to read weirpack {}", path.display()))?;
+ let pack = Weirpack::from_bytes(&bytes)
+ .with_context(|| format!("Failed to load weirpack {}", path.display()))?;
+ packs.push(pack);
+ }
+ Ok(packs)
+}
+
/// Path version of harper-ls/src/dictionary_io@file_dict_name
fn file_dict_name(path: &Path) -> PathBuf {
let mut rewritten = String::new();
@@ -54,6 +76,7 @@ pub struct LintOptions {
pub only: Option<Vec<String>>,
pub keep_overlapping_lints: bool,
pub dialect: Dialect,
+ pub weirpack_inputs: Vec<SingleInput>,
}
enum ReportStyle {
FullAriadneLintReport,
@@ -96,6 +119,7 @@ pub fn lint(
ref mut ignore,
ref mut only,
dialect,
+ ref weirpack_inputs,
..
} = lint_options;
@@ -104,9 +128,16 @@ pub fn lint(
inputs.push(SingleInput::from(StdinInput).into());
}
+ let weirpacks = load_weirpacks(weirpack_inputs)?;
+
// Filter out any rules from ignore/only lists that don't exist in the current config
// Uses a cached config to avoid expensive linter initialization
- let config = LintGroupConfig::new_curated();
+ let mut config = LintGroupConfig::new_curated();
+ for pack in &weirpacks {
+ for rule in pack.rules.keys() {
+ config.set_rule_enabled(rule, true);
+ }
+ }
if let Some(only) = only {
only.retain(|rule| {
@@ -196,6 +227,7 @@ pub fn lint(
// Passed from the user for the `lint` subcommand
&report_mode,
&lint_options,
+ &weirpacks,
&file_dict_path,
// Are we linting multiple inputs inside a directory?
batch_mode,
@@ -215,6 +247,7 @@ pub fn lint(
};
for lint_results in per_input_results {
+ let lint_results = lint_results?;
// Update the global stats
for (kind, count) in lint_results.0 {
*all_lint_kinds.entry(kind).or_insert(0) += count;
@@ -253,6 +286,7 @@ struct FullInputInfo<'a> {
source: Cow<'a, str>,
}
+#[allow(clippy::too_many_arguments)]
fn lint_one_input(
// Common properties of harper-cli
markdown_options: MarkdownOptions,
@@ -260,23 +294,25 @@ fn lint_one_input(
report_mode: &ReportStyle,
// Options passed from the user specific to the `lint` subcommand
lint_options: &LintOptions,
+ weirpacks: &[Weirpack],
file_dict_path: &Path,
// Are we linting multiple inputs?
batch_mode: bool,
// For the current input
current: InputInfo,
-) -> (
+) -> anyhow::Result<(
LintKindCount,
LintRuleCount,
LintKindRulePairCount,
SpelloCount,
-) {
+)> {
let LintOptions {
count: _,
ignore,
only,
keep_overlapping_lints,
dialect,
+ weirpack_inputs: _,
} = lint_options;
let mut lint_kinds: HashMap<LintKind, usize> = HashMap::new();
@@ -307,6 +343,11 @@ fn lint_one_input(
// Create the Lint Group from which we will lint this input, using the combined dictionary and the specified dialect
let mut lint_group = LintGroup::new_curated(merged_dictionary.into(), *dialect);
+ for pack in weirpacks {
+ let mut pack_group = pack.to_lint_group()?;
+ lint_group.merge_from(&mut pack_group);
+ }
+
// Turn specified rules on or off
configure_lint_group(&mut lint_group, only, ignore);
@@ -347,7 +388,7 @@ fn lint_one_input(
}
}
- (lint_kinds, lint_rules, lint_kind_rule_pairs, spellos)
+ Ok((lint_kinds, lint_rules, lint_kind_rule_pairs, spellos))
}
fn configure_lint_group(
diff --git a/harper-cli/src/main.rs b/harper-cli/src/main.rs
index 1f4c108a9..df2908e9f 100644
--- a/harper-cli/src/main.rs
+++ b/harper-cli/src/main.rs
@@ -72,6 +72,9 @@ enum Args {
/// Path to the directory for file-local dictionaries.
#[arg(short, long, default_value = data_local_dir().unwrap().join("harper-ls/file_dictionaries/").into_os_string())]
file_dict_path: PathBuf,
+ /// Path to a Weirpack file to load. May be supplied multiple times.
+ #[arg(long, value_name = "WEIRPACK")]
+ weirpacks: Vec<SingleInput>,
},
/// Parse a provided document and print the detected symbols.
Parse {
@@ -215,6 +218,7 @@ fn main() -> anyhow::Result<()> {
user_dict_path,
// TODO workspace_dict_path?
file_dict_path,
+ weirpacks,
} => {
lint(
markdown_options,
@@ -226,6 +230,7 @@ fn main() -> anyhow::Result<()> {
only,
keep_overlapping_lints,
dialect,
+ weirpack_inputs: weirpacks,
},
user_dict_path,
// TODO workspace_dict_path?
diff --git a/harper-core/Cargo.toml b/harper-core/Cargo.toml
index d78450efb..e4f58a5b6 100644
--- a/harper-core/Cargo.toml
+++ b/harper-core/Cargo.toml
@@ -34,6 +34,7 @@ harper-brill = { path = "../harper-brill", version = "1.0.0" }
harper-thesaurus = { path = "../harper-thesaurus", version = "1.4.1", optional = true }
bitflags = { version = "2.10.0", features = ["serde"] }
trie-rs = "0.4.2"
+zip = { version = "2.2.0", default-features = false, features = ["deflate"] }
[dev-dependencies]
criterion = { version = "0.8.1", default-features = false }
diff --git a/harper-core/src/lib.rs b/harper-core/src/lib.rs
index 02dc0c118..a059cc2c5 100644
--- a/harper-core/src/lib.rs
+++ b/harper-core/src/lib.rs
@@ -33,6 +33,7 @@ mod token_kind;
mod token_string_ext;
mod vec_ext;
pub mod weir;
+pub mod weirpack;
use render_markdown::render_markdown;
use std::collections::{BTreeMap, VecDeque};
diff --git a/harper-core/src/weir/mod.rs b/harper-core/src/weir/mod.rs
index b15f8426c..ccc797c62 100644
--- a/harper-core/src/weir/mod.rs
+++ b/harper-core/src/weir/mod.rs
@@ -35,8 +35,8 @@ enum ReplacementStrategy {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TestResult {
- expected: String,
- got: String,
+ pub expected: String,
+ pub got: String,
}
pub struct WeirLinter {
diff --git a/harper-core/src/weirpack/manifest.rs b/harper-core/src/weirpack/manifest.rs
new file mode 100644
index 000000000..54f4559e5
--- /dev/null
+++ b/harper-core/src/weirpack/manifest.rs
@@ -0,0 +1,86 @@
+use std::io::{Read, Write};
+
+use hashbrown::HashMap;
+use serde_json::Value;
+
+use super::WeirpackError;
+
+#[derive(Debug, Clone, Default)]
+pub struct WeirpackManifest {
+ data: HashMap<String, Value>,
+}
+
+impl WeirpackManifest {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn from_reader(reader: impl Read) -> Result<Self, WeirpackError> {
+ let data: HashMap<String, Value> = serde_json::from_reader(reader)?;
+ let manifest = Self { data };
+ manifest.validate_required()?;
+ Ok(manifest)
+ }
+
+ pub fn write_to(&self, writer: impl Write) -> Result<(), WeirpackError> {
+ self.validate_required()?;
+ serde_json::to_writer_pretty(writer, &self.data)?;
+ Ok(())
+ }
+
+ pub fn get_field(&self, key: &str) -> Option<&Value> {
+ self.data.get(key)
+ }
+
+ pub fn set_field(&mut self, key: impl Into<String>, value: Value) {
+ self.data.insert(key.into(), value);
+ }
+
+ pub fn author(&self) -> Result<&str, WeirpackError> {
+ self.required_str("author")
+ }
+
+ pub fn set_author(&mut self, value: impl Into<String>) {
+ self.set_field("author", Value::String(value.into()));
+ }
+
+ pub fn version(&self) -> Result<&str, WeirpackError> {
+ self.required_str("version")
+ }
+
+ pub fn set_version(&mut self, value: impl Into<String>) {
+ self.set_field("version", Value::String(value.into()));
+ }
+
+ pub fn description(&self) -> Result<&str, WeirpackError> {
+ self.required_str("description")
+ }
+
+ pub fn set_description(&mut self, value: impl Into<String>) {
+ self.set_field("description", Value::String(value.into()));
+ }
+
+ pub fn license(&self) -> Result<&str, WeirpackError> {
+ self.required_str("license")
+ }
+
+ pub fn set_license(&mut self, value: impl Into<String>) {
+ self.set_field("license", Value::String(value.into()));
+ }
+
+ fn required_str(&self, key: &'static str) -> Result<&str, WeirpackError> {
+ match self.data.get(key) {
+ Some(Value::String(value)) => Ok(value),
+ Some(_) => Err(WeirpackError::InvalidManifestFieldType(key)),
+ None => Err(WeirpackError::MissingManifestField(key)),
+ }
+ }
+
+ fn validate_required(&self) -> Result<(), WeirpackError> {
+ self.author()?;
+ self.version()?;
+ self.description()?;
+ self.license()?;
+ Ok(())
+ }
+}
diff --git a/harper-core/src/weirpack/mod.rs b/harper-core/src/weirpack/mod.rs
new file mode 100644
index 000000000..74466282d
--- /dev/null
+++ b/harper-core/src/weirpack/mod.rs
@@ -0,0 +1,194 @@
+use std::io::{Read, Write};
+use std::path::Path;
+
+use hashbrown::HashMap;
+use thiserror::Error;
+use zip::write::FileOptions;
+use zip::{CompressionMethod, ZipArchive, ZipWriter};
+
+use crate::linting::LintGroup;
+use crate::weir::{TestResult, WeirLinter};
+
+mod manifest;
+
+pub use manifest::WeirpackManifest;
+
+#[derive(Debug, Error)]
+pub enum WeirpackError {
+ #[error("IO error: {0}")]
+ Io(#[from] std::io::Error),
+ #[error("Zip error: {0}")]
+ Zip(#[from] zip::result::ZipError),
+ #[error("JSON error: {0}")]
+ Json(#[from] serde_json::Error),
+ #[error("Weir error: {0}")]
+ Weir(#[from] crate::weir::Error),
+ #[error("Missing manifest file '{0}'.")]
+ MissingManifest(&'static str),
+ #[error("Manifest field '{0}' is missing.")]
+ MissingManifestField(&'static str),
+ #[error("Manifest field '{0}' must be a string.")]
+ InvalidManifestFieldType(&'static str),
+ #[error("Duplicate manifest file '{0}'.")]
+ DuplicateManifest(&'static str),
+ #[error("Invalid rule filename '{0}'.")]
+ InvalidRuleFileName(String),
+}
+
+#[derive(Debug, Clone, Default)]
+pub struct Weirpack {
+ pub rules: HashMap<String, String>,
+ pub manifest: WeirpackManifest,
+}
+
+impl Weirpack {
+ pub fn new(manifest: WeirpackManifest) -> Self {
+ Self {
+ rules: HashMap::new(),
+ manifest,
+ }
+ }
+
+ pub fn add_rule(&mut self, name: impl Into<String>, rule: impl Into<String>) -> Option<String> {
+ self.rules.insert(name.into(), rule.into())
+ }
+
+ pub fn remove_rule(&mut self, name: &str) -> Option<String> {
+ self.rules.remove(name)
+ }
+
+ pub fn run_tests(&self) -> Result<HashMap<String, Vec<TestResult>>, WeirpackError> {
+ let mut failures = HashMap::new();
+
+ for (name, rule) in &self.rules {
+ let mut linter = WeirLinter::new(rule)?;
+ let failing_tests = linter.run_tests();
+ if !failing_tests.is_empty() {
+ failures.insert(name.to_string(), failing_tests);
+ }
+ }
+
+ Ok(failures)
+ }
+
+ pub fn to_lint_group(&self) -> Result<LintGroup, WeirpackError> {
+ let mut group = LintGroup::default();
+
+ for (name, rule) in &self.rules {
+ let linter = WeirLinter::new(rule)?;
+ group.add_chunk_expr_linter(name, linter);
+ group.config.set_rule_enabled(name, true);
+ }
+
+ Ok(group)
+ }
+
+ pub fn from_reader(mut reader: impl Read) -> Result<Self, WeirpackError> {
+ let mut bytes = Vec::new();
+ reader.read_to_end(&mut bytes)?;
+ Self::from_bytes(&bytes)
+ }
+
+ pub fn write_to(&self, mut writer: impl Write) -> Result<(), WeirpackError> {
+ let bytes = self.to_bytes()?;
+ writer.write_all(&bytes)?;
+ Ok(())
+ }
+
+ pub fn from_bytes(bytes: &[u8]) -> Result<Self, WeirpackError> {
+ let cursor = std::io::Cursor::new(bytes);
+ let mut archive = ZipArchive::new(cursor)?;
+
+ let mut manifest = None;
+ let mut rules = HashMap::new();
+
+ for i in 0..archive.len() {
+ let mut file = archive.by_index(i)?;
+ if file.is_dir() {
+ continue;
+ }
+
+ let name = file.name().to_string();
+ if name == "manifest.json" {
+ if manifest.is_some() {
+ return Err(WeirpackError::DuplicateManifest("manifest.json"));
+ }
+ let manifest_data = WeirpackManifest::from_reader(&mut file)?;
+ manifest = Some(manifest_data);
+ continue;
+ }
+
+ if !name.ends_with(".weir") {
+ continue;
+ }
+
+ let path = Path::new(&name);
+ let file_name = path
+ .file_name()
+ .and_then(|segment| segment.to_str())
+ .ok_or_else(|| WeirpackError::InvalidRuleFileName(name.clone()))?;
+ let rule_name = Path::new(file_name)
+ .file_stem()
+ .and_then(|stem| stem.to_str())
+ .ok_or_else(|| WeirpackError::InvalidRuleFileName(name.clone()))?;
+
+ let mut contents = String::new();
+ file.read_to_string(&mut contents)?;
+ rules.insert(rule_name.to_string(), contents);
+ }
+
+ let manifest = manifest.ok_or(WeirpackError::MissingManifest("manifest.json"))?;
+
+ Ok(Self { rules, manifest })
+ }
+
+ pub fn to_bytes(&self) -> Result<Vec<u8>, WeirpackError> {
+ let mut zip = ZipWriter::new(std::io::Cursor::new(Vec::new()));
+ let options = FileOptions::<()>::default().compression_method(CompressionMethod::Deflated);
+
+ let mut manifest_bytes = Vec::new();
+ self.manifest.write_to(&mut manifest_bytes)?;
+ zip.start_file("manifest.json", options)?;
+ zip.write_all(&manifest_bytes)?;
+
+ let mut rule_names: Vec<_> = self.rules.keys().collect();
+ rule_names.sort();
+
+ for rule_name in rule_names {
+ let file_name = format!("{rule_name}.weir");
+ zip.start_file(file_name, options)?;
+ if let Some(rule) = self.rules.get(rule_name) {
+ zip.write_all(rule.as_bytes())?;
+ }
+ }
+
+ let cursor = zip.finish()?;
+ Ok(cursor.into_inner())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::{Weirpack, WeirpackManifest};
+
+ #[test]
+ fn round_trip_weirpack_bytes() {
+ let mut manifest = WeirpackManifest::new();
+ manifest.set_author("Test Author");
+ manifest.set_version("0.1.0");
+ manifest.set_description("Test pack");
+ manifest.set_license("MIT");
+
+ let mut pack = Weirpack::new(manifest);
+ pack.add_rule("ExampleRule", "expr main test");
+
+ let bytes = pack.to_bytes().expect("serialize weirpack");
+ let parsed = Weirpack::from_bytes(&bytes).expect("deserialize weirpack");
+
+ assert_eq!(parsed.manifest.author().unwrap(), "Test Author");
+ assert_eq!(parsed.manifest.version().unwrap(), "0.1.0");
+ assert_eq!(parsed.manifest.description().unwrap(), "Test pack");
+ assert_eq!(parsed.manifest.license().unwrap(), "MIT");
+ assert_eq!(parsed.rules.get("ExampleRule").unwrap(), "expr main test");
+ }
+}
diff --git a/harper-wasm/src/lib.rs b/harper-wasm/src/lib.rs
index 316e484aa..90c506e5a 100644
--- a/harper-wasm/src/lib.rs
+++ b/harper-wasm/src/lib.rs
@@ -1,5 +1,6 @@
#![doc = include_str!("../README.md")]
+use std::collections::HashMap;
use std::convert::Into;
use std::io::Cursor;
use std::sync::Arc;
@@ -9,6 +10,7 @@ use harper_core::language_detection::is_doc_likely_english;
use harper_core::linting::{LintGroup, Linter as _};
use harper_core::parsers::{IsolateEnglish, Markdown, OopsAllHeadings, Parser, PlainEnglish};
use harper_core::remove_overlaps_map;
+use harper_core::weirpack::Weirpack;
use harper_core::{
CharString, DictWordMetadata, Document, IgnoredLints, LintContext, Lrc, remove_overlaps,
spell::{Dictionary, FstDictionary, MergedDictionary, MutableDictionary},
@@ -103,6 +105,12 @@ pub struct Linter {
stats: Stats,
}
+#[derive(Serialize)]
+struct WeirpackTestFailure {
+ expected: String,
+ got: String,
+}
+
#[wasm_bindgen]
impl Linter {
/// Construct a new `Linter`.
@@ -438,6 +446,39 @@ impl Linter {
Ok(())
}
+
+ /// Load a Weirpack from raw bytes, merging its rules into the current linter.
+ /// Returns test failures if any are found, and does not import in that case.
+ pub fn import_weirpack(&mut self, bytes: Vec<u8>) -> Result<JsValue, String> {
+ let pack = Weirpack::from_bytes(&bytes).map_err(|err| err.to_string())?;
+ let failures = pack.run_tests().map_err(|err| err.to_string())?;
+
+ if !failures.is_empty() {
+ let mapped: HashMap<String, Vec<WeirpackTestFailure>> = failures
+ .into_iter()
+ .map(|(rule, results)| {
+ let failures = results
+ .into_iter()
+ .map(|result| WeirpackTestFailure {
+ expected: result.expected,
+ got: result.got,
+ })
+ .collect();
+ (rule, failures)
+ })
+ .collect();
+
+ let serializer = Serializer::json_compatible();
+ let value = mapped
+ .serialize(&serializer)
+ .map_err(|err| err.to_string())?;
+ return Ok(value);
+ }
+
+ let mut group = pack.to_lint_group().map_err(|err| err.to_string())?;
+ self.lint_group.merge_from(&mut group);
+ Ok(JsValue::UNDEFINED)
+ }
}
#[wasm_bindgen]
diff --git a/packages/components/src/lib/Input.svelte b/packages/components/src/lib/Input.svelte
index 127254d85..a2af2f51d 100644
--- a/packages/components/src/lib/Input.svelte
+++ b/packages/components/src/lib/Input.svelte
@@ -1,4 +1,5 @@
<script lang="ts">
+import { createEventDispatcher } from 'svelte';
import type { InputHTMLAttributes } from 'svelte/elements';
type InputSize = 'sm' | 'md' | 'lg';
@@ -11,6 +12,7 @@ export let size: InputSize = 'md';
let restClass: string | undefined;
let restProps: Record<string, unknown> = {};
+const dispatch = createEventDispatcher<{ keydown: KeyboardEvent; blur: FocusEvent }>();
const baseClasses =
'rounded-lg border border-cream-200 bg-white text-gray-900 placeholder-gray-500 shadow-sm outline-none transition focus:ring-2 focus:ring-primary-300 focus:border-cream-300 dark:border-cream-700 dark:bg-cream-900 dark:text-white dark:placeholder-cream-200 dark:focus:border-cream-600 dark:focus:ring-primary-600';
@@ -31,5 +33,7 @@ $: classes = [baseClasses, sizeClasses[size] ?? sizeClasses.md, restClass, class
type={type}
placeholder={placeholder}
bind:value
+ on:keydown={(event) => dispatch('keydown', event)}
+ on:blur={(event) => dispatch('blur', event)}
{...restProps}
/>
diff --git a/packages/harper.js/package.json b/packages/harper.js/package.json
index f257e076e..e7807b604 100644
--- a/packages/harper.js/package.json
+++ b/packages/harper.js/package.json
@@ -46,5 +46,8 @@
"sideEffects": false,
"files": [
"dist"
- ]
+ ],
+ "dependencies": {
+ "fflate": "^0.8.2"
+ }
}
diff --git a/packages/harper.js/src/Linter.test.ts b/packages/harper.js/src/Linter.test.ts
index b041d1a27..53227e6b2 100644
--- a/packages/harper.js/src/Linter.test.ts
+++ b/packages/harper.js/src/Linter.test.ts
@@ -12,6 +12,20 @@ function randomString(length: number): string {
return result;
}
+const WEIRPACK_PASS_BASE64 =
+ 'UEsDBBQAAAAIAFR7LFx+V+AhbQAAAIgAAAANAAAAbWFuaWZlc3QuanNvbi2MMQuDMBBG9/yKI3MJdnXrWNBNcE7iaQ9DLlxil+J/l5iO33u876cAtD3Kh0X3oCfMBV5tPqr6omTiWF1nOvNsdMHshVL5m7uakSRZv8PKAjPLjjJQLCjgAjsIbBeKm2kHgTzGjDUe35NW5wVQSwMEFAAAAAgAVHssXLV8hxV2AAAAoQAAABUAAABXZWlycGFja1Rlc3RSdWxlLndlaXJNzrENwzAMBMBeUxDskx0yQMoMQEtvh7BECaKMePwYdorgyz/gH3vrVESNJrEjIWQMKnCXBcQvB4036APtTeJKHS1LRIGNO582wWPXNrQa8eNPbhk0104DPtSWH1/VEvFTPSJnMdTNr2JCrMcu8XXkNuuOxOELUEsBAhQDFAAAAAgAVHssXH5X4CFtAAAAiAAAAA0AAAAAAAAAAAAAAIABAAAAAG1hbmlmZXN0Lmpzb25QSwECFAMUAAAACABUeyxctXyHFXYAAAChAAAAFQAAAAAAAAAAAAAAgAGYAAAAV2VpcnBhY2tUZXN0UnVsZS53ZWlyUEsFBgAAAAACAAIAfgAAAEEBAAAAAA==';
+const WEIRPACK_FAIL_BASE64 =
+ 'UEsDBBQAAAAIABtOLVw9tWbJYgAAAH0AAAANAAAAbWFuaWZlc3QuanNvbi3LMQ9AMBCG4d2vuHSWhtVmNNgk5qYOF01J7zCI/07V+H1P3isDUGaXeQ2qAtUhC9Rp5pEODEyrj1boQpfpHZBtoE1++aoeKWzGLnCSzDAacuQnkJdYp8qRRc8Yi7bpVHY/UEsDBBQAAAAIABtOLVylaCfNfgAAALkAAAAVAAAAV2VpcnBhY2tUZXN0UnVsZS53ZWlyTY5RDsIwDEP/e4oo/3AHDsAnB+g6b0Rr06rJxI7PYICQf6z4WTG21qlEURqi7gohw6nALM4gvhnI76AHpLeYFupoOSYUqJ/5zY6w1KW5VCW+/JFrBk21k8NcdP7gi+hIfBVLyDkq6mpHMCDV/S/xMeQ0yYaRQ3jVv0f+mfAEUEsBAhQDFAAAAAgAG04tXD21ZsliAAAAfQAAAA0AAAAAAAAAAAAAAIABAAAAAG1hbmlmZXN0Lmpzb25QSwECFAMUAAAACAAbTi1cpWgnzX4AAAC5AAAAFQAAAAAAAAAAAAAAgAGNAAAAV2VpcnBhY2tUZXN0UnVsZS53ZWlyUEsFBgAAAAACAAIAfgAAAD4BAAAAAA==';
+
+function base64ToBytes(value: string): Uint8Array {
+ const raw = atob(value);
+ const bytes = new Uint8Array(raw.length);
+ for (let i = 0; i < raw.length; i++) {
+ bytes[i] = raw.charCodeAt(i);
+ }
+ return bytes;
+}
+
const linters = {
WorkerLinter: WorkerLinter,
LocalLinter: LocalLinter,
@@ -446,6 +460,72 @@ for (const [linterName, Linter] of Object.entries(linters)) {
await linter.dispose();
}, 120000);
+
+ test(`${linterName} can load Weirpacks from a Blob`, async () => {
+ const linter = new Linter({ binary });
+ await linter.setup();
+
+ const bytes = base64ToBytes(WEIRPACK_PASS_BASE64);
+ const arr = new Uint8Array(bytes);
+ const blob = new Blob([arr], { type: 'application/zip' });
+ const failures = await linter.loadWeirpackFromBlob(blob);
+
+ expect(failures).toBeUndefined();
+
+ const lints = await linter.organizedLints('banana');
+ expect(lints.WeirpackTestRule).toHaveLength(1);
+
+ await linter.dispose();
+ });
+
+ test(`${linterName} can load Weirpacks from Uint8Array`, async () => {
+ const linter = new Linter({ binary });
+ await linter.setup();
+
+ const bytes = base64ToBytes(WEIRPACK_PASS_BASE64);
+ const failures = await linter.loadWeirpackFromBytes(bytes);
+
+ expect(failures).toBeUndefined();
+
+ const lints = await linter.organizedLints('banana');
+ expect(lints.WeirpackTestRule).toHaveLength(1);
+
+ await linter.dispose();
+ });
+
+ test(`${linterName} rejects Weirpacks with failing tests (Blob)`, async () => {
+ const linter = new Linter({ binary });
+ await linter.setup();
+
+ const bytes = base64ToBytes(WEIRPACK_FAIL_BASE64);
+ const arr = new Uint8Array(bytes);
+ const blob = new Blob([arr], { type: 'application/zip' });
+ const failures = await linter.loadWeirpackFromBlob(blob);
+
+ expect(failures).toBeTypeOf('object');
+ expect(failures?.WeirpackTestRule?.[0]?.expected).toBe('banana');
+
+ const lints = await linter.organizedLints('banana');
+ expect(lints.WeirpackTestRule).toBeUndefined();
+
+ await linter.dispose();
+ });
+
+ test(`${linterName} rejects Weirpacks with failing tests (Uint8Array)`, async () => {
+ const linter = new Linter({ binary });
+ await linter.setup();
+
+ const bytes = base64ToBytes(WEIRPACK_FAIL_BASE64);
+ const failures = await linter.loadWeirpackFromBytes(bytes);
+
+ expect(failures).toBeTypeOf('object');
+ expect(failures?.WeirpackTestRule?.[0]?.expected).toBe('banana');
+
+ const lints = await linter.organizedLints('banana');
+ expect(lints.WeirpackTestRule).toBeUndefined();
+
+ await linter.dispose();
+ });
}
// Disabled because it significantly slows down CI
diff --git a/packages/harper.js/src/Linter.ts b/packages/harper.js/src/Linter.ts
index 7796505a8..cded01e91 100644
--- a/packages/harper.js/src/Linter.ts
+++ b/packages/harper.js/src/Linter.ts
@@ -3,6 +3,13 @@ import type { BinaryModule } from './binary';
import type { LintConfig, LintOptions } from './main';
import type Summary from './Summary';
+export interface WeirpackTestFailure {
+ expected: string;
+ got: string;
+}
+
+export type WeirpackTestFailures = Record<string, WeirpackTestFailure[]>;
+
/** An interface for an object that can perform linting actions. */
export default interface Linter {
/** Complete any setup that is necessary before linting. This may include downloading and compiling the WebAssembly binary.
@@ -114,6 +121,20 @@ export default interface Linter {
/** Import a statistics log file. */
importStatsFile(statsFile: string): Promise<void>;
+
+ /**
+ * Load a Weirpack from a Blob, merging its rules into the current linter.
+ * Returns `undefined` when the Weirpack tests pass and the rules are imported,
+ * otherwise returns a map of rule names → failing tests so the caller can
+ * surface the broken expectations.
+ */
+ loadWeirpackFromBlob(blob: Blob): Promise<WeirpackTestFailures | undefined>;
+
+ /**
+ * Load a Weirpack from an array of bytes, merging its rules into the current linter.
+ * Returns the same failure report structure as `loadWeirpackFromBlob`.
+ */
+ loadWeirpackFromBytes(bytes: Uint8Array): Promise<WeirpackTestFailures | undefined>;
}
/** The properties and information needed to construct a Linter. */
diff --git a/packages/harper.js/src/LocalLinter.ts b/packages/harper.js/src/LocalLinter.ts
index 4e1ac4fe3..edd221486 100644
--- a/packages/harper.js/src/LocalLinter.ts
+++ b/packages/harper.js/src/LocalLinter.ts
@@ -3,7 +3,7 @@ import { Language } from 'harper-wasm';
import LazyPromise from 'p-lazy';
import type { SuperBinaryModule } from './binary';
import type Linter from './Linter';
-import type { LinterInit } from './Linter';
+import type { LinterInit, WeirpackTestFailures } from './Linter';
import type { LintConfig, LintOptions } from './main';
/** A Linter that runs in the current JavaScript context (meaning it is allowed to block the event loop).
@@ -216,6 +216,34 @@ export default class LocalLinter implements Linter {
return inner.import_stats_file(statsFile);
}
+ /**
+ * Load a Weirpack from a Blob.
+ *
+ * Returns `undefined` if tests pass and rules are imported, otherwise returns
+ * the Weirpack test failures.
+ */
+ async loadWeirpackFromBlob(blob: Blob): Promise<WeirpackTestFailures | undefined> {
+ const bytes = new Uint8Array(await blob.arrayBuffer());
+ return this.loadWeirpackFromBytes(bytes);
+ }
+
+ /**
+ * Load a Weirpack from a byte array.
+ *
+ * Returns `undefined` if tests pass and rules are imported, otherwise returns
+ * the Weirpack test failures.
+ */
+ async loadWeirpackFromBytes(
+ bytes: Uint8Array | number[],
+ ): Promise<WeirpackTestFailures | undefined> {
+ const inner = await this.inner;
+ const data = bytes instanceof Uint8Array ? bytes : Uint8Array.from(bytes);
+ const result = (
+ inner as unknown as { import_weirpack: (input: Uint8Array) => unknown }
+ ).import_weirpack(data);
+ return result as WeirpackTestFailures | undefined;
+ }
+
async dispose(): Promise<void> {
if (this.disposed) {
return;
diff --git a/packages/harper.js/src/WorkerLinter/index.ts b/packages/harper.js/src/WorkerLinter/index.ts
index c79c991b5..0d876f94f 100644
--- a/packages/harper.js/src/WorkerLinter/index.ts
+++ b/packages/harper.js/src/WorkerLinter/index.ts
@@ -1,7 +1,7 @@
import type { Dialect, Lint, Suggestion } from 'harper-wasm';
import type { BinaryModule } from '../binary';
import type Linter from '../Linter';
-import type { LinterInit } from '../Linter';
+import type { LinterInit, WeirpackTestFailures } from '../Linter';
import type { LintConfig, LintOptions } from '../main';
import type { DeserializedRequest } from '../Serializer';
import Serializer from '../Serializer';
@@ -202,6 +202,30 @@ export default class WorkerLinter implements Linter {
return this.rpc('importStatsFile', [statsFile]);
}
+ /**
+ * Load a Weirpack from a Blob via the worker thread.
+ *
+ * Returns `undefined` when the tests pass and the pack is imported, otherwise
+ * forwards the failure report back to the caller.
+ */
+ async loadWeirpackFromBlob(blob: Blob): Promise<WeirpackTestFailures | undefined> {
+ const bytes = new Uint8Array(await blob.arrayBuffer());
+ const arr = Array.from(bytes);
+ return await this.rpc('loadWeirpackFromBytes', [arr]);
+ }
+
+ /**
+ * Load a Weirpack from bytes via the worker thread.
+ *
+ * Returns the failure report if tests fail or `undefined` when the pack is imported.
+ */
+ async loadWeirpackFromBytes(
+ bytes: Uint8Array | number[],
+ ): Promise<WeirpackTestFailures | undefined> {
+ const arr = Array.from(bytes);
+ return await this.rpc('loadWeirpackFromBytes', [arr]);
+ }
+
/** Run a procedure on the remote worker. */
private async rpc(procName: string, args: unknown[]): Promise<any> {
if (this.disposed) {
diff --git a/packages/harper.js/src/main.ts b/packages/harper.js/src/main.ts
index 17050bb91..12e45f5a6 100644
--- a/packages/harper.js/src/main.ts
+++ b/packages/harper.js/src/main.ts
@@ -5,10 +5,17 @@ export {
binary,
binaryInlined,
} from './binary';
-export type { default as Linter, LinterInit } from './Linter';
+export type {
+ default as Linter,
+ LinterInit,
+ WeirpackTestFailure,
+ WeirpackTestFailures,
+} from './Linter';
export { default as LocalLinter } from './LocalLinter';
export type { default as Summary } from './Summary';
export { default as WorkerLinter } from './WorkerLinter';
+export type { WeirpackArchive, WeirpackFileMap, WeirpackManifest } from './weirpack';
+export { packWeirpackFiles, unpackWeirpackBytes } from './weirpack';
/** A linting rule configuration dependent on upstream Harper's available rules.
* This is a record, since you shouldn't hard-code the existence of any particular rules and should generalize based on this struct. */
export type LintConfig = Record<string, boolean | null>;
diff --git a/packages/harper.js/src/weirpack.test.ts b/packages/harper.js/src/weirpack.test.ts
new file mode 100644
index 000000000..d32c7123d
--- /dev/null
+++ b/packages/harper.js/src/weirpack.test.ts
@@ -0,0 +1,41 @@
+import { strToU8, zipSync } from 'fflate';
+import { describe, expect, test } from 'vitest';
+import { packWeirpackFiles, unpackWeirpackBytes } from './weirpack';
+
+describe('weirpack helpers', () => {
+ test('round-trips a weirpack archive', () => {
+ const manifest = {
+ author: 'Test Author',
+ version: '0.1.0',
+ description: 'Test pack',
+ license: 'MIT',
+ };
+
+ const files = new Map([
+ ['manifest.json', JSON.stringify(manifest, null, 2)],
+ ['ExampleRule.weir', 'expr main test'],
+ ['AnotherRule.weir', 'expr main banana'],
+ ]);
+
+ const bytes = packWeirpackFiles(files);
+ const unpacked = unpackWeirpackBytes(bytes);
+
+ expect(unpacked.manifest).toEqual(manifest);
+ expect(unpacked.files.get('ExampleRule.weir')).toBe('expr main test');
+ expect(unpacked.files.get('AnotherRule.weir')).toBe('expr main banana');
+ });
+
+ test('packWeirpackFiles requires a manifest.json file', () => {
+ expect(() => packWeirpackFiles(new Map([['Rule.weir', 'expr main test']]))).toThrow(
+ 'Weirpack is missing manifest.json',
+ );
+ });
+
+ test('unpackWeirpackBytes requires a manifest.json file', () => {
+ const bytes = zipSync({
+ 'Rule.weir': strToU8('expr main test'),
+ });
+
+ expect(() => unpackWeirpackBytes(bytes)).toThrow('Weirpack is missing manifest.json');
+ });
+});
diff --git a/packages/harper.js/src/weirpack.ts b/packages/harper.js/src/weirpack.ts
new file mode 100644
index 000000000..c82fa949d
--- /dev/null
+++ b/packages/harper.js/src/weirpack.ts
@@ -0,0 +1,49 @@
+import { strFromU8, strToU8, unzipSync, zipSync } from 'fflate';
+
+export type WeirpackManifest = Record<string, unknown>;
+export type WeirpackFileMap = Map<string, string>;
+
+export type WeirpackArchive = {
+ manifest: WeirpackManifest;
+ files: WeirpackFileMap;
+};
+
+const manifestFilename = 'manifest.json';
+
+export function packWeirpackFiles(files: WeirpackFileMap): Uint8Array {
+ if (!files.has(manifestFilename)) {
+ throw new Error('Weirpack is missing manifest.json');
+ }
+
+ const entries: Record<string, Uint8Array> = {};
+ for (const [name, content] of files.entries()) {
+ entries[name] = strToU8(content);
+ }
+
+ return zipSync(entries, { level: 6 });
+}
+
+export function unpackWeirpackBytes(bytes: Uint8Array): WeirpackArchive {
+ const archive = unzipSync(bytes);
+ const manifestBytes = archive[manifestFilename];
+ if (!manifestBytes) {
+ throw new Error('Weirpack is missing manifest.json');
+ }
+
+ const manifestText = strFromU8(manifestBytes);
+ const manifest = JSON.parse(manifestText) as WeirpackManifest;
+ const files: WeirpackFileMap = new Map();
+ files.set(manifestFilename, manifestText);
+
+ const fileNames = Object.keys(archive);
+ fileNames.sort();
+ for (const name of fileNames) {
+ const data = archive[name];
+ if (!data || name === manifestFilename) {
+ continue;
+ }
+ files.set(name, strFromU8(data));
+ }
+
+ return { manifest, files };
+}
diff --git a/packages/web/package.json b/packages/web/package.json
index f89343500..d3ea94d6f 100644
--- a/packages/web/package.json
+++ b/packages/web/package.json
@@ -33,6 +33,7 @@
"dependencies": {
"@sveltepress/theme-default": "^5.0.7",
"@sveltepress/vite": "^1.1.5",
+ "brace": "^0.11.1",
"chart.js": "^4.4.8",
"components": "workspace:*",
"drizzle-orm": "^0.44.6",
@@ -44,6 +45,7 @@
"posthog-js": "^1.245.1",
"quill": "^2.0.3",
"reveal.js": "^5.1.0",
+ "svelte-ace": "^1.0.21",
"svelte-intersection-observer": "^1.0.0",
"typed.js": "^2.1.0",
"zod": "^4.1.12"
diff --git a/packages/web/src/brace.d.ts b/packages/web/src/brace.d.ts
new file mode 100644
index 000000000..557e36a46
--- /dev/null
+++ b/packages/web/src/brace.d.ts
@@ -0,0 +1,2 @@
+declare module 'brace/mode/*';
+declare module 'brace/theme/*';
diff --git a/packages/web/src/lib/components/Toasts.svelte b/packages/web/src/lib/components/Toasts.svelte
new file mode 100644
index 000000000..ddc71344d
--- /dev/null
+++ b/packages/web/src/lib/components/Toasts.svelte
@@ -0,0 +1,35 @@
+<script lang="ts" context="module">
+export type ToastTone = 'success' | 'error' | 'info';
+export type Toast = {
+ id: number;
+ title: string;
+ body?: string;
+ tone: ToastTone;
+};
+</script>
+
+<script lang="ts">
+import { Card } from 'components';
+
+export let toasts: Toast[] = [];
+export let className: string | undefined = undefined;
+</script>
+
+<div class={`fixed bottom-24 right-6 z-20 flex w-[320px] flex-col gap-3 ${className ?? ''}`}>
+ {#each toasts as toast (toast.id)}
+ <Card
+ className={`border px-4 py-3 text-sm shadow-xl ${
+ toast.tone === 'success'
+ ? 'border-green-200 bg-green-50 text-green-900'
+ : toast.tone === 'error'
+ ? 'border-red-200 bg-red-50 text-red-900'
+ : 'border-black/10 bg-white text-black'
+ }`}
+ >
+ <div class="text-sm font-semibold">{toast.title}</div>
+ {#if toast.body}
+ <div class="mt-1 text-xs leading-snug text-black/70">{toast.body}</div>
+ {/if}
+ </Card>
+ {/each}
+</div>
diff --git a/packages/web/src/lib/components/WeirStudioFileExplorer.svelte b/packages/web/src/lib/components/WeirStudioFileExplorer.svelte
new file mode 100644
index 000000000..eb015609a
--- /dev/null
+++ b/packages/web/src/lib/components/WeirStudioFileExplorer.svelte
@@ -0,0 +1,171 @@
+<script lang="ts">
+import { Button, Input } from 'components';
+import CheckIcon from '$lib/components/icons/CheckIcon.svelte';
+import ChevronLeftIcon from '$lib/components/icons/ChevronLeftIcon.svelte';
+import EditIcon from '$lib/components/icons/EditIcon.svelte';
+import PlusIcon from '$lib/components/icons/PlusIcon.svelte';
+import TrashIcon from '$lib/components/icons/TrashIcon.svelte';
+import ChevronRightIcon from './icons/ChevronRightIcon.svelte';
+
+/** Whether to render the file explorer as a closed drawer or an open one. */
+export let drawerOpen = true;
+export let files: Map<string, string> = new Map();
+/** The filename of the currently selected file. */
+export let activeFile: string | null = null;
+
+let renamingFile: string | null = null;
+let renameValue = '';
+
+export let onCreateFile: () => void;
+export let onSelectFile: (id: string) => void;
+export let onDeleteFile: (file: string) => void;
+export let onRenameFile: (from: string, to: string) => void;
+export let onToggleDrawer: () => void = () => {
+ drawerOpen = !drawerOpen;
+};
+
+function startRename(file: string) {
+ renamingFile = file;
+ renameValue = file;
+}
+
+function commitRename(from: string) {
+ if (renamingFile !== from) {
+ return;
+ }
+
+ const trimmed = renameValue.trim();
+ renamingFile = null;
+
+ if (trimmed.length === 0 || trimmed === from) {
+ return;
+ }
+
+ onRenameFile(from, trimmed);
+}
+</script>
+
+<aside
+ class={`relative z-10 flex h-full flex-col border-r border-black/10 bg-white/80 backdrop-blur transition-all duration-300 ${drawerOpen ? 'w-72' : 'w-14'}`}
+>
+ <div class="flex items-center justify-between px-3 py-3">
+ {#if drawerOpen}
+ <div class="text-sm font-semibold uppercase tracking-wider text-black/70">Weirpack</div>
+ <Button
+ size="xs"
+ color="white"
+ className="h-8 w-8 !p-0"
+ on:click={onToggleDrawer}
+ title="Collapse drawer"
+ aria-label="Collapse drawer"
+ >
+ <ChevronLeftIcon className="h-4 w-4" />
+ </Button>
+ {:else}
+ <Button
+ size="xs"
+ color="white"
+ className="mx-auto h-8 w-8 !p-0"
+ on:click={onToggleDrawer}
+ title="Expand drawer"
+ aria-label="Expand drawer"
+ >
+ <ChevronRightIcon className="h-4 w-4" />
+ </Button>
+ {/if}
+ </div>
+
+ {#if drawerOpen}
+ <div class="px-3 pb-2">
+ <Button
+ color="dark"
+ size="sm"
+ className="w-full uppercase tracking-wide"
+ on:click={onCreateFile}
+ >
+ <PlusIcon className="h-4 w-4" />
+ New file
+ </Button>
+ </div>
+
+ <div class="flex-1 overflow-auto px-2 pb-4">
+ {#each files as [file]}
+ <div
+ class={`group flex items-center justify-between rounded-lg px-2 py-2 text-sm ${file == activeFile ? 'bg-white shadow-sm' : 'hover:bg-white/60'}`}
+ >
+ <div class="flex flex-1 items-center gap-2 text-left">
+ <span class={`h-2 w-2 rounded-full ${file == activeFile ? 'bg-primary': ''} bg-cream`}></span>
+ {#if renamingFile === file}
+ <div class="flex-1">
+ <Input
+ size="sm"
+ className="w-full text-xs"
+ autofocus
+ bind:value={renameValue}
+ on:keydown={(event: CustomEvent<KeyboardEvent>) => {
+ const keyboardEvent = event.detail;
+ if (keyboardEvent.key === 'Enter') {
+ commitRename(file);
+ }
+ if (keyboardEvent.key === 'Escape') {
+ renamingFile = null;
+ }
+ }}
+ on:blur={() => commitRename(file)}
+ />
+ </div>
+ {:else}
+ <button class="flex-1 truncate text-left" on:click={() => onSelectFile(file)}>
+ {file}
+ </button>
+ {/if}
+ </div>
+
+ <div
+ class={`flex items-center gap-1 text-black/50 transition ${renamingFile === file ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'}`}
+ >
+ {#if renamingFile === file}
+ <Button
+ size="xs"
+ color="white"
+ className="h-6 w-6 !p-0"
+ on:click={() => commitRename(file)}
+ title="Confirm rename"
+ aria-label="Confirm rename"
+ >
+ <CheckIcon className="h-3.5 w-3.5" />
+ </Button>
+ {:else}
+ <Button
+ size="xs"
+ color="white"
+ className="h-6 w-6 !p-0"
+ on:click={() => startRename(file)}
+ title="Rename file"
+ aria-label="Rename file"
+ >
+ <EditIcon className="h-3.5 w-3.5" />
+ </Button>
+ {#if files.size > 1}
+ <Button
+ size="xs"
+ color="white"
+ className="h-6 w-6 !p-0"
+ on:click={() => onDeleteFile(file)}
+ title="Delete file"
+ aria-label="Delete file"
+ >
+ <TrashIcon className="h-3.5 w-3.5" />
+ </Button>
+ {/if}
+ {/if}
+ </div>
+ </div>
+ {/each}
+ </div>
+ {:else}
+ <div class="flex flex-1 flex-col items-center gap-4 pt-6 text-xs text-black/50">
+ <div class="rotate-135 text-xs font-semibold tracking-widest uppercase">Files</div>
+ </div>
+ {/if}
+</aside>
diff --git a/packages/web/src/lib/components/WeirStudioStart.svelte b/packages/web/src/lib/components/WeirStudioStart.svelte
new file mode 100644
index 000000000..e6b6c79d0
--- /dev/null
+++ b/packages/web/src/lib/components/WeirStudioStart.svelte
@@ -0,0 +1,68 @@
+<script lang="ts">
+import { Button, Card } from 'components';
+
+export let onUpload: () => void;
+export let onOpenExample: () => void;
+export let onCreateEmpty: () => void;
+export let onUploadChange: (event: Event) => void;
+export let fileInputEl: HTMLInputElement | null = null;
+export let loading = false;
+export let loadingLabel = 'Checking for saved Weirpack...';
+</script>
+
+<div class="absolute inset-0 z-30 flex items-center justify-center bg-[#fef4e7]/95">
+ <Card className="w-[min(640px,90vw)] space-y-6 border-black/10 bg-white/95 p-8">
+ <div class="space-y-2">
+ <div class="text-xs font-semibold uppercase tracking-[0.25em] text-black/50">Weir Studio</div>
+ {#if loading}
+ <h2 class="text-2xl font-semibold text-black">Restoring session</h2>
+ <p class="text-sm text-black/60">{loadingLabel}</p>
+ {:else}
+ <h2 class="text-2xl font-semibold text-black">Choose how to start</h2>
+ <p class="text-sm text-black/60">
+ Load a Weirpack to edit rules, run tests, and export updates.
+ </p>
+ {/if}
+ </div>
+
+ <div class={`grid gap-3 ${loading ? 'opacity-60' : ''}`}>
+ <input
+ class="hidden"
+ type="file"
+ accept=".weirpack,application/zip"
+ bind:this={fileInputEl}
+ on:change={onUploadChange}
+ />
+ <Button
+ color="dark"
+ size="md"
+ className="w-full justify-between"
+ on:click={onUpload}
+ disabled={loading}
+ >
+ <span>Upload an existing Weirpack</span>
+ <span class="text-xs uppercase tracking-[0.2em] text-white/60">Upload</span>
+ </Button>
+ <Button
+ color="white"
+ size="md"
+ className="w-full justify-between"
+ on:click={onOpenExample}
+ disabled={loading}
+ >
+ <span>Open example Weirpack</span>
+ <span class="text-xs uppercase tracking-[0.2em] text-black/40">Example</span>
+ </Button>
+ <Button
+ color="white"
+ size="md"
+ className="w-full justify-between"
+ on:click={onCreateEmpty}
+ disabled={loading}
+ >
+ <span>Create an empty Weirpack</span>
+ <span class="text-xs uppercase tracking-[0.2em] text-black/40">Empty</span>
+ </Button>
+ </div>
+ </Card>
+</div>
diff --git a/packages/web/src/lib/components/WeirStudioWorkspace.svelte b/packages/web/src/lib/components/WeirStudioWorkspace.svelte
new file mode 100644
index 000000000..c616da5fa
--- /dev/null
+++ b/packages/web/src/lib/components/WeirStudioWorkspace.svelte
@@ -0,0 +1,106 @@
+<script lang="ts">
+import { Button, Card } from 'components';
+import type { ComponentType } from 'svelte';
+import CloseIcon from '$lib/components/icons/CloseIcon.svelte';
+import DownloadIcon from '$lib/components/icons/DownloadIcon.svelte';
+import PlayIcon from '$lib/components/icons/PlayIcon.svelte';
+import WeirStudioFileExplorer from '$lib/components/WeirStudioFileExplorer.svelte';
+
+export let drawerOpen = true;
+export let files: Map<string, string> = new Map();
+export let activeFile: string | null = null;
+export let editorReady = false;
+export let AceEditorComponent: ComponentType | null = null;
+export let editorOptions: Record<string, unknown>;
+export let linterReady = false;
+export let runningTests = false;
+export let packLoaded = false;
+
+export let onToggleDrawer: () => void;
+export let onCreateFile: () => void;
+export let onSelectFile: (id: string) => void;
+export let onRenameFile: (from: string, to: string) => void;
+export let onDeleteFile: (file: string) => void;
+export let onUpdateContent: (value: string) => void;
+export let onRunTests: () => void;
+export let onDownload: () => void;
+export let onClosePack: () => void;
+
+export let getEditorMode: (name: string) => string;
+</script>
+
+<WeirStudioFileExplorer
+ {drawerOpen}
+ {files}
+ {activeFile}
+ {onToggleDrawer}
+ {onCreateFile}
+ {onSelectFile}
+ {onDeleteFile}
+ {onRenameFile}
+/>
+
+<main class="relative z-10 flex flex-1 flex-col">
+ <div class="flex items-center justify-between border-b border-black/10 bg-white/70 px-4 py-3">
+ <div class="flex items-center gap-3">
+ <div class="text-xs font-semibold uppercase tracking-[0.2em] text-black/50">Studio</div>
+ <div class="text-sm font-medium text-black/80">{activeFile ?? 'No file selected'}</div>
+ </div>
+ <div class="flex items-center gap-3">
+ <div class="text-xs uppercase tracking-[0.18em] text-black/40">
+ {linterReady ? 'Weir runner online' : 'Warming up harper.js'}
+ </div>
+ <Button
+ size="xs"
+ color="white"
+ className="h-8 w-8 !p-0"
+ title="Close Weirpack"
+ aria-label="Close Weirpack"
+ on:click={onClosePack}
+ >
+ <CloseIcon className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ </div>
+
+ <div class="flex-1 overflow-hidden p-4">
+ <Card className="h-full border-black/10 bg-white/95 p-0 shadow-[0_20px_60px_-40px_rgba(0,0,0,0.4)]">
+ {#if editorReady && AceEditorComponent}
+ {#key activeFile}
+ <svelte:component
+ this={AceEditorComponent}
+ width="100%"
+ height="100%"
+ value={activeFile ? files.get(activeFile) : ""}
+ lang={getEditorMode(activeFile ?? '')}
+ theme="chrome"
+ options={editorOptions}
+ on:input={(event: CustomEvent<string>) => onUpdateContent(event.detail)}
+ />
+ {/key}
+ {:else}
+ <div class="flex h-full items-center justify-center text-sm uppercase tracking-[0.3em] text-black/40">
+ Loading editor…
+ </div>
+ {/if}
+ </Card>
+ </div>
+</main>
+
+<div class="fixed bottom-6 right-6 z-20 flex items-center gap-3">
+ <Button
+ size="md"
+ color="dark"
+ pill
+ className={runningTests ? 'opacity-70' : undefined}
+ on:click={onRunTests}
+ disabled={!packLoaded || runningTests}
+ >
+ <PlayIcon className="h-4 w-4" />
+ {runningTests ? 'Running' : 'Run tests'}
+ </Button>
+ <Button size="md" color="white" pill on:click={onDownload} disabled={!packLoaded}>
+ <DownloadIcon className="h-4 w-4" />
+ Download
+ </Button>
+</div>
diff --git a/packages/web/src/lib/components/icons/CheckIcon.svelte b/packages/web/src/lib/components/icons/CheckIcon.svelte
new file mode 100644
index 000000000..185464024
--- /dev/null
+++ b/packages/web/src/lib/components/icons/CheckIcon.svelte
@@ -0,0 +1,9 @@
+<script lang="ts">
+export let className: string | undefined = undefined;
+</script>
+
+<svg viewBox="0 0 20 20" class={className} fill="currentColor" aria-hidden="true">
+ <path
+ d="M16.7 5.3a1 1 0 0 1 0 1.4l-7.3 7.3a1 1 0 0 1-1.4 0L3.3 9.3a1 1 0 1 1 1.4-1.4l3.3 3.3 6.6-6.6a1 1 0 0 1 1.4 0z"
+ />
+</svg>
diff --git a/packages/web/src/lib/components/icons/ChevronLeftIcon.svelte b/packages/web/src/lib/components/icons/ChevronLeftIcon.svelte
new file mode 100644
index 000000000..c099d6f1d
--- /dev/null
+++ b/packages/web/src/lib/components/icons/ChevronLeftIcon.svelte
@@ -0,0 +1,7 @@
+<script lang="ts">
+export let className: string | undefined = undefined;
+</script>
+
+<svg viewBox="0 0 20 20" class={className} fill="currentColor" aria-hidden="true">
+ <path d="M11.78 4.22a.75.75 0 0 1 0 1.06L8.06 9l3.72 3.72a.75.75 0 1 1-1.06 1.06L6.47 9.53a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0z" />
+</svg>
diff --git a/packages/web/src/lib/components/icons/ChevronRightIcon.svelte b/packages/web/src/lib/components/icons/ChevronRightIcon.svelte
new file mode 100644
index 000000000..3baa906f7
--- /dev/null
+++ b/packages/web/src/lib/components/icons/ChevronRightIcon.svelte
@@ -0,0 +1,7 @@
+<script lang="ts">
+export let className: string | undefined = undefined;
+</script>
+
+<svg viewBox="0 0 20 20" class={className} fill="currentColor" aria-hidden="true">
+ <path d="M8.22 4.22a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1 0 1.06l-4.25 4.25a.75.75 0 1 1-1.06-1.06L11.94 9 8.22 5.28a.75.75 0 0 1 0-1.06z" />
+</svg>
diff --git a/packages/web/src/lib/components/icons/CloseIcon.svelte b/packages/web/src/lib/components/icons/CloseIcon.svelte
new file mode 100644
index 000000000..0c9728f0c
--- /dev/null
+++ b/packages/web/src/lib/components/icons/CloseIcon.svelte
@@ -0,0 +1,7 @@
+<script lang="ts">
+export let className: string | undefined = undefined;
+</script>
+
+<svg viewBox="0 0 20 20" class={className} fill="currentColor" aria-hidden="true">
+ <path d="M5.72 5.72a.75.75 0 0 1 1.06 0L10 8.94l3.22-3.22a.75.75 0 1 1 1.06 1.06L11.06 10l3.22 3.22a.75.75 0 1 1-1.06 1.06L10 11.06l-3.22 3.22a.75.75 0 0 1-1.06-1.06L8.94 10 5.72 6.78a.75.75 0 0 1 0-1.06z" />
+</svg>
diff --git a/packages/web/src/lib/components/icons/DownloadIcon.svelte b/packages/web/src/lib/components/icons/DownloadIcon.svelte
new file mode 100644
index 000000000..892c7d780
--- /dev/null
+++ b/packages/web/src/lib/components/icons/DownloadIcon.svelte
@@ -0,0 +1,8 @@
+<script lang="ts">
+export let className: string | undefined = undefined;
+</script>
+
+<svg viewBox="0 0 20 20" class={className} fill="currentColor" aria-hidden="true">
+ <path d="M10 3.5a.75.75 0 0 1 .75.75v6.19l2.22-2.22a.75.75 0 1 1 1.06 1.06l-3.5 3.5a.75.75 0 0 1-1.06 0l-3.5-3.5a.75.75 0 1 1 1.06-1.06l2.22 2.22V4.25A.75.75 0 0 1 10 3.5z" />
+ <path d="M4 13.75a.75.75 0 0 1 .75-.75h10.5a.75.75 0 0 1 .75.75v1.5A2.75 2.75 0 0 1 13.25 18h-6.5A2.75 2.75 0 0 1 4 15.25v-1.5z" />
+</svg>
diff --git a/packages/web/src/lib/components/icons/EditIcon.svelte b/packages/web/src/lib/components/icons/EditIcon.svelte
new file mode 100644
index 000000000..9f935cd05
--- /dev/null
+++ b/packages/web/src/lib/components/icons/EditIcon.svelte
@@ -0,0 +1,8 @@
+<script lang="ts">
+export let className: string | undefined = undefined;
+</script>
+
+<svg viewBox="0 0 20 20" class={className} fill="currentColor" aria-hidden="true">
+ <path d="M13.64 2.86a1.5 1.5 0 0 1 2.12 2.12l-8.5 8.5-3.36.84.84-3.36 8.5-8.5z" />
+ <path d="M11.5 4.99 15 8.5" stroke="currentColor" stroke-width="1.2" />
+</svg>
diff --git a/packages/web/src/lib/components/icons/PlayIcon.svelte b/packages/web/src/lib/components/icons/PlayIcon.svelte
new file mode 100644
index 000000000..1ccc93eb8
--- /dev/null
+++ b/packages/web/src/lib/components/icons/PlayIcon.svelte
@@ -0,0 +1,7 @@
+<script lang="ts">
+export let className: string | undefined = undefined;
+</script>
+
+<svg viewBox="0 0 20 20" class={className} fill="currentColor" aria-hidden="true">
+ <path d="M6.75 4.25a.75.75 0 0 1 .78.02l7.5 4.75a.75.75 0 0 1 0 1.26l-7.5 4.75A.75.75 0 0 1 6 14.5v-9a.75.75 0 0 1 .75-.75z" />
+</svg>
diff --git a/packages/web/src/lib/components/icons/PlusIcon.svelte b/packages/web/src/lib/components/icons/PlusIcon.svelte
new file mode 100644
index 000000000..23270cd8f
--- /dev/null
+++ b/packages/web/src/lib/components/icons/PlusIcon.svelte
@@ -0,0 +1,7 @@
+<script lang="ts">
+export let className: string | undefined = undefined;
+</script>
+
+<svg viewBox="0 0 20 20" class={className} fill="currentColor" aria-hidden="true">
+ <path d="M10 4a.75.75 0 0 1 .75.75v4.5h4.5a.75.75 0 0 1 0 1.5h-4.5v4.5a.75.75 0 0 1-1.5 0v-4.5h-4.5a.75.75 0 0 1 0-1.5h4.5v-4.5A.75.75 0 0 1 10 4z" />
+</svg>
diff --git a/packages/web/src/lib/components/icons/TrashIcon.svelte b/packages/web/src/lib/components/icons/TrashIcon.svelte
new file mode 100644
index 000000000..808830cc8
--- /dev/null
+++ b/packages/web/src/lib/components/icons/TrashIcon.svelte
@@ -0,0 +1,7 @@
+<script lang="ts">
+export let className: string | undefined = undefined;
+</script>
+
+<svg viewBox="0 0 20 20" class={className} fill="currentColor" aria-hidden="true">
+ <path d="M7.5 3a1 1 0 0 0-1 1v1H4.75a.75.75 0 0 0 0 1.5h.57l.6 9.01A2 2 0 0 0 7.91 17h4.18a2 2 0 0 0 1.99-1.49l.6-9.01h.57a.75.75 0 0 0 0-1.5H13.5V4a1 1 0 0 0-1-1h-5zM8 6h4v8H8V6z" />
+</svg>
diff --git a/packages/web/src/routes/docs/weir/+page.md b/packages/web/src/routes/docs/weir/+page.md
index 8c3b12a72..ae224e70e 100644
--- a/packages/web/src/routes/docs/weir/+page.md
+++ b/packages/web/src/routes/docs/weir/+page.md
@@ -8,6 +8,8 @@ It could declare that a certain word should be capitalized in a specific context
Harper can cover *most* of the rules in *most* style guides, but there will always be outliers that we can't support (or simply don't know about).
That is why it is critical that Harper allow individuals and organizations to define rules and conventions for Harper to enforce.
+Try the in-browser [Weir studio](/weir/studio) to experiment with rules and tests.
+
## Introducing Weir
The heart of Weir is an expression language that mimics the pseudocode Harper contributors tend to use when describing the Rust code they intend to write.
@@ -261,6 +263,47 @@ In the future, expect new types of tests to become available.
If you have `harper-cli` available, you can run the tests in a given Weir file by running `harper-cli test <path to the Weir file>`.
+## Weirpacks
+
+Weirpacks are zip archives of Weir rules meant for distribution. They use the `.weirpack` extension for clarity, but the contents are standard ZIP.
+
+### Layout
+
+- The archive root contains one or more `.weir` files.
+- Each rule name is the filename stem (for example, `TheirToThere.weir` becomes `TheirToThere`).
+- A `manifest.json` file is required at the root.
+
+### Manifest
+
+The manifest is JSON. It must include the required fields below and may include any extra metadata you want.
+
+Required fields:
+- `author`
+- `version`
+- `description`
+- `license`
+
+Example:
+
+```json
+{
+ "author": "Ada Lovelace",
+ "version": "1.0.0",
+ "description": "Rules for Victorian technical writing.",
+ "license": "MIT",
+ "keywords": ["victorian", "technical", "style"],
+ "website": "https://example.com"
+}
+```
+
+### Loading
+
+In `harper-cli`, use `--weirpack` to load one or more packs at lint time:
+
+```bash
+harper-cli lint --weirpack path/to/rules.weirpack README.md
+```
+
## See Also:
- [Building the Weir Language](https://elijahpotter.dev/articles/building-the-weir-language)
diff --git a/packages/web/src/routes/weir/studio/+page.svelte b/packages/web/src/routes/weir/studio/+page.svelte
new file mode 100644
index 000000000..bb28b62d1
--- /dev/null
+++ b/packages/web/src/routes/weir/studio/+page.svelte
@@ -0,0 +1,442 @@
+<script lang="ts">
+import { packWeirpackFiles, unpackWeirpackBytes } from 'harper.js';
+import type { ComponentType } from 'svelte';
+import { onMount } from 'svelte';
+import { browser } from '$app/environment';
+import Isolate from '$lib/components/Isolate.svelte';
+import type { Toast } from '$lib/components/Toasts.svelte';
+import Toasts from '$lib/components/Toasts.svelte';
+import WeirStudioStart from '$lib/components/WeirStudioStart.svelte';
+import WeirStudioWorkspace from '$lib/components/WeirStudioWorkspace.svelte';
+
+type WeirpackTestFailure = {
+ expected: string;
+ got: string;
+};
+
+type WeirpackTestFailures = Record<string, WeirpackTestFailure[]>;
+
+const defaultManifest = {
+ name: 'Weirpack Studio',
+ author: 'Anonymous',
+ version: '0.1.0',
+ description: 'Exploring Weir rules in the browser.',
+ license: 'MIT',
+};
+
+const newRuleTemplate = 'expr main';
+
+const defaultRule = `expr main (w/o)
+
+let message "Use \`without\` instead of \`w/o\`"
+let description "Expands the abbreviation \`w/o\` to the full word \`without\`."
+let kind "Style"
+let becomes "without"
+
+test "She lacks w/o experience." "She lacks without experience."
+test "He has w/o skills w/o knowledge." "He has without skills without knowledge."
+`;
+
+/** Used for generating new filenames */
+let nextId = 2;
+
+/** Is the drawer open? */
+let drawerOpen = true;
+
+/** The name of the file currently in the viewport. */
+let activeFileId: string | null = '';
+
+let toasts: Toast[] = [];
+let runningTests = false;
+let linterReady = false;
+let linter: import('harper.js').LocalLinter | null = null;
+let AceEditorComponent: ComponentType | null = null;
+let editorReady = false;
+let packLoaded = false;
+let fileInputEl: HTMLInputElement | null = null;
+let checkingStorage = true;
+
+const storageKey = 'harper-weirpack-studio';
+
+let files: Map<string, string> = new Map();
+
+const editorOptions = {
+ enableBasicAutocompletion: true,
+ enableLiveAutocompletion: true,
+ enableSnippets: true,
+ showPrintMargin: false,
+ wrap: true,
+ fontFamily: '"JetBrains Mono", monospace',
+ fontSize: '14px',
+};
+
+const modeByExtension: Record<string, string> = {
+ json: 'json',
+ js: 'javascript',
+ ts: 'typescript',
+ md: 'markdown',
+ markdown: 'markdown',
+ yaml: 'yaml',
+ yml: 'yaml',
+};
+
+function createFileName(): string {
+ return `NewRule-${nextId++}.weir`;
+}
+
+function getEditorMode(name: string): string {
+ let ext = name.split('.', 2)[1];
+ if (ext == null) {
+ ('text');
+ }
+
+ let mode = modeByExtension[ext];
+ return mode;
+}
+
+function setActiveFile(id: string) {
+ activeFileId = id;
+}
+
+function updateActiveContent(value: string) {
+ if (activeFileId) files.set(activeFileId, value);
+ files = new Map(files);
+}
+
+function createFile() {
+ files.set(createFileName(), newRuleTemplate);
+ files = new Map(files);
+}
+
+function deleteFile(file: string) {
+ files.delete(file);
+ files = new Map(files);
+}
+
+function pushToast(toast: Omit<Toast, 'id'>) {
+ const id = Date.now() + Math.floor(Math.random() * 1000);
+ toasts = [...toasts, { ...toast, id }];
+ setTimeout(() => {
+ toasts = toasts.filter((item) => item.id !== id);
+ }, 4500);
+}
+
+function initializePack(entries: Map<string, string>) {
+ files = entries;
+ activeFileId = entries.keys().next().value ?? null;
+ packLoaded = true;
+}
+
+function openExamplePack() {
+ initializePack(
+ new Map([
+ ['manifest.json', JSON.stringify(defaultManifest, null, 2)],
+ ['ExampleRule.weir', defaultRule],
+ ]),
+ );
+}
+
+function onRenameFile(from: string, to: string) {
+ let origVal = files.get(from);
+
+ if (origVal == undefined) {
+ return;
+ }
+
+ files.set(to, origVal);
+ files.delete(from);
+
+ files = new Map(files);
+}
+
+function createEmptyPack() {
+ const manifest = {
+ ...defaultManifest,
+ name: 'Untitled Weirpack',
+ };
+ initializePack(new Map([['manifest.json', JSON.stringify(manifest, null, 2)]]));
+}
+
+function resetToStartScreen() {
+ files = new Map();
+ activeFileId = null;
+ packLoaded = false;
+ if (browser) {
+ localStorage.removeItem(storageKey);
+ }
+}
+
+function loadWeirpackFromBytes(bytes: Uint8Array) {
+ try {
+ const unpacked = unpackWeirpackBytes(bytes);
+ const entries: Map<string, string> = new Map(unpacked.files);
+ entries.set('manifest.json', JSON.stringify(unpacked.manifest, null, 2));
+
+ nextId = entries.size + 1;
+ initializePack(entries);
+ } catch (error) {
+ pushToast({
+ title: 'Unable to load Weirpack',
+ body: 'Make sure the file is a valid .weirpack archive.',
+ tone: 'error',
+ });
+ }
+}
+
+async function handleUpload(event: Event) {
+ const input = event.currentTarget as HTMLInputElement;
+ if (!input.files?.length) {
+ return;
+ }
+ const file = input.files[0];
+ const bytes = new Uint8Array(await file.arrayBuffer());
+ loadWeirpackFromBytes(bytes);
+ input.value = '';
+}
+
+function parseManifest() {
+ if (!files.has('manifest.json')) {
+ return defaultManifest;
+ }
+ try {
+ const parsed = JSON.parse(files.get('manifest.json')!);
+ return parsed;
+ } catch (error) {
+ pushToast({
+ title: 'manifest.json is invalid',
+ body: 'Fix the JSON before running tests or downloading.',
+ tone: 'error',
+ });
+ return null;
+ }
+}
+
+function validateManifest(manifest: Record<string, unknown>) {
+ const required = ['author', 'version', 'description', 'license'];
+ for (const key of required) {
+ if (typeof manifest[key] !== 'string' || manifest[key] === '') {
+ pushToast({
+ title: `Manifest field missing: ${key}`,
+ body: 'Each field must be a non-empty string.',
+ tone: 'error',
+ });
+ return false;
+ }
+ }
+ return true;
+}
+
+function buildWeirpackBytes(): Uint8Array<ArrayBufferLike> | null {
+ const manifest = parseManifest();
+ if (!manifest || !validateManifest(manifest)) {
+ return null;
+ }
+
+ const normalizedFiles = new Map(files);
+ normalizedFiles.set('manifest.json', JSON.stringify(manifest, null, 2));
+
+ try {
+ return packWeirpackFiles(normalizedFiles);
+ } catch (error) {
+ pushToast({
+ title: 'Weirpack export failed',
+ body: 'manifest.json is required to save a Weirpack.',
+ tone: 'error',
+ });
+ return null;
+ }
+}
+
+function bytesToBase64(bytes: Uint8Array) {
+ let binary = '';
+ for (const byte of bytes) {
+ binary += String.fromCharCode(byte);
+ }
+ return btoa(binary);
+}
+
+function base64ToBytes(base64: string) {
+ const binary = atob(base64);
+ const bytes = new Uint8Array(binary.length);
+ for (let i = 0; i < binary.length; i += 1) {
+ bytes[i] = binary.charCodeAt(i);
+ }
+ return bytes;
+}
+
+function saveWeirpackToStorage() {
+ if (!browser || !packLoaded) {
+ return;
+ }
+ const bytes = buildWeirpackBytes();
+ if (!bytes) {
+ return;
+ }
+ try {
+ localStorage.setItem(storageKey, bytesToBase64(bytes));
+ } catch (error) {
+ console.warn('Unable to store Weirpack', error);
+ }
+}
+
+async function runTests() {
+ if (!packLoaded) {
+ pushToast({
+ title: 'No Weirpack loaded',
+ body: 'Choose a Weirpack to run tests.',
+ tone: 'info',
+ });
+ return;
+ }
+ if (!linter) {
+ pushToast({
+ title: 'Linter still loading',
+ body: 'Give it a moment and try again.',
+ tone: 'info',
+ });
+ return;
+ }
+ const bytes = buildWeirpackBytes();
+ if (!bytes) {
+ return;
+ }
+ runningTests = true;
+ try {
+ const failures = (await linter.loadWeirpackFromBytes(bytes)) as
+ | WeirpackTestFailures
+ | undefined;
+ if (!failures || Object.keys(failures).length === 0) {
+ pushToast({
+ title: 'All tests passed',
+ body: 'The tests in your Weirpack all pass.',
+ tone: 'success',
+ });
+ } else {
+ for (const [ruleName, failuresForRule] of Object.entries(failures)) {
+ for (const failure of failuresForRule) {
+ pushToast({
+ title: `${ruleName} failed`,
+ body: `Expected "${failure.expected}" but got "${failure.got}".`,
+ tone: 'error',
+ });
+ }
+ }
+ }
+ } catch (error) {
+ pushToast({
+ title: 'Unable to run tests',
+ body: 'The Weirpack could not be evaluated. Make sure your rules are syntactically correct.',
+ tone: 'error',
+ });
+ } finally {
+ runningTests = false;
+ }
+}
+
+function downloadWeirpack() {
+ if (!packLoaded) {
+ pushToast({
+ title: 'No Weirpack loaded',
+ body: 'Choose a Weirpack to download.',
+ tone: 'info',
+ });
+ return;
+ }
+ const bytes = buildWeirpackBytes();
+ if (!bytes) {
+ return;
+ }
+ const manifest = parseManifest() ?? defaultManifest;
+ const baseName = String(manifest.name ?? 'weirpack').trim() || 'weirpack';
+ const safeName = baseName.replace(/[^a-zA-Z0-9_-]/g, '-');
+ const blob = new Blob([bytes.slice().buffer], { type: 'application/zip' });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = `${safeName}.weirpack`;
+ link.click();
+ URL.revokeObjectURL(url);
+}
+
+onMount(async () => {
+ if (!browser) {
+ return;
+ }
+ const stored = localStorage.getItem(storageKey);
+ if (stored) {
+ try {
+ const bytes = base64ToBytes(stored);
+ loadWeirpackFromBytes(bytes);
+ } catch (error) {
+ console.warn('Unable to restore Weirpack', error);
+ }
+ }
+ checkingStorage = false;
+
+ const [{ LocalLinter, binary }, { AceEditor }] = await Promise.all([
+ import('harper.js'),
+ import('svelte-ace'),
+ ]);
+
+ await Promise.all([
+ import('brace/mode/json'),
+ import('brace/mode/javascript'),
+ import('brace/mode/markdown'),
+ import('brace/mode/text'),
+ import('brace/mode/typescript'),
+ import('brace/mode/yaml'),
+ import('brace/theme/chrome'),
+ ]);
+
+ const newLinter = new LocalLinter({ binary });
+ await newLinter.setup();
+ linter = newLinter;
+ linterReady = true;
+ AceEditorComponent = AceEditor as unknown as ComponentType;
+ editorReady = true;
+});
+
+setInterval(saveWeirpackToStorage, 5000);
+</script>
+
+<Isolate>
+ <div class="relative flex h-screen w-screen overflow-hidden bg-[#fef4e7] text-black">
+ <div class="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_top,rgba(244,168,62,0.25),transparent_55%)]"></div>
+
+ <WeirStudioWorkspace
+ {drawerOpen}
+ {files}
+ {editorReady}
+ {AceEditorComponent}
+ {editorOptions}
+ {linterReady}
+ {runningTests}
+ {packLoaded}
+ {getEditorMode}
+ activeFile={activeFileId}
+ onToggleDrawer={() => (drawerOpen = !drawerOpen)}
+ onCreateFile={createFile}
+ onSelectFile={setActiveFile}
+ onRenameFile={onRenameFile}
+ onDeleteFile={deleteFile}
+ onUpdateContent={updateActiveContent}
+ onRunTests={runTests}
+ onDownload={downloadWeirpack}
+ onClosePack={resetToStartScreen}
+ />
+
+ <Toasts {toasts} />
+
+ {#if !packLoaded}
+ <WeirStudioStart
+ onUpload={() => fileInputEl?.click()}
+ onOpenExample={openExamplePack}
+ onCreateEmpty={createEmptyPack}
+ onUploadChange={handleUpload}
+ bind:fileInputEl
+ loading={checkingStorage}
+ loadingLabel="Checking local storage for a saved Weirpack."
+ />
+ {/if}
+ </div>
+</Isolate>
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 2d0a0f1ac..97d6ef448 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -176,6 +176,10 @@ importers:
packages/harper.js:
+ dependencies:
+ fflate:
+ specifier: ^0.8.2
+ version: 0.8.2
devDependencies:
'@microsoft/api-documenter':
specifier: ^7.28.1
@@ -393,6 +397,9 @@ importers:
'@sveltepress/vite':
specifier: ^1.1.5
+ brace:
+ specifier: ^0.11.1
+ version: 0.11.1
chart.js:
specifier: ^4.4.8
version: 4.4.8
@@ -426,6 +433,9 @@ importers:
reveal.js:
specifier: ^5.1.0
version: 5.1.0
+ svelte-ace:
+ specifier: ^1.0.21
+ version: 1.0.21
svelte-intersection-observer:
specifier: ^1.0.0
version: 1.0.0
@@ -5374,6 +5384,9 @@ packages:
resolution: {integrity: sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==}
+ resolution: {integrity: sha512-Fc8Ne62jJlKHiG/ajlonC4Sd66Pq68fFwK4ihJGNZpGqboc324SQk+lRvMzpPRuJOmfrJefdG8/7JdWX4bzJ2Q==}
+
resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==}
engines: {node: '>=8'}
@@ -5768,6 +5781,10 @@ packages:
resolution: {integrity: sha512-EiPU8G6dQG0GFHNR8ljnZFki/8a+cQwEQ+7wpxdChl02Q8HXlwEZWD5lqAF8vC2sEC3Tehr8hy7vErz88LHyUA==}
engines: {node: ^14.18.0 || >=16.10.0}
+ resolution: {integrity: sha512-pMD+MVR538ipqkG5JXeOEbKWS5um1H4LUUccUQG68qpeqBYbzYy79Gh55jkd2TtPdRfUaLWdv6LPP//5Zt0aPQ==}
+ engines: {node: '>=4'}
+
resolution: {integrity: sha512-I2hSBi7Vvs7BEuJDr5dDHfzb/Ruj3FyvFyh7KLilAjNQw3Be+xgqUBA2W6scVEcL0hL1dwPRtIqEPVUCKkSsyQ==}
@@ -7159,6 +7176,10 @@ packages:
resolution: {integrity: sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==}
engines: {node: '>=8.0.0'}
+ resolution: {integrity: sha512-x5UJKlgeUiNT8nyo/AcnwLnZuZNcSjSw0kogRB+Whd1fjjFq4B1hySFxSFWWSn4mIBzg3sRNUDFYc4g5gjPoLg==}
+ engines: {node: '>=4'}
+
resolution: {integrity: sha512-g/Q1aTSDOxFpchXC4i8ZWvxA1lnPqx/JHqcpIw0/LX9T8x/GBbi6YnlN5nhaKIFkT8oFsscUKgDJYxfwfS6QsQ==}
engines: {node: '>=8'}
@@ -8487,6 +8508,10 @@ packages:
resolution: {integrity: sha512-xXqpXoINfFhgua9xiqD8fPFHgkoq1mmmpE92WlDbm9rNRd/EbRb+Gqf908T2DMfuHjjJlksiK2RbHVOdD/MqSw==}
engines: {node: '>=8.9.0'}
+ resolution: {integrity: sha512-XfegD5pyTAfb+GY6chk283Ox5z8WexG56OvM06RWLpAc/UHozO8X6xAxEkIitZOtsSMM1Yr3DkHgW5W+onLhCw==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-WunYko2W1NcdfAFpuLUoucsgULmgDBRkdxHxWQ7mK0cQqwPiy8E1enjuRBrhLtZkB5iScJ1XIPdhVEFK8aOLSg==}
engines: {node: '>=14'}
@@ -9015,6 +9040,10 @@ packages:
resolution: {integrity: sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==}
engines: {node: '>=4'}
+ resolution: {integrity: sha512-hzzEagAgDyoU1Q6yg5uI+AorQgdvMCur3FcKf7NhMKWsaYg+RnbTyHRa/9IlLF9rf455MOCtcqqrQQ83pPP7Uw==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-Y3wQdFg2Va6etvQ5I82yUhGdsKrcYox6p7FfL1LbK2J4V01F9TGlepTIhnK24t7koZibmg82KGglhA1XK5IsLQ==}
engines: {node: '>=10'}
@@ -10431,6 +10460,10 @@ packages:
resolution: {integrity: sha512-th5B4L2U+eGLq1TVh7zNRGBapioSORUeymIydxgFpwww9d2qyKvtuPU2jJuHvYAwwqi2Y596QBL3eEqcPEYL8Q==}
engines: {node: '>=10'}
+ resolution: {integrity: sha512-QNI2ChmuioGC1/xjyYwyZYADILWyW6AmS1UH6gDj/SFUUUS4MBAWs/7mxnkRPc/F4iHezDP+O8t0dO8WHiEOdg==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-lH3f6kMbwyANB7HuOWRMlLCa2itaCrZJ+SAqqkSZrZKO/cAsk2EOyaKHUtNkVLFyFW9pct22SFesFp3Z7zpA0g==}
engines: {node: '>= 10.13.0'}
@@ -10578,6 +10611,15 @@ packages:
resolution: {integrity: sha512-D1SaWpOW8afq1CZGWB8xTfrT3FekjQmPValrqncJMX7QFl8YwhrPTZvMCANLtgBwwdS+7zURyqxDDEmY558tTw==}
+ resolution: {integrity: sha512-yyUTNr984ANKDloqepkYbBSqvx3buwYg2sQKPWjSU+IBia5loaoka2If8N9CMwt8AfP179cdEl7kYJ//iWJHjQ==}
+ engines: {node: '>= 10'}
+ hasBin: true
+
+ resolution: {integrity: sha512-JuLThK3TnZG1TAKDwNIqNq6QA2afLOCcm+iE8D1Kj3GA40pSPsxQjjJl0J8X3tsR7T+CP1GavpzLwYkgVLWrZQ==}
+ engines: {node: '>= 10'}
+
resolution: {integrity: sha512-94Bdh3cC2PKrbgSOUqTiGPWVZeSiXfKOVZNJniWoqrWrRkB1CJzBU3NEbiTsPcYy1lDsANA/THzS+9WBiy5nfQ==}
engines: {node: '>= 10'}
@@ -10928,6 +10970,9 @@ packages:
resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==}
engines: {node: '>= 0.4'}
+ resolution: {integrity: sha512-Ek86AiCNcBYH84P90NmQh4GLW9TB5jZP0zBhqPJ/dGRdOP+LOQ+gQIQ1JyTzYpMGQVlDUb9Ug4yo0hCGWNnjaw==}
+
resolution: {integrity: sha512-DVWvxhBrDsd+0hHWKfjP99lsSXASeOhHJYyuKOFYJcP7ThfSCKgjVarE8XfuMWpS5JV3AlDf+iK1YGGo2TACdw==}
engines: {node: '>= 18.0.0'}
@@ -11133,6 +11178,10 @@ packages:
resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==}
+ resolution: {integrity: sha512-7cR8rLy2QhYHpsBDBVYnnWXm8uRTr38RoZakFSW7Bs7PzfMPNZthuMLkwqZv7MTu8lhQ91cOFYS5a7iFj2oR3w==}
+ engines: {node: '>=4'}
+
resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==}
@@ -11177,6 +11226,10 @@ packages:
resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==}
engines: {node: '>=0.6'}
+ resolution: {integrity: sha512-gduQwd1rOdDMGxFG1gEvhV88Oirdo2p+KjoYFU7k2g+i7n6AFFbDQ5kMPUsW0pNbfQsB/cwXvT1i4Bue0s9g5g==}
+ engines: {node: '>=6'}
+
resolution: {integrity: sha512-sf4i37nQ2LBx4m3wB74y+ubopq6W/dIzXg0FDGjsYnZHVa1Da8FH853wlL2gtUhg+xJXjfk3kUZS3BRoQeoQBQ==}
engines: {node: '>=6'}
@@ -19020,6 +19073,8 @@ snapshots:
dependencies:
balanced-match: 1.0.2
+
dependencies:
fill-range: 7.1.1
@@ -19453,6 +19508,8 @@ snapshots:
+
dependencies:
no-case: 3.0.4
@@ -21076,6 +21133,8 @@ snapshots:
+
@@ -22696,6 +22755,8 @@ snapshots:
emojis-list: 3.0.0
json5: 2.2.3
+
dependencies:
mlly: 1.7.4
@@ -23398,6 +23459,8 @@ snapshots:
+
@@ -24935,6 +24998,8 @@ snapshots:
'@types/node-forge': 1.3.11
node-forge: 1.3.1
+
dependencies:
sver: 1.8.4
@@ -25156,6 +25221,23 @@ snapshots:
transitivePeerDependencies:
- supports-color
+ dependencies:
+ console-clear: 1.1.1
+ get-port: 3.2.0
+ kleur: 3.0.3
+ local-access: 1.1.0
+ sade: 1.8.1
+ semiver: 1.1.0
+ sirv: 1.0.19
+ tinydate: 1.3.0
+
+ dependencies:
+ '@polka/url': 1.0.0-next.28
+ mrmime: 1.0.1
+ totalist: 1.1.0
+
dependencies:
'@polka/url': 1.0.0-next.28
@@ -25583,6 +25665,11 @@ snapshots:
+ dependencies:
+ brace: 0.11.1
+ sirv-cli: 1.0.14
+
dependencies:
'@jridgewell/trace-mapping': 0.3.25
@@ -25807,6 +25894,8 @@ snapshots:
+
@@ -25843,6 +25932,8 @@ snapshots:
+