tjs-lang 0.7.5 → 0.7.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/demo/docs.json CHANGED
@@ -1619,4 +1619,4 @@
1619
1619
  "navTitle": "TJS for TS Devs",
1620
1620
  "text": "<!--{\"section\": \"tjs-for-ts\", \"group\": \"docs\", \"order\": 0, \"navTitle\": \"TJS for TS Devs\"}-->\n\n# TJS for TypeScript Programmers\n\n_What if your types didn't disappear at runtime?_\n\n---\n\nTypeScript is great. It catches bugs at compile time, makes refactoring safer,\nand gives you autocomplete. But it has a fundamental limitation: types are\nfiction. They exist only in your editor, and they vanish completely at runtime.\n\nTJS starts from a different premise: **types are example values that survive\nto runtime**. This gives you everything TypeScript gives you, plus runtime\nvalidation, reflection, documentation, inline tests of private methods, and traceability of errors back to source code -- from a single source of truth.\n\nThis guide is split into two paths:\n\n1. **[Using TJS from TypeScript](#part-1-using-tjs-from-typescript)** -- Keep your TS codebase, use TJS for safe eval and agent execution\n2. **[Migrating to TJS](#part-2-migrating-to-tjs)** -- Convert your codebase from TypeScript to TJS\n\n---\n\n# Part 1: Using TJS from TypeScript\n\nYou don't have to rewrite anything. TJS provides tools you can use directly\nfrom your TypeScript codebase.\n\n## Safe Eval\n\nThe most common reason to reach for TJS from TypeScript: running untrusted\ncode safely.\n\n```typescript\nimport { Eval, SafeFunction } from 'tjs-lang/eval'\n\n// Run user-provided code with a gas limit\nconst { result, fuelUsed } = await Eval({\n code: userCode,\n context: { items: data, threshold: 10 },\n fuel: 1000,\n capabilities: {\n fetch: sandboxedFetch, // your whitelist-wrapped fetch\n },\n})\n\n// Or create a reusable safe function\nconst transform = await SafeFunction({\n body: 'return items.filter(x => x.price < budget)',\n params: ['items', 'budget'],\n fuel: 500,\n})\n\nconst { result } = await transform(products, 100)\n```\n\nNo `eval()`. No CSP violations. No Docker containers. The code runs in a\nfuel-metered sandbox with only the capabilities you inject.\n\n## Agent VM\n\nBuild and execute JSON-serializable agents:\n\n```typescript\nimport { ajs, AgentVM } from 'tjs-lang'\n\n// Parse agent source to JSON AST\nconst agent = ajs`\n function analyze({ data, query }) {\n let filtered = data.filter(x => x.score > 0.5)\n let summary = llmPredict({\n prompt: 'Summarize findings for: ' + query,\n data: filtered\n })\n return { query, summary, count: filtered.length }\n }\n`\n\n// Execute with resource limits\nconst vm = new AgentVM()\nconst { result } = await vm.run(\n agent,\n { data, query },\n {\n fuel: 1000,\n timeoutMs: 5000,\n capabilities: { fetch: myFetch, llm: myLlm },\n }\n)\n```\n\nThe agent AST is JSON. You can store it in a database, send it over the\nnetwork, version it, diff it, audit it.\n\n## Type-Safe Builder\n\nConstruct agents programmatically with full TypeScript support:\n\n```typescript\nimport { Agent, AgentVM, s } from 'tjs-lang'\n\nconst pipeline = Agent.take(s.object({ url: s.string, maxResults: s.number }))\n .httpFetch({ url: { $kind: 'arg', path: 'url' } })\n .as('response')\n .varSet({\n key: 'results',\n value: {\n $expr: 'member',\n object: { $expr: 'ident', name: 'response' },\n property: 'items',\n },\n })\n .return(s.object({ results: s.array(s.any) }))\n\nconst vm = new AgentVM()\nconst { result } = await vm.run(\n pipeline.toJSON(),\n { url, maxResults: 10 },\n {\n fuel: 500,\n capabilities: { fetch },\n }\n)\n```\n\n## TypeScript Entry Points\n\nTJS is tree-shakeable. Import only what you need:\n\n```typescript\nimport { Agent, AgentVM, ajs, tjs } from 'tjs-lang' // Everything\nimport { Eval, SafeFunction } from 'tjs-lang/eval' // Safe eval only\nimport { tjs, transpile } from 'tjs-lang/lang' // Language tools\nimport { fromTS } from 'tjs-lang/lang/from-ts' // TS -> TJS converter\n```\n\n## When to Stay in TypeScript\n\nIf your codebase is TypeScript and you're happy with it, you probably only\nneed TJS for:\n\n- Running user-provided or LLM-generated code safely\n- Building agents that travel over the network\n- Adding runtime type validation at system boundaries\n- Eval without `eval()`\n\nYou don't need to migrate anything. The libraries work from TypeScript.\n\n---\n\n# Part 2: Migrating to TJS\n\nIf you want the full TJS experience -- runtime types, structural equality,\nmonadic errors, inline tests -- here's how to convert.\n\n## The Core Idea: Types as Examples\n\nTypeScript describes types abstractly. TJS describes them concretely:\n\n```typescript\n// TypeScript: what TYPE is this?\nfunction greet(name: string): string { ... }\n\n// TJS: what's an EXAMPLE of this?\nfunction greet(name: 'World'): '' { ... }\n```\n\n`'World'` tells TJS: this is a string, it's required, and here's a valid\nexample. The example doubles as documentation and test data.\n\n## Conversion Reference\n\n### Primitives\n\n```typescript\n// TypeScript // TJS\nname: string name: ''\ncount: number count: 0.0 // float (any number)\nindex: number index: 0 // integer\nage: number age: +0 // non-negative integer\nflag: boolean flag: true\nitems: string[] items: ['']\nnested: number[][] nested: [[0]]\n```\n\n**Important:** The example value determines the _type_, not a literal\nconstraint. `name: 'World'` means \"required string\" -- not \"must be the\nstring `'World'`.\" Any string passes validation. The example is there for\ndocumentation, testing, and type inference. Think of it as `string` with\na built-in `@example` tag.\n\n**Numeric precision:** TJS distinguishes three numeric types using valid\nJavaScript syntax that JS itself ignores:\n\n| You Write | TJS Type | Runtime Check |\n| --------- | ---------------------- | ------------------------------- |\n| `3.14` | `number` (float) | Any number |\n| `0.0` | `number` (float) | Any number |\n| `42` | `integer` | `Number.isInteger(x)` |\n| `0` | `integer` | `Number.isInteger(x)` |\n| `+20` | `non-negative integer` | `Number.isInteger(x) && x >= 0` |\n| `+0` | `non-negative integer` | `Number.isInteger(x) && x >= 0` |\n\nTypeScript's `number` is a single type. TJS gives you three levels of\nprecision -- all using expressions that are already legal JavaScript.\nThe automatic converter maps TypeScript `number` to `0.0` (float) to\npreserve the widest behavior; you can then narrow manually to `0` (integer)\nor `+0` (non-negative integer) where appropriate.\n\n### Optional Parameters\n\n```typescript\n// TypeScript // TJS\nfunction f(x?: string) {}\nfunction f(x = '') {}\nfunction f(x: string = 'hi') {}\nfunction f(x = 'hi') {}\n```\n\nIn TypeScript, `?` means optional with type `string | undefined`.\nIn TJS, `= value` means optional with that default. Same semantics, less syntax.\n\n### Object Shapes\n\n```typescript\n// TypeScript\nfunction createUser(opts: { name: string; age: number; email?: string }) {}\n\n// TJS\nfunction createUser(opts: { name: '', age: 0, email = '' }) {}\n```\n\nRequired properties use `:`, optional ones use `=`.\n\n### Return Types\n\n```typescript\n// TypeScript // TJS\nfunction add(a: number, b: number): number function add(a: 0, b: 0): 0\nfunction getUser(): { name: string } function getUser(): { name: '' }\nfunction fetchData(): Promise<string[]> function fetchData(): ['']\n```\n\nThe `fromTS` converter unwraps `Promise<T>` in return type annotations --\nyou annotate the resolved type, not the wrapper. This only applies when\nconverting from TypeScript; in native TJS you just write normal\n`async`/`await` and annotate what the function resolves to.\n\nThe return annotation also generates an automatic test: `add(0, 0)` must\nreturn a number. If it doesn't, you get an error at transpile time.\n\n### Interfaces and Type Aliases\n\n```typescript\n// TypeScript\ninterface User {\n name: string\n age: number\n email?: string\n}\n\ntype Status = 'active' | 'inactive' | 'banned'\n\n// TJS\nType User {\n description: 'a registered user'\n example: { name: '', age: 0, email = '' }\n}\n\nUnion Status 'account status' 'active' | 'inactive' | 'banned'\n```\n\n### Enums\n\n```typescript\n// TypeScript\nenum Color {\n Red = 'red',\n Green = 'green',\n Blue = 'blue',\n}\n\n// TJS\nEnum Color 'CSS color' {\n Red = 'red'\n Green = 'green'\n Blue = 'blue'\n}\n```\n\n### Classes\n\n```typescript\n// TypeScript\nclass Point {\n private x: number\n private y: number\n\n constructor(x: number, y: number) {\n this.x = x\n this.y = y\n }\n\n distanceTo(other: Point): number {\n return Math.sqrt((this.x - other.x) ** 2 + (this.y - other.y) ** 2)\n }\n}\n\nconst p = new Point(10, 20)\n\n// TJS\nclass Point {\n #x\n #y\n\n constructor(x: 0, y: 0) {\n this.#x = x\n this.#y = y\n }\n\n distanceTo(other: Point): 0 {\n return Math.sqrt((this.#x - other.#x) ** 2 + (this.#y - other.#y) ** 2)\n }\n}\n\nconst p = Point(10, 20) // no 'new' needed\n```\n\nKey differences:\n\n- `private` is stripped by default (TS `private` is compile-time only).\n With `TjsClass` (on by default in native TJS, add via `/* @tjs TjsClass */` for TS-originated code), `private` converts to `#` (true JS runtime privacy).\n- Type annotations become example values\n- With `TjsClass`, `new` is optional (linter warns against it)\n\n### Generics\n\nTJS takes a different approach to generics. TypeScript has function-level\ntype parameters (`<T>`) that vanish at runtime. TJS has `Generic` declarations\nthat produce runtime-checkable type constructors:\n\n```typescript\n// TypeScript -- compile-time only, gone at runtime\nfunction identity<T>(x: T): T { return x }\ninterface Box<T> { value: T }\n\n// TJS -- no function-level generics; use Generic for container types\nGeneric Box<T> {\n description: 'a boxed value'\n predicate(x, T) {\n return typeof x === 'object' && x !== null && 'value' in x && T(x.value)\n }\n}\n\n// Usage: Box(Number) is a runtime type checker\nconst isNumberBox = Box(Number)\nisNumberBox({ value: 42 }) // true\nisNumberBox({ value: 'nope' }) // false\n```\n\nFor simple generic functions like `identity` or `first`, you don't need\ngenerics at all -- just skip the type parameter. TJS validates the\nconcrete types at call sites, not the abstract relationship between them.\n\n```javascript\n// Simple -- no generics needed, the function just works\nfunction first(arr: [0]) { return arr[0] }\n\n// If you need runtime-checked containers, use Generic\nGeneric Pair<T, U> {\n description: 'a typed pair'\n predicate(x, T, U) { return T(x[0]) && U(x[1]) }\n}\n```\n\nWhen converting from TypeScript, the `fromTS` converter preserves generic\nmetadata but types become `any`. This is a place where manual review helps.\n\n### Nullability\n\n```typescript\n// TypeScript\nfunction find(id: number): User | null { ... }\n\n// TJS\nfunction find(id: 0): { name: '', age: 0 } || null { ... }\n```\n\nTJS distinguishes `null` from `undefined` -- they're different types, just\nas `typeOf(null)` returns `'null'` and `typeOf(undefined)` returns\n`'undefined'`. Writing `|| null` means the value can be the base type or\n`null`, but not `undefined`. Optional parameters (using `=`) accept\n`undefined` because that's what you get when the caller omits the argument.\n\n## What TypeScript Has That TJS Doesn't\n\nTJS intentionally skips TypeScript features that don't survive to runtime\nor add complexity without proportional value:\n\n| TypeScript Feature | TJS Equivalent |\n| --------------------------- | ------------------------------------------- |\n| `interface` | `Type` with example |\n| `type` aliases | `Type`, `Union`, or `Enum` |\n| Conditional types | Preserved in `.d.ts` via declaration blocks |\n| Mapped types | Preserved in `.d.ts` via declaration blocks |\n| `keyof`, `typeof` | Use runtime `Object.keys()`, `typeOf()` |\n| `Partial<T>`, `Pick<T>` | Define the shape you need directly |\n| Declaration files (`.d.ts`) | Generated from `__tjs` metadata (`--dts`) |\n| `as` type assertions | Not needed (values are checked) |\n| `any` escape hatch | `safety none` per-module or `!` per-fn |\n| Decorators | Not supported |\n| `namespace` | Use modules |\n\nThe philosophy: if a type feature doesn't do something at runtime, it's\ncomplexity without payoff.\n\n### But What About Narrowing?\n\nTypeScript's type system is Turing-complete. You can express astonishing\nconstraints -- `Pick<Omit<T, K>, Extract<keyof T, string>>` -- but the\nresulting types are often harder to understand than the code they describe.\nAnd they vanish at runtime, so they can't protect you from bad API data.\n\nTJS takes the opposite approach: `Type()` gives you a predicate function.\nIf you can write a boolean expression, you can define a type. No type-level\nprogramming language to learn.\n\n```javascript\n// TypeScript: branded types + manual validation\ntype Email = string & { __brand: 'email' }\nfunction isEmail(s: string): s is Email {\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(s)\n}\nfunction validateEmail(input: string): Email {\n if (!isEmail(input)) throw new Error('Invalid email')\n return input\n}\n\n// TJS: one line, works at runtime\nType Email {\n description: 'email address'\n example: 'user@example.com'\n predicate(v) { return typeof v === 'string' && /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(v) }\n}\n```\n\nThe TJS `Type()` built-in handles everything from simple shapes to\nsophisticated domain constraints:\n\n```javascript\n// Simple -- infer from example\nType Name 'Alice' // string\n\n// Constrained -- predicate narrows beyond the base type\nType PositiveInt {\n description: 'a positive integer'\n example: 1\n predicate(v) { return typeof v === 'number' && Number.isInteger(v) && v > 0 }\n}\n\n// Domain-specific -- readable business rules\nType USZipCode {\n description: '5-digit US zip code'\n example: '90210'\n predicate(v) { return typeof v === 'string' && /^\\d{5}$/.test(v) }\n}\n\n// Combinators -- compose types\nType OptionalEmail Nullable(Email) // Email | null\n\n// Schema-based -- use tosijs-schema for structured validation\nType AgeRange {\n description: 'valid age'\n example: 25\n predicate(v) { return typeof v === 'number' && v >= 0 && v <= 150 }\n}\n```\n\nCompare the TypeScript equivalents:\n\n| What you want | TypeScript | TJS |\n| ------------------- | ----------------------------------------------------------- | -------------------------------------- |\n| String with format | Branded type + type guard + validation function | `Type Email { predicate(v) {...} }` |\n| Number in range | Branded type + manual check | `Type Age { predicate(v) {...} }` |\n| Non-empty string | Template literal type (compile-only) | `Type NonEmpty { predicate(v) {...} }` |\n| Nullable variant | `T \\| null` (compile-only) | `Nullable(MyType)` (runtime-checked) |\n| Union of literals | `'a' \\| 'b' \\| 'c'` (compile-only) | `Union Status 'a' \\| 'b' \\| 'c'` |\n| Discriminated union | `type Shape = { kind: 'circle' } \\| ...` + manual narrowing | `Union('kind', { circle: {...} })` |\n| Generic container | `interface Box<T>` (compile-only) | `Generic Box<T> { predicate(...) }` |\n\nEvery row in the TypeScript column is compile-time fiction that disappears\nwhen your code runs. Every row in the TJS column is a runtime check that\nactually catches bugs in production. And the TJS versions are shorter,\nbecause a predicate is just a function -- not a type-level program.\n\nTJS also ships common types out of the box: `TString`, `TNumber`,\n`TBoolean`, `TInteger`, `TPositiveInt`, `TNonEmptyString`, `TEmail`,\n`TUrl`, `TUuid`, `Timestamp`, `LegalDate`. No imports from a validation\nlibrary needed.\n\n### Tooling Comparison\n\n| Concern | TypeScript | TJS |\n| ------------------- | ---------------------------------- | ---------------------------------------------------------------------- |\n| **Type checking** | `tsc` (compile-time only) | Runtime validation (survives build) |\n| **Runtime schemas** | Zod / io-ts / Ajv (separate) | Built-in (types _are_ schemas) |\n| **Linting** | ESLint + plugins | Built-in linter (unused vars, unreachable code, no-explicit-new) |\n| **Testing** | Vitest / Jest (separate files) | Inline `test` blocks (transpile-time) |\n| **Equality** | Reference-based only | Honest `==` (no coercion), `Is`/`IsNot` (structural), `===` (identity) |\n| **Build toolchain** | tsc + bundler (webpack/Vite/etc) | Transpiles in-browser, no build step |\n| **Debugging** | Source maps (brittle, build bloat) | Functions carry source identity via `__tjs` metadata |\n| **Documentation** | JSDoc / TypeDoc (manual) | Generated from `__tjs` metadata |\n| **Editor support** | Mature (VSCode, etc) | Monaco/CodeMirror/Ace + VSCode/Cursor extensions |\n\n## What TJS Has That TypeScript Doesn't\n\n### Runtime Validation\n\nTypeScript:\n\n```typescript\n// Types are a promise. A lie, if the data comes from outside.\nfunction processOrder(order: Order) {\n // If order came from an API, nothing guarantees it matches Order.\n // You need Zod/io-ts/ajv AND the TypeScript type AND keep them in sync.\n}\n```\n\nTJS:\n\n```javascript\n// Types are checked at runtime. One source of truth.\nfunction processOrder(order: { items: [{ id: 0, qty: 0 }], total: 0 }): {\n status: '',\n} {\n // If order doesn't match, caller gets a MonadicError -- no crash.\n}\n```\n\n### Honest Equality\n\nTypeScript inherits JavaScript's broken equality. Native TJS fixes this by default. For TS-originated code, add the `TjsEquals` directive (or use `/* @tjs TjsEquals */` in the source `.ts` file):\n\n```javascript\nTjsEquals // needed for TS-originated code; native TJS has this on by default\n\n// == is honest: no coercion, unwraps boxed primitives\n0 == '' // false (JS: true!)\n[] == ![] // false (JS: true!)\nnew String('foo') == 'foo' // true (unwraps boxed)\nnull == undefined // true (useful pattern preserved)\ntypeof null // 'null' (JS: 'object')\n\n// == is fast: O(1) reference equality for objects/arrays\n{a: 1} == {a: 1} // false (different refs)\n[1, 2] == [1, 2] // false (different refs)\n\n// Is/IsNot for explicit deep structural comparison (O(n))\n{a: 1} Is {a: 1} // true\n[1, 2, 3] Is [1, 2, 3] // true\nnew Set([1,2]) Is new Set([2,1]) // true (Sets are order-independent)\n\n// === unchanged: identity check\nobj === obj // true (same reference)\n```\n\n`==` fixes coercion without the performance cost of deep comparison.\nUse `Is`/`IsNot` when you explicitly need structural comparison.\n\n### Monadic Errors\n\nTypeScript uses exceptions. TJS uses values:\n\n```javascript\n// TypeScript -- you have to remember to try/catch\nfunction divide(a: number, b: number): number {\n if (b === 0) throw new Error('Division by zero')\n return a / b\n}\n// Caller forgets try/catch? Crash.\n\n// TJS -- errors flow through the pipeline\nfunction divide(a: 0, b: 0): 0 {\n if (b === 0) return MonadicError('Division by zero')\n return a / b\n}\n// Caller gets an error value. No crash. Ever.\n```\n\n**How the caller handles it:**\n\n```javascript\n// Option 1: Check the result\nconst result = divide(10, 0)\nif (result instanceof Error) {\n console.log(result.message) // 'Division by zero'\n} else {\n useResult(result)\n}\n\n// Option 2: Just keep going -- errors propagate automatically\nconst a = divide(10, 0) // MonadicError\nconst b = double(a) // Receives error, returns it immediately (skips execution)\nconst c = format(b) // Same -- error flows through the whole chain\n// c is still the original MonadicError from divide()\n```\n\nIf you've used Rust's `Result<T, E>` or Haskell's `Either`, the pattern\nis familiar. The key difference from TypeScript: you never have to guess\nwhether a function might throw. Type errors and validation failures are\nalways values, never exceptions.\n\n### Inline Tests\n\n```javascript\nfunction fibonacci(n: 0): 0 {\n if (n <= 1) return n\n return fibonacci(n - 1) + fibonacci(n - 2)\n}\n\ntest 'fibonacci sequence' {\n expect(fibonacci(0)).toBe(0)\n expect(fibonacci(1)).toBe(1)\n expect(fibonacci(10)).toBe(55)\n}\n```\n\nTests run at transpile time. They're stripped from production output.\nNo separate test files, no test runner configuration.\n\n### Safety Controls\n\n```javascript\nsafety none // This module: skip all validation (performance)\nsafety inputs // This module: validate inputs only (default)\nsafety all // This module: validate everything (debug)\n\n// Per-function overrides\nfunction hot(! x: 0) {} // Skip validation even if module says 'inputs'\nfunction safe(? x: 0) {} // Force validation even if module says 'none'\n```\n\nUse `!` (skip validation) only in hot loops where every microsecond counts\nand the data source is already trusted. In all other cases, the ~1.5x\noverhead of `safety inputs` is negligible compared to the bugs it catches.\n\n#### Additional Safety Features\n\n```javascript\nTjsNoVar // var declarations are syntax errors\nconst! config = {} // Compile-time immutability (zero runtime cost)\n\n// Debug mode: make type errors visible\nimport { configure } from 'tjs-lang/lang'\nconfigure({ logTypeErrors: true }) // console.error on every type error\nconfigure({ throwTypeErrors: true }) // throw instead of returning MonadicError\n```\n\nTypeScript has no equivalent to most of these. You're either all-in on\ntypes or you use `as any` to escape.\n\n---\n\n## Automatic Conversion\n\nTJS includes a TypeScript-to-TJS converter that has been validated against\nthe tosijs production codebase (35 files, 523 tests passing):\n\n```bash\n# Convert a single file\nbun src/cli/tjs.ts convert input.ts --emit-tjs > output.tjs\n\n# Convert a directory (produces .js + .d.ts + .md per file)\nbun src/cli/tjs.ts convert src/ -o tjs-out/\n\n# Emit JavaScript directly\nbun src/cli/tjs.ts convert input.ts > output.js\n```\n\nFrom code:\n\n```typescript\nimport { fromTS } from 'tjs-lang/lang/from-ts'\n\nconst result = fromTS(tsSource, { emitTJS: true })\nconsole.log(result.code) // TJS source\n```\n\n### What `fromTS` Handles\n\n- Primitive annotations (`string`, `number`, `boolean`) → example values\n- Interfaces → `Type` declarations with declaration blocks for `.d.ts` round-tripping\n- Generic interfaces → `Generic` with predicates + declaration blocks\n- Conditional/mapped types → preserved verbatim in declaration blocks\n- Function type aliases → `FunctionPredicate` declarations (including generics)\n- String literal unions → `Union`\n- Enums → `Enum`\n- Rest parameters (`...args: T[]`) → preserved with `...` prefix\n- Nullable types (`T | null`) → proper null guards in runtime checks\n- Optional params, default values\n- `private` → stripped (or `#` with `TjsClass`)\n- Static getters/setters → `static` keyword preserved\n- `Promise<T>` → unwrapped return types\n- DOM types (130+) → `{}` (opaque object, keeps params annotated)\n- JSDoc comments → TDoc comments\n- Exported constants → type-inferred `.d.ts` entries\n\n### `@tjs` Annotations in TypeScript\n\nAnnotate your `.ts` files with `/* @tjs ... */` comments to enrich\nthe TJS output. The TS compiler ignores them.\n\n```typescript\n/* @tjs TjsClass TjsEquals */ // Enable TJS modes (off by default in TS-originated code)\n\n/* @tjs-skip */ // Skip this type declaration\nexport type Unboxed<T> = T extends { value: infer U } ? U : T\n\n/* @tjs predicate(x, T) { return typeof x === 'object' && T(x.value) } */\nexport interface Box<T> {\n value: T\n}\n\n/* @tjs example: { name: 'Alice', age: 30 } */\nexport interface User {\n name: string\n age: number\n}\n\n/* @tjs declaration { value: T; path: string } */\nexport interface BoxedProxy<T> {\n /* complex conditional type */\n}\n```\n\n### `.d.ts` Generation\n\nThe DTS emitter produces TypeScript declarations from TJS transpilation:\n\n```bash\nbun src/cli/tjs.ts emit input.tjs # emits .js, .d.ts, .md\n```\n\n- **Interfaces with declaration blocks** → `export interface Name<T> { ... }`\n- **Conditional/mapped types** → `export type Name<T> = ...` (verbatim TS body)\n- **Function types** → `export type Name = (...) => T`\n- **Simple type aliases** → `export type Name = original TS body`\n- **Constants** → `export declare const Name: type`\n- **Functions** → `export declare function Name(params): returnType`\n- **Classes** → callable function + class declaration\n\n### Constrained Generics\n\nWhen the converter encounters a constrained generic like\n`<T extends { id: number }>`, it uses the constraint shape as the\nexample value instead of falling back to `any`. This means:\n\n```typescript\n// TypeScript\nfunction first<T extends { id: number }>(items: T[]): T {\n return items[0]\n}\n\n// Converted TJS — uses constraint shape, not 'any'\nfunction first(items: [{ id: 0.0 }]):! { id: 0.0 } { ... }\n```\n\nGeneric defaults also work: `<T = string>` uses `string` as the example.\nUnconstrained generics (`<T>` with no `extends` or default) still degrade\nto `any` — there's genuinely no information about what T is.\n\n### What `fromTS` Can't Fully Express\n\nTJS types are example values, not abstract type algebra. Some TypeScript\npatterns have no direct TJS equivalent — but most now preserve their\noriginal TS body for `.d.ts` round-tripping:\n\n| TypeScript Pattern | What Happens |\n| ------------------------------------------- | ----------------------------------------------------- |\n| Conditional types (`T extends U ? X : Y`) | TS body preserved verbatim in `.d.ts` |\n| Mapped types (`{ [K in keyof T]: ... }`) | TS body preserved verbatim in `.d.ts` |\n| Intersection types (`A & B`) | TS body preserved verbatim in `.d.ts` |\n| `Partial<T>`, `Required<T>`, `Pick`, `Omit` | Emits warning, uses base shape |\n| `ReturnType<T>`, `Parameters<T>` | Drops to `any` |\n| Template literal types (`` `${A}-${B}` ``) | Becomes `string` |\n| Deeply nested generics (`Foo<Bar<U>>`) | Inner params become `any` |\n| `readonly`, `as const` | Stripped (use `const!` for compile-time immutability) |\n\nThe key improvement: complex types that can't be expressed as runtime\npredicates are still preserved in the `.d.ts` output via declaration blocks.\nThe runtime code works with `any`, but TypeScript consumers of your library\nget the full type information.\n\n## Migration Strategy\n\n### Incremental Adoption\n\nYou don't have to convert everything at once:\n\n1. **Start at boundaries.** Convert API handlers and validation layers\n first -- these benefit most from runtime types.\n2. **Convert hot modules.** Modules with frequent type-related bugs are\n good candidates.\n3. **Leave internals for last.** Pure computational code that's already\n well-tested benefits least from migration.\n\n### The Bun Plugin\n\nIf you use Bun, `.tjs` files work alongside `.ts` files with zero config:\n\n```javascript\n// bunfig.toml already preloads the TJS plugin\nimport { processOrder } from './orders.tjs' // just works\nimport { validateUser } from './users.ts' // also works\n```\n\n### What to Watch For\n\n**Example values matter.** `count: 0` means \"number, example is 0.\" If\nyour function breaks on 0 (division, array index), the automatic signature\ntest will catch it immediately. Choose examples that exercise the\nhappy path.\n\n**Return types generate tests.** `: 0` means TJS will call your function\nwith the parameter examples and check the result. If your function has\nside effects or requires setup, use `:! 0` to skip the signature test.\n\n**Structural equality changes behavior.** If your code relies on `==`\nfor type coercion (comparing numbers to strings, etc.), you'll need to\nupdate those comparisons. This is almost always a bug fix.\n\n---\n\n## Side-by-Side: A Complete Example\n\n### TypeScript\n\n```typescript\ninterface Product {\n id: string\n name: string\n price: number\n tags: string[]\n}\n\ninterface CartItem {\n product: Product\n quantity: number\n}\n\nfunction calculateTotal(items: CartItem[], taxRate: number = 0.1): number {\n const subtotal = items.reduce(\n (sum, item) => sum + item.product.price * item.quantity,\n 0\n )\n return Math.round(subtotal * (1 + taxRate) * 100) / 100\n}\n\nfunction applyDiscount(\n total: number,\n code: string | null\n): { final: number; discount: number } {\n const discounts: Record<string, number> = {\n SAVE10: 0.1,\n SAVE20: 0.2,\n }\n const rate = code ? discounts[code] ?? 0 : 0\n return {\n final: Math.round(total * (1 - rate) * 100) / 100,\n discount: rate,\n }\n}\n```\n\n### TJS\n\n```javascript\nType Product {\n description: 'a product in the catalog'\n example: { id: '', name: '', price: 0.0, tags: [''] }\n}\n\nType CartItem {\n description: 'a product with quantity'\n example: { product: { id: '', name: '', price: 0.0, tags: [''] }, quantity: +0 }\n}\n\nfunction calculateTotal(items: [CartItem], taxRate = 0.1): 0.0 {\n const subtotal = items.reduce(\n (sum, item) => sum + item.product.price * item.quantity,\n 0\n )\n return Math.round(subtotal * (1 + taxRate) * 100) / 100\n}\n\nfunction applyDiscount(total: 0.0, code: '' || null): { final: 0.0, discount: 0.0 } {\n const discounts = {\n SAVE10: 0.1,\n SAVE20: 0.2,\n }\n const rate = code ? discounts[code] ?? 0 : 0\n return {\n final: Math.round(total * (1 - rate) * 100) / 100,\n discount: rate,\n }\n}\n\ntest 'cart calculation' {\n const items = [\n { product: { id: '1', name: 'Widget', price: 10, tags: [] }, quantity: 3 }\n ]\n expect(calculateTotal(items, 0)).toBe(30)\n expect(calculateTotal(items, 0.1)).toBe(33)\n}\n\ntest 'discount codes' {\n expect(applyDiscount(100, 'SAVE10')).toEqual({ final: 90, discount: 0.1 })\n expect(applyDiscount(100, null)).toEqual({ final: 100, discount: 0 })\n expect(applyDiscount(100, 'INVALID')).toEqual({ final: 100, discount: 0 })\n}\n```\n\nThe TJS version is about the same length, but the types exist at runtime,\nthe tests live with the code, and invalid inputs return errors instead\nof crashing.\n\n---\n\n## Traceability: The Death of Source Maps\n\nTypeScript debugging relies on source maps -- external files that try to\nmap minified, transpiled JavaScript back to your original code. They're\nbrittle, often out of sync, and fail entirely in complex build pipelines.\n\nTJS eliminates source maps. Every function carries its source identity\nin `__tjs` metadata:\n\n```javascript\nfunction add(a: 0, b: 0): 0 {\n return a + b\n}\n\nadd.__tjs.source // \"mymodule.tjs:3\"\n```\n\n- **Zero-config debugging:** If a function fails validation, the error\n points to the exact line in your `.tjs` source, not a generated `.js` file.\n- **Transparent eval:** Even code run via `Eval()` or the `AgentVM`\n provides clear traces because AST and source metadata are preserved.\n- **No build bloat:** You don't ship `.map` files to production just to\n know why your app crashed.\n\n---\n\n## FAQ\n\n### How do I use TJS with existing NPM packages?\n\nTJS is a superset of JavaScript. Import any NPM package as usual:\n\n```javascript\nimport lodash from 'https://esm.sh/lodash@4.17.21'\nimport { z } from 'zod' // works, though you won't need it\n```\n\nWhen you import a vanilla JS library, its exports have no TJS metadata.\nYou can wrap them in a TJS boundary to get runtime safety:\n\n```javascript\nimport { rawGeocode } from 'legacy-geo-pkg'\n\n// Wrap to validate at your system boundary\nfunction geocode(addr: ''): { lat: 0.0, lon: 0.0 } {\n return rawGeocode(addr)\n}\n```\n\nThe untyped library code runs freely. Your TJS wrapper validates the\nresult before it enters your typed world.\n\n### Do Proxies, WeakMaps, and other advanced patterns work?\n\nYes. TJS is purely additive — it adds inline type checks and metadata\nproperties but does not wrap, intercept, or modify JavaScript runtime\nbehavior. Specifically:\n\n- **Proxies** work identically to plain JS. TJS attaches `.__tjs` as a\n plain property on function objects, which doesn't trigger Proxy traps.\n If your Proxy needs custom equality, use the `[tjsEquals]` symbol protocol.\n- **WeakMap/WeakSet** are unaffected. TJS doesn't inspect collection contents.\n- **Symbols** work normally. TJS reserves `Symbol.for('tjs.equals')` for\n custom equality but doesn't interfere with other symbols.\n- **`Object.defineProperty`**, getters/setters, non-enumerable properties\n — all work as expected. TJS validation checks value types, not property\n descriptors.\n- **Prototype chains** are preserved. `instanceof` works correctly with\n TJS-wrapped classes.\n\nIf you're building a Proxy-heavy library (reactive state, ORMs, etc.),\nTJS will not interfere. The transpiled output is plain JavaScript with\nsome `typeof` checks at function entry points.\n\n### Does structural equality (`==`) handle circular references?\n\nNo. Circular structures will cause infinite recursion. Use identity\ncomparison (`===`) for objects that might be circular, or define a\ncustom `.Equals` method on the class.\n\n### What happens to TypeScript's `strict` mode checks?\n\nTJS doesn't have `strictNullChecks` or `noImplicitAny` because the\nproblems they solve don't exist:\n\n- **Null safety:** `|| null` explicitly marks nullable parameters.\n Functions without it reject null at runtime.\n- **Implicit any:** Every TJS parameter has an example value that\n determines its type. There's nothing to be implicit about.\n- **Strict property access:** Runtime validation catches missing\n properties with a clear error message instead of `undefined`.\n\n---\n\n## Learn More\n\n- [TJS Language Reference](DOCS-TJS.md) -- Full syntax and features\n- [TJS for JavaScript Programmers](TJS-FOR-JS.md) -- Coming from vanilla JS?\n- [AJS Agent Language](DOCS-AJS.md) -- The sandboxed agent VM\n- [Playground](https://tjs-platform.web.app) -- Try it live\n"
