rustica 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of rustica might be problematic. Click here for more details.

@@ -0,0 +1,118 @@
1
+ /**
2
+ * Lazy-loaded WASM module singleton
3
+ */
4
+ let wasmModule = null;
5
+ /**
6
+ * Initialize WASM module
7
+ * Must be called before validation
8
+ */
9
+ export async function initWasm() {
10
+ if (wasmModule)
11
+ return;
12
+ try {
13
+ // Dynamic import of WASM module
14
+ const module = (await import("../../pkg/rustica.js"));
15
+ // For web target, call init function. For nodejs target, it's already loaded
16
+ if (typeof module.default === "function") {
17
+ await module.default();
18
+ }
19
+ wasmModule = module;
20
+ }
21
+ catch (error) {
22
+ throw new Error(`Failed to load WASM module. Make sure to run 'npm run build:wasm' first. Error: ${error}`);
23
+ }
24
+ }
25
+ /**
26
+ * Get initialized WASM module
27
+ */
28
+ function getWasm() {
29
+ if (!wasmModule) {
30
+ throw new Error("WASM module not initialized. Call initWasm() before validation.");
31
+ }
32
+ return wasmModule;
33
+ }
34
+ /**
35
+ * Core validator using WASM
36
+ */
37
+ export class Validator {
38
+ /**
39
+ * Validate data against a schema
40
+ *
41
+ * @param schema - Schema definition (builder or JSON)
42
+ * @param value - Data to validate
43
+ * @returns Validation result with errors if any
44
+ */
45
+ static validate(schema, value) {
46
+ const wasm = getWasm();
47
+ // Serialize schema to JSON
48
+ const schemaJson = JSON.stringify(schema instanceof Object && "toJSON" in schema ? schema.toJSON() : schema);
49
+ // Serialize value to JSON
50
+ const valueJson = JSON.stringify(value);
51
+ // Call WASM validator (single call, zero-copy)
52
+ const resultJson = wasm.WasmValidator.validate(schemaJson, valueJson);
53
+ // Parse result
54
+ return JSON.parse(resultJson);
55
+ }
56
+ /**
57
+ * Validate data at a specific path in the schema
58
+ * Useful for field-level validation in forms
59
+ *
60
+ * @param schema - Schema definition
61
+ * @param value - Complete data object
62
+ * @param path - Path to validate (e.g., ['user', 'email'])
63
+ * @returns Validation result for the specific field
64
+ */
65
+ static validateAtPath(schema, value, path) {
66
+ const wasm = getWasm();
67
+ // Serialize inputs
68
+ const schemaJson = JSON.stringify(schema instanceof Object && "toJSON" in schema ? schema.toJSON() : schema);
69
+ const valueJson = JSON.stringify(value);
70
+ const pathJson = JSON.stringify(path);
71
+ // Call WASM validator (single call)
72
+ const resultJson = wasm.WasmValidator.validate_at_path(schemaJson, valueJson, pathJson);
73
+ // Parse result
74
+ return JSON.parse(resultJson);
75
+ }
76
+ /**
77
+ * Validate and throw on error (for convenience)
78
+ */
79
+ static parse(schema, value) {
80
+ const result = this.validate(schema, value);
81
+ if (!result.success) {
82
+ throw new ValidationException(result.errors || []);
83
+ }
84
+ return value;
85
+ }
86
+ /**
87
+ * Safe parse that returns result object
88
+ */
89
+ static safeParse(schema, value) {
90
+ const result = this.validate(schema, value);
91
+ if (result.success) {
92
+ return { success: true, data: value };
93
+ }
94
+ else {
95
+ return { success: false, errors: result.errors || [] };
96
+ }
97
+ }
98
+ }
99
+ /**
100
+ * Validation exception for parse() method
101
+ */
102
+ export class ValidationException extends Error {
103
+ constructor(errors) {
104
+ super("Validation failed:\n" +
105
+ errors.map((e) => ` - ${e.path.join(".")}: ${e.message}`).join("\n"));
106
+ this.errors = errors;
107
+ this.name = "ValidationException";
108
+ }
109
+ }
110
+ /**
111
+ * Auto-initialization wrapper
112
+ * Automatically initializes WASM on first use
113
+ */
114
+ export async function createValidator() {
115
+ await initWasm();
116
+ return Validator;
117
+ }
118
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/validator/index.ts"],"names":[],"mappings":"AAsBA;;GAEG;AACH,IAAI,UAAU,GAAsB,IAAI,CAAC;AAEzC;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,QAAQ;IAC5B,IAAI,UAAU;QAAE,OAAO;IAEvB,IAAI,CAAC;QACH,gCAAgC;QAChC,MAAM,MAAM,GAAG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,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IAC5C,YAAmB,MAAyB;QAC1C,KAAK,CACH,sBAAsB;YACpB,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,OAAO,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CACxE,CAAC;QAJe,WAAM,GAAN,MAAM,CAAmB;QAK1C,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;IACpC,CAAC;CACF;AAED;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,eAAe;IACnC,MAAM,QAAQ,EAAE,CAAC;IACjB,OAAO,SAAS,CAAC;AACnB,CAAC"}
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "rustica",
3
+ "version": "0.1.0",
4
+ "description": "Production-grade schema validation powered by Rust and WebAssembly",
5
+ "author": "Nikos Kechris",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/fourth-ally/rustica.git"
10
+ },
11
+ "homepage": "https://github.com/fourth-ally/rustica#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/fourth-ally/rustica/issues"
14
+ },
15
+ "type": "module",
16
+ "main": "./dist/index.js",
17
+ "types": "./dist/index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./dist/index.d.ts",
21
+ "import": "./dist/index.js"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist",
26
+ "pkg",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "scripts": {
31
+ "build:wasm": "wasm-pack build --target bundler --out-dir pkg",
32
+ "build:wasm:node": "wasm-pack build --target nodejs --out-dir pkg",
33
+ "build:ts": "tsc",
34
+ "build": "npm run build:wasm && npm run build:ts",
35
+ "build:npm": "node scripts/build-npm.cjs",
36
+ "dev": "tsc --watch",
37
+ "test": "cargo test && npm run test:ts",
38
+ "test:ts": "npm run build:wasm:node && node --import tsx --test tests/*.test.ts",
39
+ "prepublishOnly": "npm run build:npm"
40
+ },
41
+ "keywords": [
42
+ "validation",
43
+ "schema",
44
+ "wasm",
45
+ "webassembly",
46
+ "rust",
47
+ "zod",
48
+ "forms",
49
+ "react",
50
+ "typescript",
51
+ "validator",
52
+ "yup",
53
+ "joi",
54
+ "form-validation",
55
+ "schema-validation"
56
+ ],
57
+ "devDependencies": {
58
+ "@types/node": "^25.0.9",
59
+ "@types/react": "^18.2.0",
60
+ "react": "^18.2.0",
61
+ "tsx": "^4.7.0",
62
+ "typescript": "^5.3.0"
63
+ },
64
+ "peerDependencies": {
65
+ "react": ">=18.0.0"
66
+ },
67
+ "peerDependenciesMeta": {
68
+ "react": {
69
+ "optional": true
70
+ }
71
+ }
72
+ }
package/pkg/README.md ADDED
@@ -0,0 +1,228 @@
1
+ # Rust-JS Validator
2
+
3
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.3-blue)](https://www.typescriptlang.org/)
5
+ [![Rust](https://img.shields.io/badge/Rust-1.70+-orange)](https://www.rust-lang.org/)
6
+ [![WebAssembly](https://img.shields.io/badge/WebAssembly-✓-blueviolet)](https://webassembly.org/)
7
+
8
+ Production-grade Zod-like schema and form validation system powered by Rust and WebAssembly.
9
+
10
+ ## ✨ Features
11
+
12
+ <table>
13
+ <tr>
14
+ <td width="50%">
15
+
16
+ ### 🦀 Rust Core
17
+
18
+ - **WASM-powered** validation
19
+ - **Zero-copy** architecture
20
+ - **~0.1-0.5ms** per validation
21
+ - **Single call** per validation
22
+
23
+ </td>
24
+ <td width="50%">
25
+
26
+ ### 📝 TypeScript API
27
+
28
+ - **Fluent API** like Zod
29
+ - **Full type inference**
30
+ - **Schema serialization**
31
+ - **Custom error messages**
32
+ - **UI metadata** support
33
+
34
+ </td>
35
+ </tr>
36
+ <tr>
37
+ <td width="50%">
38
+
39
+ ### ⚛️ React Integration
40
+
41
+ - **useWasmForm** hook
42
+ - **Field registration**
43
+ - **Auto re-rendering**
44
+ - **RHF-compatible** API
45
+
46
+ </td>
47
+ <td width="50%">
48
+
49
+ ### 🔧 Framework Agnostic
50
+
51
+ - **createForm** for any framework
52
+ - **Vanilla JS** support
53
+ - **Node.js** compatible
54
+ - **Browser** ready
55
+
56
+ </td>
57
+ </tr>
58
+ </table>
59
+
60
+ ## Installation
61
+
62
+ ```bash
63
+ npm install rustica
64
+ ```
65
+
66
+ ## Quick Start
67
+
68
+ ```typescript
69
+ import { r, useWasmForm } from 'rustica';
70
+
71
+ // Define schema
72
+ const loginSchema = r.object({
73
+ email: r.string().min(3, 'Email must be at least 3 characters').email('Please enter a valid email').ui({ label: "Email" }),
74
+ password: r.string().min(8, 'Password must be at least 8 characters').ui({ label: "Password" })
75
+ });
76
+
77
+ // Infer types
78
+ type LoginForm = r.Infer<typeof loginSchema>;
79
+
80
+ // Use in React
81
+ function LoginForm() {
82
+ const form = useWasmForm({
83
+ schema: loginSchema,
84
+ defaultValues: { email: '', password: '' },
85
+ onSubmit: async (data) => {
86
+ console.log('Valid data:', data);
87
+ }
88
+ });
89
+
90
+ return (
91
+ <form onSubmit={form.handleSubmit}>
92
+ <input {...form.register('email')} />
93
+ {form.errors.email && <span>{form.errors.email.message}</span>}
94
+
95
+ <input type="password" {...form.register('password')} />
96
+ {form.errors.password && <span>{form.errors.password.message}</span>}
97
+
98
+ <button type="submit">Login</button>
99
+ </form>
100
+ );
101
+ }
102
+ ```
103
+
104
+ ## Building from Source
105
+
106
+ ```bash
107
+ # Quick setup (recommended)
108
+ chmod +x scripts/setup.sh
109
+ ./scripts/setup.sh
110
+
111
+ # Or manual setup
112
+ npm install
113
+ npm run build
114
+ ```
115
+
116
+ See [Getting Started Guide](./docs/GETTING_STARTED.md) for detailed instructions.
117
+
118
+ ## Architecture
119
+
120
+ - **Rust Core** (`src/lib.rs`, `src/schema.rs`, `src/validator.rs`) - Schema definitions and validation logic
121
+ - **WASM Interface** (`src/wasm.rs`) - WebAssembly bindings with wasm-bindgen
122
+ - **TypeScript Schema Builder** (`src/schema/`) - Fluent API for schema definition
123
+ - **Form Runtime** (`src/form/`) - Form state management
124
+ - **React Hook** (`src/react/`) - React integration
125
+
126
+ ## Documentation
127
+
128
+ - 📖 **[Complete Documentation Index](./docs/INDEX.md)** - All docs in one place
129
+ - 🚀 **[Getting Started Guide](./docs/GETTING_STARTED.md)** - Quick start tutorial
130
+ - 📚 **[API Reference](./docs/API.md)** - Complete API documentation
131
+ - 💬 **[Custom Error Messages](./docs/custom-messages.md)** - User-friendly validation messages
132
+ - 🏗️ **[Architecture Guide](./docs/ARCHITECTURE.md)** - How it works
133
+ - 📊 **[Feature Comparison](./docs/COMPARISON.md)** - vs Zod, Yup, Joi
134
+ - 🤝 **[Contributing Guide](./CONTRIBUTING.md)** - How to contribute
135
+
136
+ ## Project Structure
137
+
138
+ ```
139
+ rustica/
140
+ ├── src/ # Rust source (validation core)
141
+ │ ├── lib.rs # Module exports
142
+ │ ├── schema.rs # Schema AST types
143
+ │ ├── validator.rs # Validation engine
144
+ │ └── wasm.rs # WASM bindings
145
+ ├── src/ # TypeScript source
146
+ │ ├── schema/ # Schema builders (r.string(), etc.)
147
+ │ ├── validator/ # WASM wrapper
148
+ │ ├── form/ # Form runtime
149
+ │ ├── react/ # React hooks
150
+ │ └── index.ts # Main entry point
151
+ ├── examples/ # Usage examples
152
+ │ ├── quick-test.ts # Basic validation tests
153
+ │ ├── standalone.ts # Standalone examples
154
+ │ ├── forms.tsx # Form component examples
155
+ │ └── react-form-app/ # Full React app with API integration
156
+ ├── tests/ # Test suite
157
+ ├── docs/ # Documentation
158
+ └── scripts/ # Build scripts
159
+ ```
160
+
161
+ ## Commands
162
+
163
+ ```bash
164
+ # Development
165
+ make install # Install dependencies
166
+ make build # Build WASM + TypeScript
167
+ make test # Run all tests
168
+ make dev # Watch mode
169
+
170
+ # Quick Commands
171
+ make example # Run quick test
172
+ make clean # Clean build artifacts
173
+ make help # Show all commands
174
+ ```
175
+
176
+ ## Performance
177
+
178
+ <table>
179
+ <tr>
180
+ <td><b>Metric</b></td>
181
+ <td><b>Value</b></td>
182
+ <td><b>Notes</b></td>
183
+ </tr>
184
+ <tr>
185
+ <td>Validation Speed</td>
186
+ <td>~0.1-0.5ms</td>
187
+ <td>Per validation (warm)</td>
188
+ </tr>
189
+ <tr>
190
+ <td>Throughput</td>
191
+ <td>5,000-10,000/sec</td>
192
+ <td>1000 validations in ~100-200ms</td>
193
+ </tr>
194
+ <tr>
195
+ <td>WASM Size</td>
196
+ <td>~15-20KB</td>
197
+ <td>Gzipped: ~8-10KB</td>
198
+ </tr>
199
+ <tr>
200
+ <td>Overhead</td>
201
+ <td>Single call</td>
202
+ <td>Zero-copy where possible</td>
203
+ </tr>
204
+ </table>
205
+
206
+ See [Performance Comparison](./docs/COMPARISON.md) for detailed benchmarks.
207
+
208
+ ## Contributing
209
+
210
+ We welcome contributions! See [CONTRIBUTING.md](./CONTRIBUTING.md) for guidelines.
211
+
212
+ ## Roadmap
213
+
214
+ - [x] Core validation (string, number, boolean, object)
215
+ - [x] React hooks
216
+ - [x] Form runtime
217
+ - [x] Type inference
218
+ - [x] Custom error messages
219
+ - [ ] Array/tuple schemas
220
+ - [ ] Union/intersection types
221
+ - [ ] Async validation helpers
222
+ - [ ] i18n support
223
+
224
+ See [CHANGELOG.md](./CHANGELOG.md) for version history.
225
+
226
+ ## License
227
+
228
+ MIT