hedl-wasm 2.0.0

WebAssembly bindings for HEDL with TypeScript support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
# hedl-wasm

**Parse, validate, and convert HEDL documents directly in browsers and Node.js with near-native performance.**

Every web developer has faced the same frustration: JSON is everywhere but loses type information, YAML parsers are heavy, and XML processing adds complexity. What if you could parse structured data at near-native speed, validate it with full schema checking, and convert between formats instantly, all without leaving JavaScript?

That's what `hedl-wasm` delivers. The complete Rust HEDL implementation, compiled to WebAssembly, running in your browser or Node.js environment. Parse multi-megabyte documents at 50-100 MB/s. Validate data structures client-side before they ever hit your server. Convert seamlessly between HEDL, JSON, YAML, XML, and CSV with zero compromises on correctness.

## Installation

```bash
npm install hedl-wasm
```

## Quick Start

### Browser (ESM)

```html
<script type="module">
  import init, { parse, validate, toJson } from './hedl_wasm.js';

  await init();

  const doc = parse(`
%V:2.0
%S:User:[id, name, age]
---
users: @User
 | alice, Alice Smith, 30
 | bob, Bob Jones, 25
  `);

  console.log('Parsed:', doc);
  console.log('JSON:', doc.toJson());
</script>
```

### Node.js (CommonJS)

```javascript
const hedl = require('hedl-wasm');

const doc = hedl.parse(`
%V:2.0
---
config:
  name: MyApp
  version: 1.0.0
`);

console.log('Document:', doc);
```

### Node.js (ESM)

```javascript
import init, { parse, validate } from 'hedl-wasm';

await init();

const result = validate(hedlContent);

if (result.valid) {
  console.log('Valid HEDL document');
} else {
  result.errors.forEach(err => {
    console.error(`Line ${err.line}: ${err.message}`);
  });
}
```

## Core API

### parse(input: string): HedlDocument

Parse HEDL content into a structured document.

```javascript
import { parse } from 'hedl-wasm';

const doc = parse(`
%V:2.0
%S:User:[id, name, email]
---
users: @User
 | alice, Alice Smith, alice@example.com
 | bob, Bob Jones, bob@example.com
`);

console.log('Version:', doc.version);
console.log('Schemas:', doc.getSchemaNames());
console.log('Aliases:', doc.getAliases());
```

**Returns**: `HedlDocument` with these properties:
- `version: string` - HEDL version (e.g., "2.0")
- `schemaCount: number` - Number of schema definitions
- `aliasCount: number` - Number of aliases
- `nestCount: number` - Number of nest relationships
- `rootItemCount: number` - Number of root items

**Methods**:
- `getSchemaNames(): string[]` - Get all schema type names
- `getSchema(typeName: string): string[] | null` - Get schema columns for a type
- `getAliases(): object` - Get all aliases as a JSON object
- `getNests(): object` - Get all nest relationships
- `countEntities(): object` - Count entities by type
- `query(typeName?: string, id?: string): Array<{ type: string, id: string, fields: object }>` - Query entities (requires "query-api" feature)
- `toJson(): JsonValue` - Convert to JSON object (requires "json" feature)
- `toJsonString(pretty?: boolean): string` - Convert to JSON string (requires "json" feature)
- `toHedl(): string` - Convert to canonical HEDL string

**Throws**: `JsError` on parse failure with line number information in the message.

### validate(input: string, runLint?: boolean): ValidationResult

Validate HEDL documents and return detailed diagnostics.

```javascript
import { validate } from 'hedl-wasm';

const result = validate(hedlContent, true);

if (!result.valid) {
  result.errors.forEach(err => {
    console.error(`Line ${err.line} [${err.type}]: ${err.message}`);
  });
}

result.warnings.forEach(warn => {
  console.warn(`Line ${warn.line} [${warn.rule}]: ${warn.message}`);
});
```

**Parameters**:
- `input: string` - HEDL document content
- `runLint?: boolean` - Enable lint checks (default: true, requires "full-validation" feature)

**Returns**: `ValidationResult` with:
- `valid: boolean` - Whether document is valid
- `errors: Array<{ line: number, message: string, type: string }>` - Parse and validation errors
- `warnings: Array<{ line: number, message: string, rule: string }>` - Lint warnings