1621
1621
  }
1622
- ]
1622
+ ]
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@ var Bi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var ws=Bi((mf,ko)
3
3
  `)}},Or=class extends z{expected;received;suggestion;constructor(t,n,r){super(t,n,r?.source,r?.filename),this.name="TypeError",this.expected=r?.expected,this.received=r?.received,this.suggestion=r?.suggestion}};function pe(e){return{depth:e.depth+1,locals:new Map,parent:e,parameters:e.parameters,atoms:e.atoms,warnings:e.warnings,source:e.source,filename:e.filename,options:e.options}}function Fi(e,t){if(t.locals.has(e))return t.locals.get(e);if(t.parameters.has(e))return t.parameters.get(e)?.type;if(t.parent)return Fi(e,t.parent)}function Z(e){return e.loc?{line:e.loc.start.line,column:e.loc.start.column}:{line:1,column:0}}function Bt(e,t){let n="",r=0,s,i,o="normal",a=[],c=[{type:"top-level",braceDepth:0}],l=0,u=()=>c[c.length-1]?.type||"top-level",p=()=>{let f=c[c.length-1];return f?.type==="class-body"&&l===f.braceDepth+1};for(;r<e.length;){let f=e[r],m=e[r+1];switch(o){case"single-string":if(n+=f,f==="\\"&&r+1<e.length){n+=m,r+=2;continue}f==="'"&&(o="normal"),r++;continue;case"double-string":if(n+=f,f==="\\"&&r+1<e.length){n+=m,r+=2;continue}f==='"'&&(o="normal"),r++;continue;case"template-string":if(n+=f,f==="\\"&&r+1<e.length){n+=m,r+=2;continue}if(f==="$"&&m==="{"){n+=m,r+=2,a.push(1),o="normal";continue}f==="`"&&(o="normal"),r++;continue;case"line-comment":n+=f,f===`
4
4
  `&&(o="normal"),r++;continue;case"block-comment":if(n+=f,f==="*"&&m==="/"){n+=m,r+=2,o="normal";continue}r++;continue;case"regex":if(n+=f,f==="\\"&&r+1<e.length){n+=m,r+=2;continue}if(f==="["){for(r++;r<e.length&&e[r]!=="]";)n+=e[r],e[r]==="\\"&&r+1<e.length?(n+=e[r+1],r+=2):r++;r<e.length&&(n+=e[r],r++);continue}if(f==="/"){for(r++;r<e.length&&/[gimsuy]/.test(e[r]);)n+=e[r],r++;o="normal";continue}r++;continue;case"normal":if(a.length>0){if(f==="{")a[a.length-1]++;else if(f==="}"&&(a[a.length-1]--,a[a.length-1]===0)){a.pop(),n+=f,r++,o="template-string";continue}}if(f==="'"){n+=f,r++,o="single-string";continue}if(f==='"'){n+=f,r++,o="double-string";continue}if(f==="`"){n+=f,r++,o="template-string";continue}if(f==="/"&&m==="/"){n+=f+m,r+=2,o="line-comment";continue}if(f==="/"&&m==="*"){n+=f+m,r+=2,o="block-comment";continue}if(f==="/"){let b=n.trimEnd();if(!b[b.length-1]||/[=(!,;:{[&|?+\-*%<>~^]$/.test(b)||/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)\s*$/.test(b)){n+=f,r++,o="regex";continue}}break}if(f==="{"){l++,n+=f,r++;continue}if(f==="}"){l--;let b=c[c.length-1];b&&l===b.braceDepth&&c.pop(),n+=f,r++;continue}let d=e.slice(r).match(/^class\s+\w+(?:\s+extends\s+\w+)?\s*\{/);if(d){let b=d[0].slice(0,-1);n+=b,r+=b.length,c.push({type:"class-body",braceDepth:l});continue}let y=e.slice(r).match(/^function\s+(\w+)\s*\(/);if(y){let b=y[1],T=y[0].length,k=e[r+T],w=null,j=r+T;(k==="?"||k==="!")&&(w=k,j++,w==="!"?t.unsafeFunctions.add(b):t.safeFunctions.add(b)),n+=`function ${b}(`,r=j;let C=Dt(e,r,"(",")");if(!C){n+=e[r],r++;continue}let{content:$,endPos:R}=C;r=R;let A=Wn($,t,!0);n+=A+")";let P=r;for(;P<e.length&&/\s/.test(e[P]);)P++;if(e[P]===":"){let v=e.slice(P,P+2),I;for(v===":?"||v===":!"?(P+=2,I=v===":?"?"safe":"unsafe"):P+=1;P<e.length&&/\s/.test(e[P]);)P++;let O=Jn(e,P);O&&(s===void 0&&(s=O.type,I&&(i=I)),r=O.endPos)}continue}let x=e.slice(r).match(/^(constructor|(?:get|set)\s+\w+|async\s+\w+|\w+)\s*\(/),E=(()=>{for(let b=n.length-1;b>=0;b--)if(!/\s/.test(n[b]))return n[b];return`
