@niscorp/loom 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/DESIGN.md +253 -0
  2. package/LICENSE +202 -0
  3. package/README.md +101 -0
  4. package/dist/chunk-A3UOFGL4.js +29 -0
  5. package/dist/chunk-A3UOFGL4.js.map +1 -0
  6. package/dist/chunk-D743DI5J.js +17 -0
  7. package/dist/chunk-D743DI5J.js.map +1 -0
  8. package/dist/chunk-DWQWPBBV.js +63 -0
  9. package/dist/chunk-DWQWPBBV.js.map +1 -0
  10. package/dist/chunk-LWY5TG7M.js +208 -0
  11. package/dist/chunk-LWY5TG7M.js.map +1 -0
  12. package/dist/chunk-MIRMQPUE.js +132 -0
  13. package/dist/chunk-MIRMQPUE.js.map +1 -0
  14. package/dist/chunk-PTXRAWJX.js +58 -0
  15. package/dist/chunk-PTXRAWJX.js.map +1 -0
  16. package/dist/chunk-TV4U22MY.js +176 -0
  17. package/dist/chunk-TV4U22MY.js.map +1 -0
  18. package/dist/chunk-X7PCPONB.js +380 -0
  19. package/dist/chunk-X7PCPONB.js.map +1 -0
  20. package/dist/chunk-XTY7XO5C.js +61 -0
  21. package/dist/chunk-XTY7XO5C.js.map +1 -0
  22. package/dist/index.cjs +630 -0
  23. package/dist/index.cjs.map +1 -0
  24. package/dist/index.d.cts +40 -0
  25. package/dist/index.d.ts +40 -0
  26. package/dist/index.js +6 -0
  27. package/dist/index.js.map +1 -0
  28. package/dist/loom-editor-CQ_GI4IA.d.cts +27 -0
  29. package/dist/loom-editor-D5SBQ4_F.d.ts +27 -0
  30. package/dist/plugins/nova/index.cjs +81 -0
  31. package/dist/plugins/nova/index.cjs.map +1 -0
  32. package/dist/plugins/nova/index.d.cts +14 -0
  33. package/dist/plugins/nova/index.d.ts +14 -0
  34. package/dist/plugins/nova/index.js +5 -0
  35. package/dist/plugins/nova/index.js.map +1 -0
  36. package/dist/plugins/nova/react/index.cjs +107 -0
  37. package/dist/plugins/nova/react/index.cjs.map +1 -0
  38. package/dist/plugins/nova/react/index.d.cts +17 -0
  39. package/dist/plugins/nova/react/index.d.ts +17 -0
  40. package/dist/plugins/nova/react/index.js +36 -0
  41. package/dist/plugins/nova/react/index.js.map +1 -0
  42. package/dist/plugins/prism/index.cjs +48 -0
  43. package/dist/plugins/prism/index.cjs.map +1 -0
  44. package/dist/plugins/prism/index.d.cts +18 -0
  45. package/dist/plugins/prism/index.d.ts +18 -0
  46. package/dist/plugins/prism/index.js +4 -0
  47. package/dist/plugins/prism/index.js.map +1 -0
  48. package/dist/plugins/prism/react/index.cjs +744 -0
  49. package/dist/plugins/prism/react/index.cjs.map +1 -0
  50. package/dist/plugins/prism/react/index.d.cts +12 -0
  51. package/dist/plugins/prism/react/index.d.ts +12 -0
  52. package/dist/plugins/prism/react/index.js +419 -0
  53. package/dist/plugins/prism/react/index.js.map +1 -0
  54. package/dist/plugins/vex/index.cjs +67 -0
  55. package/dist/plugins/vex/index.cjs.map +1 -0
  56. package/dist/plugins/vex/index.d.cts +25 -0
  57. package/dist/plugins/vex/index.d.ts +25 -0
  58. package/dist/plugins/vex/index.js +4 -0
  59. package/dist/plugins/vex/index.js.map +1 -0
  60. package/dist/plugins/vex/react/index.cjs +432 -0
  61. package/dist/plugins/vex/react/index.cjs.map +1 -0
  62. package/dist/plugins/vex/react/index.d.cts +13 -0
  63. package/dist/plugins/vex/react/index.d.ts +13 -0
  64. package/dist/plugins/vex/react/index.js +296 -0
  65. package/dist/plugins/vex/react/index.js.map +1 -0
  66. package/dist/react/index.cjs +1076 -0
  67. package/dist/react/index.cjs.map +1 -0
  68. package/dist/react/index.d.cts +82 -0
  69. package/dist/react/index.d.ts +82 -0
  70. package/dist/react/index.js +120 -0
  71. package/dist/react/index.js.map +1 -0
  72. package/dist/schema--OhtatTX.d.cts +10 -0
  73. package/dist/schema--OhtatTX.d.ts +10 -0
  74. package/dist/types-BonjN3CB.d.cts +144 -0
  75. package/dist/types-BonjN3CB.d.ts +144 -0
  76. package/package.json +144 -0
