@niscorp/loom 0.2.0 → 0.3.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.
Files changed (41) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/DESIGN.md +38 -8
  3. package/README.md +28 -5
  4. package/dist/{chunk-LWY5TG7M.js → chunk-IZ5B6IMX.js} +7 -3
  5. package/dist/chunk-IZ5B6IMX.js.map +1 -0
  6. package/dist/{chunk-X7PCPONB.js → chunk-TCCN6LKV.js} +6 -4
  7. package/dist/chunk-TCCN6LKV.js.map +1 -0
  8. package/dist/index.cjs +4 -2
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +2 -2
  11. package/dist/index.d.ts +2 -2
  12. package/dist/index.js +1 -1
  13. package/dist/{loom-editor-D5SBQ4_F.d.ts → loom-editor-Clohg49u.d.ts} +1 -1
  14. package/dist/{loom-editor-CQ_GI4IA.d.cts → loom-editor-MACwUjLC.d.cts} +1 -1
  15. package/dist/plugins/nova/index.d.cts +1 -1
  16. package/dist/plugins/nova/index.d.ts +1 -1
  17. package/dist/plugins/nova/react/index.d.cts +2 -2
  18. package/dist/plugins/nova/react/index.d.ts +2 -2
  19. package/dist/plugins/prism/index.d.cts +1 -1
  20. package/dist/plugins/prism/index.d.ts +1 -1
  21. package/dist/plugins/prism/react/index.cjs +2 -0
  22. package/dist/plugins/prism/react/index.cjs.map +1 -1
  23. package/dist/plugins/prism/react/index.d.cts +2 -2
  24. package/dist/plugins/prism/react/index.d.ts +2 -2
  25. package/dist/plugins/prism/react/index.js +2 -0
  26. package/dist/plugins/prism/react/index.js.map +1 -1
  27. package/dist/plugins/vex/index.d.cts +1 -1
  28. package/dist/plugins/vex/index.d.ts +1 -1
  29. package/dist/plugins/vex/react/index.d.cts +2 -2
  30. package/dist/plugins/vex/react/index.d.ts +2 -2
  31. package/dist/plugins/vex/react/index.js +1 -1
  32. package/dist/react/index.cjs +9 -3
  33. package/dist/react/index.cjs.map +1 -1
  34. package/dist/react/index.d.cts +3 -3
  35. package/dist/react/index.d.ts +3 -3
  36. package/dist/react/index.js +3 -3
  37. package/dist/{types-BonjN3CB.d.cts → types-l8sDxrMR.d.cts} +5 -1
  38. package/dist/{types-BonjN3CB.d.ts → types-l8sDxrMR.d.ts} +5 -1
  39. package/package.json +9 -8
  40. package/dist/chunk-LWY5TG7M.js.map +0 -1
  41. package/dist/chunk-X7PCPONB.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/compile/parse.ts","../src/compile/roles.ts","../src/compile/to-nova.ts","../src/validate.ts","../src/editor/default.layout.ts","../src/editor/view.ts","../src/editor/editor.ts"],"names":["literal","child","stripErrors","createLayoutStore","createShell","z"],"mappings":";;;;;;AA6CA,IAAM,KAAA,GAAQ,CAAC,MAAA,KAA4B,MAAA,CAAO,GAAA;AAalD,IAAM,cAAA,GAAiB,SAAA;AAEvB,IAAM,YAAA,GAAe,CAAC,MAAA,KAAwC;AAC5D,EAAA,MAAM,GAAA,GAAM,MAAM,MAAM,CAAA;AACxB,EAAA,IAAI,GAAA,CAAI,MAAA,KAAW,MAAA,EAAW,OAAO,GAAA,CAAI,MAAA;AACzC,EAAA,KAAA,MAAW,KAAA,IAAS,GAAA,CAAI,MAAA,IAAU,EAAC,EAAG;AACpC,IAAA,IAAI,MAAM,GAAA,EAAK,MAAA,KAAW,MAAA,EAAW,OAAO,MAAM,GAAA,CAAI,MAAA;AAAA,EACxD;AACA,EAAA,OAAO,MAAA;AACT,CAAA;AAEA,IAAM,SAAA,GAAY,CAAC,MAAA,KAA6B;AAC9C,EAAA,MAAM,GAAA,GAAM,MAAM,MAAM,CAAA;AACxB,EAAA,IAAI,GAAA,CAAI,MAAA,KAAW,cAAA,EAAgB,OAAO,IAAA;AAC1C,EAAA,OAAA,CAAQ,GAAA,CAAI,MAAA,IAAU,EAAC,EAAG,IAAA,CAAK,CAAC,KAAA,KAAU,KAAA,CAAM,GAAA,EAAK,MAAA,KAAW,cAA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AA,IACT,CAAA;AAAA,IACA,IAAI,WAAA,GAAc;AAChB,MAAA,OAAO,WAAA;AAAA,IACT,CAAA;AAAA,IACA,UAAA,EAAY,CAAC,MAAA,KAAW;AACtB,MAAA,OAAA,CAAQ,GAAA,CAAI,MAAA,CAAO,IAAA,EAAM,MAAM,CAAA;AAC/B,MAAA,MAAA,CAAO,QAAQ,MAAM,CAAA;AAAA,IACvB,CAAA;AAAA,IACA,IAAA;AAAA,IACA,EAAA,EAAI,CAAC,KAAA,EAAO,OAAA,KAAY;AACtB,MAAA,SAAA,CAAU,KAAK,CAAA,CAAE,GAAA,CAAI,OAAO,CAAA;AAC5B,MAAA,OAAO,MAAM,SAAA,CAAU,KAAK,CAAA,CAAE,OAAO,OAAO,CAAA;AAAA,IAC9C,CAAA;AAAA,IACA,SAAS,MAAM;AACb,MAAA,MAAA,CAAO,OAAA,CAAQ,CAAC,GAAA,KAAQ,GAAA,EAAK,CAAA;AAC7B,MAAA,MAAA,GAAS,EAAC;AACV,MAAA,KAAA,CAAM,OAAA,EAAQ;AAAA,IAChB;AAAA,GACF;AAEA,EAAA,OAAO,MAAA;AACT","file":"index.cjs","sourcesContent":["import type { ZodType } from 'zod';\nimport type {\n CompileOptions,\n EmptyValue,\n EnumOption,\n Field,\n FieldKind,\n FieldMeta,\n ObjectField,\n Pattern,\n Variant,\n} from './types.js';\n\n// parse — turn a Zod schema into Loom's field model (IR). The only Zod-aware\n// code in the package, and pure data in / pure data out: no Nova. `parseByType`\n// is keyed by Zod's own `def.type` tag, so the type vocabulary lives as table\n// keys, not scattered checks.\n//\n// A recursive schema (`z.lazy`, or an object whose getter returns itself) would\n// expand forever. The walk carries the set of schemas it is currently inside;\n// re-entering one is a back-edge, emitted as a `self` marker and recorded so\n// the object it points back to can be tagged `recursive`. Expansion stops at\n// the cycle — the document, not the schema, decides how deep an editor goes.\n\n// The slice of a Zod schema's internal definition that parsing reads.\ntype ZodDef = {\n type: string;\n innerType?: ZodType;\n element?: ZodType;\n shape?: Record<string, ZodType>;\n entries?: Record<string, unknown>;\n defaultValue?: unknown;\n format?: string;\n checks?: ReadonlyArray<{ def?: { format?: string } }>;\n discriminator?: string;\n options?: readonly ZodType[];\n items?: readonly ZodType[];\n values?: readonly unknown[];\n getter?: () => ZodType;\n};\n\n// Zod types every schema's `.def` as the base `$ZodTypeDef` (just the `type`\n// discriminant); the per-type fields we read live on the concrete defs. This\n// views `.def` through the structural slice above — the single place the\n// parser depends on Zod's internal shape.\nconst defOf = (schema: ZodType): ZodDef => schema.def as ZodDef;\n\n// While walking, the schemas currently on the stack (cycle detection) and the\n// schemas a `self` pointed back to (so the matching object is tagged recursive).\n// Keyed by def, not instance: `.describe()`/`.meta()` clone the wrapper but\n// share the def, so a described alias of a recursive schema must read as the\n// schema itself — or every back-edge re-expands the whole thing one more level.\ntype Walk = { stack: Set<ZodDef>; targets: Set<ZodDef> };\n\n// ─── Reading Zod ─────────────────────────────────────────────\n\n// `safeint` is Zod's format tag for an integer-constrained number — the one\n// Zod-vocabulary token this file matches on.\nconst INTEGER_FORMAT = 'safeint';\n\nconst stringFormat = (schema: ZodType): string | undefined => {\n const def = defOf(schema);\n if (def.format !== undefined) return def.format;\n for (const check of def.checks ?? []) {\n if (check.def?.format !== undefined) return check.def.format;\n }\n return undefined;\n};\n\nconst isInteger = (schema: ZodType): boolean => {\n const def = defOf(schema);\n if (def.format === INTEGER_FORMAT) return true;\n return (def.checks ?? []).some((check) => check.def?.format === INTEGER_FORMAT);\n};\n\nconst enumOptions = (schema: ZodType): EnumOption[] =>\n Object.values(defOf(schema).entries ?? {}).map((value) => ({ value, label: String(value) }));\n\nconst objectFields = (schema: ZodType, walk: Walk): ObjectField[] =>\n Object.entries(defOf(schema).shape ?? {}).map(([key, value]) => ({\n key,\n // A property is optional when the schema accepts `undefined` for it\n // (covers `.optional()` and `.default()`) — asked of Zod, not inferred.\n required: !value.safeParse(undefined).success,\n field: parseField(value, walk),\n }));\n\n// ─── Union discrimination ────────────────────────────────────\n// For each branch, the cheapest fact that tells it apart from its siblings: the\n// declared tag's value, else a key only it carries, else a JS type only it is.\n// One function covers tagged, structural, and mixed unions; a branch that none\n// of these distinguish makes the whole union fall back to the raw editor.\n\nconst branchKeys = (branch: ZodType): string[] => Object.keys(defOf(branch).shape ?? {});\n\n// The branch's JS type, when it's one the runtime matcher checks (Zod names\n// these the same as `typeof`/`Array.isArray` do); otherwise undefined.\nconst JSON_TYPES = new Set(['string', 'number', 'boolean', 'object', 'array', 'null']);\nconst jsonType = (branch: ZodType): string | undefined => {\n const type = defOf(branch).type;\n return JSON_TYPES.has(type) ? type : undefined;\n};\n\nconst distinguish = (branch: ZodType, siblings: readonly ZodType[], tag: string | undefined): Pattern | undefined => {\n if (tag !== undefined) {\n const literal = (defOf(branch).shape ?? {})[tag];\n return { kind: 'tag', key: tag, value: literal !== undefined ? defOf(literal).values?.[0] : undefined };\n }\n const elsewhere = new Set(siblings.flatMap(branchKeys));\n const key = branchKeys(branch).find((k) => !elsewhere.has(k));\n if (key !== undefined) return { kind: 'key', key };\n const type = jsonType(branch);\n if (type !== undefined && siblings.every((s) => jsonType(s) !== type)) return { kind: 'type', type };\n return undefined;\n};\n\nconst patternLabel = (pattern: Pattern): string =>\n pattern.kind === 'tag'\n ? String(pattern.value)\n : pattern.kind === 'key'\n ? pattern.key\n : pattern.kind === 'type'\n ? pattern.type\n : 'other';\n\n// A union may nest unions (`z.union([...primitives, ...ops])` where the\n// primitives are themselves a `z.union`). The branches of a nested union are\n// siblings of the outer ones for discrimination, so inline them. Each branch is\n// unwrapped first (a described/optional sub-union still flattens); a non-union\n// branch passes through untouched. Unwrapping resolves lazies, so `seen` guards\n// a union that nests back into itself: once a union core is being flattened,\n// re-encountering it keeps the branch as a leaf rather than recursing forever.\nconst flattenBranches = (branches: readonly ZodType[], seen: Set<ZodDef> = new Set()): ZodType[] =>\n branches.flatMap((branch) => {\n const { core } = unwrap(branch);\n const def = defOf(core);\n if (def.type !== 'union' || seen.has(def)) return [branch];\n return flattenBranches(def.options ?? [], new Set(seen).add(def));\n });\n\n// A branch's editor. A tagged union owns its discriminant in the chooser, so it\n// is dropped from the fields; every other branch is edited whole — including a\n// `string` or `array` branch, which is just its own field, not a group.\nconst branchField = (branch: ZodType, walk: Walk, tag: string | undefined): Field =>\n tag === undefined\n ? parseField(branch, walk)\n : { kind: 'object', fields: objectFields(branch, walk).filter((f) => f.key !== tag) };\n\nconst parseByType: Record<string, (schema: ZodType, walk: Walk) => Field> = {\n string: (schema) => {\n const format = stringFormat(schema);\n return format !== undefined ? { kind: 'string', format } : { kind: 'string' };\n },\n number: (schema) => (isInteger(schema) ? { kind: 'number', integer: true } : { kind: 'number' }),\n boolean: () => ({ kind: 'boolean' }),\n enum: (schema) => ({ kind: 'enum', options: enumOptions(schema) }),\n object: (schema, walk) => {\n // On the stack while its fields parse, so a self-reference re-entering it\n // is caught as a cycle. If one was, the object is a recursion anchor.\n const def = defOf(schema);\n walk.stack.add(def);\n const fields = objectFields(schema, walk);\n walk.stack.delete(def);\n return walk.targets.has(def) ? { kind: 'object', fields, recursive: true } : { kind: 'object', fields };\n },\n array: (schema, walk) => {\n const element = defOf(schema).element;\n return { kind: 'array', item: element !== undefined ? parseField(element, walk) : { kind: 'unknown' } };\n },\n tuple: (schema, walk) => ({ kind: 'tuple', items: (defOf(schema).items ?? []).map((item) => parseField(item, walk)) }),\n union: (schema, walk) => {\n // Flatten nested unions into sibling branches, then dedup by identity — a\n // self-referential union resolves the same cached member instances twice, so\n // the same schema can appear more than once.\n const branches = [...new Set(flattenBranches(defOf(schema).options ?? []))];\n const tag = defOf(schema).discriminator;\n // Patterns don't need the stack — compute them first.\n const patterns = branches.map((b) => distinguish(b, branches.filter((x) => x !== b), tag));\n // A branch nothing distinguishes is the catch-all: allow exactly one, as the\n // fallback the widget picks when no other pattern matches. Two such branches\n // are ambiguous (which catches a plain value?), so the union still falls back\n // to the raw editor whole.\n const open = patterns.reduce<number[]>((acc, p, i) => (p === undefined ? [...acc, i] : acc), []);\n if (branches.length === 0 || open.length > 1) return { kind: 'unknown' };\n if (open.length === 1) patterns[open[0]!] = { kind: 'fallback' };\n // Parse the branch fields with the union on the stack, so a child that\n // re-enters it (a `children: LayoutNode[]`) is caught as a cycle.\n const def = defOf(schema);\n walk.stack.add(def);\n const variants: Variant[] = branches.map((branch, i) => ({\n label: readMeta(branch).title ?? patternLabel(patterns[i]!),\n field: branchField(branch, walk, tag),\n pattern: patterns[i]!,\n }));\n walk.stack.delete(def);\n return walk.targets.has(def) ? { kind: 'union', variants, recursive: true } : { kind: 'union', variants };\n },\n};\n\nconst unknownField = (): Field => ({ kind: 'unknown' });\n\n// Modifier wrappers that don't change the editing shape — peeled to reach the\n// core type, capturing any default along the way. `lazy` is peeled too: it is\n// the deferral that makes a schema recursive, resolved here to the schema it\n// guards (whose identity the cycle check then recognizes).\nconst WRAPPERS = new Set(['optional', 'nullable', 'default', 'readonly']);\n\n// A `lazy` is a deferred reference to one schema, but its getter may *build* a\n// fresh instance on every call (`z.lazy(() => z.union([...]))`) rather than\n// close over a stable const. Cycle detection needs the same resolution each\n// time, so resolve each lazy once and reuse it. Keyed by the lazy's def — the\n// def owns the getter, and a `.describe()` alias of the lazy shares it, so the\n// alias resolves to the same instance instead of a second copy of the tree.\nconst lazyResolved = new WeakMap<ZodDef, ZodType>();\nconst resolveLazy = (lazy: ZodType): ZodType | undefined => {\n const def = defOf(lazy);\n const cached = lazyResolved.get(def);\n if (cached !== undefined) return cached;\n const resolved = def.getter?.();\n if (resolved !== undefined) lazyResolved.set(def, resolved);\n return resolved;\n};\n\nconst unwrap = (schema: ZodType): { core: ZodType; default?: unknown } => {\n let core = schema;\n let fallback: unknown;\n let def = defOf(core);\n while (WRAPPERS.has(def.type) || def.type === 'lazy') {\n // `lazy` reaches its schema through a memoized getter; the other wrappers\n // through `innerType`. Either may be absent on a malformed def — stop if so.\n const inner = def.type === 'lazy' ? resolveLazy(core) : def.innerType;\n if (inner === undefined) break;\n if ('defaultValue' in def) fallback = def.defaultValue;\n core = inner;\n def = defOf(core);\n }\n return fallback !== undefined ? { core, default: fallback } : { core };\n};\n\nconst readMeta = (schema: ZodType): FieldMeta => {\n const meta: FieldMeta = {};\n const title = (schema.meta() as { title?: unknown } | undefined)?.title;\n if (typeof title === 'string') meta.title = title;\n if (schema.description !== undefined) meta.description = schema.description;\n return meta;\n};\n\nconst parseField = (schema: ZodType, walk: Walk): Field => {\n const { core, default: fallback } = unwrap(schema);\n // A schema already on the stack is a recursion back-edge: stop and record\n // it, so the object it cycles to is tagged when its parse unwinds.\n if (walk.stack.has(defOf(core))) {\n walk.targets.add(defOf(core));\n return { kind: 'self' };\n }\n const body = (parseByType[defOf(core).type] ?? unknownField)(core, walk);\n // Read metadata from both the core and the original, so a `.describe()` on\n // either the type or a wrapper is picked up; the outer one wins.\n const meta = { ...readMeta(core), ...readMeta(schema) };\n return { ...body, ...meta, ...(fallback !== undefined ? { default: fallback } : {}) };\n};\n\nexport const parse = (schema: ZodType): Field =>\n parseField(schema, { stack: new Set(), targets: new Set() });\n\n// ─── buildDocument: IR → default document ────────────────────\n// The default value of a field, by kind. Pure JSON — a model concern, not a\n// rendering one. Recursion bottoms out naturally: a recursive object's array\n// of itself defaults to empty, so no `self` is ever expanded into a default.\n\n// Each entry takes the whole field; the scalar kinds ignore it, and the two that\n// read their own shape (`object`, `union`) narrow with a guard rather than a\n// cast — the guard never fires (dispatch keys on `kind`), but it keeps the\n// types honest without a type assertion.\nconst EMPTY: Record<FieldKind, EmptyValue> = {\n string: () => '',\n number: () => 0,\n boolean: () => false,\n // No neutral in-domain value: \"no selection\" is absence (undefined), which\n // an optional enum accepts and a required one flags — unlike null, which a\n // Zod enum rejects outright. Defaults drop undefined, so no stray key.\n enum: () => undefined,\n array: () => [],\n // Each slot built from its own field; a fixed-length list, so no growth.\n tuple: (field, options) => (field.kind === 'tuple' ? field.items.map((item) => buildDocument(item, options)) : []),\n // A recursion point has no value of its own; the array holding it defaults to [].\n self: () => undefined,\n unknown: () => null,\n object: (field, options) => {\n if (field.kind !== 'object') return {};\n const includeOptional = options.includeOptional ?? true;\n const document: Record<string, unknown> = {};\n for (const child of field.fields) {\n if (!child.required && !includeOptional) continue;\n const value = buildDocument(child.field, options);\n if (value !== undefined) document[child.key] = value; // no stray undefined keys\n }\n return document;\n },\n // An empty union defaults to its first variant (tag + branch defaults).\n union: (field) => {\n if (field.kind !== 'union') return {};\n const first = field.variants[0];\n return first === undefined ? {} : variantDefaults(first);\n },\n};\n\nexport const buildDocument = (field: Field, options: CompileOptions): unknown => {\n if (field.default !== undefined) return field.default;\n return (options.empty?.[field.kind] ?? EMPTY[field.kind])(field, options);\n};\n\n// A plain object — not an array or null. Guards the spread of a built default\n// document, whose static type is `unknown` (so we check rather than assert).\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n// A branch's default value: whatever its field builds — an object, but also a\n// bare `''` or `[]` for a scalar/array branch. A tagged union additionally sets\n// its discriminant alongside. Used as an empty union's value and to reshape the\n// document when the chooser switches branches.\nexport const variantDefaults = (variant: Variant): unknown => {\n const defaults = buildDocument(variant.field, {});\n if (variant.pattern.kind !== 'tag') return defaults;\n return { [variant.pattern.key]: variant.pattern.value, ...(isRecord(defaults) ? defaults : {}) };\n};\n","// The widget vocabulary the compiler emits as Nova component names. Each is\n// an abstract role; a kit registers a concrete component under the name, so\n// swapping the kit swaps the pixels without touching the compiler. Small and\n// stable on purpose — sub-variants ride as props, not new roles.\n//\n// Structural shapes (objects, arrays, unions) are compiled compositions of\n// these roles, not roles of their own.\n\nexport const Roles = {\n // Layout primitives — arrange other nodes.\n box: 'loom:box', // a flexible cell that grows to fill its row (an array item's editor)\n group: 'loom:group',\n array: 'loom:array',\n arrayItem: 'loom:array-item',\n variant: 'loom:variant',\n // One branch of a variant — shows itself only when it's the active branch\n // (the widget matches the value to a branch in JS and tells it through context).\n branch: 'loom:branch',\n\n // Field wrapper — label, description, error, and required marker around one control.\n field: 'loom:field',\n\n // Controls — edit a value; emit `ui:model`.\n text: 'loom:text',\n number: 'loom:number',\n checkbox: 'loom:checkbox',\n select: 'loom:select',\n raw: 'loom:raw',\n\n // List actions — model writes to the bound array (no triggers). `append` adds\n // a default element to the list it binds. `rowMenu` is the per-row actions menu\n // (move / remove, and wrap / unwrap when the list's items are a recursive union\n // with container variants); it reads `$items` and `$index` and writes the new\n // array. Both work at any depth, since the bound path resolves per render.\n append: 'loom:append',\n rowMenu: 'loom:row-menu',\n} as const;\n\nexport type Role = (typeof Roles)[keyof typeof Roles];\n","import type { ActionDefinition, ComponentNode, LayoutNode } from '@niscorp/nova';\nimport { buildDocument, isRecord, variantDefaults } from './parse.js';\nimport { Roles, type Role } from './roles.js';\nimport type { CompileOptions, Field, ObjectField, Pattern, Variant } from './types.js';\n\n// toNova — turn Loom's field model into a Nova editor: a layout + the document\n// it edits (+ any named templates a recursive schema needs). This is the\n// rendering half, and the only half that speaks Nova. The model (`parse`) knows\n// nothing about it. Every edit — including add / remove / reorder — is a model\n// write through Nova's `ui:model` pipeline; no action triggers are emitted.\n//\n// Field (IR) ──toNova──▶ { action, layouts }\n//\n// Fields bind to the document by a *binding expression* threaded through the\n// build: `$.name` at the root, `$item` inside an array loop. A recursive object\n// is emitted once as a named layout authored against `$item`; its `self`\n// reference points back to that layout, and Nova resolves it per render against\n// the live data — so the editor goes exactly as deep as the document does.\n\n// The reserved data namespace the editor writes validation errors into and each\n// field binds its error slot to. Excluded from the reported document.\nexport const ERROR_NAMESPACE = '_errors';\n\n// The loop variable an array binds each element under, plus the two other loop\n// bindings Nova exposes per iteration: the element's index, and `$items` — the\n// whole array — which the row controls write back to (remove / reorder).\nconst ITEM = 'item';\nconst INDEX = '$index';\nconst ITEM_EXPR = `$${ITEM}`;\nconst LIST_EXPR = '$items';\n\n// What Loom hands Nova: the action plus the named layouts it references. The\n// layouts are the recursive templates; for a non-recursive schema it's empty.\nexport type NovaEditor = { action: ActionDefinition; layouts: Record<string, LayoutNode> };\n\n// A container variant of a recursive union: one whose value can hold a list of\n// the same recursive type. `key` is the field that holds that list. Used to\n// wrap an element into one, and to recognize / unwrap an element that is one.\n// Purely structural — nothing here knows what the schema represents.\ntype Container = { label: string; pattern: Pattern; defaults: unknown; key: string };\n\n// A recursive template in scope while its object is built: the layout name a\n// `self` points back to, the default node an \"add\" appends, and (for a union)\n// the container variants its items can be wrapped into.\ntype Template = { name: string; defaultChild: unknown; containers: Container[] };\n\ntype BuildContext = {\n /** Register a named layout (a recursive object's reusable template). */\n register: (name: string, node: LayoutNode) => void;\n /** The recursive templates currently being built; `self` refs the innermost. */\n templates: Template[];\n /** A fresh, stable layout name for a recursion template. */\n name: () => string;\n /** The custom-widget role for a field at a path, if a plugin matcher claims it. */\n widgetRole: (field: Field, path: string) => string | undefined;\n options: CompileOptions;\n};\n\ntype Build<K extends Field['kind']> = (\n field: Extract<Field, { kind: K }>,\n loc: Loc,\n ctx: BuildContext,\n) => LayoutNode;\n\n// ─── Location: binding expression + structural path ──────────\n\n// Where a field sits: the binding expression Nova resolves at render (`$.from`,\n// `$item.eq`), and the structural path a widget matcher targets (`from`,\n// `fields.*`, `…eq`). They diverge inside a loop — the expression rebinds to\n// `$item`, losing the array key, but the path keeps it (`fields.*`), which is\n// exactly what tells the two list-item kinds apart.\ntype Loc = { expr: string; path: string };\n\nconst ROOT: Loc = { expr: '$', path: '' };\n\n// Extend to a child key: `$.a` + `b` → `$.a.b`; path `a` + `b` → `a.b`.\nconst child = (loc: Loc, key: string): Loc => ({\n expr: `${loc.expr}.${key}`,\n path: loc.path === '' ? key : `${loc.path}.${key}`,\n});\n\n// An array element: the loop rebinds the expression to `$item`; the path gains a\n// `*` segment (the index, resolved at render, is irrelevant to matching).\nconst itemLoc = (loc: Loc): Loc => ({ expr: ITEM_EXPR, path: loc.path === '' ? '*' : `${loc.path}.*` });\n\n// A recursive template is authored against `$item` and rooted afresh, so its\n// inner paths are scope-relative — a matcher's suffix (`endsWith('.eq')`) still\n// hits at any depth.\nconst TEMPLATE_ROOT: Loc = { expr: ITEM_EXPR, path: '' };\n\n// The error binding for a field, derived from its expression. Only absolute\n// (`$.`) expressions map to the error channel; loop-relative item paths\n// (`$item…`) carry an index resolved at render and are left for later.\nconst errorBinding = (expr: string): string | undefined =>\n expr.startsWith('$.') ? `$.${ERROR_NAMESPACE}.${expr.slice(2)}` : undefined;\n\n// ─── Node helpers ────────────────────────────────────────────\n\n// Attach `props` only when there is something to attach — keeps emitted layouts\n// free of empty `props: {}` noise.\nconst withProps = (node: ComponentNode, props: Record<string, unknown>): ComponentNode =>\n Object.keys(props).length > 0 ? { ...node, props } : node;\n\n// A leaf control bound to its expression. No explicit ref: the renderer derives\n// one from the resolved path, which is distinct per array element.\nconst control = (role: Role | string, expr: string, props: Record<string, unknown> = {}): ComponentNode =>\n withProps({ component: role, model: expr }, props);\n\n// Static JSON metadata a component reads (a variant's branches, a list's\n// containers, an \"add\" default) — not a binding. Nova resolves *every* prop as a\n// binding expression, so a value carrying `$`-prefixed data (a Prism op key, a\n// `$ref`) would be mangled, and a `$eq`/`$if`/`$exists` key would be evaluated as\n// a directive. Encoding it as a JSON string passes it through the resolver\n// untouched; the component decodes it (`decodeLiteral` in the kit).\nconst literal = (data: unknown): string | undefined => (data === undefined ? undefined : JSON.stringify(data));\n\n// An object property: a field wrapper (label / required / error chrome) around\n// the property's own layout. `loc` already points at the property.\nconst wrapField = (loc: Loc, prop: ObjectField, ctx: BuildContext): ComponentNode => {\n const error = errorBinding(loc.expr);\n return {\n component: Roles.field,\n props: {\n label: prop.field.title ?? prop.key,\n required: prop.required,\n ...(error !== undefined ? { error } : {}),\n ...(prop.field.description !== undefined ? { description: prop.field.description } : {}),\n },\n children: buildLayout(prop.field, loc, ctx),\n };\n};\n\n// A field's optional `title`, as props — shared by the title chrome of groups,\n// arrays, and the variant chooser.\nconst titleProps = (field: { title?: string }): Record<string, unknown> =>\n field.title !== undefined ? { title: field.title } : {};\n\nconst withTitle = (node: ComponentNode, field: { title?: string }): ComponentNode =>\n withProps(node, titleProps(field));\n\n// ─── Builds: IR → layout ─────────────────────────────────────\n\nconst stringBuild: Build<'string'> = (field, loc) =>\n control(Roles.text, loc.expr, field.format !== undefined ? { format: field.format } : {});\n\nconst numberBuild: Build<'number'> = (field, loc) =>\n control(Roles.number, loc.expr, field.integer ? { integer: true } : {});\n\nconst booleanBuild: Build<'boolean'> = (_field, loc) => control(Roles.checkbox, loc.expr);\n\nconst enumBuild: Build<'enum'> = (field, loc) => control(Roles.select, loc.expr, { options: field.options });\n\nconst unknownBuild: Build<'unknown'> = (_field, loc) => control(Roles.raw, loc.expr);\n\n// The group of wrapped fields an object renders as — shared by the inline\n// occurrence and the recursive template (same shape, different base loc).\nconst buildGroup = (field: Extract<Field, { kind: 'object' }>, loc: Loc, ctx: BuildContext): ComponentNode =>\n withTitle(\n {\n component: Roles.group,\n children: field.fields.map((prop) => wrapField(child(loc, prop.key), prop, ctx)),\n },\n field,\n );\n\nconst objectBuild: Build<'object'> = (field, loc, ctx) => {\n if (field.recursive !== true) return buildGroup(field, loc, ctx);\n // A recursive object: emit its group once as a named template authored\n // against the template root (so it binds correctly at any depth), keep it in\n // scope so the `self` inside refs it and an \"add\" knows the default node, then\n // render the object inline at its real loc. Both builds bottom out at `self`.\n const name = ctx.name();\n ctx.templates.push({ name, defaultChild: buildDocument(field, ctx.options), containers: [] });\n ctx.register(name, buildGroup(field, TEMPLATE_ROOT, ctx));\n const inline = buildGroup(field, loc, ctx);\n ctx.templates.pop();\n return inline;\n};\n\n// A tuple: one wrapped field per slot, bound to its numeric index (`$.x.0`).\n// Fixed-length, so no add / remove — the difference from an array.\nconst tupleBuild: Build<'tuple'> = (field, loc, ctx) =>\n withTitle(\n {\n component: Roles.group,\n children: field.items.map((item, index) =>\n wrapField(child(loc, String(index)), { key: String(index + 1), required: true, field: item }, ctx),\n ),\n },\n field,\n );\n\nconst selfBuild: Build<'self'> = (_field, loc, ctx) => {\n const template = ctx.templates[ctx.templates.length - 1];\n // Reached as an array item (the loop rebinds `$item` to the element), a\n // `self` becomes a reference to the enclosing template — Nova re-resolves it\n // per render against the live data, so depth follows the document. A `self`\n // anywhere else is a direct self-reference (a linked list); it has no loop to\n // rebind its scope, so it shows raw until that case lands.\n if (template !== undefined && loc.expr === ITEM_EXPR) return { ref: template.name };\n return control(Roles.raw, loc.expr);\n};\n\n// The default element an \"add\" appends: for a recursive list, the enclosing\n// template's default node; otherwise the item field's own default.\nconst defaultItem = (field: Extract<Field, { kind: 'array' }>, ctx: BuildContext): unknown =>\n field.item.kind === 'self'\n ? ctx.templates[ctx.templates.length - 1]?.defaultChild\n : buildDocument(field.item, ctx.options);\n\n// The key of a field's child-list, if it has one: an object property that is an\n// array of `self` (the same recursive type). This is the whole definition of a\n// \"container\" — structural, with no knowledge of the domain.\nconst childrenKey = (field: Field): string | undefined => {\n if (field.kind !== 'object') return undefined;\n return field.fields.find((f) => f.field.kind === 'array' && f.field.item.kind === 'self')?.key;\n};\n\n// A union's container variants: the ones whose branch holds a child-list.\nconst containersOf = (variants: Variant[]): Container[] =>\n variants.flatMap((variant) => {\n const key = childrenKey(variant.field);\n return key === undefined ? [] : [{ label: variant.label, pattern: variant.pattern, defaults: variantDefaults(variant), key }];\n });\n\n// A list editor: every element rendered (the recursive item is a `self` ref;\n// any other is its own editor), each in a row with an actions menu (✕ / ↑ / ↓,\n// and wrap / unwrap when the items are a recursive union with container\n// variants), plus an \"add\". The menu binds the loop's `$items` (the whole list)\n// and acts on its own `$index`; the add binds the list itself and appends a\n// default. Everything is a `ui:model` write — path resolution handles the\n// nesting, so a list edits at any depth with no static target and no triggers.\nconst arrayBuild: Build<'array'> = (field, loc, ctx) => {\n // Containers come from the recursive union the items belong to (when the item\n // is `self`); a plain list has none, so its menu is just move / remove.\n const containers = field.item.kind === 'self' ? ctx.templates[ctx.templates.length - 1]?.containers ?? [] : [];\n const itemRow: LayoutNode = {\n component: Roles.arrayItem,\n children: [\n { component: Roles.box, children: buildLayout(field.item, itemLoc(loc), ctx) }, // the editor cell — grows\n {\n component: Roles.rowMenu,\n model: LIST_EXPR,\n props: { index: INDEX, ...(containers.length > 0 ? { containers: literal(containers) } : {}) },\n },\n ],\n };\n return withTitle(\n {\n component: Roles.array,\n children: [\n { for: loc.expr, as: ITEM, do: itemRow },\n { component: Roles.append, model: loc.expr, props: { label: 'Add', child: literal(defaultItem(field, ctx)) } },\n ],\n },\n field,\n );\n};\n\n// A union is the variant widget bound to the value: it holds each branch's\n// pattern + label + default, and renders the branch editors as its children.\n// The widget reads the value, matches it to a branch (in JS), and shows that\n// child; on change it writes the chosen branch's default. No discrimination is\n// compiled into the layout — Nova never learns what a union is.\nconst buildVariant = (field: Extract<Field, { kind: 'union' }>, loc: Loc, ctx: BuildContext): ComponentNode =>\n withProps(\n {\n component: Roles.variant,\n model: loc.expr,\n // Each branch editor in its own `branch` wrapper, indexed; the widget shows\n // only the one whose index it matched. (Nova hands a component its children\n // as one tree, so the branches need to be individually addressable.) A\n // branch edits the same value, so it shares the union's loc.\n children: field.variants.map((variant: Variant, index) => ({\n component: Roles.branch,\n props: { index },\n children: buildLayout(variant.field, loc, ctx),\n })),\n },\n {\n // `childrenKey` lets the chooser carry children when switching between two\n // container variants (and warn before dropping them otherwise). Encoded as\n // a literal: the patterns and defaults carry `$`-bearing data Nova must not\n // resolve.\n branches: literal(\n field.variants.map((variant: Variant) => ({\n label: variant.label,\n pattern: variant.pattern,\n defaults: variantDefaults(variant),\n ...(childrenKey(variant.field) !== undefined ? { childrenKey: childrenKey(variant.field) } : {}),\n })),\n ),\n ...titleProps(field),\n },\n );\n\nconst variantBuild: Build<'union'> = (field, loc, ctx) => {\n if (field.recursive !== true) return buildVariant(field, loc, ctx);\n // A recursive union (a tree of typed nodes): emit the chooser once as a named\n // template authored against the template root, keep it in scope so the `self`\n // inside a branch's children refs it, then render the node inline. Same\n // machinery as a recursive object — the template is just a variant, not a group.\n const name = ctx.name();\n const first = field.variants[0];\n ctx.templates.push({ name, defaultChild: first !== undefined ? variantDefaults(first) : {}, containers: containersOf(field.variants) });\n ctx.register(name, buildVariant(field, TEMPLATE_ROOT, ctx));\n const inline = buildVariant(field, loc, ctx);\n ctx.templates.pop();\n return inline;\n};\n\n// Dispatch a field to its build. The switch narrows `field` per case, so each\n// build receives its own field type with no assertion; the union is closed, so\n// it is also exhaustive (a new kind won't compile until it is handled here).\nconst buildLayout = (field: Field, loc: Loc, ctx: BuildContext): LayoutNode => {\n // A plugin widget claims this field by where it sits (its structural path) —\n // render with the registered component instead of the type default. It binds\n // the value and a model like any control, so it can be a leaf editor or\n // replace a whole subtree.\n const role = ctx.widgetRole(field, loc.path);\n if (role !== undefined) return control(role, loc.expr);\n switch (field.kind) {\n case 'string':\n return stringBuild(field, loc, ctx);\n case 'number':\n return numberBuild(field, loc, ctx);\n case 'boolean':\n return booleanBuild(field, loc, ctx);\n case 'enum':\n return enumBuild(field, loc, ctx);\n case 'object':\n return objectBuild(field, loc, ctx);\n case 'array':\n return arrayBuild(field, loc, ctx);\n case 'tuple':\n return tupleBuild(field, loc, ctx);\n case 'union':\n return variantBuild(field, loc, ctx);\n case 'self':\n return selfBuild(field, loc, ctx);\n case 'unknown':\n return unknownBuild(field, loc, ctx);\n }\n};\n\n// ─── Public entry ────────────────────────────────────────────\n\nexport const toNova = (ir: Field, options: CompileOptions = {}): NovaEditor => {\n const layouts: Record<string, LayoutNode> = {};\n let counter = 0;\n const matchers = options.widgets ?? [];\n const ctx: BuildContext = {\n register: (name, node) => {\n layouts[name] = node;\n },\n templates: [],\n name: () => `loom:tree:${counter++}`,\n // Match on where the field sits (its structural path) plus its facts.\n widgetRole: (field, path) =>\n matchers.find((matcher) =>\n matcher.match({ kind: field.kind, path, title: field.title, description: field.description }),\n )?.role,\n options,\n };\n\n // A non-object root (a union, scalar, or array) is a single control that can't\n // bind the bare document root, so `rootKey` binds it one level in (`$.<key>`)\n // and the document wraps the value under that key. An object root binds `$` and\n // its leaves bind `$.<field>` as usual.\n const rootLoc: Loc = options.rootKey !== undefined ? { expr: `$.${options.rootKey}`, path: '' } : ROOT;\n const layout = buildLayout(ir, rootLoc, ctx);\n const value = options.value ?? buildDocument(ir, options);\n const document = options.rootKey !== undefined ? { [options.rootKey]: value } : value;\n // The action's data must be a record. An object root builds one directly; a\n // wrapped root is a record by construction. A bare scalar root with no key has\n // no record document.\n if (!isRecord(document)) {\n throw new Error('loom.toNova: the root document must be an object (or use rootKey).');\n }\n const action: ActionDefinition = {\n id: options.id ?? 'loom-form',\n data: document,\n layout,\n };\n return { action, layouts };\n};\n","import type { Shell } from '@niscorp/nova';\nimport type { ZodType } from 'zod';\nimport { ERROR_NAMESPACE } from './compile/to-nova.js';\n\n// Validate-on-edit. The Zod schema is the truth: on each change, the working\n// document (everything except the reserved error channel) is parsed, and a\n// nested error tree — mirroring the document, keyed by Zod's issue paths —\n// is written back under that channel for the fields to bind to. The document\n// itself stays clean; `onDocument` reports it without the error channel.\n\ntype Doc = Record<string, unknown>;\n\ntype Issue = { readonly path: ReadonlyArray<PropertyKey>; readonly message: string };\n\n// Place a message at a nested path, mirroring the document shape. First issue\n// per path wins (the most specific message Zod emits first).\nconst setPath = (root: Doc, path: ReadonlyArray<PropertyKey>, message: string): void => {\n let node = root;\n for (let i = 0; i < path.length - 1; i += 1) {\n const key = String(path[i]);\n const next = node[key];\n node = typeof next === 'object' && next !== null ? (next as Doc) : (node[key] = {});\n }\n const leaf = String(path[path.length - 1]);\n if (!(leaf in node)) node[leaf] = message;\n};\n\nconst errorTree = (issues: ReadonlyArray<Issue>): Doc => {\n const tree: Doc = {};\n for (const issue of issues) {\n if (issue.path.length > 0) setPath(tree, issue.path, issue.message);\n }\n return tree;\n};\n\nconst stripErrors = (data: Doc): Doc => {\n const { [ERROR_NAMESPACE]: _omit, ...document } = data;\n return document;\n};\n\nexport const attachValidation = (\n shell: Shell,\n instanceId: string,\n schema: ZodType,\n onDocument?: (document: Doc) => void,\n): (() => void) => {\n const runtime = shell.getRuntime(instanceId);\n if (runtime === undefined) return () => {};\n\n let lastDocument = '';\n const handle = (data: Doc): void => {\n const document = stripErrors(data);\n const fingerprint = JSON.stringify(document);\n if (fingerprint === lastDocument) return; // our own error write — not a real edit\n lastDocument = fingerprint;\n\n const result = schema.safeParse(document);\n const errors = result.success ? {} : errorTree(result.error.issues);\n runtime.setData({ ...document, [ERROR_NAMESPACE]: errors });\n onDocument?.(document);\n };\n\n return shell.onDataChange((change) => {\n if (change.instanceId === instanceId) handle(change.data);\n });\n};\n","import type { LayoutNode } from '@niscorp/nova';\n\n// The editor's default canvasLayout — a plain Nova layout. The forms are the main\n// column (each in a titled, bordered panel); every other canvas (preview, JSON\n// views) stacks in a side column (those already render their own panel). No Nova\n// primitive can size a flex child, so the columns use Loom's `loom:column` (a Loom\n// component, registered with the kit). A plugin can replace the whole arrangement\n// with shell.setCanvasLayout.\n\nexport const LOOM_COLUMN = 'loom:column';\n\nconst slot = (canvasId: string): LayoutNode => ({ component: 'CanvasSlot', props: { canvasId } });\n\n// `form:data` -> `Data`. A form canvas's title is its document name.\nconst titleOf = (formId: string): string => {\n const name = formId.replace(/^form:/, '');\n return name.charAt(0).toUpperCase() + name.slice(1);\n};\n\n// A form sits in a bordered panel headed by its document name.\nconst formPanel = (formId: string): LayoutNode => ({\n component: 'Box',\n props: { border: true, radius: 8, padding: 16 },\n children: [{ component: 'loom:group', props: { title: titleOf(formId) }, children: [slot(formId)] }],\n});\n\nconst column = (grow: number, min: number, children: LayoutNode[]): LayoutNode => ({\n component: LOOM_COLUMN,\n props: { grow, min },\n children: [{ component: 'Stack', props: { direction: 'column', gap: 16 }, children }],\n});\n\nexport const defaultCanvasLayout = (formIds: string[], viewIds: string[]): LayoutNode => ({\n component: 'Stack',\n props: { direction: 'row', gap: 16, align: 'start' },\n children: [\n ...(formIds.length > 0 ? [column(2, 420, formIds.map(formPanel))] : []),\n ...(viewIds.length > 0 ? [column(1, 340, viewIds.map(slot))] : []),\n ],\n});\n","import type { ActionDefinition } from '@niscorp/nova';\nimport type { LoomEditor } from './types.js';\n\n// Mount a view canvas: register `action`, add a canvas that renders it, and keep\n// its data in sync with the editor's live state — `read(editor)` is pushed onto\n// the canvas on every `change`. The canvas id is the action id. Used by the\n// default plugins (jsonviewer, validation) and any domain preview; the contributor\n// owns the canvas, so a later plugin can `shell.removeCanvas(action.id)` to drop it.\nexport const mountView = (\n editor: LoomEditor,\n action: ActionDefinition,\n read: (editor: LoomEditor) => Record<string, unknown>,\n): void => {\n const { shell } = editor;\n shell.registerAction(action);\n shell.addCanvas({ id: action.id, initial: action.id });\n const instance = shell.getCanvasState(action.id).active?.id;\n if (instance === undefined) return;\n const sync = (): void => {\n shell.getRuntime(instance)?.setData(read(editor));\n };\n editor.on('change', sync);\n sync();\n};\n","import { z, type ZodType } from 'zod';\nimport { createLayoutStore, createShell, type ActionDefinition, type Shell } from '@niscorp/nova';\nimport { parse, buildDocument, isRecord } from '@compile/parse';\nimport { toNova, ERROR_NAMESPACE } from '@compile/to-nova';\nimport { attachValidation } from '../validate.js';\nimport { defaultCanvasLayout } from './default.layout.js';\nimport type { LoomArtifact, LoomEditor, LoomEditorConfig, LoomEvent, LoomPlugin } from './types.js';\n\nexport type { LoomArtifact, LoomEditor, LoomEditorConfig, LoomEvent, LoomPlugin, Document, DocumentLayout, WidgetBinding } from './types.js';\nexport { mountView } from './view.js';\n\n// The Loom Editor controller — framework-free. It owns one Nova shell, built\n// empty, and a plugin loader. Everything visible is plugin-contributed: domain\n// plugins (nova, vex) declare the documents that `open` compiles into form\n// canvases; default plugins (jsonviewer, validation) and previews mount their own\n// view canvases against the live shell. The controller only compiles forms and\n// publishes the live `documents` / `validations`; the React (or Vue) layer\n// supplies the component registry and renders the shell.\n\n// The canvas a document's form lives on.\nconst formCanvas = (document: string): string => `form:${document}`;\n\n// The key a non-object document (a union, scalar, or array) is wrapped under so\n// its single control has a bindable path. Internal: the editor wraps the value\n// before compiling and unwraps it before publishing, so it never reaches a\n// plugin or the reported document. A document key collides with nothing — it\n// holds the whole value, no sibling.\nconst ROOT_KEY = '$root';\n\n// A document whose schema's root is not an object needs wrapping; an object root\n// binds the document root directly.\nconst needsWrap = (document: ZodType): boolean => parse(document).kind !== 'object';\n\nconst stripErrors = (data: Record<string, unknown>): Record<string, unknown> => {\n const { [ERROR_NAMESPACE]: _omit, ...document } = data;\n return document;\n};\n\nexport const createLoomEditor = (config: LoomEditorConfig): LoomEditor => {\n const plugins = new Map<string, LoomPlugin>();\n const listeners: Record<LoomEvent, Set<() => void>> = { change: new Set(), open: new Set() };\n const emit = (event: LoomEvent): void => listeners[event].forEach((handler) => handler());\n\n // The shell exists from creation (empty), so plugins can mount onto it. With no\n // canvasLayout, Nova renders the canvases in creation order; a plugin can call\n // shell.setCanvasLayout to arrange them. Form recursion templates are written\n // into this shared store as documents compile.\n const store = createLayoutStore();\n const shell: Shell = createShell({\n canvases: [],\n registry: config.registry,\n actions: {},\n layoutStore: store,\n });\n\n let active: LoomPlugin | undefined;\n let formInstances: Record<string, string> = {};\n // Documents whose root was wrapped under ROOT_KEY (non-object roots): their\n // value is unwrapped before it is published or validated against the schema.\n let wrappedDocs = new Set<string>();\n let formCanvasIds: string[] = [];\n let documents: Record<string, unknown> = {};\n let validations: Record<string, unknown> = {};\n let detach: Array<() => void> = [];\n\n // Read every form's live value into `documents` / `validations`. View plugins\n // self-sync off the `change` event, so nothing is pushed to them here.\n const refresh = (): void => {\n const nextDocs: Record<string, unknown> = {};\n const nextProblems: Record<string, unknown> = {};\n for (const [name, instanceId] of Object.entries(formInstances)) {\n const data = shell.getRuntime(instanceId)?.getData() ?? {};\n const document = stripErrors(data);\n const problems = (data[ERROR_NAMESPACE] ?? {}) as Record<string, unknown>;\n // A wrapped document is published as its bare value (and its errors as that\n // value's subtree), so ROOT_KEY never surfaces to a view or a consumer.\n if (wrappedDocs.has(name)) {\n nextDocs[name] = document[ROOT_KEY];\n nextProblems[name] = problems[ROOT_KEY] ?? {};\n } else {\n nextDocs[name] = document;\n nextProblems[name] = problems;\n }\n }\n documents = nextDocs;\n validations = nextProblems;\n };\n\n // Drop the previous artifact's form canvases (the plugin canvases stay).\n const clearForms = (): void => {\n detach.forEach((off) => off());\n detach = [];\n for (const canvasId of formCanvasIds) shell.removeCanvas(canvasId);\n formCanvasIds = [];\n formInstances = {};\n wrappedDocs = new Set();\n };\n\n const open = (artifact: LoomArtifact): void => {\n const plugin = plugins.get(artifact.type);\n if (plugin === undefined) throw new Error(`loom editor: no plugin '${artifact.type}'`);\n clearForms();\n active = plugin;\n\n // Build each document's form action and add its canvas. A schema document is\n // compiled (toNova); a layout document (freeform, no schema) takes its layout\n // from the plugin. Either way the action's `data` is the document's value —\n // seeded from the artifact, tracked by `refresh`.\n for (const [name, document] of Object.entries(plugin.documents)) {\n const canvasId = formCanvas(name);\n let action: ActionDefinition;\n if (typeof document === 'function') {\n const value = artifact.documents?.[name];\n action = { id: canvasId, data: isRecord(value) ? value : {}, layout: document(value) };\n } else {\n const ir = parse(document);\n // A non-object root binds one level in, under ROOT_KEY (see `needsWrap`).\n const wrap = needsWrap(document);\n if (wrap) wrappedDocs.add(name);\n const value = artifact.documents?.[name] ?? buildDocument(ir, {});\n const built = toNova(ir, {\n id: canvasId,\n ...(wrap ? { rootKey: ROOT_KEY } : {}),\n ...(isRecord(value) ? { value } : {}),\n widgets: plugin.widgets ?? [],\n });\n for (const [id, node] of Object.entries(built.layouts)) store.set(id, node);\n action = built.action;\n }\n shell.registerAction(action);\n shell.addCanvas({ id: canvasId, initial: action.id });\n formCanvasIds.push(canvasId);\n const instanceId = shell.getCanvasState(canvasId).active?.id;\n if (instanceId !== undefined) formInstances[name] = instanceId;\n }\n\n // Validate only schema documents — a freeform layout document has no schema.\n for (const [name, instanceId] of Object.entries(formInstances)) {\n const document = plugin.documents[name];\n if (typeof document !== 'function' && document !== undefined) {\n // A wrapped document is validated against the same wrapper, so the data\n // and schema agree and the error tree keys under ROOT_KEY (matching the\n // field bindings).\n const schema = wrappedDocs.has(name) ? z.object({ [ROOT_KEY]: document }) : document;\n detach.push(attachValidation(shell, instanceId, schema));\n }\n }\n detach.push(\n shell.onDataChange((change) => {\n if (!Object.values(formInstances).includes(change.instanceId)) return;\n refresh();\n emit('change');\n }),\n );\n\n // Arrange the canvases: the forms as the main pane, each contributed view in\n // its own sized pane. View canvases come after the forms; the default JSON\n // panes (loom:*) sort last, so a domain preview sits next to the forms.\n const viewIds = Object.keys(shell.getState().canvases)\n .filter((id) => !formCanvasIds.includes(id))\n .sort((a, b) => Number(a.startsWith('loom:')) - Number(b.startsWith('loom:')));\n shell.setCanvasLayout(defaultCanvasLayout(formCanvasIds, viewIds));\n\n refresh();\n emit('open');\n // Prime the view plugins with the opened documents.\n emit('change');\n };\n\n const editor: LoomEditor = {\n get shell() {\n return shell;\n },\n get plugin() {\n return active;\n },\n get documents() {\n return documents;\n },\n get validations() {\n return validations;\n },\n loadPlugin: (plugin) => {\n plugins.set(plugin.name, plugin);\n plugin.mount?.(editor);\n },\n open,\n on: (event, handler) => {\n listeners[event].add(handler);\n return () => listeners[event].delete(handler);\n },\n dispose: () => {\n detach.forEach((off) => off());\n detach = [];\n shell.dispose();\n },\n };\n\n return editor;\n};\n"]}
