form-value.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. import type { FormBranch, FormFieldSchema, FormSchema } from "./form-schema.js";
  2. /**
  3. * Form value model (E3). The working value of a form is a plain JSON object.
  4. * Load: `applyValue` coerces a parsed def into the working shape while keeping
  5. * unknown fields (lossless — saving must not drop data). Create: `initialValue`
  6. * builds a blank def. Save: `coerceForValidate` produces the JSON handed to
  7. * `contentSchemas[kind].safeParse` — optional fields emptied by the user are
  8. * dropped, `any`-typed strings are parsed back to numbers/booleans.
  9. *
  10. * Roundtrip guarantee: for a valid def, `coerceForValidate(applyValue(def))`
  11. * is JSON-identical to `def` when nothing was edited.
  12. */
  13. const DROP: unique symbol = Symbol("drop");
  14. /** A missing form field is omitted from the saved def (documented E3 rule:
  15. * optional fields emptied by the form stay absent). */
  16. type CoerceResult = unknown | typeof DROP;
  17. export function initialValue(schema: FormSchema): Record<string, unknown> {
  18. const out: Record<string, unknown> = {};
  19. for (const field of schema.fields) {
  20. if (!field.optional) out[field.name] = initialFieldValue(field);
  21. }
  22. return out;
  23. }
  24. export function initialItemValue(element: FormFieldSchema): unknown {
  25. return initialFieldValue(element);
  26. }
  27. function initialFieldValue(field: FormFieldSchema): unknown {
  28. switch (field.type) {
  29. case "string":
  30. case "ref":
  31. case "any":
  32. return "";
  33. case "enum": {
  34. const values = field.enumValues ?? [];
  35. return values[0] ?? "";
  36. }
  37. case "number":
  38. return 0;
  39. case "boolean":
  40. return false;
  41. case "array":
  42. return [];
  43. case "object": {
  44. const out: Record<string, unknown> = {};
  45. for (const f of field.fields ?? []) {
  46. if (!f.optional) out[f.name] = initialFieldValue(f);
  47. }
  48. return out;
  49. }
  50. case "union": {
  51. const first = field.branches?.[0];
  52. return first !== undefined ? branchInitial(field, first) : {};
  53. }
  54. case "record":
  55. return {};
  56. }
  57. }
  58. /** Initial JSON for a union branch (used when the branch selector changes). */
  59. export function branchInitial(field: FormFieldSchema, branch: FormBranch): Record<string, unknown> {
  60. const out: Record<string, unknown> = {};
  61. if (field.discriminator !== undefined) {
  62. out[field.discriminator] = branch.discriminatorValues?.[0] ?? branch.id;
  63. }
  64. for (const f of branch.fields ?? []) {
  65. if (!f.optional) out[f.name] = initialFieldValue(f);
  66. }
  67. return out;
  68. }
  69. /** The standalone value for a branch: a literal string for primitive branches,
  70. * the branch object for object branches. */
  71. export function unionBranchValue(field: FormFieldSchema, branch: FormBranch): unknown {
  72. if (branch.primitive !== undefined) {
  73. if (branch.primitive.type === "enum") return branch.primitive.enumValues?.[0] ?? "";
  74. if (branch.primitive.type === "number") return 0;
  75. if (branch.primitive.type === "boolean") return false;
  76. return "";
  77. }
  78. if (branch.nested !== undefined) return initialFieldValue(branch.nested);
  79. return branchInitial(field, branch);
  80. }
  81. /** Which union branch a value currently selects (first matching branch; for
  82. * discriminated unions the discriminator field's value wins). */
  83. export function detectUnionBranch(field: FormFieldSchema, value: unknown): FormBranch | null {
  84. const branches = field.branches ?? [];
  85. if (branches.length === 0) return null;
  86. if (field.discriminator !== undefined) {
  87. if (isPlainObject(value)) {
  88. const discriminator = value[field.discriminator];
  89. if (typeof discriminator === "string") {
  90. for (const branch of branches) {
  91. if ((branch.discriminatorValues ?? [branch.id]).includes(discriminator)) return branch;
  92. }
  93. }
  94. }
  95. return branches[0] ?? null;
  96. }
  97. if (!isPlainObject(value)) {
  98. for (const branch of branches) {
  99. if (branch.primitive !== undefined && primitiveMatches(branch.primitive, value)) return branch;
  100. }
  101. return branches[0] ?? null;
  102. }
  103. for (const branch of branches) {
  104. if (branchMatches(branch, value)) return branch;
  105. }
  106. return branches[0] ?? null;
  107. }
  108. export function applyValue(schema: FormSchema, json: unknown): Record<string, unknown> {
  109. if (!isPlainObject(json)) return initialValue(schema);
  110. return applyObject(schema.fields, json);
  111. }
  112. function applyObject(fields: FormFieldSchema[], json: Record<string, unknown>): Record<string, unknown> {
  113. const out: Record<string, unknown> = {};
  114. const byName = new Map<string, FormFieldSchema>();
  115. for (const f of fields) byName.set(f.name, f);
  116. for (const [key, value] of Object.entries(json)) {
  117. const field = byName.get(key);
  118. if (field === undefined) {
  119. out[key] = value;
  120. } else {
  121. out[key] = applyField(field, value);
  122. }
  123. }
  124. for (const field of fields) {
  125. if (!field.optional && !(field.name in out)) out[field.name] = initialFieldValue(field);
  126. }
  127. return out;
  128. }
  129. function applyField(field: FormFieldSchema, value: unknown): unknown {
  130. switch (field.type) {
  131. case "string":
  132. case "ref":
  133. if (value === null && field.nullable === true) return null;
  134. return coerceString(value);
  135. case "enum":
  136. return value;
  137. case "number":
  138. return coerceNumber(value);
  139. case "boolean":
  140. return coerceBoolean(value);
  141. case "any":
  142. return value;
  143. case "array": {
  144. if (!Array.isArray(value)) return [];
  145. const element = field.element;
  146. if (element === undefined) return value;
  147. return value.map((item) => applyField(element, item));
  148. }
  149. case "object": {
  150. if (!isPlainObject(value)) return initialFieldValue(field);
  151. return applyObject(field.fields ?? [], value);
  152. }
  153. case "union": {
  154. const branch = detectUnionBranch(field, value);
  155. if (branch === null) {
  156. const first = field.branches?.[0];
  157. return first !== undefined ? unionBranchValue(field, first) : value;
  158. }
  159. if (branch.primitive !== undefined) return value;
  160. if (branch.nested !== undefined) return applyField(branch.nested, value);
  161. if (!isPlainObject(value)) return branchInitial(field, branch);
  162. return applyObject(branch.fields ?? [], value);
  163. }
  164. case "record": {
  165. if (!isPlainObject(value)) return {};
  166. const valueField = field.recordValue;
  167. if (valueField === undefined) return value;
  168. const out: Record<string, unknown> = {};
  169. for (const [key, entry] of Object.entries(value)) out[key] = applyField(valueField, entry);
  170. return out;
  171. }
  172. }
  173. }
  174. export function coerceForValidate(schema: FormSchema, value: Record<string, unknown>): Record<string, unknown> {
  175. return coerceObject(schema.fields, value);
  176. }
  177. function coerceObject(fields: FormFieldSchema[], value: Record<string, unknown>): Record<string, unknown> {
  178. const out: Record<string, unknown> = {};
  179. const byName = new Map<string, FormFieldSchema>();
  180. for (const f of fields) byName.set(f.name, f);
  181. for (const [key, raw] of Object.entries(value)) {
  182. const field = byName.get(key);
  183. if (field === undefined) {
  184. out[key] = raw;
  185. continue;
  186. }
  187. const coerced = coerceField(field, raw);
  188. if (coerced !== DROP) out[key] = coerced;
  189. }
  190. return out;
  191. }
  192. function coerceField(field: FormFieldSchema, raw: unknown): CoerceResult {
  193. if (raw === undefined) return field.optional ? DROP : undefined;
  194. switch (field.type) {
  195. case "string":
  196. case "ref":
  197. if (raw === "") return field.optional ? DROP : raw;
  198. if (raw === null) return field.nullable === true ? null : field.optional ? DROP : "";
  199. if (typeof raw === "string") return raw;
  200. return String(raw);
  201. case "enum":
  202. if (raw === "") return field.optional ? DROP : raw;
  203. return typeof raw === "string" ? raw : (field.enumValues?.[0] ?? "");
  204. case "number": {
  205. if (raw === null) return field.optional ? DROP : raw;
  206. if (typeof raw === "number") return Number.isFinite(raw) ? raw : field.optional ? DROP : raw;
  207. if (typeof raw === "string") {
  208. const trimmed = raw.trim();
  209. if (trimmed === "") return field.optional ? DROP : raw;
  210. const n = Number(trimmed);
  211. return Number.isFinite(n) ? n : raw;
  212. }
  213. if (typeof raw === "boolean") return raw ? 1 : 0;
  214. return raw;
  215. }
  216. case "boolean":
  217. if (raw === "true") return true;
  218. if (raw === "false") return false;
  219. return Boolean(raw);
  220. case "any":
  221. return coerceAny(raw);
  222. case "array": {
  223. if (!Array.isArray(raw)) return [];
  224. const element = field.element;
  225. if (element === undefined) return raw;
  226. const out: unknown[] = [];
  227. for (const item of raw) {
  228. const coerced = coerceField(element, item);
  229. if (coerced !== DROP) out.push(coerced);
  230. }
  231. return out;
  232. }
  233. case "object":
  234. return isPlainObject(raw) ? coerceObject(field.fields ?? [], raw) : {};
  235. case "union": {
  236. const branch = detectUnionBranch(field, raw);
  237. if (branch === null) return raw;
  238. if (branch.primitive !== undefined) {
  239. if (typeof raw === "string") return raw;
  240. return unionBranchValue(field, branch);
  241. }
  242. if (branch.nested !== undefined) return coerceField(branch.nested, raw);
  243. if (!isPlainObject(raw)) return branchInitial(field, branch);
  244. return coerceObject(branch.fields ?? [], raw);
  245. }
  246. case "record": {
  247. if (!isPlainObject(raw)) return {};
  248. const valueField = field.recordValue;
  249. if (valueField === undefined) return raw;
  250. const out: Record<string, unknown> = {};
  251. for (const [key, entry] of Object.entries(raw)) {
  252. const coerced = coerceField(valueField, entry);
  253. if (coerced !== DROP) out[key] = coerced;
  254. }
  255. return out;
  256. }
  257. }
  258. }
  259. function coerceAny(value: unknown): unknown {
  260. if (typeof value !== "string") return value;
  261. const trimmed = value.trim();
  262. if (trimmed === "") return value;
  263. // Only coerce when the conversion round-trips EXACTLY — "007", "1.50", "1e3"
  264. // and friends stay strings (a save must never silently rewrite untouched
  265. // any-field values; "007" → 7 is data corruption).
  266. if (/^-?\d+(\.\d+)?$/.test(trimmed)) {
  267. const n = Number(trimmed);
  268. if (Number.isFinite(n) && String(n) === trimmed) return n;
  269. }
  270. if (trimmed === "true") return true;
  271. if (trimmed === "false") return false;
  272. return value;
  273. }
  274. /** Read a value at a path (arrays index by number). */
  275. export function getPath(value: Record<string, unknown>, path: readonly (string | number)[]): unknown {
  276. let current: unknown = value;
  277. for (const key of path) {
  278. if (typeof current !== "object" || current === null) return undefined;
  279. const container = current as Record<string | number, unknown>;
  280. const next = container[key];
  281. if (next === undefined) return undefined;
  282. current = next;
  283. }
  284. return current;
  285. }
  286. /** Mutate the working value at a path, creating intermediate objects/arrays. */
  287. export function setPath(value: Record<string, unknown>, path: readonly (string | number)[], next: unknown): void {
  288. if (path.length === 0) return;
  289. let current: Record<string | number, unknown> = value;
  290. for (let i = 0; i < path.length - 1; i++) {
  291. const key = path[i];
  292. if (key === undefined) return;
  293. const existing = current[key];
  294. if (typeof existing === "object" && existing !== null) {
  295. current = existing as Record<string | number, unknown>;
  296. } else {
  297. const fresh = containerFor(path[i + 1]);
  298. current[key] = fresh;
  299. current = fresh;
  300. }
  301. }
  302. const last = path[path.length - 1];
  303. if (last !== undefined) current[last] = next;
  304. }
  305. /** A path segment that indexes into an array needs an array container; an
  306. * object field name needs an object. */
  307. function containerFor(nextKey: string | number | undefined): Record<string | number, unknown> {
  308. return (typeof nextKey === "number" ? [] : {}) as unknown as Record<string | number, unknown>;
  309. }
  310. function branchMatches(branch: FormBranch, value: Record<string, unknown>): boolean {
  311. if (branch.nested !== undefined) return detectUnionBranch(branch.nested, value) !== null;
  312. const fields = branch.fields ?? [];
  313. if (fields.length === 0) return Object.keys(value).length === 0;
  314. for (const f of fields) {
  315. if (f.optional) continue;
  316. const entry = value[f.name];
  317. if (entry === undefined) return false;
  318. if (f.type === "enum") {
  319. const values = f.enumValues ?? [];
  320. if (typeof entry !== "string" || !values.includes(entry)) return false;
  321. }
  322. }
  323. return true;
  324. }
  325. function primitiveMatches(primitive: NonNullable<FormBranch["primitive"]>, value: unknown): boolean {
  326. if (primitive.type === "enum") {
  327. const values = primitive.enumValues ?? [];
  328. return typeof value === "string" && values.includes(value);
  329. }
  330. if (primitive.type === "number") return typeof value === "number";
  331. if (primitive.type === "boolean") return typeof value === "boolean";
  332. return typeof value === "string";
  333. }
  334. function coerceString(value: unknown): string {
  335. if (typeof value === "string") return value;
  336. if (value === null || value === undefined) return "";
  337. return String(value);
  338. }
  339. function coerceNumber(value: unknown): number {
  340. if (typeof value === "number") return Number.isFinite(value) ? value : 0;
  341. if (typeof value === "string") {
  342. const n = Number(value.trim());
  343. return Number.isFinite(n) ? n : 0;
  344. }
  345. if (typeof value === "boolean") return value ? 1 : 0;
  346. return 0;
  347. }
  348. function coerceBoolean(value: unknown): boolean {
  349. if (typeof value === "boolean") return value;
  350. if (value === "true") return true;
  351. if (value === "false") return false;
  352. return Boolean(value);
  353. }
  354. export function isPlainObject(value: unknown): value is Record<string, unknown> {
  355. return typeof value === "object" && value !== null && !Array.isArray(value);
  356. }