### format(input: string): string

Format and canonicalize HEDL documents.

```javascript
import { format } from 'hedl-wasm';

const formatted = format(messyHedl);
```

Returns normalized HEDL with consistent indentation, float representation, and spacing.

### version(): string

Get the HEDL library version.

```javascript
import { version } from 'hedl-wasm';

console.log('HEDL version:', version());
```

### setMaxInputSize(size: number): void

Configure the maximum input size in bytes for all parsing operations.

```javascript
import { setMaxInputSize } from 'hedl-wasm';

// Allow processing up to 1 GB documents
setMaxInputSize(1024 * 1024 * 1024);
```

Default is 500 MB. The size check runs before parsing to prevent memory exhaustion.

### getMaxInputSize(): number

Get the current maximum input size configuration.

```javascript
import { getMaxInputSize } from 'hedl-wasm';

const currentLimit = getMaxInputSize();
console.log(`Current limit: ${currentLimit / (1024 * 1024)} MB`);
```

## Format Conversion

All conversion functions work both as standalone functions on strings and as methods on `HedlDocument` objects.

### toJson(input: string, pretty?: boolean): string

Convert HEDL to JSON. Requires the **"json"** feature flag.

```javascript
import { toJson } from 'hedl-wasm';

const json = toJson(hedlContent, true); // true for pretty-print
```

### fromJson(json: string): string

Convert JSON to HEDL. Requires the **"json"** feature flag.

```javascript
import { fromJson } from 'hedl-wasm';

const hedl = fromJson(jsonString);
```

### toYaml(input: string): string

Convert HEDL to YAML. Requires the **"yaml"** feature flag.

```javascript
import { toYaml } from 'hedl-wasm';

const yaml = toYaml(hedlContent);
```

### fromYaml(yaml: string): string

Convert YAML to HEDL. Requires the **"yaml"** feature flag.

```javascript
import { fromYaml } from 'hedl-wasm';

const hedl = fromYaml(yamlContent);
```

### toXml(input: string): string

Convert HEDL to XML. Requires the **"xml"** feature flag.

```javascript
import { toXml } from 'hedl-wasm';

const xml = toXml(hedlContent);
```

### fromXml(xml: string): string

Convert XML to HEDL. Requires the **"xml"** feature flag.

```javascript
import { fromXml } from 'hedl-wasm';

const hedl = fromXml(xmlContent);
```

### toCsv(input: string): string

Convert HEDL to CSV (first entity list). Requires the **"csv"** feature flag.

```javascript
import { toCsv } from 'hedl-wasm';

const csv = toCsv(hedlContent);
```

### fromCsv(csv: string, typeName?: string): string

Convert CSV to HEDL. Requires the **"csv"** feature flag.

```javascript
import { fromCsv } from 'hedl-wasm';

const hedl = fromCsv(csvContent, 'User');
```

**Parameters**:
- `csv: string` - CSV content (must have header row)
- `typeName?: string` - Entity type name (default: "Row")

### toToon(input: string): string

Convert HEDL to TOON format. Requires the **"toon"** feature flag.

```javascript
import { toToon } from 'hedl-wasm';

const toon = toToon(hedlContent);
```

### fromToon(toon: string): string

Convert TOON to HEDL. Requires the **"toon"** feature flag.

```javascript
import { fromToon } from 'hedl-wasm';

const hedl = fromToon(toonContent);
```

## Statistics and Analysis

### getStats(input: string): TokenStats

Get token usage statistics comparing HEDL to JSON. Requires the **"statistics"** feature flag.

```javascript
import { getStats } from 'hedl-wasm';

const stats = getStats(hedlContent);

console.log('HEDL bytes:', stats.hedlBytes);
console.log('HEDL tokens:', stats.hedlTokens);
console.log('JSON bytes:', stats.jsonBytes);
console.log('JSON tokens:', stats.jsonTokens);
console.log('Savings:', stats.savingsPercent + '%');
```