1
+ {"version":3,"sources":["../src/compile/parse.ts","../src/compile/roles.ts","../src/compile/to-nova.ts","../src/validate.ts","../src/editor/default.layout.ts","../src/editor/view.ts","../src/editor/editor.ts"],"names":["literal","child","stripErrors","createLayoutStore","createShell","z"],"mappings":";;;;;;AA6CA,IAAM,KAAA,GAAQ,CAAC,MAAA,KAA4B,MAAA,CAAO,GAAA;AAalD,IAAM,cAAA,GAAiB,SAAA;AAEvB,IAAM,YAAA,GAAe,CAAC,MAAA,KAAwC;AAC5D,EAAA,MAAM,GAAA,GAAM,MAAM,MAAM,CAAA;AACxB,EAAA,IAAI,GAAA,CAAI,MAAA,KAAW,MAAA,EAAW,OAAO,GAAA,CAAI,MAAA;AACzC,EAAA,KAAA,MAAW,KAAA,IAAS,GAAA,CAAI,MAAA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E,OAAO,OAAO,CAAA;AAAA,IAC9C,CAAA;AAAA,IACA,SAAS,MAAM;AACb,MAAA,MAAA,CAAO,OAAA,CAAQ,CAAC,GAAA,KAAQ,GAAA,EAAK,CAAA;AAC7B,MAAA,MAAA,GAAS,EAAC;AACV,MAAA,KAAA,CAAM,OAAA,EAAQ;AAAA,IAChB;AAAA,GACF;AAEA,EAAA,OAAO,MAAA;AACT","file":"index.cjs","sourcesContent":["import type { ZodType } from 'zod';\nimport type {\n CompileOptions,\n EmptyValue,\n EnumOption,\n Field,\n FieldKind,\n FieldMeta,\n ObjectField,\n Pattern,\n Variant,\n} from './types.js';\n\n// parse — turn a Zod schema into Loom's field model (IR). The only Zod-aware\n// code in the package, and pure data in / pure data out: no Nova. `parseByType`\n// is keyed by Zod's own `def.type` tag, so the type vocabulary lives as table\n// keys, not scattered checks.\n//\n// A recursive schema (`z.lazy`, or an object whose getter returns itself) would\n// expand forever. The walk carries the set of schemas it is currently inside;\n// re-entering one is a back-edge, emitted as a `self` marker and recorded so\n// the object it points back to can be tagged `recursive`. Expansion stops at\n// the cycle — the document, not the schema, decides how deep an editor goes.\n\n// The slice of a Zod schema's internal definition that parsing reads.\ntype ZodDef = {\n type: string;\n innerType?: ZodType;\n element?: ZodType;\n shape?: Record<string, ZodType>;\n entries?: Record<string, unknown>;\n defaultValue?: unknown;\n format?: string;\n checks?: ReadonlyArray<{ def?: { format?: string } }>;\n discriminator?: string;\n options?: readonly ZodType[];\n items?: readonly ZodType[];\n values?: readonly unknown[];\n getter?: () => ZodType;\n};\n\n// Zod types every schema's `.def` as the base `$ZodTypeDef` (just the `type`\n// discriminant); the per-type fields we read live on the concrete defs. This\n// views `.def` through the structural slice above — the single place the\n// parser depends on Zod's internal shape.\nconst defOf = (schema: ZodType): ZodDef => schema.def as ZodDef;\n\n// While walking, the schemas currently on the stack (cycle detection) and the\n// schemas a `self` pointed back to (so the matching object is tagged recursive).\n// Keyed by def, not instance: `.describe()`/`.meta()` clone the wrapper but\n// share the def, so a described alias of a recursive schema must read as the\n// schema itself — or every back-edge re-expands the whole thing one more level.\ntype Walk = { stack: Set<ZodDef>; targets: Set<ZodDef> };\n\n// ─── Reading Zod ─────────────────────────────────────────────\n\n// `safeint` is Zod's format tag for an integer-constrained number — the one\n// Zod-vocabulary token this file matches on.\nconst INTEGER_FORMAT = 'safeint';\n\nconst stringFormat = (schema: ZodType): string | undefined => {\n const def = defOf(schema);\n if (def.format !== undefined) return def.format;\n for (const check of def.checks ?? []) {\n if (check.def?.format !== undefined) return check.def.format;\n }\n return undefined;\n};\n\nconst isInteger = (schema: ZodType): boolean => {\n const def = defOf(schema);\n if (def.format === INTEGER_FORMAT) return true;\n return (def.checks ?? []).some((check) => check.def?.format === INTEGER_FORMAT);\n};\n\nconst enumOptions = (schema: ZodType): EnumOption[] =>\n Object.values(defOf(schema).entries ?? {}).map((value) => ({ value, label: String(value) }));\n\nconst objectFields = (schema: ZodType, walk: Walk): ObjectField[] =>\n Object.entries(defOf(schema).shape ?? {}).map(([key, value]) => ({\n key,\n // A property is optional when the schema accepts `undefined` for it\n // (covers `.optional()` and `.default()`) — asked of Zod, not inferred.\n required: !value.safeParse(undefined).success,\n field: parseField(value, walk),\n }));\n\n// ─── Union discrimination ────────────────────────────────────\n// For each branch, the cheapest fact that tells it apart from its siblings: the\n// declared tag's value, else a key only it carries, else a JS type only it is.\n// One function covers tagged, structural, and mixed unions; a branch that none\n// of these distinguish makes the whole union fall back to the raw editor.\n\nconst branchKeys = (branch: ZodType): string[] => Object.keys(defOf(branch).shape ?? {});\n\n// The branch's JS type, when it's one the runtime matcher checks (Zod names\n// these the same as `typeof`/`Array.isArray` do); otherwise undefined.\nconst JSON_TYPES = new Set(['string', 'number', 'boolean', 'object', 'array', 'null']);\nconst jsonType = (branch: ZodType): string | undefined => {\n const type = defOf(branch).type;\n return JSON_TYPES.has(type) ? type : undefined;\n};\n\nconst distinguish = (branch: ZodType, siblings: readonly ZodType[], tag: string | undefined): Pattern | undefined => {\n if (tag !== undefined) {\n const literal = (defOf(branch).shape ?? {})[tag];\n return { kind: 'tag', key: tag, value: literal !== undefined ? defOf(literal).values?.[0] : undefined };\n }\n const elsewhere = new Set(siblings.flatMap(branchKeys));\n const key = branchKeys(branch).find((k) => !elsewhere.has(k));\n if (key !== undefined) return { kind: 'key', key };\n const type = jsonType(branch);\n if (type !== undefined && siblings.every((s) => jsonType(s) !== type)) return { kind: 'type', type };\n return undefined;\n};\n\nconst patternLabel = (pattern: Pattern): string =>\n pattern.kind === 'tag'\n ? String(pattern.value)\n : pattern.kind === 'key'\n ? pattern.key\n : pattern.kind === 'type'\n ? pattern.type\n : 'other';\n\n// A union may nest unions (`z.union([...primitives, ...ops])` where the\n// primitives are themselves a `z.union`). The branches of a nested union are\n// siblings of the outer ones for discrimination, so inline them. Each branch is\n// unwrapped first (a described/optional sub-union still flattens); a non-union\n// branch passes through untouched. Unwrapping resolves lazies, so `seen` guards\n// a union that nests back into itself: once a union core is being flattened,\n// re-encountering it keeps the branch as a leaf rather than recursing forever.\nconst flattenBranches = (branches: readonly ZodType[], seen: Set<ZodDef> = new Set()): ZodType[] =>\n branches.flatMap((branch) => {\n const { core } = unwrap(branch);\n const def = defOf(core);\n if (def.type !== 'union' || seen.has(def)) return [branch];\n return flattenBranches(def.options ?? [], new Set(seen).add(def));\n });\n\n// A branch's editor. A tagged union owns its discriminant in the chooser, so it\n// is dropped from the fields; every other branch is edited whole — including a\n// `string` or `array` branch, which is just its own field, not a group.\nconst branchField = (branch: ZodType, walk: Walk, tag: string | undefined): Field =>\n tag === undefined\n ? parseField(branch, walk)\n : { kind: 'object', fields: objectFields(branch, walk).filter((f) => f.key !== tag) };\n\nconst parseByType: Record<string, (schema: ZodType, walk: Walk) => Field> = {\n string: (schema) => {\n const format = stringFormat(schema);\n return format !== undefined ? { kind: 'string', format } : { kind: 'string' };\n },\n number: (schema) => (isInteger(schema) ? { kind: 'number', integer: true } : { kind: 'number' }),\n boolean: () => ({ kind: 'boolean' }),\n enum: (schema) => ({ kind: 'enum', options: enumOptions(schema) }),\n object: (schema, walk) => {\n // On the stack while its fields parse, so a self-reference re-entering it\n // is caught as a cycle. If one was, the object is a recursion anchor.\n const def = defOf(schema);\n walk.stack.add(def);\n const fields = objectFields(schema, walk);\n walk.stack.delete(def);\n return walk.targets.has(def) ? { kind: 'object', fields, recursive: true } : { kind: 'object', fields };\n },\n array: (schema, walk) => {\n const element = defOf(schema).element;\n return { kind: 'array', item: element !== undefined ? parseField(element, walk) : { kind: 'unknown' } };\n },\n tuple: (schema, walk) => ({ kind: 'tuple', items: (defOf(schema).items ?? []).map((item) => parseField(item, walk)) }),\n union: (schema, walk) => {\n // Flatten nested unions into sibling branches, then dedup by identity — a\n // self-referential union resolves the same cached member instances twice, so\n // the same schema can appear more than once.\n const branches = [...new Set(flattenBranches(defOf(schema).options ?? []))];\n const tag = defOf(schema).discriminator;\n // Patterns don't need the stack — compute them first.\n const patterns = branches.map((b) => distinguish(b, branches.filter((x) => x !== b), tag));\n // A branch nothing distinguishes is the catch-all: allow exactly one, as the\n // fallback the widget picks when no other pattern matches. Two such branches\n // are ambiguous (which catches a plain value?), so the union still falls back\n // to the raw editor whole.\n const open = patterns.reduce<number[]>((acc, p, i) => (p === undefined ? [...acc, i] : acc), []);\n if (branches.length === 0 || open.length > 1) return { kind: 'unknown' };\n if (open.length === 1) patterns[open[0]!] = { kind: 'fallback' };\n // Parse the branch fields with the union on the stack, so a child that\n // re-enters it (a `children: LayoutNode[]`) is caught as a cycle.\n const def = defOf(schema);\n walk.stack.add(def);\n const variants: Variant[] = branches.map((branch, i) => ({\n label: readMeta(branch).title ?? patternLabel(patterns[i]!),\n field: branchField(branch, walk, tag),\n pattern: patterns[i]!,\n }));\n walk.stack.delete(def);\n return walk.targets.has(def) ? { kind: 'union', variants, recursive: true } : { kind: 'union', variants };\n },\n};\n\nconst unknownField = (): Field => ({ kind: 'unknown' });\n\n// Modifier wrappers that don't change the editing shape — peeled to reach the\n// core type, capturing any default along the way. `lazy` is peeled too: it is\n// the deferral that makes a schema recursive, resolved here to the schema it\n// guards (whose identity the cycle check then recognizes).\nconst WRAPPERS = new Set(['optional', 'nullable', 'default', 'readonly']);\n\n// A `lazy` is a deferred reference to one schema, but its getter may *build* a\n// fresh instance on every call (`z.lazy(() => z.union([...]))`) rather than\n// close over a stable const. Cycle detection needs the same resolution each\n// time, so resolve each lazy once and reuse it. Keyed by the lazy's def — the\n// def owns the getter, and a `.describe()` alias of the lazy shares it, so the\n// alias resolves to the same instance instead of a second copy of the tree.\nconst lazyResolved = new WeakMap<ZodDef, ZodType>();\nconst resolveLazy = (lazy: ZodType): ZodType | undefined => {\n const def = defOf(lazy);\n const cached = lazyResolved.get(def);\n if (cached !== undefined) return cached;\n const resolved = def.getter?.();\n if (resolved !== undefined) lazyResolved.set(def, resolved);\n return resolved;\n};\n\nconst unwrap = (schema: ZodType): { core: ZodType; default?: unknown } => {\n let core = schema;\n let fallback: unknown;\n let def = defOf(core);\n while (WRAPPERS.has(def.type) || def.type === 'lazy') {\n // `lazy` reaches its schema through a memoized getter; the other wrappers\n // through `innerType`. Either may be absent on a malformed def — stop if so.\n const inner = def.type === 'lazy' ? resolveLazy(core) : def.innerType;\n if (inner === undefined) break;\n if ('defaultValue' in def) fallback = def.defaultValue;\n core = inner;\n def = defOf(core);\n }\n return fallback !== undefined ? { core, default: fallback } : { core };\n};\n\nconst readMeta = (schema: ZodType): FieldMeta => {\n const meta: FieldMeta = {};\n const title = (schema.meta() as { title?: unknown } | undefined)?.title;\n if (typeof title === 'string') meta.title = title;\n if (schema.description !== undefined) meta.description = schema.description;\n return meta;\n};\n\nconst parseField = (schema: ZodType, walk: Walk): Field => {\n const { core, default: fallback } = unwrap(schema);\n // A schema already on the stack is a recursion back-edge: stop and record\n // it, so the object it cycles to is tagged when its parse unwinds.\n if (walk.stack.has(defOf(core))) {\n walk.targets.add(defOf(core));\n return { kind: 'self' };\n }\n const body = (parseByType[defOf(core).type] ?? unknownField)(core, walk);\n // Read metadata from both the core and the original, so a `.describe()` on\n // either the type or a wrapper is picked up; the outer one wins.\n const meta = { ...readMeta(core), ...readMeta(schema) };\n return { ...body, ...meta, ...(fallback !== undefined ? { default: fallback } : {}) };\n};\n\nexport const parse = (schema: ZodType): Field =>\n parseField(schema, { stack: new Set(), targets: new Set() });\n\n// ─── buildDocument: IR → default document ────────────────────\n// The default value of a field, by kind. Pure JSON — a model concern, not a\n// rendering one. Recursion bottoms out naturally: a recursive object's array\n// of itself defaults to empty, so no `self` is ever expanded into a default.\n\n// Each entry takes the whole field; the scalar kinds ignore it, and the two that\n// read their own shape (`object`, `union`) narrow with a guard rather than a\n// cast — the guard never fires (dispatch keys on `kind`), but it keeps the\n// types honest without a type assertion.\nconst EMPTY: Record<FieldKind, EmptyValue> = {\n string: () => '',\n number: () => 0,\n boolean: () => false,\n // No neutral in-domain value: \"no selection\" is absence (undefined), which\n // an optional enum accepts and a required one flags — unlike null, which a\n // Zod enum rejects outright. Defaults drop undefined, so no stray key.\n enum: () => undefined,\n array: () => [],\n // Each slot built from its own field; a fixed-length list, so no growth.\n tuple: (field, options) => (field.kind === 'tuple' ? field.items.map((item) => buildDocument(item, options)) : []),\n // A recursion point has no value of its own; the array holding it defaults to [].\n self: () => undefined,\n unknown: () => null,\n object: (field, options) => {\n if (field.kind !== 'object') return {};\n const includeOptional = options.includeOptional ?? true;\n const document: Record<string, unknown> = {};\n for (const child of field.fields) {\n if (!child.required && !includeOptional) continue;\n const value = buildDocument(child.field, options);\n if (value !== undefined) document[child.key] = value; // no stray undefined keys\n }\n return document;\n },\n // An empty union defaults to its first variant (tag + branch defaults).\n union: (field) => {\n if (field.kind !== 'union') return {};\n const first = field.variants[0];\n return first === undefined ? {} : variantDefaults(first);\n },\n};\n\nexport const buildDocument = (field: Field, options: CompileOptions): unknown => {\n if (field.default !== undefined) return field.default;\n return (options.empty?.[field.kind] ?? EMPTY[field.kind])(field, options);\n};\n\n// A plain object — not an array or null. Guards the spread of a built default\n// document, whose static type is `unknown` (so we check rather than assert).\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n// A branch's default value: whatever its field builds — an object, but also a\n// bare `''` or `[]` for a scalar/array branch. A tagged union additionally sets\n// its discriminant alongside. Used as an empty union's value and to reshape the\n// document when the chooser switches branches.\nexport const variantDefaults = (variant: Variant): unknown => {\n const defaults = buildDocument(variant.field, {});\n if (variant.pattern.kind !== 'tag') return defaults;\n return { [variant.pattern.key]: variant.pattern.value, ...(isRecord(defaults) ? defaults : {}) };\n};\n","// The widget vocabulary the compiler emits as Nova component names. Each is\n// an abstract role; a kit registers a concrete component under the name, so\n// swapping the kit swaps the pixels without touching the compiler. Small and\n// stable on purpose — sub-variants ride as props, not new roles.\n//\n// Structural shapes (objects, arrays, unions) are compiled compositions of\n// these roles, not roles of their own.\n\nexport const Roles = {\n // Layout primitives — arrange other nodes.\n box: 'loom:box', // a flexible cell that grows to fill its row (an array item's editor)\n group: 'loom:group',\n array: 'loom:array',\n arrayItem: 'loom:array-item',\n variant: 'loom:variant',\n // One branch of a variant — shows itself only when it's the active branch\n // (the widget matches the value to a branch in JS and tells it through context).\n branch: 'loom:branch',\n\n // Field wrapper — label, description, error, and required marker around one control.\n field: 'loom:field',\n\n // Controls — edit a value; emit `ui:model`.\n text: 'loom:text',\n number: 'loom:number',\n checkbox: 'loom:checkbox',\n select: 'loom:select',\n raw: 'loom:raw',\n\n // List actions — model writes to the bound array (no triggers). `append` adds\n // a default element to the list it binds. `rowMenu` is the per-row actions menu\n // (move / remove, and wrap / unwrap when the list's items are a recursive union\n // with container variants); it reads `$items` and `$index` and writes the new\n // array. Both work at any depth, since the bound path resolves per render.\n append: 'loom:append',\n rowMenu: 'loom:row-menu',\n} as const;\n\nexport type Role = (typeof Roles)[keyof typeof Roles];\n","import type { ActionDefinition, ComponentNode, LayoutNode } from '@niscorp/nova';\nimport { buildDocument, isRecord, variantDefaults } from './parse.js';\nimport { Roles, type Role } from './roles.js';\nimport type { CompileOptions, Field, ObjectField, Pattern, Variant } from './types.js';\n\n// toNova — turn Loom's field model into a Nova editor: a layout + the document\n// it edits (+ any named templates a recursive schema needs). This is the\n// rendering half, and the only half that speaks Nova. The model (`parse`) knows\n// nothing about it. Every edit — including add / remove / reorder — is a model\n// write through Nova's `ui:model` pipeline; no action triggers are emitted.\n//\n// Field (IR) ──toNova──▶ { action, layouts }\n//\n// Fields bind to the document by a *binding expression* threaded through the\n// build: `$.name` at the root, `$item` inside an array loop. A recursive object\n// is emitted once as a named layout authored against `$item`; its `self`\n// reference points back to that layout, and Nova resolves it per render against\n// the live data — so the editor goes exactly as deep as the document does.\n\n// The reserved data namespace the editor writes validation errors into and each\n// field binds its error slot to. Excluded from the reported document.\nexport const ERROR_NAMESPACE = '_errors';\n\n// The loop variable an array binds each element under, plus the two other loop\n// bindings Nova exposes per iteration: the element's index, and `$items` — the\n// whole array — which the row controls write back to (remove / reorder).\nconst ITEM = 'item';\nconst INDEX = '$index';\nconst ITEM_EXPR = `$${ITEM}`;\nconst LIST_EXPR = '$items';\n\n// What Loom hands Nova: the action plus the named layouts it references. The\n// layouts are the recursive templates; for a non-recursive schema it's empty.\nexport type NovaEditor = { action: ActionDefinition; layouts: Record<string, LayoutNode> };\n\n// A container variant of a recursive union: one whose value can hold a list of\n// the same recursive type. `key` is the field that holds that list. Used to\n// wrap an element into one, and to recognize / unwrap an element that is one.\n// Purely structural — nothing here knows what the schema represents.\ntype Container = { label: string; pattern: Pattern; defaults: unknown; key: string };\n\n// A recursive template in scope while its object is built: the layout name a\n// `self` points back to, the default node an \"add\" appends, and (for a union)\n// the container variants its items can be wrapped into.\ntype Template = { name: string; defaultChild: unknown; containers: Container[] };\n\ntype BuildContext = {\n /** Register a named layout (a recursive object's reusable template). */\n register: (name: string, node: LayoutNode) => void;\n /** The recursive templates currently being built; `self` refs the innermost. */\n templates: Template[];\n /** A fresh, stable layout name for a recursion template. */\n name: () => string;\n /** The custom-widget role for a field at a path, if a plugin matcher claims it. */\n widgetRole: (field: Field, path: string) => string | undefined;\n options: CompileOptions;\n};\n\ntype Build<K extends Field['kind']> = (\n field: Extract<Field, { kind: K }>,\n loc: Loc,\n ctx: BuildContext,\n) => LayoutNode;\n\n// ─── Location: binding expression + structural path ──────────\n\n// Where a field sits: the binding expression Nova resolves at render (`$.from`,\n// `$item.eq`), and the structural path a widget matcher targets (`from`,\n// `fields.*`, `…eq`). They diverge inside a loop — the expression rebinds to\n// `$item`, losing the array key, but the path keeps it (`fields.*`), which is\n// exactly what tells the two list-item kinds apart.\ntype Loc = { expr: string; path: string };\n\nconst ROOT: Loc = { expr: '$', path: '' };\n\n// Extend to a child key: `$.a` + `b` → `$.a.b`; path `a` + `b` → `a.b`.\nconst child = (loc: Loc, key: string): Loc => ({\n expr: `${loc.expr}.${key}`,\n path: loc.path === '' ? key : `${loc.path}.${key}`,\n});\n\n// An array element: the loop rebinds the expression to `$item`; the path gains a\n// `*` segment (the index, resolved at render, is irrelevant to matching).\nconst itemLoc = (loc: Loc): Loc => ({ expr: ITEM_EXPR, path: loc.path === '' ? '*' : `${loc.path}.*` });\n\n// A recursive template is authored against `$item` and rooted afresh, so its\n// inner paths are scope-relative — a matcher's suffix (`endsWith('.eq')`) still\n// hits at any depth.\nconst TEMPLATE_ROOT: Loc = { expr: ITEM_EXPR, path: '' };\n\n// The error binding for a field, derived from its expression. Only absolute\n// (`$.`) expressions map to the error channel; loop-relative item paths\n// (`$item…`) carry an index resolved at render and are left for later.\nconst errorBinding = (expr: string): string | undefined =>\n expr.startsWith('$.') ? `$.${ERROR_NAMESPACE}.${expr.slice(2)}` : undefined;\n\n// ─── Node helpers ────────────────────────────────────────────\n\n// Attach `props` only when there is something to attach — keeps emitted layouts\n// free of empty `props: {}` noise.\nconst withProps = (node: ComponentNode, props: Record<string, unknown>): ComponentNode =>\n Object.keys(props).length > 0 ? { ...node, props } : node;\n\n// A leaf control bound to its expression. No explicit ref: the renderer derives\n// one from the resolved path, which is distinct per array element.\nconst control = (role: Role | string, expr: string, props: Record<string, unknown> = {}): ComponentNode =>\n withProps({ component: role, model: expr }, props);\n\n// Static JSON metadata a component reads (a variant's branches, a list's\n// containers, an \"add\" default) — not a binding. Nova resolves *every* prop as a\n// binding expression, so a value carrying `$`-prefixed data (a Prism op key, a\n// `$ref`) would be mangled, and a `$eq`/`$if`/`$exists` key would be evaluated as\n// a directive. Encoding it as a JSON string passes it through the resolver\n// untouched; the component decodes it (`decodeLiteral` in the kit).\nconst literal = (data: unknown): string | undefined => (data === undefined ? undefined : JSON.stringify(data));\n\n// An object property: a field wrapper (label / required / error chrome) around\n// the property's own layout. `loc` already points at the property.\nconst wrapField = (loc: Loc, prop: ObjectField, ctx: BuildContext): ComponentNode => {\n const error = errorBinding(loc.expr);\n return {\n component: Roles.field,\n props: {\n label: prop.field.title ?? prop.key,\n required: prop.required,\n ...(error !== undefined ? { error } : {}),\n ...(prop.field.description !== undefined ? { description: prop.field.description } : {}),\n },\n children: buildLayout(prop.field, loc, ctx),\n };\n};\n\n// A field's optional `title`, as props — shared by the title chrome of groups,\n// arrays, and the variant chooser.\nconst titleProps = (field: { title?: string }): Record<string, unknown> =>\n field.title !== undefined ? { title: field.title } : {};\n\nconst withTitle = (node: ComponentNode, field: { title?: string }): ComponentNode =>\n withProps(node, titleProps(field));\n\n// ─── Builds: IR → layout ─────────────────────────────────────\n\nconst stringBuild: Build<'string'> = (field, loc) =>\n control(Roles.text, loc.expr, field.format !== undefined ? { format: field.format } : {});\n\nconst numberBuild: Build<'number'> = (field, loc) =>\n control(Roles.number, loc.expr, field.integer ? { integer: true } : {});\n\nconst booleanBuild: Build<'boolean'> = (_field, loc) => control(Roles.checkbox, loc.expr);\n\nconst enumBuild: Build<'enum'> = (field, loc) => control(Roles.select, loc.expr, { options: field.options });\n\nconst unknownBuild: Build<'unknown'> = (_field, loc) => control(Roles.raw, loc.expr);\n\n// The group of wrapped fields an object renders as — shared by the inline\n// occurrence and the recursive template (same shape, different base loc).\nconst buildGroup = (field: Extract<Field, { kind: 'object' }>, loc: Loc, ctx: BuildContext): ComponentNode =>\n withTitle(\n {\n component: Roles.group,\n children: field.fields.map((prop) => wrapField(child(loc, prop.key), prop, ctx)),\n },\n field,\n );\n\nconst objectBuild: Build<'object'> = (field, loc, ctx) => {\n if (field.recursive !== true) return buildGroup(field, loc, ctx);\n // A recursive object: emit its group once as a named template authored\n // against the template root (so it binds correctly at any depth), keep it in\n // scope so the `self` inside refs it and an \"add\" knows the default node, then\n // render the object inline at its real loc. Both builds bottom out at `self`.\n const name = ctx.name();\n ctx.templates.push({ name, defaultChild: buildDocument(field, ctx.options), containers: [] });\n ctx.register(name, buildGroup(field, TEMPLATE_ROOT, ctx));\n const inline = buildGroup(field, loc, ctx);\n ctx.templates.pop();\n return inline;\n};\n\n// A tuple: one wrapped field per slot, bound to its numeric index (`$.x.0`).\n// Fixed-length, so no add / remove — the difference from an array.\nconst tupleBuild: Build<'tuple'> = (field, loc, ctx) =>\n withTitle(\n {\n component: Roles.group,\n children: field.items.map((item, index) =>\n wrapField(child(loc, String(index)), { key: String(index + 1), required: true, field: item }, ctx),\n ),\n },\n field,\n );\n\nconst selfBuild: Build<'self'> = (_field, loc, ctx) => {\n const template = ctx.templates[ctx.templates.length - 1];\n // Reached as an array item (the loop rebinds `$item` to the element), a\n // `self` becomes a reference to the enclosing template — Nova re-resolves it\n // per render against the live data, so depth follows the document. A `self`\n // anywhere else is a direct self-reference (a linked list); it has no loop to\n // rebind its scope, so it shows raw until that case lands.\n if (template !== undefined && loc.expr === ITEM_EXPR) return { ref: template.name };\n return control(Roles.raw, loc.expr);\n};\n\n// The default element an \"add\" appends: for a recursive list, the enclosing\n// template's default node; otherwise the item field's own default.\nconst defaultItem = (field: Extract<Field, { kind: 'array' }>, ctx: BuildContext): unknown =>\n field.item.kind === 'self'\n ? ctx.templates[ctx.templates.length - 1]?.defaultChild\n : buildDocument(field.item, ctx.options);\n\n// The key of a field's child-list, if it has one: an object property that is an\n// array of `self` (the same recursive type). This is the whole definition of a\n// \"container\" — structural, with no knowledge of the domain.\nconst childrenKey = (field: Field): string | undefined => {\n if (field.kind !== 'object') return undefined;\n return field.fields.find((f) => f.field.kind === 'array' && f.field.item.kind === 'self')?.key;\n};\n\n// A union's container variants: the ones whose branch holds a child-list.\nconst containersOf = (variants: Variant[]): Container[] =>\n variants.flatMap((variant) => {\n const key = childrenKey(variant.field);\n return key === undefined ? [] : [{ label: variant.label, pattern: variant.pattern, defaults: variantDefaults(variant), key }];\n });\n\n// A list editor: every element rendered (the recursive item is a `self` ref;\n// any other is its own editor), each in a row with an actions menu (✕ / ↑ / ↓,\n// and wrap / unwrap when the items are a recursive union with container\n// variants), plus an \"add\". The menu binds the loop's `$items` (the whole list)\n// and acts on its own `$index`; the add binds the list itself and appends a\n// default. Everything is a `ui:model` write — path resolution handles the\n// nesting, so a list edits at any depth with no static target and no triggers.\nconst arrayBuild: Build<'array'> = (field, loc, ctx) => {\n // Containers come from the recursive union the items belong to (when the item\n // is `self`); a plain list has none, so its menu is just move / remove.\n const containers = field.item.kind === 'self' ? ctx.templates[ctx.templates.length - 1]?.containers ?? [] : [];\n const itemRow: LayoutNode = {\n component: Roles.arrayItem,\n children: [\n { component: Roles.box, children: buildLayout(field.item, itemLoc(loc), ctx) }, // the editor cell — grows\n {\n component: Roles.rowMenu,\n model: LIST_EXPR,\n props: { index: INDEX, ...(containers.length > 0 ? { containers: literal(containers) } : {}) },\n },\n ],\n };\n return withTitle(\n {\n component: Roles.array,\n children: [\n { for: loc.expr, as: ITEM, do: itemRow },\n { component: Roles.append, model: loc.expr, props: { label: 'Add', child: literal(defaultItem(field, ctx)) } },\n ],\n },\n field,\n );\n};\n\n// A union is the variant widget bound to the value: it holds each branch's\n// pattern + label + default, and renders the branch editors as its children.\n// The widget reads the value, matches it to a branch (in JS), and shows that\n// child; on change it writes the chosen branch's default. No discrimination is\n// compiled into the layout — Nova never learns what a union is.\nconst buildVariant = (field: Extract<Field, { kind: 'union' }>, loc: Loc, ctx: BuildContext): ComponentNode =>\n withProps(\n {\n component: Roles.variant,\n model: loc.expr,\n // Each branch editor in its own `branch` wrapper, indexed; the widget shows\n // only the one whose index it matched. (Nova hands a component its children\n // as one tree, so the branches need to be individually addressable.) A\n // branch edits the same value, so it shares the union's loc.\n children: field.variants.map((variant: Variant, index) => ({\n component: Roles.branch,\n props: { index },\n children: buildLayout(variant.field, loc, ctx),\n })),\n },\n {\n // `childrenKey` lets the chooser carry children when switching between two\n // container variants (and warn before dropping them otherwise). Encoded as\n // a literal: the patterns and defaults carry `$`-bearing data Nova must not\n // resolve.\n branches: literal(\n field.variants.map((variant: Variant) => ({\n label: variant.label,\n pattern: variant.pattern,\n defaults: variantDefaults(variant),\n ...(childrenKey(variant.field) !== undefined ? { childrenKey: childrenKey(variant.field) } : {}),\n })),\n ),\n ...titleProps(field),\n },\n );\n\nconst variantBuild: Build<'union'> = (field, loc, ctx) => {\n if (field.recursive !== true) return buildVariant(field, loc, ctx);\n // A recursive union (a tree of typed nodes): emit the chooser once as a named\n // template authored against the template root, keep it in scope so the `self`\n // inside a branch's children refs it, then render the node inline. Same\n // machinery as a recursive object — the template is just a variant, not a group.\n const name = ctx.name();\n const first = field.variants[0];\n ctx.templates.push({ name, defaultChild: first !== undefined ? variantDefaults(first) : {}, containers: containersOf(field.variants) });\n ctx.register(name, buildVariant(field, TEMPLATE_ROOT, ctx));\n const inline = buildVariant(field, loc, ctx);\n ctx.templates.pop();\n return inline;\n};\n\n// Dispatch a field to its build. The switch narrows `field` per case, so each\n// build receives its own field type with no assertion; the union is closed, so\n// it is also exhaustive (a new kind won't compile until it is handled here).\nconst buildLayout = (field: Field, loc: Loc, ctx: BuildContext): LayoutNode => {\n // A plugin widget claims this field by where it sits (its structural path) —\n // render with the registered component instead of the type default. It binds\n // the value and a model like any control, so it can be a leaf editor or\n // replace a whole subtree.\n const role = ctx.widgetRole(field, loc.path);\n if (role !== undefined) return control(role, loc.expr);\n switch (field.kind) {\n case 'string':\n return stringBuild(field, loc, ctx);\n case 'number':\n return numberBuild(field, loc, ctx);\n case 'boolean':\n return booleanBuild(field, loc, ctx);\n case 'enum':\n return enumBuild(field, loc, ctx);\n case 'object':\n return objectBuild(field, loc, ctx);\n case 'array':\n return arrayBuild(field, loc, ctx);\n case 'tuple':\n return tupleBuild(field, loc, ctx);\n case 'union':\n return variantBuild(field, loc, ctx);\n case 'self':\n return selfBuild(field, loc, ctx);\n case 'unknown':\n return unknownBuild(field, loc, ctx);\n }\n};\n\n// ─── Public entry ────────────────────────────────────────────\n\nexport const toNova = (ir: Field, options: CompileOptions = {}): NovaEditor => {\n const layouts: Record<string, LayoutNode> = {};\n let counter = 0;\n const matchers = options.widgets ?? [];\n const ctx: BuildContext = {\n register: (name, node) => {\n layouts[name] = node;\n },\n templates: [],\n name: () => `loom:tree:${counter++}`,\n // Match on where the field sits (its structural path) plus its facts.\n widgetRole: (field, path) =>\n matchers.find((matcher) =>\n matcher.match({ kind: field.kind, path, title: field.title, description: field.description }),\n )?.role,\n options,\n };\n\n // A non-object root (a union, scalar, or array) is a single control that can't\n // bind the bare document root, so `rootKey` binds it one level in (`$.<key>`)\n // and the document wraps the value under that key. An object root binds `$` and\n // its leaves bind `$.<field>` as usual.\n const rootLoc: Loc = options.rootKey !== undefined ? { expr: `$.${options.rootKey}`, path: '' } : ROOT;\n const layout = buildLayout(ir, rootLoc, ctx);\n const value = options.value ?? buildDocument(ir, options);\n const document = options.rootKey !== undefined ? { [options.rootKey]: value } : value;\n // The action's data must be a record. An object root builds one directly; a\n // wrapped root is a record by construction. A bare scalar root with no key has\n // no record document.\n if (!isRecord(document)) {\n throw new Error('loom.toNova: the root document must be an object (or use rootKey).');\n }\n const action: ActionDefinition = {\n id: options.id ?? 'loom-form',\n data: document,\n layout,\n };\n return { action, layouts };\n};\n","import type { Shell } from '@niscorp/nova';\nimport type { ZodType } from 'zod';\nimport { ERROR_NAMESPACE } from './compile/to-nova.js';\n\n// Validate-on-edit. The Zod schema is the truth: on each change, the working\n// document (everything except the reserved error channel) is parsed, and a\n// nested error tree — mirroring the document, keyed by Zod's issue paths —\n// is written back under that channel for the fields to bind to. The document\n// itself stays clean; `onDocument` reports it without the error channel.\n\ntype Doc = Record<string, unknown>;\n\ntype Issue = { readonly path: ReadonlyArray<PropertyKey>; readonly message: string };\n\n// Place a message at a nested path, mirroring the document shape. First issue\n// per path wins (the most specific message Zod emits first).\nconst setPath = (root: Doc, path: ReadonlyArray<PropertyKey>, message: string): void => {\n let node = root;\n for (let i = 0; i < path.length - 1; i += 1) {\n const key = String(path[i]);\n const next = node[key];\n node = typeof next === 'object' && next !== null ? (next as Doc) : (node[key] = {});\n }\n const leaf = String(path[path.length - 1]);\n if (!(leaf in node)) node[leaf] = message;\n};\n\nconst errorTree = (issues: ReadonlyArray<Issue>): Doc => {\n const tree: Doc = {};\n for (const issue of issues) {\n if (issue.path.length > 0) setPath(tree, issue.path, issue.message);\n }\n return tree;\n};\n\nconst stripErrors = (data: Doc): Doc => {\n const { [ERROR_NAMESPACE]: _omit, ...document } = data;\n return document;\n};\n\nexport const attachValidation = (\n shell: Shell,\n instanceId: string,\n schema: ZodType,\n onDocument?: (document: Doc) => void,\n): (() => void) => {\n const runtime = shell.getRuntime(instanceId);\n if (runtime === undefined) return () => {};\n\n let lastDocument = '';\n const handle = (data: Doc): void => {\n const document = stripErrors(data);\n const fingerprint = JSON.stringify(document);\n if (fingerprint === lastDocument) return; // our own error write — not a real edit\n lastDocument = fingerprint;\n\n const result = schema.safeParse(document);\n const errors = result.success ? {} : errorTree(result.error.issues);\n runtime.setData({ ...document, [ERROR_NAMESPACE]: errors });\n onDocument?.(document);\n };\n\n return shell.onDataChange((change) => {\n if (change.instanceId === instanceId) handle(change.data);\n });\n};\n","import type { LayoutNode } from '@niscorp/nova';\n\n// The editor's default canvasLayout — a plain Nova layout. The forms are the main\n// column (each in a titled, bordered panel); every other canvas (preview, JSON\n// views) stacks in a side column (those already render their own panel). No Nova\n// primitive can size a flex child, so the columns use Loom's `loom:column` (a Loom\n// component, registered with the kit). A plugin can replace the whole arrangement\n// with shell.setCanvasLayout.\n\nexport const LOOM_COLUMN = 'loom:column';\n\nconst slot = (canvasId: string): LayoutNode => ({ component: 'CanvasSlot', props: { canvasId } });\n\n// `form:data` -> `Data`. A form canvas's title is its document name.\nconst titleOf = (formId: string): string => {\n const name = formId.replace(/^form:/, '');\n return name.charAt(0).toUpperCase() + name.slice(1);\n};\n\n// A form sits in a bordered panel headed by its document name.\nconst formPanel = (formId: string): LayoutNode => ({\n component: 'Box',\n props: { border: true, radius: 8, padding: 16 },\n children: [{ component: 'loom:group', props: { title: titleOf(formId) }, children: [slot(formId)] }],\n});\n\nconst column = (grow: number, min: number, children: LayoutNode[]): LayoutNode => ({\n component: LOOM_COLUMN,\n props: { grow, min },\n children: [{ component: 'Stack', props: { direction: 'column', gap: 16 }, children }],\n});\n\nexport const defaultCanvasLayout = (formIds: string[], viewIds: string[]): LayoutNode => ({\n component: 'Stack',\n props: { direction: 'row', gap: 16, align: 'start' },\n children: [\n ...(formIds.length > 0 ? [column(2, 420, formIds.map(formPanel))] : []),\n ...(viewIds.length > 0 ? [column(1, 340, viewIds.map(slot))] : []),\n ],\n});\n","import type { ActionDefinition } from '@niscorp/nova';\nimport type { LoomEditor } from './types.js';\n\n// Mount a view canvas: register `action`, add a canvas that renders it, and keep\n// its data in sync with the editor's live state — `read(editor)` is pushed onto\n// the canvas on every `change`. The canvas id is the action id. Used by the\n// default plugins (jsonviewer, validation) and any domain preview; the contributor\n// owns the canvas, so a later plugin can `shell.removeCanvas(action.id)` to drop it.\nexport const mountView = (\n editor: LoomEditor,\n action: ActionDefinition,\n read: (editor: LoomEditor) => Record<string, unknown>,\n): void => {\n const { shell } = editor;\n shell.registerAction(action);\n shell.addCanvas({ id: action.id, initial: action.id });\n const instance = shell.getCanvasState(action.id).active?.id;\n if (instance === undefined) return;\n const sync = (): void => {\n shell.getRuntime(instance)?.setData(read(editor));\n };\n editor.on('change', sync);\n sync();\n};\n","import { z, type ZodType } from 'zod';\nimport { createLayoutStore, createShell, type ActionDefinition, type Shell } from '@niscorp/nova';\nimport { parse, buildDocument, isRecord } from '@compile/parse';\nimport { toNova, ERROR_NAMESPACE } from '@compile/to-nova';\nimport { attachValidation } from '../validate.js';\nimport { defaultCanvasLayout } from './default.layout.js';\nimport type { LoomArtifact, LoomEditor, LoomEditorConfig, LoomEvent, LoomPlugin } from './types.js';\n\nexport type { LoomArtifact, LoomEditor, LoomEditorConfig, LoomEvent, LoomPlugin, Document, DocumentLayout, WidgetBinding } from './types.js';\nexport { mountView } from './view.js';\n\n// The Loom Editor controller — framework-free. It owns one Nova shell, built\n// empty, and a plugin loader. Everything visible is plugin-contributed: domain\n// plugins (nova, vex) declare the documents that `open` compiles into form\n// canvases; default plugins (jsonviewer, validation) and previews mount their own\n// view canvases against the live shell. The controller only compiles forms and\n// publishes the live `documents` / `validations`; the React (or Vue) layer\n// supplies the component registry and renders the shell.\n\n// The canvas a document's form lives on.\nconst formCanvas = (document: string): string => `form:${document}`;\n\n// The key a non-object document (a union, scalar, or array) is wrapped under so\n// its single control has a bindable path. Internal: the editor wraps the value\n// before compiling and unwraps it before publishing, so it never reaches a\n// plugin or the reported document. A document key collides with nothing — it\n// holds the whole value, no sibling.\nconst ROOT_KEY = '$root';\n\n// A document whose schema's root is not an object needs wrapping; an object root\n// binds the document root directly.\nconst needsWrap = (document: ZodType): boolean => parse(document).kind !== 'object';\n\nconst stripErrors = (data: Record<string, unknown>): Record<string, unknown> => {\n const { [ERROR_NAMESPACE]: _omit, ...document } = data;\n return document;\n};\n\nexport const createLoomEditor = (config: LoomEditorConfig): LoomEditor => {\n const plugins = new Map<string, LoomPlugin>();\n const listeners: Record<LoomEvent, Set<() => void>> = { change: new Set(), open: new Set() };\n const emit = (event: LoomEvent): void => listeners[event].forEach((handler) => handler());\n\n // The shell exists from creation (empty), so plugins can mount onto it. With no\n // canvasLayout, Nova renders the canvases in creation order; a plugin can call\n // shell.setCanvasLayout to arrange them. Form recursion templates are written\n // into this shared store as documents compile.\n const store = createLayoutStore();\n const shell: Shell = createShell({\n canvases: [],\n registry: config.registry,\n actions: {},\n layoutStore: store,\n });\n\n let active: LoomPlugin | undefined;\n let formInstances: Record<string, string> = {};\n // Documents whose root was wrapped under ROOT_KEY (non-object roots): their\n // value is unwrapped before it is published or validated against the schema.\n let wrappedDocs = new Set<string>();\n let formCanvasIds: string[] = [];\n let documents: Record<string, unknown> = {};\n let validations: Record<string, unknown> = {};\n let detach: Array<() => void> = [];\n\n // Read every form's live value into `documents` / `validations`. View plugins\n // self-sync off the `change` event, so nothing is pushed to them here.\n const refresh = (): void => {\n const nextDocs: Record<string, unknown> = {};\n const nextProblems: Record<string, unknown> = {};\n for (const [name, instanceId] of Object.entries(formInstances)) {\n const data = shell.getRuntime(instanceId)?.getData() ?? {};\n const document = stripErrors(data);\n const problems = (data[ERROR_NAMESPACE] ?? {}) as Record<string, unknown>;\n // A wrapped document is published as its bare value (and its errors as that\n // value's subtree), so ROOT_KEY never surfaces to a view or a consumer.\n if (wrappedDocs.has(name)) {\n nextDocs[name] = document[ROOT_KEY];\n nextProblems[name] = problems[ROOT_KEY] ?? {};\n } else {\n nextDocs[name] = document;\n nextProblems[name] = problems;\n }\n }\n documents = nextDocs;\n validations = nextProblems;\n };\n\n // Drop the previous artifact's form canvases (the plugin canvases stay).\n const clearForms = (): void => {\n detach.forEach((off) => off());\n detach = [];\n for (const canvasId of formCanvasIds) shell.removeCanvas(canvasId);\n formCanvasIds = [];\n formInstances = {};\n wrappedDocs = new Set();\n };\n\n const open = (artifact: LoomArtifact): void => {\n const plugin = plugins.get(artifact.type);\n if (plugin === undefined) throw new Error(`loom editor: no plugin '${artifact.type}'`);\n clearForms();\n active = plugin;\n\n // Build each document's form action and add its canvas. A schema document is\n // compiled (toNova); a layout document (freeform, no schema) takes its layout\n // from the plugin. Either way the action's `data` is the document's value —\n // seeded from the artifact, tracked by `refresh`.\n for (const [name, document] of Object.entries(plugin.documents)) {\n const canvasId = formCanvas(name);\n let action: ActionDefinition;\n if (typeof document === 'function') {\n const value = artifact.documents?.[name];\n action = { id: canvasId, data: isRecord(value) ? value : {}, layout: document(value) };\n } else {\n const ir = parse(document);\n // A non-object root binds one level in, under ROOT_KEY (see `needsWrap`).\n const wrap = needsWrap(document);\n if (wrap) wrappedDocs.add(name);\n const seed = artifact.documents?.[name];\n const value = seed ?? buildDocument(ir, {});\n const built = toNova(ir, {\n id: canvasId,\n ...(wrap ? { rootKey: ROOT_KEY } : {}),\n ...(isRecord(value) ? { value } : {}),\n widgets: plugin.widgets ?? [],\n });\n for (const [id, node] of Object.entries(built.layouts)) store.set(id, node);\n // A wrapped document's value need not be an object — a list, a string, a\n // number — and the compiler's `value` takes objects. Such a seed goes\n // under ROOT_KEY here, where the wrapping is the editor's own; without\n // this it was dropped and the default opened in its place. One the schema\n // refuses is still left out, and the default opens as it always did.\n const seedsRoot = wrap && seed !== undefined && seed !== null && !isRecord(seed) && document.safeParse(seed).success;\n action = seedsRoot ? { ...built.action, data: { [ROOT_KEY]: seed } } : built.action;\n }\n shell.registerAction(action);\n shell.addCanvas({ id: canvasId, initial: action.id });\n formCanvasIds.push(canvasId);\n const instanceId = shell.getCanvasState(canvasId).active?.id;\n if (instanceId !== undefined) formInstances[name] = instanceId;\n }\n\n // Validate only schema documents — a freeform layout document has no schema.\n for (const [name, instanceId] of Object.entries(formInstances)) {\n const document = plugin.documents[name];\n if (typeof document !== 'function' && document !== undefined) {\n // A wrapped document is validated against the same wrapper, so the data\n // and schema agree and the error tree keys under ROOT_KEY (matching the\n // field bindings).\n const schema = wrappedDocs.has(name) ? z.object({ [ROOT_KEY]: document }) : document;\n detach.push(attachValidation(shell, instanceId, schema));\n }\n }\n detach.push(\n shell.onDataChange((change) => {\n if (!Object.values(formInstances).includes(change.instanceId)) return;\n refresh();\n emit('change');\n }),\n );\n\n // Arrange the canvases: the forms as the main pane, each contributed view in\n // its own sized pane. View canvases come after the forms; the default JSON\n // panes (loom:*) sort last, so a domain preview sits next to the forms.\n const viewIds = Object.keys(shell.getState().canvases)\n .filter((id) => !formCanvasIds.includes(id))\n .sort((a, b) => Number(a.startsWith('loom:')) - Number(b.startsWith('loom:')));\n shell.setCanvasLayout(defaultCanvasLayout(formCanvasIds, viewIds));\n\n refresh();\n emit('open');\n // Prime the view plugins with the opened documents.\n emit('change');\n };\n\n const editor: LoomEditor = {\n get shell() {\n return shell;\n },\n get plugin() {\n return active;\n },\n get documents() {\n return documents;\n },\n get validations() {\n return validations;\n },\n loadPlugin: (plugin) => {\n plugins.set(plugin.name, plugin);\n plugin.mount?.(editor);\n },\n open,\n on: (event, handler) => {\n listeners[event].add(handler);\n return () => listeners[event].delete(handler);\n },\n dispose: () => {\n detach.forEach((off) => off());\n detach = [];\n shell.dispose();\n },\n };\n\n return editor;\n};\n"]}
package/dist/index.d.cts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ZodType } from 'zod';
2
- import { F as Field, C as CompileOptions, L as LoomEditor, a as LoomEditorConfig } from './types-BonjN3CB.cjs';
3
- export { D as Document, b as DocumentLayout, E as EmptyValue, c as EnumOption, d as FieldKind, e as FieldMeta, f as LoomArtifact, g as LoomEvent, h as LoomPlugin, O as ObjectField, P as Pattern, V as Variant, W as WidgetBinding } from './types-BonjN3CB.cjs';
2
+ import { F as Field, C as CompileOptions, L as LoomEditor, a as LoomEditorConfig } from './types-l8sDxrMR.cjs';
3
+ export { D as Document, b as DocumentLayout, E as EmptyValue, c as EnumOption, d as FieldKind, e as FieldMeta, f as LoomArtifact, g as LoomEvent, h as LoomPlugin, O as ObjectField, P as Pattern, V as Variant, W as WidgetBinding } from './types-l8sDxrMR.cjs';
4
4
  import { ActionDefinition, LayoutNode, Shell } from '@niscorp/nova';