5
5
  `})(),_=E!=="="&&E!==","&&E!=="("&&E!=="["&&E!==">";if(x&&p()&&!_){let b=x[1].length;n+=e.slice(r,r+b),r+=b;continue}if(x&&p()&&_){let b=x[1],T=x[0].length,k=r+T;n+=b+"(",r=k;let w=Dt(e,r,"(",")");if(!w){n+=e[r],r++;continue}let{content:j,endPos:C}=w;r=C;let $=Wn(j,t,!0);n+=$+")";let R=r;for(;R<e.length&&/\s/.test(e[R]);)R++;if(e[R]===":"){let A=e.slice(R,R+2);for(A===":?"||A===":!"?R+=2:R++;R<e.length&&/\s/.test(e[R]);)R++;let P=Jn(e,R);P&&(r=P.endPos)}continue}if(e[r]==="("){let b=Dt(e,r+1,"(",")");if(!b){n+=e[r],r++;continue}let T=b.content,k=b.endPos,w=k;for(;w<e.length&&/\s/.test(e[w]);)w++;let j;if(e[w]===":"){let C=e.slice(w,w+2);for(C===":?"||C===":!"?w+=2:w++;w<e.length&&/\s/.test(e[w]);)w++;let $=Jn(e,w);if($)for(j=$.type,w=$.endPos;w<e.length&&/\s/.test(e[w]);)w++}if(e.slice(w,w+2)==="=>"){let C=null,$=T,R=T.trimStart();R.startsWith("?")&&(R.length===1||/\s/.test(R[1]))?(C="?",$=R.slice(1)):R.startsWith("!")&&(R.length===1||/\s/.test(R[1]))&&(C="!",$=R.slice(1));let A=Wn($,t,!1);for(n+=`(${C==="?"?"/* safe */ ":C==="!"?"/* unsafe */ ":""}${A})`,r=k;r<w&&/\s/.test(e[r]);)n+=e[r],r++;j&&(r=w)}else{let C=Bt(T,t);n+=`(${C.source})`,r=k}continue}n+=e[r],r++}return{source:n,returnType:s,returnSafety:i}}function Dt(e,t,n,r){let s=1,i=t,o=!1,a="";for(;i<e.length&&s>0;){let c=e[i];!o&&(c==="'"||c==='"'||c==="`")?(o=!0,a=c):o&&c===a&&e[i-1]!=="\\"?o=!1:o||(c===n?s++:c===r&&s--),i++}return s!==0?null:{content:e.slice(t,i-1),endPos:i}}function Fr(e,t){let n=t;for(;n<e.length&&/\s/.test(e[n]);)n++;if(n>=e.length)return null;let r=n,s=e[n];if(s==="{"||s==="["){let o=s==="{"?"}":"]",a=Dt(e,n+1,s,o);return a?{value:e.slice(r,a.endPos),endPos:a.endPos}:null}if(s==="'"||s==='"'||s==="`"){for(n++;n<e.length;){if(e[n]===s&&e[n-1]!=="\\")return n++,{value:e.slice(r,n),endPos:n};n++}return null}if(/[-+\d]/.test(s)){for(;n<e.length&&/[\d.eE+-]/.test(e[n]);)n++;return{value:e.slice(r,n),endPos:n}}let i=e.slice(n).match(/^(true|false|null|undefined)\b/);return i?{value:i[1],endPos:n+i[1].length}:null}function ft(e){return e.replace(/(?<!\|)\|(?!\|)/g," || ")}function Jn(e,t){let n=t,r=0,s=!1,i="",o=!1,a=c=>({type:ft(e.slice(t,c).trim()),endPos:c});for(;n<e.length;){let c=e[n];if(!s&&(c==="'"||c==='"'||c==="`")){s=!0,i=c,o=!0,n++;continue}if(s){if(c===i&&e[n-1]!=="\\"){if(s=!1,n++,r===0){let l=n;for(;l<e.length&&/\s/.test(e[l]);)l++;if(e[l]==="{"&&!e.slice(l+1).match(/^\s*(\w+)\s*:/)||e[l]!=="|"&&e[l]!=="&")return a(n)}continue}n++;continue}if(c==="{"||c==="["||c==="("){r++,o=!0,n++;continue}if(c==="}"||c==="]"||c===")"){if(r--,r===0){n++;let l=n;for(;l<e.length&&/\s/.test(e[l]);)l++;if(e[l]==="|"||e[l]==="&")continue;return a(n)}n++;continue}if(r===0&&c==="{"){if(o)return a(n);if(e.slice(n+1).match(/^\s*(\w+)\s*:/)){r++,o=!0,n++;continue}return a(n)}if(r===0&&(c==="|"||c==="&")){for(n++,n<e.length&&e[n]==="|"&&n++;n<e.length&&/\s/.test(e[n]);)n++;continue}if(r===0&&(/\d/.test(c)||c==="-"&&/\d/.test(e[n+1]))){let l=n;for(e[l]==="-"&&l++;l<e.length&&/\d/.test(e[l]);)l++;if(l<e.length&&e[l]==="."&&/\d/.test(e[l+1]))for(l++;l<e.length&&/\d/.test(e[l]);)l++;if(l<e.length&&(e[l]==="e"||e[l]==="E"))for(l++,l<e.length&&(e[l]==="+"||e[l]==="-")&&l++;l<e.length&&/\d/.test(e[l]);)l++;for(o=!0,n=l;n<e.length&&/\s/.test(e[n]);)n++;if(n<e.length&&e[n]==="{")return{type:ft(e.slice(t,l).trim()),endPos:l};if(e[n]!=="|"&&e[n]!=="&")return{type:ft(e.slice(t,l).trim()),endPos:l};continue}if(r===0&&/[a-zA-Z_]/.test(c)){let l=n;for(;l<e.length&&/\w/.test(e[l]);)l++;for(o=!0,n=l;n<e.length&&/\s/.test(e[n]);)n++;if(n<e.length&&e[n]==="("){r++,n++;continue}if(n<e.length&&e[n]==="{"&&!e.slice(n+1).match(/^\s*(\w+)\s*:/)){let p=l;for(;p>t&&/\s/.test(e[p-1]);)p--;return{type:ft(e.slice(t,p).trim()),endPos:l}}if(e[n]!=="|"&&e[n]!=="&")return{type:ft(e.slice(t,l).trim()),endPos:l};continue}n++}return o?a(n):null}function Ft(e){let t=[],n="",r=0,s=!1,i=!1,o=0;for(;o<e.length;){let a=e[o],c=e[o+1];if(!i&&a==="/"&&c==="/"){s=!0,n+="//",o+=2;continue}if(!s&&a==="/"&&c==="*"){i=!0,n+="/*",o+=2;continue}if(s&&a===`
6
- `){s=!1,n+=a,o++;continue}if(i&&a==="*"&&c==="/"){i=!1,n+="*/",o+=2;continue}if(s||i){n+=a,o++;continue}a==="("||a==="{"||a==="["?(r++,n+=a):a===")"||a==="}"||a==="]"?(r--,n+=a):a===","&&r===0?(t.push(n),n=""):n+=a,o++}return n.trim()&&t.push(n),t}function Wn(e,t,n){let r=Bt(e,{originalSource:e,requiredParams:t.requiredParams,unsafeFunctions:t.unsafeFunctions,safeFunctions:t.safeFunctions}).source,s=Ft(r),i=!1,o=new Set,a=l=>{if(n&&/^\w+$/.test(l)){if(o.has(l))throw new Error(`Duplicate parameter name '${l}'`);o.add(l)}};return s.map(l=>{let u=l.trim();if(!u)return l;if(n&&u.startsWith("{")&&u.endsWith("}")){let m=u.slice(1,-1);return`{ ${Lr(m,t)} }`}if(n&&u.startsWith("[")&&u.endsWith("]")){let m=u.slice(1,-1);return`[ ${Lr(m,t)} ]`}if(u.startsWith("...")){let m=Br(u);return m!==-1?u.slice(0,m).trim():l}let p=u.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(p){let[,m,d]=p;return a(m),i=!0,`${m} = ${d}`}if(!Ui(u)){let m=u.match(/^(\w+)\s*=/);return m&&a(m[1]),i=!0,l}let f=Br(u);if(f!==-1){let m=u.slice(0,f).trim(),d=u.slice(f+1).trim();return a(m),i&&n&&/^\w+$/.test(m),n&&/^\w+$/.test(m)&&t.requiredParams.add(m),`${m} = ${d}`}return l}).join(",")}function Lr(e,t){return Ft(e).map(s=>{let i=s.trim();if(!i)return s;let o=i.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(o){let[,l,u]=o;t.requiredParams.add(l);let p=Ot(u);return`${l} = ${p}`}let a=i.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(a){let[,l,u]=a;t.requiredParams.add(l);let p=Lt(u);return`${l} = ${p}`}let c=i.match(/^(\w+)\s*:\s*([\s\S]+)$/);if(c){let[,l,u]=c;return t.requiredParams.add(l),`${l} = ${u}`}return s}).join(", ")}function Ot(e){let t=e.slice(1,-1).trim();return`{ ${Ft(t).map(s=>{let i=s.trim();if(!i)return s;let o=i.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(o){let[,p,f]=o;return`${p}: ${Ot(f)}`}let a=i.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(a){let[,p,f]=a;return`${p}: ${Ot(f)}`}let c=i.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(c){let[,p,f]=c;return`${p}: ${Lt(f)}`}let l=i.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(l){let[,p,f]=l;return`${p}: ${Lt(f)}`}let u=i.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(u){let[,p,f]=u;return`${p}: ${f}`}return s}).join(", ")} }`}function Lt(e){let t=e.slice(1,-1).trim();return`[ ${Ft(t).map(s=>{let i=s.trim();return i?i.startsWith("{")&&i.endsWith("}")?Ot(i):i.startsWith("[")&&i.endsWith("]")?Lt(i):s:s}).join(", ")} ]`}function Ui(e){let t=0,n=!1,r=!1,s=!1,i="";for(let o=0;o<e.length;o++){let a=e[o];if(!s&&(a==="'"||a==='"'||a==="`")){s=!0,i=a;continue}if(s){a===i&&e[o-1]!=="\\"&&(s=!1);continue}a==="("||a==="{"||a==="["?t++:a===")"||a==="}"||a==="]"?t--:t===0&&(a===":"&&(n=!0),a==="="&&e[o+1]!==">"&&(r=!0))}return n&&!r}function Br(e){let t=0,n=!1,r="";for(let s=0;s<e.length;s++){let i=e[s];if(!n&&(i==="'"||i==='"'||i==="`")){n=!0,r=i;continue}if(n){i===r&&e[s-1]!=="\\"&&(n=!1);continue}if(i==="("||i==="{"||i==="[")t++;else if(i===")"||i==="}"||i==="]")t--;else if(t===0&&i===":")return s}return-1}function qi(e,t){let n=e.match(t);if(!n)return null;let r=n.index+n[0].length-1,s=1,i=r+1;for(;i<e.length&&s>0;)e[i]==="{"?s++:e[i]==="}"&&s--,i++;if(s!==0)return null;let o=e.slice(r,i),a=[n[0].slice(0,-1)+o,o];return a.index=n.index,a}function Vr(e){let t="",n=0;for(;n<e.length;){let r=e.slice(n).match(/^\btry\s*\{/);if(r){let i=n+r[0].length-1+1,o=1,a=i;for(;a<e.length&&o>0;){let l=e[a];l==="{"?o++:l==="}"&&o--,a++}if(o!==0){t+=e[n],n++;continue}if(e.slice(a).match(/^\s*(catch|finally)\b/))t+=e.slice(n,a),n=a;else{let l=e.slice(i,a-1);t+=`try {${l}} catch (__try_err) { return new (__tjs?.MonadicError ?? Error)(__try_err?.message || String(__try_err), 'try', undefined, undefined, __tjs?.getStack?.()) }`,n=a}}else t+=e[n],n++}return t}function Kr(e){let t=[],n="",r=0,s=0;for(;r<e.length;){let i=e.slice(r).match(/^\bwasm\s*\{/);if(i){let o=r,a=r+i[0].length,c=1,l=a;for(;l<e.length&&c>0;){let w=e[l];w==="{"?c++:w==="}"&&c--,l++}if(c!==0){n+=e[r],r++;continue}let u=e.slice(a,l-1),p,f=l,m=e.slice(l).match(/^\s*fallback\s*\{/);if(m){let w=l+m[0].length;c=1;let j=w;for(;j<e.length&&c>0;){let C=e[j];C==="{"?c++:C==="}"&&c--,j++}c===0&&(p=e.slice(w,j-1),f=j)}let y=Wi(u).map(w=>{let j=Vi(e,o,w);return j?`${w}: ${j}`:w}),x={id:`__tjs_wasm_${s}`,body:u,fallback:p,captures:y,start:o,end:f};t.push(x);let E=p??u,_=y.map(w=>w.split(":")[0].trim()),b=_.length>0?_.join(", "):"",T=_.length>0?`globalThis.${x.id}(${b})`:`globalThis.${x.id}()`,k=`(globalThis.${x.id} ? ${T} : (() => {${E}})())`;n+=k,r=f,s++}else n+=e[r],r++}return{source:n,blocks:t}}function Ji(e){return e.startsWith("f32x4_")||e.startsWith("v128_")}function Wi(e){let t=e.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,""),n=new Set,r=/\.([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,s;for(;(s=r.exec(t))!==null;)n.add(s[1]);let i=/(?<!\.)(\b[a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,o=new Set;for(;(s=i.exec(t))!==null;)o.add(s[1]);for(let f of n){if(!o.has(f))continue;let m=new RegExp(`(?<!\\.)\\b${f}\\b`,"g"),d=new RegExp(`\\.${f}\\b`,"g"),y=t.match(m)?.length||0,x=t.match(d)?.length||0;y<=x&&o.delete(f)}let a=new Set,c=/\b(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;for(;(s=c.exec(t))!==null;)a.add(s[1]);let l=/\bfor\s*\(\s*(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;for(;(s=l.exec(t))!==null;)a.add(s[1]);let u=new Set(["if","else","for","while","do","switch","case","break","continue","return","function","let","const","var","new","this","true","false","null","undefined","typeof","instanceof","in","of","try","catch","finally","throw","async","await","class","extends","super","import","export","default","from","as","static","get","set","yield","console","Math","Array","Object","String","Number","Boolean","Date","JSON","Promise","Map","Set","WeakMap","WeakSet","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","ArrayBuffer","DataView","Error","TypeError","RangeError","length","push","pop","shift","unshift","slice","splice","map","filter","reduce","forEach","find","findIndex","indexOf","includes","globalThis","window","document","Infinity","NaN","isNaN","isFinite","parseInt","parseFloat","encodeURI","decodeURI","eval","wasmBuffer"]),p=[];for(let f of o)!a.has(f)&&!u.has(f)&&!Ji(f)&&p.push(f);return p.sort()}function Vi(e,t,n){let r=e.slice(0,t),s=/function\s+\w+\s*\(([^)]*)\)\s*(?:->.*?)?\s*\{[^}]*$/,i=r.match(s);if(!i){let o=/(?:const|let|var)?\s*\w+\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?:=>|->)?\s*\{[^}]*$/,a=r.match(o);return a?Ur(a[1],n):void 0}return Ur(i[1],n)}function Ur(e,t){let n=e.split(",").map(r=>r.trim());for(let r of n){let s=r.match(new RegExp(`^${t}\\s*:\\s*([A-Za-z][A-Za-z0-9]*)`));if(s)return s[1];let i=r.match(new RegExp(`^${t}\\s*=\\s*(Float32Array|Float64Array|Int32Array|Uint8Array|Int8Array|Int16Array|Uint16Array|Uint32Array)`));if(i)return i[1]}}function zr(e){let t=`([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")`,n=new RegExp(t+"\\s+IsNot\\s+"+t,"g");e=e.replace(n,"IsNot($1, $2)");let r=new RegExp(t+"\\s+Is\\s+"+t,"g");return e=e.replace(r,"Is($1, $2)"),e}function Gr(e){let t=/^[\s]*[([/+\-`]/,n=/[{([,;:+\-*/%=&|?<>!~^]\s*$|^\s*$/,r=/\b(return|throw|yield|await|case|default|extends|new|typeof|void|delete|in|of|instanceof)\s*$/,s=e.split(`
6
+ `){s=!1,n+=a,o++;continue}if(i&&a==="*"&&c==="/"){i=!1,n+="*/",o+=2;continue}if(s||i){n+=a,o++;continue}a==="("||a==="{"||a==="["?(r++,n+=a):a===")"||a==="}"||a==="]"?(r--,n+=a):a===","&&r===0?(t.push(n),n=""):n+=a,o++}return n.trim()&&t.push(n),t}function Wn(e,t,n){let r=Bt(e,{originalSource:e,requiredParams:t.requiredParams,unsafeFunctions:t.unsafeFunctions,safeFunctions:t.safeFunctions}).source,s=Ft(r),i=!1,o=new Set,a=l=>{if(n&&/^\w+$/.test(l)){if(o.has(l))throw new Error(`Duplicate parameter name '${l}'`);o.add(l)}};return s.map(l=>{let u=l.trim();if(!u)return l;if(n&&u.startsWith("{")&&u.endsWith("}")){let m=u.slice(1,-1);return`{ ${Lr(m,t)} }`}if(n&&u.startsWith("[")&&u.endsWith("]")){let m=u.slice(1,-1);return`[ ${Lr(m,t)} ]`}if(u.startsWith("...")){let m=Br(u);return m!==-1?u.slice(0,m).trim():l}let p=u.match(/^(\w+)\s*\?\s*:\s*(.+)$/);if(p){let[,m,d]=p;return a(m),i=!0,`${m} = ${d}`}if(!Ui(u)){let m=u.match(/^(\w+)\s*=/);return m&&a(m[1]),i=!0,l}let f=Br(u);if(f!==-1){let m=u.slice(0,f).trim(),d=u.slice(f+1).trim();return a(m),i&&n&&/^\w+$/.test(m),n&&/^\w+$/.test(m)&&t.requiredParams.add(m),`${m} = ${d}`}return l}).join(",")}function Lr(e,t){return Ft(e).map(s=>{let i=s.trim();if(!i)return s;let o=i.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(o){let[,l,u]=o;t.requiredParams.add(l);let p=Ot(u);return`${l} = ${p}`}let a=i.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(a){let[,l,u]=a;t.requiredParams.add(l);let p=Lt(u);return`${l} = ${p}`}let c=i.match(/^(\w+)\s*:\s*([\s\S]+)$/);if(c){let[,l,u]=c;return t.requiredParams.add(l),`${l} = ${u}`}return s}).join(", ")}function Ot(e){let t=e.slice(1,-1).trim();return`{ ${Ft(t).map(s=>{let i=s.trim();if(!i)return s;let o=i.match(/^(\w+)\s*:\s*(\{[\s\S]*\})$/);if(o){let[,p,f]=o;return`${p}: ${Ot(f)}`}let a=i.match(/^(\w+)\s*=\s*(\{[\s\S]*\})$/);if(a){let[,p,f]=a;return`${p}: ${Ot(f)}`}let c=i.match(/^(\w+)\s*:\s*(\[[\s\S]*\])$/);if(c){let[,p,f]=c;return`${p}: ${Lt(f)}`}let l=i.match(/^(\w+)\s*=\s*(\[[\s\S]*\])$/);if(l){let[,p,f]=l;return`${p}: ${Lt(f)}`}let u=i.match(/^(\w+)\s*=\s*([\s\S]+)$/);if(u){let[,p,f]=u;return`${p}: ${f}`}return s}).join(", ")} }`}function Lt(e){let t=e.slice(1,-1).trim();return`[ ${Ft(t).map(s=>{let i=s.trim();return i?i.startsWith("{")&&i.endsWith("}")?Ot(i):i.startsWith("[")&&i.endsWith("]")?Lt(i):s:s}).join(", ")} ]`}function Ui(e){let t=0,n=!1,r=!1,s=!1,i="";for(let o=0;o<e.length;o++){let a=e[o];if(!s&&(a==="'"||a==='"'||a==="`")){s=!0,i=a;continue}if(s){a===i&&e[o-1]!=="\\"&&(s=!1);continue}a==="("||a==="{"||a==="["?t++:a===")"||a==="}"||a==="]"?t--:t===0&&(a===":"&&(n=!0),a==="="&&e[o+1]!==">"&&(r=!0))}return n&&!r}function Br(e){let t=0,n=!1,r="";for(let s=0;s<e.length;s++){let i=e[s];if(!n&&(i==="'"||i==='"'||i==="`")){n=!0,r=i;continue}if(n){i===r&&e[s-1]!=="\\"&&(n=!1);continue}if(i==="("||i==="{"||i==="[")t++;else if(i===")"||i==="}"||i==="]")t--;else if(t===0&&i===":")return s}return-1}function qi(e,t){let n=e.match(t);if(!n)return null;let r=n.index+n[0].length-1,s=1,i=r+1;for(;i<e.length&&s>0;)e[i]==="{"?s++:e[i]==="}"&&s--,i++;if(s!==0)return null;let o=e.slice(r,i),a=[n[0].slice(0,-1)+o,o];return a.index=n.index,a}function Vr(e){let t="",n=0;for(;n<e.length;){let r=e.slice(n).match(/^\btry\s*\{/);if(r){let i=n+r[0].length-1+1,o=1,a=i;for(;a<e.length&&o>0;){let l=e[a];l==="{"?o++:l==="}"&&o--,a++}if(o!==0){t+=e[n],n++;continue}if(e.slice(a).match(/^\s*(catch|finally)\b/))t+=e.slice(n,a),n=a;else{let l=e.slice(i,a-1);t+=`try {${l}} catch (__try_err) { return new (__tjs?.MonadicError ?? Error)(__try_err?.message || String(__try_err), 'try', undefined, undefined, __tjs?.getStack?.()) }`,n=a}}else t+=e[n],n++}return t}function Kr(e){let t=[],n="",r=0,s=0;for(;r<e.length;){let i=e.slice(r).match(/^\bwasm\s*\{/);if(i){let o=r,a=r+i[0].length,c=1,l=a;for(;l<e.length&&c>0;){let w=e[l];w==="{"?c++:w==="}"&&c--,l++}if(c!==0){n+=e[r],r++;continue}let u=e.slice(a,l-1),p,f=l,m=e.slice(l).match(/^\s*fallback\s*\{/);if(m){let w=l+m[0].length;c=1;let j=w;for(;j<e.length&&c>0;){let C=e[j];C==="{"?c++:C==="}"&&c--,j++}c===0&&(p=e.slice(w,j-1),f=j)}let y=Wi(u).map(w=>{let j=Vi(e,o,w);return j?`${w}: ${j}`:w}),x={id:`__tjs_wasm_${s}`,body:u,fallback:p,captures:y,start:o,end:f};t.push(x);let E=p??u,_=y.map(w=>w.split(":")[0].trim()),b=_.length>0?_.join(", "):"",T=_.length>0?`globalThis.${x.id}(${b})`:`globalThis.${x.id}()`,k=`(globalThis.${x.id} ? ${T} : (() => {${E}})())`;n+=k,r=f,s++}else n+=e[r],r++}return{source:n,blocks:t}}function Ji(e){return e.startsWith("f32x4_")||e.startsWith("v128_")}function Wi(e){let t=e.replace(/\/\/[^\n]*/g,"").replace(/\/\*[\s\S]*?\*\//g,""),n=new Set,r=/\.([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,s;for(;(s=r.exec(t))!==null;)n.add(s[1]);let i=/(?<!\.)(\b[a-zA-Z_$][a-zA-Z0-9_$]*)\b/g,o=new Set;for(;(s=i.exec(t))!==null;)o.add(s[1]);for(let f of n){if(!o.has(f))continue;let m=new RegExp(`(?<!\\.)\\b${f}\\b`,"g"),d=new RegExp(`\\.${f}\\b`,"g"),y=t.match(m)?.length||0,x=t.match(d)?.length||0;y<=x&&o.delete(f)}let a=new Set,c=/\b(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;for(;(s=c.exec(t))!==null;)a.add(s[1]);let l=/\bfor\s*\(\s*(?:let|const|var)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)/g;for(;(s=l.exec(t))!==null;)a.add(s[1]);let u=new Set(["if","else","for","while","do","switch","case","break","continue","return","function","let","const","var","new","this","true","false","null","undefined","typeof","instanceof","in","of","try","catch","finally","throw","async","await","class","extends","super","import","export","default","from","as","static","get","set","yield","console","Math","Array","Object","String","Number","Boolean","Date","JSON","Promise","Map","Set","WeakMap","WeakSet","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","ArrayBuffer","DataView","Error","TypeError","RangeError","length","push","pop","shift","unshift","slice","splice","map","filter","reduce","forEach","find","findIndex","indexOf","includes","globalThis","window","document","Infinity","NaN","isNaN","isFinite","parseInt","parseFloat","encodeURI","decodeURI","eval","wasmBuffer"]),p=[];for(let f of o)!a.has(f)&&!u.has(f)&&!Ji(f)&&p.push(f);return p.sort()}function Vi(e,t,n){let r=e.slice(0,t),s=/function\s+\w+\s*\(([^)]*)\)\s*(?:->.*?)?\s*\{[^}]*$/,i=r.match(s);if(!i){let o=/(?:const|let|var)?\s*\w+\s*=\s*(?:async\s*)?\(([^)]*)\)\s*(?:=>|->)?\s*\{[^}]*$/,a=r.match(o);return a?Ur(a[1],n):void 0}return Ur(i[1],n)}function Ur(e,t){let n=e.split(",").map(r=>r.trim());for(let r of n){let s=r.match(new RegExp(`^${t}\\s*:\\s*([A-Za-z][A-Za-z0-9]*)`));if(s)return s[1];let i=r.match(new RegExp(`^${t}\\s*=\\s*(Float32Array|Float64Array|Int32Array|Uint8Array|Int8Array|Int16Array|Uint16Array|Uint32Array)`));if(i)return i[1]}}function zr(e){let t=`([\\w][\\w.\\[\\]()]*|null|undefined|true|false|\\d+(?:\\.\\d+)?|'[^']*'|"[^"]*")`,n=new RegExp(t+"\\s+IsNot\\s+"+t,"g");e=e.replace(n,"IsNot($1, $2)");let r=new RegExp(t+"\\s+Is\\s+"+t,"g");return e=e.replace(r,"Is($1, $2)"),e}function Gr(e){let t=/^[\s]*[([`]/,n=/[{([,;:+\-*/%=&|?<>!~^]\s*$|^\s*$/,r=/\b(return|throw|yield|await|case|default|extends|new|typeof|void|delete|in|of|instanceof)\s*$/,s=e.split(`
7
7
  `),i=[],o=!1;for(let a=0;a<s.length;a++){let c=s[a],l=a>0?s[a-1]:"";if(o){i.push(c),c.includes("*/")&&(o=!1);continue}let u=c.indexOf("/*"),p=c.indexOf("*/");if(u!==-1&&(p===-1||p<u)){o=!0,i.push(c);continue}if(a>0&&t.test(c)){let f=l.replace(/\/\/.*$/,"").replace(/\/\*.*\*\/\s*$/,"");if(!n.test(f)&&!r.test(f)){let m=c.match(/^(\s*)/),d=m?m[1]:"",y=c.slice(d.length);i.push(d+";"+y);continue}}i.push(c)}return i.join(`
8
8
  `)}function Hr(e){e=e.replace(/\btypeof\s+([a-zA-Z_$][\w$.]*(?:\?\.[\w$]+)*)/g,"TypeOf($1)");let t=[],n=0,r="normal",s=[];for(;n<e.length;){let o=e[n],a=e[n+1];switch(r){case"single-string":if(o==="\\"&&n+1<e.length){n+=2;continue}o==="'"&&(r="normal"),n++;continue;case"double-string":if(o==="\\"&&n+1<e.length){n+=2;continue}o==='"'&&(r="normal"),n++;continue;case"template-string":if(o==="\\"&&n+1<e.length){n+=2;continue}if(o==="$"&&a==="{"){n+=2,s.push(1),r="normal";continue}o==="`"&&(r="normal"),n++;continue;case"line-comment":o===`
9
9
  `&&(r="normal"),n++;continue;case"block-comment":if(o==="*"&&a==="/"){n+=2,r="normal";continue}n++;continue;case"regex":if(o==="\\"&&n+1<e.length){n+=2;continue}if(o==="["){for(n++;n<e.length&&e[n]!=="]";)e[n]==="\\"&&n+1<e.length?n+=2:n++;n<e.length&&n++;continue}if(o==="/"){for(n++;n<e.length&&/[gimsuy]/.test(e[n]);)n++;r="normal";continue}n++;continue;case"normal":if(s.length>0){if(o==="{")s[s.length-1]++;else if(o==="}"&&(s[s.length-1]--,s[s.length-1]===0)){s.pop(),n++,r="template-string";continue}}if(o==="'"){n++,r="single-string";continue}if(o==='"'){n++,r="double-string";continue}if(o==="`"){n++,r="template-string";continue}if(o==="/"&&a==="/"){n+=2,r="line-comment";continue}if(o==="/"&&a==="*"){n+=2,r="block-comment";continue}if(o==="/"){let c=n-1;for(;c>=0&&/\s/.test(e[c]);)c--;let l=c>=0?e[c]:"";if(!l||/[=(!,;:{[&|?+\-*%<>~^]/.test(l)||c>=5&&/\b(return|case|throw|in|of|typeof|instanceof|new|delete|void)$/.test(e.slice(Math.max(0,c-10),c+1))){n++,r="regex";continue}}if(o==="="&&a==="="&&e[n+2]!=="="&&e[n-1]!=="!"){t.push({pos:n,op:"=="}),n+=2;continue}if(o==="!"&&a==="="&&e[n+2]!=="="){t.push({pos:n,op:"!="}),n+=2;continue}break}n++}if(t.length===0)return e;let i=e;for(let o=t.length-1;o>=0;o--){let{pos:a,op:c}=t[o],l=c==="=="?"Eq":"NotEq",u=Ki(i,a),p=zi(i,a+2),f=i.slice(u,a).trim(),m=i.slice(a+2,p).trim();if(f&&m){let d=i.slice(0,u),y=i.slice(p),E=/[a-zA-Z0-9_$]$/.test(d)?" ":"";i=`${d}${E}${l}(${f}, ${m})${y}`}}return i}function Ki(e,t){let n=t-1;for(;n>=0&&/\s/.test(e[n]);)n--;if(n<0)return 0;let r=0,s=!1,i="";for(;n>=0;){let o=e[n],a=n>0?e[n-1]:"";if(s){o===i&&a!=="\\"&&(s=!1),n--;continue}if((o==='"'||o==="'"||o==="`")&&a!=="\\"){s=!0,i=o,n--;continue}if(o===")"||o==="]"||o==="}"){r++,n--;continue}if(o==="("||o==="["){if(r>0){r--,n--;continue}return n+1}if(o==="{"){if(r>0){r--,n--;continue}return n+1}if(r>0){n--;continue}if(o===";")return n+1;if(/[a-z]/.test(o)){let c=n+1,l=n;for(;l>0&&/[a-z]/i.test(e[l-1]);)l--;let u=e.slice(l,c),p=l>0?e[l-1]:"";if(!/[a-zA-Z0-9_$]/.test(p)){if(["return","throw","case","typeof","void","delete","await","yield"].includes(u))return c;if(u==="new")return l}}if(o===">"&&a==="="||o==="="&&a!=="="&&a!=="!"&&a!=="<"&&a!==">"||o==="&"&&a==="&"||o==="|"&&a==="|"||o==="?"||o===":"||o===",")return n+1;n--}return 0}function zi(e,t){let n=t;for(;n<e.length&&/\s/.test(e[n]);)n++;if(n>=e.length)return e.length;let r=0,s=!1,i="";for(;n<e.length;){let o=e[n],a=n+1<e.length?e[n+1]:"";if(s){o===i&&e[n-1]!=="\\"&&(s=!1),n++;continue}if((o==='"'||o==="'"||o==="`")&&e[n-1]!=="\\"){s=!0,i=o,n++;continue}if(o==="("||o==="["||o==="{"){r++,n++;continue}if(o===")"||o==="]"||o==="}"){if(r>0){r--,n++;continue}return n}if(r>0){n++;continue}if(o===";"||o==="&"&&a==="&"||o==="|"&&a==="|"||o==="?"||o===":"||o===","||(o==="="||o==="!")&&a==="="&&e[n+2]!=="=")return n;n++}return e.length}function Zr(e){let t="",n=0;for(;n<e.length;){let r=e.slice(n).match(/^\bType\s+([A-Z_][a-zA-Z0-9_]*)\s*/);if(r){let s=r[1],i=n+r[0].length,o=s,a=!1,c=e.slice(i).match(/^(['"`])([^]*?)\1\s*/);if(c){let f=i+c[0].length,m=e[f],d=m===void 0||f>=e.length||m!=="="&&m!=="{";if(m==="="||m==="{")o=c[2],a=!0,i=f;else if(d){let y=c[0].trim(),x=c[0].slice(y.length);t+=`const ${s} = Type('${s}', ${y})${x}`,n=f;continue}}let l,u=i,p=e.slice(i).match(/^=\s*/);if(p){i+=p[0].length;let f=e.slice(i).match(/^(\+?\d+(?:\.\d+)?|['"`][^'"`]*['"`]|\{[^}]*\}|\[[^\]]*\]|true|false|null)/);if(f){l=f[0],i+=f[0].length,u=i;let m=e.slice(i).match(/^\s*/);m&&(i+=m[0].length)}}if(e[i]==="{"){let f=i+1,m=1,d=f;for(;d<e.length&&m>0;){let k=e[d];k==="{"?m++:k==="}"&&m--,d++}if(m!==0){t+=e[n],n++;continue}let y=e.slice(f,d-1).trim(),x=d,E=y.match(/description\s*:\s*(['"`])([^]*?)\1/);E&&!a&&(o=E[2]);let _,b=y.match(/example\s*:\s*/);if(b){let k=b.index+b[0].length,w=Fr(y,k);w&&(_=w.value.trim())}let T=y.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/);if(T&&_){let k=T[1].trim(),w=T[2].trim(),j=l?`, ${l}`:"";t+=`const ${s} = Type('${o}', (${k}) => { if (!globalThis.__tjs?.validate(${k}, globalThis.__tjs?.infer(${_}))) return false; ${w} }, ${_}${j})`}else if(T){let k=T[1].trim(),w=T[2].trim(),j=l?`, undefined, ${l}`:"";t+=`const ${s} = Type('${o}', (${k}) => { ${w} }${j})`}else if(_){let k=l?`, ${l}`:"";t+=`const ${s} = Type('${o}', undefined, ${_}${k})`}else l?t+=`const ${s} = Type('${o}', ${l})`:t+=`const ${s} = Type('${o}')`;n=x;continue}else if(l){t+=`const ${s} = Type('${o}', ${l})`,n=u;continue}else if(!c){let f=e.slice(i).match(/^(['"`][^]*?['"`]|\+?\d+(?:\.\d+)?|true|false|null|\{[^]*?\}|\[[^]*?\])/);if(f){let m=f[0];t+=`const ${s} = Type('${s}', ${m})`,n=i+f[0].length;continue}}}t+=e[n],n++}return t}function Yr(e){let t="",n=0;for(;n<e.length;){let r=e.slice(n).match(/^\bFunctionPredicate\s+([A-Z_][a-zA-Z0-9_]*)\s*(?:<([^>]+)>)?\s*/);if(r){let s=r[1],i=r[2],o=n+r[0].length;if(e[o]==="{"){let a=1,c=o+1;for(;c<e.length&&a>0;)e[c]==="{"?a++:e[c]==="}"&&a--,c++;if(a===0){let l=e.slice(o+1,c-1).trim(),u=qi(l,/params\s*:\s*\{/),p=l.match(/returns\s*:\s*(.+?)(?:\n|$)/),f=l.match(/returnContract\s*:\s*['"](\w+)['"]/),m=l.match(/description\s*:\s*(['"])([^]*?)\1/),d=[];u&&d.push(`params: ${u[1]}`),p&&d.push(`returns: ${p[1].trim()}`),f&&d.push(`returnContract: '${f[1]}'`);let y=m?m[2]:s;if(i){let x=i.split(",").map(_=>{let b=_.trim().split("=").map(T=>T.trim());if(b.length===2){let T=b[1]==="any"||b[1]==="undefined"?"null":b[1];return`['${b[0]}', ${T}]`}return`'${b[0]}'`}),E=i.split(",").map(_=>_.trim().split("=")[0].trim());t+=`const ${s} = FunctionPredicate('${y}', [${x.join(", ")}], (${E.join(", ")}) => ({ ${d.join(", ")} }))`}else t+=`const ${s} = FunctionPredicate('${y}', { ${d.join(", ")} })`;n=c;continue}}if(e[o]==="("){let a=1,c=o+1;for(;c<e.length&&a>0;)e[c]==="("?a++:e[c]===")"&&a--,c++;if(a===0){let l=e.slice(o+1,c-1).trim(),u=l.indexOf(",");if(u!==-1){let p=l.slice(0,u).trim(),f=l.slice(u+1).trim();t+=`const ${s} = FunctionPredicate(${f}, ${p})`}else t+=`const ${s} = FunctionPredicate('${s}', ${l})`;n=c;continue}}}t+=e[n],n++}return t}function Xr(e){let t="",n=0;for(;n<e.length;){let r=e.slice(n).match(/^\bGeneric\s+([A-Z][a-zA-Z0-9_]*)\s*<([^>]+)>\s*\{/);if(r){let s=r[1],i=r[2],a=n+r[0].length-1+1,c=1,l=a;for(;l<e.length&&c>0;){let _=e[l];_==="{"?c++:_==="}"&&c--,l++}if(c!==0){t+=e[n],n++;continue}let u=e.slice(a,l-1).trim(),p=l,f=i.split(",").map(_=>{let b=_.trim().split("=").map(T=>T.trim());if(b.length===2){let T=b[1]==="any"||b[1]==="undefined"?"null":b[1];return`['${b[0]}', ${T}]`}return`'${b[0]}'`}),m=u,d=m.search(/\bdeclaration\s*\{/);if(d!==-1){let _=m.indexOf("{",d),b=1,T=_+1;for(;T<m.length&&b>0;)m[T]==="{"?b++:m[T]==="}"&&b--,T++;m=m.slice(0,d)+m.slice(T)}let y=m.match(/description\s*:\s*(['"`])([^]*?)\1/),x=m.match(/predicate\s*\(([^)]*)\)\s*\{([^]*)\}/),E=y?y[2]:s;if(x){let _=x[1].trim().split(",").map(j=>j.trim()),b=x[2].trim(),T=_[0]||"x",k=_.slice(1),w=k.map(j=>`check${j}`);k.forEach((j,C)=>{b=b.replace(new RegExp(`\\b${j}\\s*\\(`,"g"),`${w[C]}(`)}),t+=`const ${s} = Generic([${f.join(", ")}], (${T}, ${w.join(", ")}) => { ${b} }, '${E}')`}else t+=`const ${s} = Generic([${f.join(", ")}], () => true, '${E}')`;n=p;continue}t+=e[n],n++}return t}function Qr(e){let t="",n=0;for(;n<e.length;){let r=e.slice(n).match(/^\bUnion\s+([A-Z][a-zA-Z0-9_]*)\s+(['"`])([^]*?)\2\s*/);if(r){let s=r[1],i=r[3],o=n+r[0].length;if(e[o]==="{"){let a=o+1,c=1,l=a;for(;l<e.length&&c>0;){let m=e[l];m==="{"?c++:m==="}"&&c--,l++}if(c!==0){t+=e[n],n++;continue}let u=e.slice(a,l-1).trim(),p=l,f=qr(u);t+=`const ${s} = Union('${i}', [${f.join(", ")}])`,n=p;continue}else{let a=e.indexOf(`