**Returns**: `TokenStats` with:
- `hedlBytes: number` - Input HEDL size in bytes
- `hedlTokens: number` - Estimated token count for HEDL
- `hedlLines: number` - Line count in HEDL
- `jsonBytes: number` - Equivalent JSON size in bytes
- `jsonTokens: number` - Estimated token count for JSON
- `savingsPercent: number` - Token savings percentage
- `tokensSaved: number` - Absolute token count difference

### compareTokens(hedl: string, json: string): object

Compare token counts between HEDL and JSON. Requires the **"token-tools"** feature flag.

```javascript
import { compareTokens } from 'hedl-wasm';

const comparison = compareTokens(hedlString, jsonString);

console.log('HEDL tokens:', comparison.hedl.tokens);
console.log('JSON tokens:', comparison.json.tokens);
console.log('Savings:', comparison.savings.percent + '%');
```

**Returns**: Object with:
- `hedl: { bytes: number, tokens: number, lines: number }`
- `json: { bytes: number, tokens: number }`
- `savings: { percent: number, tokens: number }`

## Error Handling

All functions throw structured errors with line number information.

```javascript
try {
  const doc = parse(invalidHedl);
} catch (error) {
  console.error(`Parse error: ${error.message}`);
}
```

When using `validate()`, errors are returned in the `ValidationResult` object with:
- `line: number` - Source line number (1-indexed)
- `message: string` - Human-readable description
- `type: string` - Error category

**Error Types**:
- `Syntax` - Invalid HEDL syntax
- `Schema` - Type/schema mismatch
- `Reference` - Unresolved reference
- `ShapeMismatch` - Column count mismatch
- `OrphanRow` - Child without parent
- `Utf8` - Invalid UTF-8 encoding
- `MaxSizeExceeded` - Input too large

## TypeScript Support

Complete type definitions are included for full IntelliSense support.

```typescript
import {
  parse,
  validate,
  format,
  toJson,
  fromJson,
  getStats,
  compareTokens,
  HedlDocument,
  ValidationResult,
  TokenStats
} from 'hedl-wasm';

const doc: HedlDocument = parse(content);

const result: ValidationResult = validate(content, false);

if (!result.valid) {
  result.errors.forEach(err => {
    console.error(`Line ${err.line}: ${err.message}`);
  });
}

const stats: TokenStats = getStats(content);
console.log(`Savings: ${stats.savingsPercent}%`);
```

**Exported Types**:
- `HedlDocument` - Parsed HEDL document with methods
- `ValidationResult` - Validation diagnostics
- `TokenStats` - Token usage statistics
- `JsonValue` - JSON value union type
- `JsonPrimitive` - JSON primitive types
- `JsonObject` - JSON object type
- `JsonArray` - JSON array type

## Bundle Sizes

Optimized for web delivery with `wasm-opt -Os`, tree-shaking support, and dead code elimination.

| Format | Size |
|--------|------|
| Uncompressed | ~600 KB |
| Gzipped | ~200 KB |
| Brotli | ~180 KB |

**Bundle Variants**:
- `hedl_wasm.js` - ESM for browsers
- `hedl_wasm_node.js` - CommonJS for Node.js
- `hedl_wasm_bg.wasm` - WebAssembly binary
- `hedl.d.ts` - TypeScript definitions

## Performance

Parsing runs at near-native speed, typically within 10% of the pure Rust implementation. Expect 50-100 MB/s throughput on modern browsers. Token estimation uses an O(1) memory algorithm with efficient byte-level iteration, running 3x faster than character-by-character approaches.

Memory scales linearly with document size. Initial WASM module load adds approximately 50-100ms overhead, a one-time cost per page load.

## Building from Source

### Prerequisites

```bash
cargo install wasm-pack
cargo install wasm-tools
cargo install wasm-bindgen-cli --version 0.2.108
```

### Build

```bash
cd crates/hedl-wasm

# Build for browsers
./build-wasm.sh web

# Build for bundlers (webpack, etc.)
./build-wasm.sh bundler

# Build for Node.js
./build-wasm.sh nodejs
```

Output is placed in `pkg/`:
- `hedl_wasm.js` - JavaScript glue code
- `hedl_wasm.d.ts` - TypeScript definitions
- `hedl_wasm_bg.wasm` - WebAssembly binary

## License

Apache-2.0