5
5
 
6
6
  declare const parse: (schema: ZodType) => Field;
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ZodType } from 'zod';
2
- import { F as Field, C as CompileOptions, L as LoomEditor, a as LoomEditorConfig } from './types-BonjN3CB.js';
3
- export { D as Document, b as DocumentLayout, E as EmptyValue, c as EnumOption, d as FieldKind, e as FieldMeta, f as LoomArtifact, g as LoomEvent, h as LoomPlugin, O as ObjectField, P as Pattern, V as Variant, W as WidgetBinding } from './types-BonjN3CB.js';
2
+ import { F as Field, C as CompileOptions, L as LoomEditor, a as LoomEditorConfig } from './types-l8sDxrMR.js';
3
+ export { D as Document, b as DocumentLayout, E as EmptyValue, c as EnumOption, d as FieldKind, e as FieldMeta, f as LoomArtifact, g as LoomEvent, h as LoomPlugin, O as ObjectField, P as Pattern, V as Variant, W as WidgetBinding } from './types-l8sDxrMR.js';
4
4
  import { ActionDefinition, LayoutNode, Shell } from '@niscorp/nova';
5
5
 
6
6
  declare const parse: (schema: ZodType) => Field;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- export { ERROR_NAMESPACE, attachValidation, createLoomEditor, toNova } from './chunk-X7PCPONB.js';