@@ -0,0 +1,176 @@
1
+ // src/compile/parse.ts
2
+ var defOf = (schema) => schema.def;
3
+ var INTEGER_FORMAT = "safeint";
4
+ var stringFormat = (schema) => {
5
+ const def = defOf(schema);
6
+ if (def.format !== void 0) return def.format;
7
+ for (const check of def.checks ?? []) {
8
+ if (check.def?.format !== void 0) return check.def.format;
9
+ }
10
+ return void 0;
11
+ };
12
+ var isInteger = (schema) => {
13
+ const def = defOf(schema);
14
+ if (def.format === INTEGER_FORMAT) return true;
15
+ return (def.checks ?? []).some((check) => check.def?.format === INTEGER_FORMAT);
16
+ };
17
+ var enumOptions = (schema) => Object.values(defOf(schema).entries ?? {}).map((value) => ({ value, label: String(value) }));
18
+ var objectFields = (schema, walk) => Object.entries(defOf(schema).shape ?? {}).map(([key, value]) => ({
19
+ key,
20
+ // A property is optional when the schema accepts `undefined` for it
21
+ // (covers `.optional()` and `.default()`) — asked of Zod, not inferred.
22
+ required: !value.safeParse(void 0).success,
23
+ field: parseField(value, walk)
24
+ }));
25
+ var branchKeys = (branch) => Object.keys(defOf(branch).shape ?? {});
26
+ var JSON_TYPES = /* @__PURE__ */ new Set(["string", "number", "boolean", "object", "array", "null"]);
27
+ var jsonType = (branch) => {
28
+ const type = defOf(branch).type;
29
+ return JSON_TYPES.has(type) ? type : void 0;
30
+ };
31
+ var distinguish = (branch, siblings, tag) => {
32
+ if (tag !== void 0) {
33
+ const literal = (defOf(branch).shape ?? {})[tag];
34
+ return { kind: "tag", key: tag, value: literal !== void 0 ? defOf(literal).values?.[0] : void 0 };
35
+ }
36
+ const elsewhere = new Set(siblings.flatMap(branchKeys));
37
+ const key = branchKeys(branch).find((k) => !elsewhere.has(k));
38
+ if (key !== void 0) return { kind: "key", key };
39
+ const type = jsonType(branch);
40
+ if (type !== void 0 && siblings.every((s) => jsonType(s) !== type)) return { kind: "type", type };
41
+ return void 0;
42
+ };
43
+ var patternLabel = (pattern) => pattern.kind === "tag" ? String(pattern.value) : pattern.kind === "key" ? pattern.key : pattern.kind === "type" ? pattern.type : "other";
44
+ var flattenBranches = (branches, seen = /* @__PURE__ */ new Set()) => branches.flatMap((branch) => {
45
+ const { core } = unwrap(branch);
46
+ const def = defOf(core);
47
+ if (def.type !== "union" || seen.has(def)) return [branch];
48
+ return flattenBranches(def.options ?? [], new Set(seen).add(def));
49
+ });
50
+ var branchField = (branch, walk, tag) => tag === void 0 ? parseField(branch, walk) : { kind: "object", fields: objectFields(branch, walk).filter((f) => f.key !== tag) };
51
+ var parseByType = {
52
+ string: (schema) => {
53
+ const format = stringFormat(schema);
54
+ return format !== void 0 ? { kind: "string", format } : { kind: "string" };
55
+ },
56
+ number: (schema) => isInteger(schema) ? { kind: "number", integer: true } : { kind: "number" },
57
+ boolean: () => ({ kind: "boolean" }),
58
+ enum: (schema) => ({ kind: "enum", options: enumOptions(schema) }),
59
+ object: (schema, walk) => {
60
+ const def = defOf(schema);
61
+ walk.stack.add(def);
62
+ const fields = objectFields(schema, walk);
63
+ walk.stack.delete(def);
64
+ return walk.targets.has(def) ? { kind: "object", fields, recursive: true } : { kind: "object", fields };
65
+ },
66
+ array: (schema, walk) => {
67
+ const element = defOf(schema).element;
68
+ return { kind: "array", item: element !== void 0 ? parseField(element, walk) : { kind: "unknown" } };
69
+ },
70
+ tuple: (schema, walk) => ({ kind: "tuple", items: (defOf(schema).items ?? []).map((item) => parseField(item, walk)) }),
71
+ union: (schema, walk) => {
72
+ const branches = [...new Set(flattenBranches(defOf(schema).options ?? []))];
73
+ const tag = defOf(schema).discriminator;
74
+ const patterns = branches.map((b) => distinguish(b, branches.filter((x) => x !== b), tag));
75
+ const open = patterns.reduce((acc, p, i) => p === void 0 ? [...acc, i] : acc, []);
76
+ if (branches.length === 0 || open.length > 1) return { kind: "unknown" };
77
+ if (open.length === 1) patterns[open[0]] = { kind: "fallback" };
78
+ const def = defOf(schema);
79
+ walk.stack.add(def);
80
+ const variants = branches.map((branch, i) => ({
81
+ label: readMeta(branch).title ?? patternLabel(patterns[i]),
82
+ field: branchField(branch, walk, tag),
83
+ pattern: patterns[i]
84
+ }));
85
+ walk.stack.delete(def);
86
+ return walk.targets.has(def) ? { kind: "union", variants, recursive: true } : { kind: "union", variants };
87
+ }
88
+ };
89
+ var unknownField = () => ({ kind: "unknown" });
90
+ var WRAPPERS = /* @__PURE__ */ new Set(["optional", "nullable", "default", "readonly"]);
91
+ var lazyResolved = /* @__PURE__ */ new WeakMap();
92
+ var resolveLazy = (lazy) => {
93
+ const def = defOf(lazy);
94
+ const cached = lazyResolved.get(def);
95
+ if (cached !== void 0) return cached;
96
+ const resolved = def.getter?.();
97
+ if (resolved !== void 0) lazyResolved.set(def, resolved);
98
+ return resolved;
99
+ };
100
+ var unwrap = (schema) => {
101
+ let core = schema;
102
+ let fallback;
103
+ let def = defOf(core);
104
+ while (WRAPPERS.has(def.type) || def.type === "lazy") {
105
+ const inner = def.type === "lazy" ? resolveLazy(core) : def.innerType;
106
+ if (inner === void 0) break;
107
+ if ("defaultValue" in def) fallback = def.defaultValue;
108
+ core = inner;
109
+ def = defOf(core);
110
+ }
111
+ return fallback !== void 0 ? { core, default: fallback } : { core };
112
+ };
113
+ var readMeta = (schema) => {
114
+ const meta = {};
115
+ const title = schema.meta()?.title;
116
+ if (typeof title === "string") meta.title = title;
117
+ if (schema.description !== void 0) meta.description = schema.description;
118
+ return meta;
119
+ };
120
+ var parseField = (schema, walk) => {
121
+ const { core, default: fallback } = unwrap(schema);
122
+ if (walk.stack.has(defOf(core))) {
123
+ walk.targets.add(defOf(core));
124
+ return { kind: "self" };
125
+ }
126
+ const body = (parseByType[defOf(core).type] ?? unknownField)(core, walk);
127
+ const meta = { ...readMeta(core), ...readMeta(schema) };
128
+ return { ...body, ...meta, ...fallback !== void 0 ? { default: fallback } : {} };
129
+ };
130
+ var parse = (schema) => parseField(schema, { stack: /* @__PURE__ */ new Set(), targets: /* @__PURE__ */ new Set() });
131
+ var EMPTY = {
132
+ string: () => "",
133
+ number: () => 0,
134
+ boolean: () => false,
135
+ // No neutral in-domain value: "no selection" is absence (undefined), which
136
+ // an optional enum accepts and a required one flags — unlike null, which a
137
+ // Zod enum rejects outright. Defaults drop undefined, so no stray key.
138
+ enum: () => void 0,
139
+ array: () => [],
140
+ // Each slot built from its own field; a fixed-length list, so no growth.
141
+ tuple: (field, options) => field.kind === "tuple" ? field.items.map((item) => buildDocument(item, options)) : [],
142
+ // A recursion point has no value of its own; the array holding it defaults to [].
143
+ self: () => void 0,
144
+ unknown: () => null,
145
+ object: (field, options) => {
146
+ if (field.kind !== "object") return {};
147
+ const includeOptional = options.includeOptional ?? true;
148
+ const document = {};
149
+ for (const child of field.fields) {
150
+ if (!child.required && !includeOptional) continue;
151
+ const value = buildDocument(child.field, options);
152
+ if (value !== void 0) document[child.key] = value;
153
+ }
154
+ return document;
155
+ },
156
+ // An empty union defaults to its first variant (tag + branch defaults).
157
+ union: (field) => {
158
+ if (field.kind !== "union") return {};
159
+ const first = field.variants[0];
160
+ return first === void 0 ? {} : variantDefaults(first);
161
+ }
162
+ };
163
+ var buildDocument = (field, options) => {
164
+ if (field.default !== void 0) return field.default;
165
+ return (options.empty?.[field.kind] ?? EMPTY[field.kind])(field, options);
166
+ };
167
+ var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
168
+ var variantDefaults = (variant) => {
169
+ const defaults = buildDocument(variant.field, {});
170
+ if (variant.pattern.kind !== "tag") return defaults;
171
+ return { [variant.pattern.key]: variant.pattern.value, ...isRecord(defaults) ? defaults : {} };
172
+ };
173
+
174
+ export { buildDocument, isRecord, parse, variantDefaults };
175
+ //# sourceMappingURL=chunk-TV4U22MY.js.map
176
+ //# sourceMappingURL=chunk-TV4U22MY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/compile/parse.ts"],"names":[],"mappings":";AA6CA,IAAM,KAAA,GAAQ,CAAC,MAAA,KAA4B,MAAA,CAAO,GAAA;AAalD,IAAM,cAAA,GAAiB,S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,QAAA;AAC3C,EAAA,OAAO,EAAE,CAAC,OAAA,CAAQ,OAAA,CAAQ,GAAG,GAAG,OAAA,CAAQ,OAAA,CAAQ,KAAA,EAAO,GAAI,QAAA,CAAS,QAAQ,CAAA,GAAI,QAAA,GAAW,EAAC,EAAG;AACjG","file":"chunk-TV4U22MY.js","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"]}
@@ -0,0 +1,380 @@
1
+ import { defaultCanvasLayout, Roles } from './chunk-PTXRAWJX.js';
2
+ import { buildDocument, isRecord, parse, variantDefaults } from './chunk-TV4U22MY.js';
3
+ import { z } from 'zod';
4
+ import { createLayoutStore, createShell } from '@niscorp/nova';
5
+
6
+ // src/compile/to-nova.ts
7
+ var ERROR_NAMESPACE = "_errors";
8
+ var ITEM = "item";
9
+ var INDEX = "$index";
10
+ var ITEM_EXPR = `$${ITEM}`;
11
+ var LIST_EXPR = "$items";
12
+ var ROOT = { expr: "$", path: "" };
13
+ var child = (loc, key) => ({
14
+ expr: `${loc.expr}.${key}`,
15
+ path: loc.path === "" ? key : `${loc.path}.${key}`
16
+ });
17
+ var itemLoc = (loc) => ({ expr: ITEM_EXPR, path: loc.path === "" ? "*" : `${loc.path}.*` });
18
+ var TEMPLATE_ROOT = { expr: ITEM_EXPR, path: "" };
19
+ var errorBinding = (expr) => expr.startsWith("$.") ? `$.${ERROR_NAMESPACE}.${expr.slice(2)}` : void 0;
20
+ var withProps = (node, props) => Object.keys(props).length > 0 ? { ...node, props } : node;
21
+ var control = (role, expr, props = {}) => withProps({ component: role, model: expr }, props);
22
+ var literal = (data) => data === void 0 ? void 0 : JSON.stringify(data);
23
+ var wrapField = (loc, prop, ctx) => {
24
+ const error = errorBinding(loc.expr);
25
+ return {
26
+ component: Roles.field,
27
+ props: {
28
+ label: prop.field.title ?? prop.key,
29
+ required: prop.required,
30
+ ...error !== void 0 ? { error } : {},
31
+ ...prop.field.description !== void 0 ? { description: prop.field.description } : {}
32
+ },
33
+ children: buildLayout(prop.field, loc, ctx)
34
+ };
35
+ };
36
+ var titleProps = (field) => field.title !== void 0 ? { title: field.title } : {};
37
+ var withTitle = (node, field) => withProps(node, titleProps(field));
38
+ var stringBuild = (field, loc) => control(Roles.text, loc.expr, field.format !== void 0 ? { format: field.format } : {});
39
+ var numberBuild = (field, loc) => control(Roles.number, loc.expr, field.integer ? { integer: true } : {});
40
+ var booleanBuild = (_field, loc) => control(Roles.checkbox, loc.expr);
41
+ var enumBuild = (field, loc) => control(Roles.select, loc.expr, { options: field.options });
42
+ var unknownBuild = (_field, loc) => control(Roles.raw, loc.expr);
43
+ var buildGroup = (field, loc, ctx) => withTitle(
44
+ {
45
+ component: Roles.group,
46
+ children: field.fields.map((prop) => wrapField(child(loc, prop.key), prop, ctx))
47
+ },
48
+ field
49
+ );
50
+ var objectBuild = (field, loc, ctx) => {
51
+ if (field.recursive !== true) return buildGroup(field, loc, ctx);
52
+ const name = ctx.name();
53
+ ctx.templates.push({ name, defaultChild: buildDocument(field, ctx.options), containers: [] });
54
+ ctx.register(name, buildGroup(field, TEMPLATE_ROOT, ctx));
55
+ const inline = buildGroup(field, loc, ctx);
56
+ ctx.templates.pop();
57
+ return inline;
58
+ };
59
+ var tupleBuild = (field, loc, ctx) => withTitle(
60
+ {
61
+ component: Roles.group,
62
+ children: field.items.map(
63
+ (item, index) => wrapField(child(loc, String(index)), { key: String(index + 1), required: true, field: item }, ctx)
64
+ )
65
+ },
66
+ field
67
+ );
68
+ var selfBuild = (_field, loc, ctx) => {
69
+ const template = ctx.templates[ctx.templates.length - 1];
70
+ if (template !== void 0 && loc.expr === ITEM_EXPR) return { ref: template.name };
71
+ return control(Roles.raw, loc.expr);
72
+ };
73
+ var defaultItem = (field, ctx) => field.item.kind === "self" ? ctx.templates[ctx.templates.length - 1]?.defaultChild : buildDocument(field.item, ctx.options);
74
+ var childrenKey = (field) => {
75
+ if (field.kind !== "object") return void 0;
76
+ return field.fields.find((f) => f.field.kind === "array" && f.field.item.kind === "self")?.key;
77
+ };
78
+ var containersOf = (variants) => variants.flatMap((variant) => {
79
+ const key = childrenKey(variant.field);
80
+ return key === void 0 ? [] : [{ label: variant.label, pattern: variant.pattern, defaults: variantDefaults(variant), key }];
81
+ });
82
+ var arrayBuild = (field, loc, ctx) => {
83
+ const containers = field.item.kind === "self" ? ctx.templates[ctx.templates.length - 1]?.containers ?? [] : [];
84
+ const itemRow = {
85
+ component: Roles.arrayItem,
86
+ children: [
87
+ { component: Roles.box, children: buildLayout(field.item, itemLoc(loc), ctx) },
88
+ // the editor cell — grows
89
+ {
90
+ component: Roles.rowMenu,
91
+ model: LIST_EXPR,
92
+ props: { index: INDEX, ...containers.length > 0 ? { containers: literal(containers) } : {} }
93
+ }
94
+ ]
95
+ };
96
+ return withTitle(
97
+ {
98
+ component: Roles.array,
99
+ children: [
100
+ { for: loc.expr, as: ITEM, do: itemRow },
101
+ { component: Roles.append, model: loc.expr, props: { label: "Add", child: literal(defaultItem(field, ctx)) } }
102
+ ]
103
+ },
104
+ field
105
+ );
106
+ };
107
+ var buildVariant = (field, loc, ctx) => withProps(
108
+ {
109
+ component: Roles.variant,
110
+ model: loc.expr,
111
+ // Each branch editor in its own `branch` wrapper, indexed; the widget shows
112
+ // only the one whose index it matched. (Nova hands a component its children
113
+ // as one tree, so the branches need to be individually addressable.) A
114
+ // branch edits the same value, so it shares the union's loc.
115
+ children: field.variants.map((variant, index) => ({
116
+ component: Roles.branch,
117
+ props: { index },
118
+ children: buildLayout(variant.field, loc, ctx)
119
+ }))
120
+ },
121
+ {
122
+ // `childrenKey` lets the chooser carry children when switching between two
123
+ // container variants (and warn before dropping them otherwise). Encoded as
124
+ // a literal: the patterns and defaults carry `$`-bearing data Nova must not
125
+ // resolve.
126
+ branches: literal(
127
+ field.variants.map((variant) => ({
128
+ label: variant.label,
129
+ pattern: variant.pattern,
130
+ defaults: variantDefaults(variant),
131
+ ...childrenKey(variant.field) !== void 0 ? { childrenKey: childrenKey(variant.field) } : {}
132
+ }))
133
+ ),
134
+ ...titleProps(field)
135
+ }
136
+ );
137
+ var variantBuild = (field, loc, ctx) => {
138
+ if (field.recursive !== true) return buildVariant(field, loc, ctx);
139
+ const name = ctx.name();
140
+ const first = field.variants[0];
141
+ ctx.templates.push({ name, defaultChild: first !== void 0 ? variantDefaults(first) : {}, containers: containersOf(field.variants) });
142
+ ctx.register(name, buildVariant(field, TEMPLATE_ROOT, ctx));
143
+ const inline = buildVariant(field, loc, ctx);
144
+ ctx.templates.pop();
145
+ return inline;
146
+ };
147
+ var buildLayout = (field, loc, ctx) => {
148
+ const role = ctx.widgetRole(field, loc.path);
149
+ if (role !== void 0) return control(role, loc.expr);
150
+ switch (field.kind) {
151
+ case "string":
152
+ return stringBuild(field, loc);
153
+ case "number":
154
+ return numberBuild(field, loc);
155
+ case "boolean":
156
+ return booleanBuild(field, loc);
157
+ case "enum":
158
+ return enumBuild(field, loc);
159
+ case "object":
160
+ return objectBuild(field, loc, ctx);
161
+ case "array":
162
+ return arrayBuild(field, loc, ctx);
163
+ case "tuple":
164
+ return tupleBuild(field, loc, ctx);
165
+ case "union":
166
+ return variantBuild(field, loc, ctx);
167
+ case "self":
168
+ return selfBuild(field, loc, ctx);
169
+ case "unknown":
170
+ return unknownBuild(field, loc);
171
+ }
172
+ };
173
+ var toNova = (ir, options = {}) => {
174
+ const layouts = {};
175
+ let counter = 0;
176
+ const matchers = options.widgets ?? [];
177
+ const ctx = {
178
+ register: (name, node) => {
179
+ layouts[name] = node;
180
+ },
181
+ templates: [],
182
+ name: () => `loom:tree:${counter++}`,
183
+ // Match on where the field sits (its structural path) plus its facts.
184
+ widgetRole: (field, path) => matchers.find(
185
+ (matcher) => matcher.match({ kind: field.kind, path, title: field.title, description: field.description })
186
+ )?.role,
187
+ options
188
+ };
189
+ const rootLoc = options.rootKey !== void 0 ? { expr: `$.${options.rootKey}`, path: "" } : ROOT;
190
+ const layout = buildLayout(ir, rootLoc, ctx);
191
+ const value = options.value ?? buildDocument(ir, options);
192
+ const document = options.rootKey !== void 0 ? { [options.rootKey]: value } : value;
193
+ if (!isRecord(document)) {
194
+ throw new Error("loom.toNova: the root document must be an object (or use rootKey).");
195
+ }
196
+ const action = {
197
+ id: options.id ?? "loom-form",
198
+ data: document,
199
+ layout
200
+ };
201
+ return { action, layouts };
202
+ };
203
+
204
+ // src/validate.ts
205
+ var setPath = (root, path, message) => {
206
+ let node = root;
207
+ for (let i = 0; i < path.length - 1; i += 1) {
208
+ const key = String(path[i]);
209
+ const next = node[key];
210
+ node = typeof next === "object" && next !== null ? next : node[key] = {};
211
+ }
212
+ const leaf = String(path[path.length - 1]);
213
+ if (!(leaf in node)) node[leaf] = message;
214
+ };
215
+ var errorTree = (issues) => {
216
+ const tree = {};
217
+ for (const issue of issues) {
218
+ if (issue.path.length > 0) setPath(tree, issue.path, issue.message);
219
+ }
220
+ return tree;
221
+ };
222
+ var stripErrors = (data) => {
223
+ const { [ERROR_NAMESPACE]: _omit, ...document } = data;
224
+ return document;
225
+ };
226
+ var attachValidation = (shell, instanceId, schema, onDocument) => {
227
+ const runtime = shell.getRuntime(instanceId);
228
+ if (runtime === void 0) return () => {
229
+ };
230
+ let lastDocument = "";
231
+ const handle = (data) => {
232
+ const document = stripErrors(data);
233
+ const fingerprint = JSON.stringify(document);
234
+ if (fingerprint === lastDocument) return;
235
+ lastDocument = fingerprint;
236
+ const result = schema.safeParse(document);
237
+ const errors = result.success ? {} : errorTree(result.error.issues);
238
+ runtime.setData({ ...document, [ERROR_NAMESPACE]: errors });
239
+ onDocument?.(document);
240
+ };
241
+ return shell.onDataChange((change) => {
242
+ if (change.instanceId === instanceId) handle(change.data);
243
+ });
244
+ };
245
+ var formCanvas = (document) => `form:${document}`;
246
+ var ROOT_KEY = "$root";
247
+ var needsWrap = (document) => parse(document).kind !== "object";
248
+ var stripErrors2 = (data) => {
249
+ const { [ERROR_NAMESPACE]: _omit, ...document } = data;
250
+ return document;
251
+ };
252
+ var createLoomEditor = (config) => {
253
+ const plugins = /* @__PURE__ */ new Map();
254
+ const listeners = { change: /* @__PURE__ */ new Set(), open: /* @__PURE__ */ new Set() };
255
+ const emit = (event) => listeners[event].forEach((handler) => handler());
256
+ const store = createLayoutStore();
257
+ const shell = createShell({
258
+ canvases: [],
259
+ registry: config.registry,
260
+ actions: {},
261
+ layoutStore: store
262
+ });
263
+ let active;
264
+ let formInstances = {};
265
+ let wrappedDocs = /* @__PURE__ */ new Set();
266
+ let formCanvasIds = [];
267
+ let documents = {};
268
+ let validations = {};
269
+ let detach = [];
270
+ const refresh = () => {
271
+ const nextDocs = {};
272
+ const nextProblems = {};
273
+ for (const [name, instanceId] of Object.entries(formInstances)) {
274
+ const data = shell.getRuntime(instanceId)?.getData() ?? {};
275
+ const document = stripErrors2(data);
276
+ const problems = data[ERROR_NAMESPACE] ?? {};
277
+ if (wrappedDocs.has(name)) {
278
+ nextDocs[name] = document[ROOT_KEY];
279
+ nextProblems[name] = problems[ROOT_KEY] ?? {};
280
+ } else {
281
+ nextDocs[name] = document;
282
+ nextProblems[name] = problems;
283
+ }
284
+ }
285
+ documents = nextDocs;
286
+ validations = nextProblems;
287
+ };
288
+ const clearForms = () => {
289
+ detach.forEach((off) => off());
290
+ detach = [];
291
+ for (const canvasId of formCanvasIds) shell.removeCanvas(canvasId);
292
+ formCanvasIds = [];
293
+ formInstances = {};
294
+ wrappedDocs = /* @__PURE__ */ new Set();
295
+ };
296
+ const open = (artifact) => {
297
+ const plugin = plugins.get(artifact.type);
298
+ if (plugin === void 0) throw new Error(`loom editor: no plugin '${artifact.type}'`);
299
+ clearForms();
300
+ active = plugin;
301
+ for (const [name, document] of Object.entries(plugin.documents)) {
302
+ const canvasId = formCanvas(name);
303
+ let action;
304
+ if (typeof document === "function") {
305
+ const value = artifact.documents?.[name];
306
+ action = { id: canvasId, data: isRecord(value) ? value : {}, layout: document(value) };
307
+ } else {
308
+ const ir = parse(document);
309
+ const wrap = needsWrap(document);
310
+ if (wrap) wrappedDocs.add(name);
311
+ const value = artifact.documents?.[name] ?? buildDocument(ir, {});
312
+ const built = toNova(ir, {
313
+ id: canvasId,
314
+ ...wrap ? { rootKey: ROOT_KEY } : {},
315
+ ...isRecord(value) ? { value } : {},
316
+ widgets: plugin.widgets ?? []
317
+ });
318
+ for (const [id, node] of Object.entries(built.layouts)) store.set(id, node);
319
+ action = built.action;
320
+ }
321
+ shell.registerAction(action);
322
+ shell.addCanvas({ id: canvasId, initial: action.id });
323
+ formCanvasIds.push(canvasId);
324
+ const instanceId = shell.getCanvasState(canvasId).active?.id;
325
+ if (instanceId !== void 0) formInstances[name] = instanceId;
326
+ }
327
+ for (const [name, instanceId] of Object.entries(formInstances)) {
328
+ const document = plugin.documents[name];
329
+ if (typeof document !== "function" && document !== void 0) {
330
+ const schema = wrappedDocs.has(name) ? z.object({ [ROOT_KEY]: document }) : document;
331
+ detach.push(attachValidation(shell, instanceId, schema));
332
+ }
333
+ }
334
+ detach.push(
335
+ shell.onDataChange((change) => {
336
+ if (!Object.values(formInstances).includes(change.instanceId)) return;
337
+ refresh();
338
+ emit("change");
339
+ })
340
+ );
341
+ const viewIds = Object.keys(shell.getState().canvases).filter((id) => !formCanvasIds.includes(id)).sort((a, b) => Number(a.startsWith("loom:")) - Number(b.startsWith("loom:")));
342
+ shell.setCanvasLayout(defaultCanvasLayout(formCanvasIds, viewIds));
343
+ refresh();
344
+ emit("open");
345
+ emit("change");
346
+ };
347
+ const editor = {
348
+ get shell() {
349
+ return shell;
350
+ },
351
+ get plugin() {
352
+ return active;
353
+ },
354
+ get documents() {
355
+ return documents;
356
+ },
357
+ get validations() {
358
+ return validations;
359
+ },
360
+ loadPlugin: (plugin) => {
361
+ plugins.set(plugin.name, plugin);
362
+ plugin.mount?.(editor);
363
+ },
364
+ open,
365
+ on: (event, handler) => {
366
+ listeners[event].add(handler);
367
+ return () => listeners[event].delete(handler);
368
+ },
369
+ dispose: () => {
370
+ detach.forEach((off) => off());
371
+ detach = [];
372
+ shell.dispose();
373
+ }
374
+ };
375
+ return editor;
376
+ };
377
+
378
+ export { ERROR_NAMESPACE, attachValidation, createLoomEditor, toNova };
379
+ //# sourceMappingURL=chunk-X7PCPONB.js.map
380
+ //# sourceMappingURL=chunk-X7PCPONB.js.map