1
+ export { ERROR_NAMESPACE, attachValidation, createLoomEditor, toNova } from './chunk-TCCN6LKV.js';
2
2
  export { Roles } from './chunk-PTXRAWJX.js';
3
3
  export { parse } from './chunk-TV4U22MY.js';
4
4
  export { mountView } from './chunk-D743DI5J.js';
@@ -2,7 +2,7 @@ import { FC } from 'react';
2
2
  import { ZodType } from 'zod';
3
3
  import { LayoutNode } from '@niscorp/nova';
4
4
  import { NovaComponent } from '@niscorp/nova/adapters/react';
5
- import { i as FieldContext, L as LoomEditor$1, f as LoomArtifact } from './types-BonjN3CB.js';
5
+ import { i as FieldContext, L as LoomEditor$1, f as LoomArtifact } from './types-l8sDxrMR.js';
6
6
 
7
7
  type LoomEditorPlugin = {
8
8
  name: string;
@@ -2,7 +2,7 @@ import { FC } from 'react';
2
2
  import { ZodType } from 'zod';
3
3
  import { LayoutNode } from '@niscorp/nova';
4
4
  import { NovaComponent } from '@niscorp/nova/adapters/react';
5
- import { i as FieldContext, L as LoomEditor$1, f as LoomArtifact } from './types-BonjN3CB.cjs';
5
+ import { i as FieldContext, L as LoomEditor$1, f as LoomArtifact } from './types-l8sDxrMR.cjs';
6
6
 
7
7
  type LoomEditorPlugin = {
8
8
  name: string;
@@ -1,4 +1,4 @@
1
- import { h as LoomPlugin } from '../../types-BonjN3CB.cjs';
1
+ import { h as LoomPlugin } from '../../types-l8sDxrMR.cjs';
2
2
  import { N as NovaComponentShape } from '../../schema--OhtatTX.cjs';
3
3
  export { l as layoutSchema } from '../../schema--OhtatTX.cjs';
4
4
  import 'zod';
@@ -1,4 +1,4 @@
1
- import { h as LoomPlugin } from '../../types-BonjN3CB.js';
1
+ import { h as LoomPlugin } from '../../types-l8sDxrMR.js';
2
2
  import { N as NovaComponentShape } from '../../schema--OhtatTX.js';
3
3
  export { l as layoutSchema } from '../../schema--OhtatTX.js';
4
4
  import 'zod';
@@ -1,10 +1,10 @@
1
1
  import { NovaComponent } from '@niscorp/nova/adapters/react';
2
- import { L as LoomEditorPlugin } from '../../../loom-editor-CQ_GI4IA.cjs';
2
+ import { L as LoomEditorPlugin } from '../../../loom-editor-MACwUjLC.cjs';
3
3
  import { N as NovaComponentShape } from '../../../schema--OhtatTX.cjs';
4
4
  import 'react';
5
5
  import 'zod';
6
6
  import '@niscorp/nova';
7
- import '../../../types-BonjN3CB.cjs';
7
+ import '../../../types-l8sDxrMR.cjs';
8
8
 
9
9
  type NovaManifestEntry = NovaComponentShape & {
10
10
  render: NovaComponent;
@@ -1,10 +1,10 @@
1
1
  import { NovaComponent } from '@niscorp/nova/adapters/react';
2
- import { L as LoomEditorPlugin } from '../../../loom-editor-D5SBQ4_F.js';
2
+ import { L as LoomEditorPlugin } from '../../../loom-editor-Clohg49u.js';
3
3
  import { N as NovaComponentShape } from '../../../schema--OhtatTX.js';
4
4
  import 'react';
5
5
  import 'zod';
6
6
  import '@niscorp/nova';
7
- import '../../../types-BonjN3CB.js';
7
+ import '../../../types-l8sDxrMR.js';
8
8
 
9
9
  type NovaManifestEntry = NovaComponentShape & {
10
10
  render: NovaComponent;
@@ -1,7 +1,7 @@
1
1
  import { ZodType } from 'zod';
2
2
  import { JsonObject } from '@niscorp/prism';
3
3
  export { Config, JsonObject, JsonValue } from '@niscorp/prism';
4
- import { h as LoomPlugin } from '../../types-BonjN3CB.cjs';
4
+ import { h as LoomPlugin } from '../../types-l8sDxrMR.cjs';
5
5
  import '@niscorp/nova';
6
6
 
7
7
  declare const PREVIEW = "prism:preview";
@@ -1,7 +1,7 @@
1
1
  import { ZodType } from 'zod';
2
2
  import { JsonObject } from '@niscorp/prism';
3
3
  export { Config, JsonObject, JsonValue } from '@niscorp/prism';
4
- import { h as LoomPlugin } from '../../types-BonjN3CB.js';
4
+ import { h as LoomPlugin } from '../../types-l8sDxrMR.js';
5
5
  import '@niscorp/nova';
6
6
 
7
7
  declare const PREVIEW = "prism:preview";
@@ -383,7 +383,9 @@ var OP_CATEGORY = {
383
383
  $sub: "Math",
384
384
  $mul: "Math",
385
385
  $div: "Math",
386
+ $mod: "Math",
386
387
  $round: "Math",
388
+ $toNumber: "Math",
387
389
  $join: "String",
388
390
  $toString: "String",
389
391
  $interpolate: "String",