@a-ludi/rjsf-formulas 0.6.0 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +175 -169
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","sources":["../src/analyzeSchema.ts","../node_modules/fast-deep-equal/index.js","../src/buildContext.ts","../src/enrich.ts","../src/useAsyncFormulas.ts","../src/mergeReadOnly.ts","../src/FormulaForm.tsx"],"sourcesContent":["import type { RJSFSchema } from '@rjsf/utils'\nimport { findSchemaDefinition } from '@rjsf/utils'\n\n/**\n * Sentinel used in formula field paths to represent a uniform array item position.\n * @internal\n */\nexport const ARRAY_INDEX: unique symbol = Symbol('arrayIndex')\n\n/** @internal */\nexport type ArrayIndex = typeof ARRAY_INDEX\n\n/**\n * Controls which values are injected into the formula evaluation context.\n *\n * - `'siblings'` (default): only the sibling fields of the computed field are available by name.\n * - `'extended'`: full form data and the field's resolved path are injected alongside sibling\n * values, under the keys configured by `formulaDataKey` and `formulaPathKey`.\n *\n * Set via the `x-formula-context` schema key (or the `formulaContextKey` prop).\n */\nexport type ContextMode = 'siblings' | 'extended'\n\n/**\n * Describes a single computed field discovered by {@link analyzeSchema}.\n */\nexport type FormulaField = {\n /** JSON path to the field within the form data. Uniform array item positions are represented by {@link ARRAY_INDEX}. */\n path: (string | number | ArrayIndex)[]\n /** The raw formula string from the schema. */\n formula: string\n /** Which values are available when evaluating this field's formula. */\n contextMode: ContextMode\n /**\n * The schema condition under which this formula is active.\n *\n * - `true` — always active (fields from `properties`, `items`, `prefixItems`, or `allOf` branches).\n * - `RJSFSchema` — a conditional schema (a `oneOf`/`anyOf` branch condition, possibly composed\n * via `{ allOf: [...] }` for nested branches).\n */\n condition: RJSFSchema | true\n}\n\n/**\n * Options for {@link analyzeSchema}.\n */\nexport type AnalyzeSchemaOptions = {\n /** Schema key that marks a field as computed. Defaults to `'x-formula'`. */\n formulaKey?: string\n /** Schema key that selects the context mode for a computed field. Defaults to `'x-formula-context'`. */\n formulaContextKey?: string\n /**\n * What to do when multiple `allOf` branches define a formula for the same path.\n *\n * - `'ignore'`: silently take the last definition.\n * - `'warn'` (default): emit `console.warn` and take the last definition.\n * - `'error'`: throw a `TypeError` synchronously.\n */\n formulaConflictBehavior?: 'ignore' | 'warn' | 'error'\n}\n\n/**\n * Scans a JSON Schema and returns descriptors for every field that carries a formula key.\n *\n * @remarks\n * Traversal is depth-first. `allOf`, `$ref`, `oneOf`, and `anyOf` are all supported.\n * `allOf` branches are merged with conflict detection. `oneOf`/`anyOf` branches are each\n * recursed and fields are collected with the branch schema as the `condition`. Nested\n * `oneOf`/`anyOf` conditions are composed via `{ allOf: [...] }`. `$ref` is resolved\n * synchronously using `findSchemaDefinition` (external refs will throw).\n *\n * @param schema - The root RJSF schema to scan.\n * @param options - Optional key overrides for locating formulas in the schema.\n * @returns An array of {@link FormulaField} descriptors, one per computed field found.\n *\n * @example\n * ```ts\n * import { analyzeSchema } from '@a-ludi/rjsf-formulas'\n *\n * const fields = analyzeSchema({\n * type: 'object',\n * properties: {\n * price: { type: 'number' },\n * total: { type: 'number', 'x-formula': 'price * 2' },\n * },\n * })\n * // fields[0].path => ['total']\n * // fields[0].formula => 'price * 2'\n * ```\n */\nexport function analyzeSchema(\n schema: RJSFSchema,\n options?: AnalyzeSchemaOptions\n): FormulaField[] {\n const formulaKey = options?.formulaKey ?? 'x-formula'\n const formulaContextKey = options?.formulaContextKey ?? 'x-formula-context'\n const formulaConflictBehavior = options?.formulaConflictBehavior ?? 'warn'\n const fields: FormulaField[] = []\n traverse(schema, [], fields, formulaKey, formulaContextKey, formulaConflictBehavior, true, schema)\n return fields\n}\n\n/**\n * Compose an ambient condition with a new branch schema.\n *\n * - If `ambient === true`: returns `branch` directly (no wrapping needed).\n * - If `ambient` already has an `allOf`: appends `branch` to that array.\n * - Otherwise: wraps both in `{ allOf: [ambient, branch] }`.\n */\nfunction composeCondition(ambient: RJSFSchema | true, branch: RJSFSchema): RJSFSchema {\n if (ambient === true) return branch\n const ambientAny = ambient as Record<string, unknown>\n if (Array.isArray(ambientAny['allOf'])) {\n return { allOf: [...(ambientAny['allOf'] as RJSFSchema[]), branch] }\n }\n return { allOf: [ambient, branch] }\n}\n\nfunction resolveContextMode(\n value: unknown,\n path: (string | number | ArrayIndex)[]\n): ContextMode {\n if (value === undefined || value === 'siblings') return 'siblings'\n if (value === 'extended') return 'extended'\n console.warn(\n `[rjsf-formulas] Unknown x-formula-context value \"${value}\" at path [${formatPath(path)}], treating as \"siblings\"`\n )\n return 'siblings'\n}\n\nfunction formatPath(path: (string | number | ArrayIndex)[]): string {\n return path.map(s => (typeof s === 'symbol' ? '[*]' : String(s))).join(', ')\n}\n\nfunction pathKey(path: (string | number | ArrayIndex)[]): string {\n return path.map(s => (typeof s === 'symbol' ? '[*]' : String(s))).join('.')\n}\n\nfunction applyConflictBehavior(\n existing: FormulaField,\n incoming: FormulaField,\n behavior: 'ignore' | 'warn' | 'error'\n): void {\n const key = pathKey(existing.path)\n if (behavior === 'error') {\n throw new TypeError(\n `[rjsf-formulas] Formula conflict at path [${formatPath(existing.path)}]: \"${existing.formula}\" vs \"${incoming.formula}\". Resolve the conflict or set formulaConflictBehavior to 'ignore' or 'warn'.`\n )\n }\n if (behavior === 'warn') {\n console.warn(\n `[rjsf-formulas] Formula conflict at path [${key}]: \"${existing.formula}\" (earlier allOf branch) is overridden by \"${incoming.formula}\" (later allOf branch).`\n )\n }\n}\n\nfunction mergeFields(\n base: FormulaField[],\n incoming: FormulaField[],\n behavior: 'ignore' | 'warn' | 'error'\n): void {\n for (const field of incoming) {\n const key = pathKey(field.path)\n const existingIndex = base.findIndex(f => pathKey(f.path) === key)\n if (existingIndex !== -1) {\n applyConflictBehavior(base[existingIndex], field, behavior)\n base[existingIndex] = field\n } else {\n base.push(field)\n }\n }\n}\n\nfunction traverse(\n schema: RJSFSchema,\n path: (string | number | ArrayIndex)[],\n fields: FormulaField[],\n formulaKey: string,\n formulaContextKey: string,\n formulaConflictBehavior: 'ignore' | 'warn' | 'error',\n ambientCondition: RJSFSchema | true,\n rootSchema: RJSFSchema\n): void {\n const schemaAny = schema as Record<string, unknown>\n\n // $ref — resolve and continue traversal with the same ambientCondition\n if (typeof schemaAny['$ref'] === 'string') {\n const resolved = findSchemaDefinition(schemaAny['$ref'] as string, rootSchema)\n traverse(resolved, path, fields, formulaKey, formulaContextKey, formulaConflictBehavior, ambientCondition, rootSchema)\n return\n }\n\n // Rule 1: computed field — record and stop\n if (formulaKey in schema) {\n const formula = schemaAny[formulaKey]\n if (typeof formula !== 'string') {\n console.warn(\n `[rjsf-formulas] Formula at path [${formatPath(path)}] is not a string (got ${typeof formula}), skipping.`\n )\n return\n }\n fields.push({\n path,\n formula,\n contextMode: resolveContextMode(schemaAny[formulaContextKey], path),\n condition: ambientCondition,\n })\n return\n }\n\n // Rule 2: object — recurse into properties (type: 'object' is implicit when properties are present)\n const isArray = schema.type === 'array' ||\n (schema.type == null && (Array.isArray(schemaAny['prefixItems']) || schema.items != null))\n if (schema.properties && !isArray) {\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n traverse(\n propSchema as RJSFSchema,\n [...path, key],\n fields,\n formulaKey,\n formulaContextKey,\n formulaConflictBehavior,\n ambientCondition,\n rootSchema\n )\n }\n }\n\n // Rule 3: array — recurse into prefixItems and/or items (type: 'array' is implicit when items/prefixItems are present)\n if (isArray) {\n // Rule 3a: prefixItems (tuple positions with static indices)\n if (Array.isArray(schemaAny['prefixItems'])) {\n const prefixItems = schemaAny['prefixItems'] as RJSFSchema[]\n prefixItems.forEach((itemSchema, index) => {\n traverse(itemSchema, [...path, index], fields, formulaKey, formulaContextKey, formulaConflictBehavior, ambientCondition, rootSchema)\n })\n }\n\n // Rule 3b: items as array (legacy draft-07 tuple — positional schemas, equivalent to prefixItems)\n if (Array.isArray(schema.items)) {\n ;(schema.items as RJSFSchema[]).forEach((itemSchema, index) => {\n traverse(itemSchema, [...path, index], fields, formulaKey, formulaContextKey, formulaConflictBehavior, ambientCondition, rootSchema)\n })\n }\n\n // Rule 3c: items as object (uniform array — all elements share one schema)\n if (schema.items && !Array.isArray(schema.items)) {\n traverse(\n schema.items as RJSFSchema,\n [...path, ARRAY_INDEX],\n fields,\n formulaKey,\n formulaContextKey,\n formulaConflictBehavior,\n ambientCondition,\n rootSchema\n )\n }\n }\n\n // Rule 4: allOf — recurse into each branch, then merge with conflict detection\n // allOf does not add to the condition — branches are always active within their parent's condition\n if (Array.isArray(schemaAny['allOf'])) {\n const allOfBranches = schemaAny['allOf'] as RJSFSchema[]\n for (const branch of allOfBranches) {\n const branchFields: FormulaField[] = []\n traverse(branch, path, branchFields, formulaKey, formulaContextKey, formulaConflictBehavior, ambientCondition, rootSchema)\n mergeFields(fields, branchFields, formulaConflictBehavior)\n }\n }\n\n // Rule 5: oneOf / anyOf — recurse each branch with a composed condition\n for (const compositionKey of ['oneOf', 'anyOf'] as const) {\n if (Array.isArray(schemaAny[compositionKey])) {\n const branches = schemaAny[compositionKey] as RJSFSchema[]\n for (const branch of branches) {\n const branchCondition = composeCondition(ambientCondition, branch)\n traverse(branch, path, fields, formulaKey, formulaContextKey, formulaConflictBehavior, branchCondition, rootSchema)\n }\n }\n }\n\n // Rule 6: if/then/else — traverse then/else with appropriate conditions; warn if formula found in if\n if ('if' in schemaAny) {\n const ifSchema = schemaAny['if'] as RJSFSchema\n const thenSchema = schemaAny['then'] as RJSFSchema | undefined\n const elseSchema = schemaAny['else'] as RJSFSchema | undefined\n\n // Warn if the if schema itself contains a formula key (it is never rendered by RJSF)\n if (formulaKey in (ifSchema as Record<string, unknown>)) {\n console.warn(\n `[rjsf-formulas] Formula key \"${formulaKey}\" found inside an \"if\" schema at path [${formatPath(path)}]. The \"if\" schema is a validation predicate and is never rendered — the formula will be ignored.`\n )\n }\n\n if (thenSchema !== undefined) {\n const thenCondition = composeCondition(ambientCondition, ifSchema)\n traverse(thenSchema, path, fields, formulaKey, formulaContextKey, formulaConflictBehavior, thenCondition, rootSchema)\n }\n\n if (elseSchema !== undefined) {\n const elseCondition = composeCondition(ambientCondition, { not: ifSchema })\n traverse(elseSchema, path, fields, formulaKey, formulaContextKey, formulaConflictBehavior, elseCondition, rootSchema)\n }\n }\n}\n","'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n","import type { FormulaField } from './analyzeSchema'\n\nexport type BuildContextOptions = {\n formulaDataKey: string\n formulaPathKey: string\n}\n\nexport function buildContext(\n field: FormulaField,\n resolvedPath: (string | number)[],\n candidateFormData: unknown,\n options: BuildContextOptions\n): object {\n const parentPath = resolvedPath.slice(0, -1)\n const parent = parentPath.reduce<unknown>((curr, key) => {\n if (curr == null || typeof curr !== 'object') return undefined\n return (curr as Record<string | number, unknown>)[key]\n }, candidateFormData)\n\n const siblings =\n parent != null && typeof parent === 'object' && !Array.isArray(parent)\n ? { ...(parent as object) }\n : {}\n\n if (field.contextMode === 'extended') {\n if (options.formulaDataKey in siblings || options.formulaPathKey in siblings) {\n console.warn(\n `[rjsf-formulas] Extended context key collision: sibling field named \"${\n options.formulaDataKey in siblings ? options.formulaDataKey : options.formulaPathKey\n }\" will be overwritten by the injected context. Use formulaDataKey/formulaPathKey props to choose a different key.`\n )\n }\n return {\n ...siblings,\n [options.formulaDataKey]: candidateFormData,\n [options.formulaPathKey]: [...resolvedPath],\n }\n }\n\n return siblings\n}\n","import equal from 'fast-deep-equal'\nimport type { RJSFSchema } from '@rjsf/utils'\nimport type { FormulaField, ArrayIndex } from './analyzeSchema'\nimport { ARRAY_INDEX } from './analyzeSchema'\nimport { buildContext } from './buildContext'\nimport type { BuildContextOptions } from './buildContext'\n\nexport { ARRAY_INDEX }\n\nfunction formatPath(path: (string | number | ArrayIndex)[]): string {\n return path.map(s => (typeof s === 'symbol' ? '[*]' : String(s))).join(', ')\n}\n\nexport function getAt(data: unknown, path: (string | number)[]): unknown {\n return path.reduce<unknown>((curr, key) => {\n if (curr == null || typeof curr !== 'object') return undefined\n return (curr as Record<string | number, unknown>)[key]\n }, data)\n}\n\nexport function setAt(data: unknown, path: (string | number)[], value: unknown): void {\n if (path.length === 0) return\n const parent = getAt(data, path.slice(0, -1))\n if (parent != null && typeof parent === 'object') {\n ;(parent as Record<string | number, unknown>)[path[path.length - 1]] = value\n }\n}\n\nexport function expandPaths(\n templatePath: (string | number | ArrayIndex)[],\n data: unknown,\n currentPath: (string | number)[] = []\n): (string | number)[][] {\n if (templatePath.length === 0) return [currentPath]\n const [head, ...rest] = templatePath\n if (head === ARRAY_INDEX) {\n const arr = getAt(data, currentPath)\n if (!Array.isArray(arr)) return []\n const results: (string | number)[][] = []\n for (let i = 0; i < arr.length; i++) {\n results.push(...expandPaths(rest, data, [...currentPath, i]))\n }\n return results\n }\n return expandPaths(rest, data, [...currentPath, head as string | number])\n}\n\nexport function deepEqual(a: unknown, b: unknown): boolean {\n return equal(a, b)\n}\n\ntype EvalTask = { field: FormulaField; concretePath: (string | number)[]; context: object }\n\ninterface PassResult {\n data: unknown\n errors: Array<{ path: (string | number)[]; error: Error }>\n}\n\nasync function applyAllFormulas(\n formData: unknown,\n formulaFields: FormulaField[],\n evaluator: (formula: string, context: object) => unknown | Promise<unknown>,\n contextOptions: BuildContextOptions\n): Promise<PassResult> {\n const result = structuredClone(formData)\n\n // Collect all tasks from the snapshot before any evaluation\n const tasks: EvalTask[] = []\n for (const field of formulaFields) {\n for (const concretePath of expandPaths(field.path, result)) {\n const context = buildContext(field, concretePath, result, contextOptions)\n tasks.push({ field, concretePath, context })\n }\n }\n\n // Evaluate all formulas in parallel; new Promise() executor is try-catched, catching sync throws\n const settled = await Promise.allSettled(\n tasks.map(({ field, context }) => new Promise<unknown>(resolve => resolve(evaluator(field.formula, context))))\n )\n\n // Apply results\n const errors: Array<{ path: (string | number)[]; error: Error }> = []\n for (let i = 0; i < tasks.length; i++) {\n const { concretePath } = tasks[i]\n const outcome = settled[i]\n if (outcome.status === 'fulfilled') {\n setAt(result, concretePath, outcome.value)\n } else {\n const err = outcome.reason instanceof Error\n ? outcome.reason\n : new Error(String(outcome.reason))\n errors.push({ path: concretePath, error: err })\n setAt(result, concretePath, undefined)\n }\n }\n\n return { data: result, errors }\n}\n\nfunction allConverged(\n prev: unknown,\n next: unknown,\n formulaFields: FormulaField[],\n convergenceKey: (value: unknown, path: (string | number)[]) => unknown\n): boolean {\n for (const field of formulaFields) {\n for (const concretePath of expandPaths(field.path, next)) {\n if (!deepEqual(\n convergenceKey(getAt(prev, concretePath), concretePath),\n convergenceKey(getAt(next, concretePath), concretePath)\n )) {\n return false\n }\n }\n }\n return true\n}\n\nexport async function enrich(\n formData: unknown,\n formulaFields: FormulaField[],\n evaluator: (formula: string, context: object) => unknown | Promise<unknown>,\n maxConvergencePasses: number,\n onFormulaError: ((path: (string | number)[], error: Error) => void) | undefined,\n formulaDataKey: string,\n formulaPathKey: string,\n checkCondition: (condition: RJSFSchema, formData: unknown) => boolean,\n formulaConflictBehavior: 'ignore' | 'warn' | 'error',\n convergenceKey: (value: unknown, path: (string | number)[]) => unknown = v => v\n): Promise<unknown> {\n // Filter to only active fields based on condition\n const activeFields = formulaFields.filter(field =>\n field.condition === true || checkCondition(field.condition as RJSFSchema, formData)\n )\n\n if (activeFields.length === 0) return formData\n\n // Detect runtime conflicts among active fields with the same template path\n const pathSeen = new Map<string, FormulaField>()\n const deduped: FormulaField[] = []\n for (const field of activeFields) {\n const key = JSON.stringify(field.path)\n if (pathSeen.has(key)) {\n if (formulaConflictBehavior === 'error') {\n throw new TypeError(\n `[rjsf-formulas] Formula conflict: two active fields share path [${formatPath(field.path)}]`\n )\n } else if (formulaConflictBehavior === 'warn') {\n console.warn(\n `[rjsf-formulas] Formula conflict: two active fields share path [${formatPath(field.path)}]; taking last`\n )\n }\n // Replace the previous entry with the last one (take last)\n const idx = deduped.indexOf(pathSeen.get(key)!)\n deduped[idx] = field\n pathSeen.set(key, field)\n } else {\n pathSeen.set(key, field)\n deduped.push(field)\n }\n }\n\n const contextOptions: BuildContextOptions = { formulaDataKey, formulaPathKey }\n let current = formData\n\n for (let pass = 0; pass < maxConvergencePasses; pass++) {\n const { data: candidate, errors } = await applyAllFormulas(current, deduped, evaluator, contextOptions)\n if (allConverged(current, candidate, deduped, convergenceKey)) {\n // Stable — emit error callbacks now that we know this is the final result\n for (const { path, error } of errors) {\n onFormulaError?.(path, error)\n }\n return candidate\n }\n current = candidate\n }\n\n // maxConvergencePasses exceeded — identify and report non-converging fields\n const { data: candidate } = await applyAllFormulas(current, deduped, evaluator, contextOptions)\n const result = structuredClone(candidate)\n\n for (const field of deduped) {\n for (const concretePath of expandPaths(field.path, candidate)) {\n if (!deepEqual(\n convergenceKey(getAt(current, concretePath), concretePath),\n convergenceKey(getAt(candidate, concretePath), concretePath)\n )) {\n onFormulaError?.(\n concretePath,\n new Error(\n `[rjsf-formulas] Formula at [${concretePath.join(', ')}] did not converge after ${maxConvergencePasses} passes`\n )\n )\n setAt(result, concretePath, undefined)\n }\n }\n }\n\n return result\n}\n","import { useState, useRef, useEffect, useCallback } from 'react'\nimport type { FormulaField } from './analyzeSchema'\nimport { expandPaths, enrich, deepEqual } from './enrich'\nimport type { BuildContextOptions } from './buildContext'\nimport type { RJSFSchema } from '@rjsf/utils'\n\ntype FieldState = 'idle' | 'running' | 'dirty'\n\nfunction pathKey(path: (string | number)[]): string {\n return JSON.stringify(path)\n}\n\nexport function useAsyncFormulas(\n formData: unknown,\n formulaFields: FormulaField[],\n evaluator: (formula: string, context: object) => unknown | Promise<unknown>,\n debounceMs: number,\n maxConvergencePasses: number,\n onFormulaError: ((path: (string | number)[], error: Error) => void) | undefined,\n onLoadingChange: ((loadingPaths: (string | number)[][]) => void) | undefined,\n contextOptions: BuildContextOptions,\n checkCondition: (condition: RJSFSchema, formData: unknown) => boolean,\n formulaConflictBehavior: 'ignore' | 'warn' | 'error',\n initialComputationMode: 'always' | 'skip' | 'silent',\n convergenceKey: (value: unknown, path: (string | number)[]) => unknown\n): { enrichedFormData: unknown; handleInput: (newFormData: unknown) => void } {\n const [enrichedFormData, setEnrichedFormData] = useState<unknown>(formData)\n\n const pendingInputRef = useRef<unknown>(formData)\n const lastExternalFormDataRef = useRef<unknown>(formData)\n const fieldStateRef = useRef<Map<string, FieldState>>(new Map())\n const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)\n const runningRef = useRef(false)\n\n // Stable refs so callbacks/config don't require restarting the debounce\n const onFormulaErrorRef = useRef(onFormulaError)\n const onLoadingChangeRef = useRef(onLoadingChange)\n const evaluatorRef = useRef(evaluator)\n const formulaFieldsRef = useRef(formulaFields)\n const maxPassesRef = useRef(maxConvergencePasses)\n const contextOptionsRef = useRef(contextOptions)\n const checkConditionRef = useRef(checkCondition)\n const formulaConflictBehaviorRef = useRef(formulaConflictBehavior)\n const convergenceKeyRef = useRef(convergenceKey)\n\n useEffect(() => { onFormulaErrorRef.current = onFormulaError }, [onFormulaError])\n useEffect(() => { onLoadingChangeRef.current = onLoadingChange }, [onLoadingChange])\n useEffect(() => { evaluatorRef.current = evaluator }, [evaluator])\n useEffect(() => { formulaFieldsRef.current = formulaFields }, [formulaFields])\n useEffect(() => { maxPassesRef.current = maxConvergencePasses }, [maxConvergencePasses])\n useEffect(() => { contextOptionsRef.current = contextOptions }, [contextOptions])\n useEffect(() => { checkConditionRef.current = checkCondition }, [checkCondition])\n useEffect(() => { formulaConflictBehaviorRef.current = formulaConflictBehavior }, [formulaConflictBehavior])\n useEffect(() => { convergenceKeyRef.current = convergenceKey }, [convergenceKey])\n\n // startSequence reads all config from refs so it is stable across renders\n const startSequence = useCallback(() => {\n if (runningRef.current) return\n\n const run = async () => {\n runningRef.current = true\n\n try {\n while (true) {\n const input = pendingInputRef.current\n const fields = formulaFieldsRef.current\n\n // Only report loading for fields whose condition is currently active\n const activeFields = fields.filter(f =>\n f.condition === true || checkConditionRef.current(f.condition as any, input)\n )\n\n // Collect concrete paths for loading reporting\n const concretePaths: (string | number)[][] = []\n for (const field of activeFields) {\n for (const cp of expandPaths(field.path, input)) {\n concretePaths.push(cp)\n }\n }\n\n // Mark all fields running\n const stateMap = fieldStateRef.current\n stateMap.clear()\n for (const cp of concretePaths) stateMap.set(pathKey(cp), 'running')\n if (concretePaths.length > 0) onLoadingChangeRef.current?.(concretePaths)\n\n const result = await enrich(\n input,\n fields,\n evaluatorRef.current,\n maxPassesRef.current,\n onFormulaErrorRef.current,\n contextOptionsRef.current.formulaDataKey,\n contextOptionsRef.current.formulaPathKey,\n checkConditionRef.current,\n formulaConflictBehaviorRef.current,\n convergenceKeyRef.current\n )\n\n if (isUnmountedRef.current) break\n\n const anyDirty = [...stateMap.values()].some(s => s === 'dirty')\n stateMap.clear()\n\n if (!anyDirty) {\n setEnrichedFormData(result)\n if (concretePaths.length > 0) onLoadingChangeRef.current?.([])\n break\n }\n // New input arrived while evaluating — re-run with pendingInputRef.current\n }\n } finally {\n runningRef.current = false\n }\n }\n\n run()\n }, []) // stable: all dependencies accessed via refs\n\n const handleInput = useCallback(\n (newFormData: unknown) => {\n pendingInputRef.current = newFormData\n\n // Flip any running fields to dirty\n const stateMap = fieldStateRef.current\n for (const [key, state] of stateMap) {\n if (state === 'running') stateMap.set(key, 'dirty')\n }\n\n // Only manage debounce when no sequence is in flight;\n // the while loop picks up dirty fields automatically\n if (!runningRef.current) {\n if (debounceTimerRef.current !== null) clearTimeout(debounceTimerRef.current)\n debounceTimerRef.current = setTimeout(() => {\n debounceTimerRef.current = null\n startSequence()\n }, debounceMs)\n }\n },\n [debounceMs, startSequence]\n )\n\n // React to external formData prop changes.\n // We use a no-dependency effect that runs every render but guards with deep equality\n // to avoid spurious re-evaluations when the parent re-renders with a new object\n // reference but the same value. On first render this always fires (initialises evaluation).\n const hasMountedRef = useRef(false)\n const isUnmountedRef = useRef(false)\n useEffect(() => {\n if (!hasMountedRef.current) {\n hasMountedRef.current = true\n lastExternalFormDataRef.current = formData\n // Read from param directly (not a ref) — this branch only executes once on mount.\n if (initialComputationMode !== 'skip') {\n handleInput(formData)\n }\n } else if (!deepEqual(formData, lastExternalFormDataRef.current)) {\n // Subsequent renders: only trigger on actual value change\n lastExternalFormDataRef.current = formData\n handleInput(formData)\n }\n }) // runs every render — guarded by deep equality\n\n // Reset lifecycle sentinels on every (re)mount; clean up on unmount.\n // The setup body runs before any debounce fires, so isUnmountedRef is false\n // by the time startSequence checks it.\n useEffect(() => {\n isUnmountedRef.current = false\n return () => {\n isUnmountedRef.current = true\n hasMountedRef.current = false // allow re-init on next mount (React StrictMode)\n if (debounceTimerRef.current !== null) clearTimeout(debounceTimerRef.current)\n }\n }, [])\n\n return { enrichedFormData, handleInput }\n}\n","import type { FormulaField, ArrayIndex } from './analyzeSchema'\nimport { ARRAY_INDEX } from './analyzeSchema'\n\ntype UiSchema = Record<string, unknown>\n\nexport function mergeReadOnly(\n uiSchema: UiSchema | undefined,\n formulaFields: FormulaField[]\n): UiSchema {\n const result: UiSchema = structuredClone(uiSchema ?? {})\n const mixedArrayPaths = findMixedArrayPaths(formulaFields)\n\n for (const field of formulaFields) {\n setReadOnly(result, field.path, mixedArrayPaths)\n }\n\n return result\n}\n\n// Returns a set of serialized parent paths for arrays that have both integer\n// (prefixItems) and ARRAY_INDEX (items) formula fields at the same depth.\nfunction findMixedArrayPaths(formulaFields: FormulaField[]): Set<string> {\n const mixed = new Set<string>()\n\n for (let i = 0; i < formulaFields.length; i++) {\n const path = formulaFields[i].path\n\n for (let depth = 0; depth < path.length; depth++) {\n const seg = path[depth]\n if (typeof seg !== 'number' && seg !== ARRAY_INDEX) continue\n\n const parentKey = serializePath(path.slice(0, depth))\n const isInt = typeof seg === 'number'\n\n const hasSibling = formulaFields.some((f, j) => {\n if (j === i) return false\n if (f.path.length <= depth) return false\n if (serializePath(f.path.slice(0, depth)) !== parentKey) return false\n const sibling = f.path[depth]\n return isInt ? sibling === ARRAY_INDEX : typeof sibling === 'number'\n })\n\n if (hasSibling) mixed.add(parentKey)\n }\n }\n\n return mixed\n}\n\nfunction serializePath(path: (string | number | ArrayIndex)[]): string {\n return JSON.stringify(path.map(s => (typeof s === 'symbol' ? '__ARRAY_INDEX__' : s)))\n}\n\nfunction setReadOnly(\n uiSchema: UiSchema,\n path: (string | number | ArrayIndex)[],\n mixedArrayPaths: Set<string>,\n traversedPath: (string | number | ArrayIndex)[] = []\n): void {\n if (path.length === 0) {\n uiSchema['ui:readonly'] = true\n return\n }\n\n const [head, ...tail] = path\n\n if (typeof head === 'string') {\n if (!uiSchema[head] || typeof uiSchema[head] !== 'object' || Array.isArray(uiSchema[head])) {\n uiSchema[head] = {}\n }\n setReadOnly(uiSchema[head] as UiSchema, tail, mixedArrayPaths, [...traversedPath, head])\n return\n }\n\n if (typeof head === 'number') {\n // prefixItems tuple slot — use items as array\n if (uiSchema['items'] !== undefined && !Array.isArray(uiSchema['items'])) {\n console.warn('[rjsf-formulas] mergeReadOnly: cannot inject ui:readonly at tuple index because existing uiSchema has items as an object. Skipping.')\n return\n }\n if (!Array.isArray(uiSchema['items'])) {\n uiSchema['items'] = []\n }\n const items = uiSchema['items'] as unknown[]\n if (!items[head] || typeof items[head] !== 'object') {\n items[head] = {}\n }\n setReadOnly(items[head] as UiSchema, tail, mixedArrayPaths, [...traversedPath, head])\n return\n }\n\n // head === ARRAY_INDEX\n const parentKey = serializePath(traversedPath)\n const isMixed = mixedArrayPaths.has(parentKey)\n\n if (isMixed) {\n // Mixed array: ARRAY_INDEX → additionalItems\n if (!uiSchema['additionalItems'] || typeof uiSchema['additionalItems'] !== 'object') {\n uiSchema['additionalItems'] = {}\n }\n setReadOnly(uiSchema['additionalItems'] as UiSchema, tail, mixedArrayPaths, [...traversedPath, head])\n } else {\n // Uniform array: ARRAY_INDEX → items as object\n if (Array.isArray(uiSchema['items'])) {\n console.warn('[rjsf-formulas] mergeReadOnly: cannot inject ui:readonly for uniform array because existing uiSchema has items as an array. Skipping.')\n return\n }\n if (!uiSchema['items'] || typeof uiSchema['items'] !== 'object') {\n uiSchema['items'] = {}\n }\n setReadOnly(uiSchema['items'] as UiSchema, tail, mixedArrayPaths, [...traversedPath, head])\n }\n}\n","import React, { useMemo, useEffect, useRef, useCallback, forwardRef } from 'react'\nimport Form from '@rjsf/core'\nimport type { FormProps, IChangeEvent } from '@rjsf/core'\nimport type { StrictRJSFSchema, RJSFSchema, FormContextType } from '@rjsf/utils'\nimport { analyzeSchema } from './analyzeSchema'\nimport type { FormulaField } from './analyzeSchema'\nimport { useAsyncFormulas } from './useAsyncFormulas'\nimport { mergeReadOnly } from './mergeReadOnly'\nimport type { BuildContextOptions } from './buildContext'\n\n/**\n * Props accepted by {@link FormulaForm}.\n *\n * Extends all standard RJSF `FormProps` with formula-specific configuration.\n * All formula-specific props are optional except `evaluator`.\n */\nexport type FormulaFormProps<\n T = any,\n S extends StrictRJSFSchema = RJSFSchema,\n F extends FormContextType = any\n> = FormProps<T, S, F> & {\n /**\n * Evaluates a formula string against a context object and returns the computed value.\n *\n * @remarks\n * May return a plain value or a `Promise`. For user-supplied formulas, **do not use `eval`**\n * — it allows arbitrary code execution. Prefer a sandboxed evaluator such as\n * [`expr-eval`](https://github.com/silentmatt/expr-eval) or\n * [`mathjs`](https://mathjs.org/). For additional isolation, run the evaluator in a Web Worker.\n *\n * @param formula - The formula string from the schema.\n * @param context - Sibling field values, or full form data in extended mode.\n * @returns The computed value, or a Promise resolving to it.\n */\n evaluator: (formula: string, context: object) => unknown | Promise<unknown>\n\n /**\n * Inner RJSF `Form` component to render.\n * Defaults to `Form` from `@rjsf/core`. Swap to use a themed form\n * (e.g. `Form` from `@rjsf/bootstrap-4`).\n */\n Form?: React.ComponentType<FormProps<T, S, F>>\n\n /** Schema key that marks a field as computed. Defaults to `'x-formula'`. */\n formulaKey?: string\n\n /** Schema key that selects the context mode for a field. Defaults to `'x-formula-context'`. */\n formulaContextKey?: string\n\n /**\n * Key injected into the extended context carrying the full form data.\n * Defaults to `'__formData__'`. Override if a sibling field uses the same name.\n */\n formulaDataKey?: string\n\n /**\n * Key injected into the extended context carrying the field's resolved path.\n * Defaults to `'__path__'`. Override if a sibling field uses the same name.\n */\n formulaPathKey?: string\n\n /**\n * Maximum number of re-evaluation passes triggered by a single input event.\n * Guards against infinite loops from circular formula dependencies. Defaults to `10`.\n */\n maxConvergencePasses?: number\n\n /**\n * Milliseconds to debounce formula evaluation after a user input event. Defaults to `300`.\n * Set to `0` to disable the debounce delay and evaluate on the next event loop tick.\n */\n debounceMs?: number\n\n /**\n * Called when a formula throws during evaluation.\n * @param path - JSON path of the field whose formula failed.\n * @param error - The error thrown by the evaluator.\n */\n onFormulaError?: (path: (string | number)[], error: Error) => void\n\n /**\n * Called whenever the set of currently-evaluating fields changes.\n * Useful for showing per-field loading indicators.\n * @param loadingPaths - Paths of all fields whose evaluations are in progress.\n */\n onLoadingChange?: (loadingPaths: (string | number)[][]) => void\n\n /**\n * What to do when multiple branches of a composition operator (`allOf` at schema-analysis\n * time, or simultaneously-active `oneOf`/`anyOf` branches at evaluation time) define a\n * formula for the same field path.\n * - `'ignore'` — silently take the last definition.\n * - `'warn'` (default) — emit `console.warn` and take the last definition.\n * - `'error'` — throw a `TypeError` synchronously (useful during development).\n */\n formulaConflictBehavior?: 'ignore' | 'warn' | 'error'\n\n /**\n * Controls what happens when the component mounts and runs its first formula evaluation pass.\n *\n * - `'always'` (default): evaluate on mount and call `onChange` with the enriched result.\n * - `'skip'`: skip evaluation on mount entirely; the form renders with the initial `formData` values as-is.\n * - `'silent'`: evaluate on mount (so the UI shows correct values), but do not call `onChange`.\n * User edits trigger `onChange` normally from that point on.\n *\n * `onFormulaError` and `onLoadingChange` fire normally regardless of mode.\n */\n initialComputationMode?: 'always' | 'skip' | 'silent'\n\n /**\n * Extracts a comparable key from a computed field value for convergence checking.\n * Two values are considered converged when their keys are deeply equal.\n * Defaults to the identity function — full deep equality of the computed value.\n *\n * Useful when a formula returns a compound value that includes non-deterministic parts\n * (e.g. a timestamp) that should not prevent convergence.\n *\n * @param value - The computed field's value from a convergence pass.\n * @param path - The concrete path of the computed field.\n * @returns The value to use for convergence comparison.\n */\n convergenceKey?: (value: unknown, path: (string | number)[]) => unknown\n}\n\n/**\n * Drop-in replacement for RJSF's `<Form>` with support for computed fields.\n *\n * @remarks\n * Fields marked with a formula key in the JSON schema are evaluated automatically\n * on every data change and rendered as read-only. The `evaluator` prop receives\n * the formula string and a context object, and returns the computed value.\n *\n * @example\n * ```tsx\n * import { FormulaForm } from '@a-ludi/rjsf-formulas'\n * import validator from '@rjsf/validator-ajv8'\n * import { Parser } from 'expr-eval'\n *\n * const parser = new Parser()\n *\n * const schema = {\n * type: 'object' as const,\n * properties: {\n * price: { type: 'number' as const },\n * quantity: { type: 'number' as const },\n * total: { type: 'number' as const, 'x-formula': 'price * quantity' },\n * },\n * }\n *\n * function MyForm() {\n * return (\n * <FormulaForm\n * schema={schema}\n * validator={validator}\n * evaluator={(formula, ctx) => parser.evaluate(formula, ctx)}\n * />\n * )\n * }\n * ```\n */\nfunction FormulaFormImpl<\n T = any,\n S extends StrictRJSFSchema = RJSFSchema,\n F extends FormContextType = any\n>(props: FormulaFormProps<T, S, F>, ref: React.Ref<Form<T, S, F>>): JSX.Element {\n const {\n schema,\n formData,\n validator,\n uiSchema,\n evaluator,\n Form: InnerForm = Form as React.ComponentType<FormProps<T, S, F>>,\n formulaKey = 'x-formula',\n formulaContextKey = 'x-formula-context',\n formulaDataKey = '__formData__',\n formulaPathKey = '__path__',\n maxConvergencePasses = 10,\n debounceMs = 300,\n onFormulaError,\n onLoadingChange,\n formulaConflictBehavior = 'warn',\n initialComputationMode = 'always',\n convergenceKey = (v: unknown) => v,\n onChange,\n ...rest\n } = props\n\n const formulaFields: FormulaField[] = useMemo(\n () => analyzeSchema(schema as RJSFSchema, { formulaKey, formulaContextKey }),\n [schema, formulaKey, formulaContextKey]\n )\n\n const contextOptions: BuildContextOptions = useMemo(\n () => ({ formulaDataKey, formulaPathKey }),\n [formulaDataKey, formulaPathKey]\n )\n\n const mergedUiSchema = useMemo(\n () => mergeReadOnly(uiSchema as Record<string, unknown> | undefined, formulaFields),\n [uiSchema, formulaFields]\n )\n\n const checkCondition = useCallback(\n (condition: RJSFSchema, formData: unknown) =>\n validator.isValid(condition as any, formData as any, schema as any),\n [validator, schema]\n )\n\n const suppressCount =\n initialComputationMode === 'always' ? 0 :\n initialComputationMode === 'skip' ? 1 : 2\n\n const suppressCountRef = useRef(suppressCount)\n\n // Reset the suppression counter on every (re)mount. This runs before the\n // enrichedFormData effect (React fires effects in source order), so the\n // counter is always fresh when the enrichedFormData effect reads it.\n // The cleanup restores it on StrictMode's simulated unmount so the\n // re-mount phase starts with a full count.\n useEffect(() => {\n suppressCountRef.current = suppressCount\n return () => { suppressCountRef.current = suppressCount }\n }, []) // eslint-disable-line react-hooks/exhaustive-deps\n\n const { enrichedFormData, handleInput } = useAsyncFormulas(\n formData,\n formulaFields,\n evaluator,\n debounceMs,\n maxConvergencePasses,\n onFormulaError,\n onLoadingChange,\n contextOptions,\n checkCondition,\n formulaConflictBehavior,\n initialComputationMode,\n convergenceKey\n )\n\n const onChangeRef = useRef(onChange)\n useEffect(() => { onChangeRef.current = onChange }, [onChange])\n\n useEffect(() => {\n if (formulaFields.length === 0) return\n if (suppressCountRef.current > 0) {\n suppressCountRef.current--\n return\n }\n onChangeRef.current?.({ formData: enrichedFormData as T } as IChangeEvent<T, S, F>, undefined)\n }, [enrichedFormData]) // eslint-disable-line react-hooks/exhaustive-deps\n\n const handleChange = (data: IChangeEvent<T, S, F>, id?: string) => {\n handleInput(data.formData)\n onChange?.(data, id)\n }\n\n return (\n <InnerForm\n ref={ref as any}\n {...rest}\n schema={schema}\n validator={validator}\n formData={enrichedFormData as T}\n uiSchema={mergedUiSchema as any}\n onChange={handleChange}\n />\n )\n}\n\nexport const FormulaForm = forwardRef(FormulaFormImpl) as <\n T = any,\n S extends StrictRJSFSchema = RJSFSchema,\n F extends FormContextType = any\n>(props: FormulaFormProps<T, S, F>) => JSX.Element\n"],"names":["ARRAY_INDEX","analyzeSchema","schema","options","formulaKey","formulaContextKey","formulaConflictBehavior","fields","traverse","composeCondition","ambient","branch","ambientAny","resolveContextMode","value","path","formatPath","s","pathKey","applyConflictBehavior","existing","incoming","behavior","key","mergeFields","base","field","existingIndex","f","ambientCondition","rootSchema","schemaAny","resolved","findSchemaDefinition","formula","isArray","propSchema","itemSchema","index","allOfBranches","branchFields","compositionKey","branches","branchCondition","ifSchema","thenSchema","elseSchema","thenCondition","elseCondition","fastDeepEqual","equal","a","b","length","i","keys","buildContext","resolvedPath","candidateFormData","parent","curr","siblings","getAt","data","setAt","expandPaths","templatePath","currentPath","head","rest","arr","results","deepEqual","applyAllFormulas","formData","formulaFields","evaluator","contextOptions","result","tasks","concretePath","context","settled","resolve","errors","outcome","err","allConverged","prev","next","convergenceKey","enrich","maxConvergencePasses","onFormulaError","formulaDataKey","formulaPathKey","checkCondition","v","activeFields","pathSeen","deduped","idx","current","pass","candidate","error","useAsyncFormulas","debounceMs","onLoadingChange","initialComputationMode","enrichedFormData","setEnrichedFormData","useState","pendingInputRef","useRef","lastExternalFormDataRef","fieldStateRef","debounceTimerRef","runningRef","onFormulaErrorRef","onLoadingChangeRef","evaluatorRef","formulaFieldsRef","maxPassesRef","contextOptionsRef","checkConditionRef","formulaConflictBehaviorRef","convergenceKeyRef","useEffect","startSequence","useCallback","input","concretePaths","cp","stateMap","_a","isUnmountedRef","anyDirty","_b","handleInput","newFormData","state","hasMountedRef","mergeReadOnly","uiSchema","mixedArrayPaths","findMixedArrayPaths","setReadOnly","mixed","depth","seg","parentKey","serializePath","isInt","j","sibling","traversedPath","tail","items","FormulaFormImpl","props","ref","validator","InnerForm","Form","onChange","useMemo","mergedUiSchema","condition","suppressCount","suppressCountRef","onChangeRef","jsx","id","FormulaForm","forwardRef"],"mappings":";;;;AAOO,MAAMA,IAA6B,OAAO,YAAY;AAmFtD,SAASC,GACdC,GACAC,GACgB;AAChB,QAAMC,KAAaD,KAAA,gBAAAA,EAAS,eAAc,aACpCE,KAAoBF,KAAA,gBAAAA,EAAS,sBAAqB,qBAClDG,KAA0BH,KAAA,gBAAAA,EAAS,4BAA2B,QAC9DI,IAAyB,CAAA;AAC/B,SAAAC,EAASN,GAAQ,CAAA,GAAIK,GAAQH,GAAYC,GAAmBC,GAAyB,IAAMJ,CAAM,GAC1FK;AACT;AASA,SAASE,EAAiBC,GAA4BC,GAAgC;AACpF,MAAID,MAAY,GAAM,QAAOC;AAC7B,QAAMC,IAAaF;AACnB,SAAI,MAAM,QAAQE,EAAW,KAAQ,IAC5B,EAAE,OAAO,CAAC,GAAIA,EAAW,OAA2BD,CAAM,EAAA,IAE5D,EAAE,OAAO,CAACD,GAASC,CAAM,EAAA;AAClC;AAEA,SAASE,GACPC,GACAC,GACa;AACb,SAAID,MAAU,UAAaA,MAAU,aAAmB,aACpDA,MAAU,aAAmB,cACjC,QAAQ;AAAA,IACN,oDAAoDA,CAAK,cAAcE,EAA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OACR0C,EAAiB,UAAUD,GACpB,MAAM;AAAE,IAAAC,EAAiB,UAAUD;AAAA,EAAc,IACvD,CAAA,CAAE;AAEL,QAAM,EAAE,kBAAA3D,GAAkB,aAAA6B,EAAA,IAAgBjC;AAAA,IACxChC;AAAA,IACAC;AAAA,IACAC;AAAA,IACA+B;AAAA,IACAf;AAAA,IACAC;AAAA,IACAe;AAAA,IACA/B;AAAA,IACAmB;AAAA,IACA1F;AAAA,IACAuG;AAAA,IACAnB;AAAA,EAAA,GAGIiF,IAAczD,EAAOmD,CAAQ;AACnC,SAAArC,EAAU,MAAM;AAAE,IAAA2C,EAAY,UAAUN;AAAA,EAAS,GAAG,CAACA,CAAQ,CAAC,GAE9DrC,EAAU,MAAM;;AACd,QAAIrD,EAAc,WAAW,GAC7B;AAAA,UAAI+F,EAAiB,UAAU,GAAG;AAChC,QAAAA,EAAiB;AACjB;AAAA,MACF;AACA,OAAAnC,IAAAoC,EAAY,YAAZ,QAAApC,EAAA,KAAAoC,GAAsB,EAAE,UAAU7D,EAAA,GAAkD;AAAA;AAAA,EACtF,GAAG,CAACA,CAAgB,CAAC,GAQnB,gBAAA8D;AAAA,IAACT;AAAA,IAAA;AAAA,MACC,KAAAF;AAAA,MACC,GAAG5F;AAAA,MACJ,QAAAnE;AAAA,MACA,WAAAgK;AAAA,MACA,UAAUpD;AAAA,MACV,UAAUyD;AAAA,MACV,UAbiB,CAACxG,GAA6B8G,MAAgB;AACjE,QAAAlC,EAAY5E,EAAK,QAAQ,GACzBsG,KAAA,QAAAA,EAAWtG,GAAM8G;AAAA,MACnB;AAAA,IAUc;AAAA,EAAA;AAGhB;AAEO,MAAMC,KAAcC,GAAWhB,EAAe;","x_google_ignoreList":[1]}
|
|
1
|
+
{"version":3,"file":"index.mjs","sources":["../src/analyzeSchema.ts","../node_modules/fast-deep-equal/index.js","../src/buildContext.ts","../src/enrich.ts","../src/useAsyncFormulas.ts","../src/mergeReadOnly.ts","../src/FormulaForm.tsx"],"sourcesContent":["import type { RJSFSchema } from '@rjsf/utils'\nimport { findSchemaDefinition } from '@rjsf/utils'\n\n/**\n * Sentinel used in formula field paths to represent a uniform array item position.\n * @internal\n */\nexport const ARRAY_INDEX: unique symbol = Symbol('arrayIndex')\n\n/** @internal */\nexport type ArrayIndex = typeof ARRAY_INDEX\n\n/**\n * Controls which values are injected into the formula evaluation context.\n *\n * - `'siblings'` (default): only the sibling fields of the computed field are available by name.\n * - `'extended'`: full form data and the field's resolved path are injected alongside sibling\n * values, under the keys configured by `formulaDataKey` and `formulaPathKey`.\n *\n * Set via the `x-formula-context` schema key (or the `formulaContextKey` prop).\n */\nexport type ContextMode = 'siblings' | 'extended'\n\n/**\n * Describes a single computed field discovered by {@link analyzeSchema}.\n */\nexport type FormulaField = {\n /** JSON path to the field within the form data. Uniform array item positions are represented by {@link ARRAY_INDEX}. */\n path: (string | number | ArrayIndex)[]\n /** The raw formula string from the schema. */\n formula: string\n /** Which values are available when evaluating this field's formula. */\n contextMode: ContextMode\n /**\n * The schema condition under which this formula is active.\n *\n * - `true` — always active (fields from `properties`, `items`, `prefixItems`, or `allOf` branches).\n * - `RJSFSchema` — a conditional schema (a `oneOf`/`anyOf` branch condition, possibly composed\n * via `{ allOf: [...] }` for nested branches).\n */\n condition: RJSFSchema | true\n}\n\n/**\n * Options for {@link analyzeSchema}.\n */\nexport type AnalyzeSchemaOptions = {\n /** Schema key that marks a field as computed. Defaults to `'x-formula'`. */\n formulaKey?: string\n /** Schema key that selects the context mode for a computed field. Defaults to `'x-formula-context'`. */\n formulaContextKey?: string\n /**\n * What to do when multiple `allOf` branches define a formula for the same path.\n *\n * - `'ignore'`: silently take the last definition.\n * - `'warn'` (default): emit `console.warn` and take the last definition.\n * - `'error'`: throw a `TypeError` synchronously.\n */\n formulaConflictBehavior?: 'ignore' | 'warn' | 'error'\n}\n\n/**\n * Scans a JSON Schema and returns descriptors for every field that carries a formula key.\n *\n * @remarks\n * Traversal is depth-first. `allOf`, `$ref`, `oneOf`, and `anyOf` are all supported.\n * `allOf` branches are merged with conflict detection. `oneOf`/`anyOf` branches are each\n * recursed and fields are collected with the branch schema as the `condition`. Nested\n * `oneOf`/`anyOf` conditions are composed via `{ allOf: [...] }`. `$ref` is resolved\n * synchronously using `findSchemaDefinition` (external refs will throw).\n *\n * @param schema - The root RJSF schema to scan.\n * @param options - Optional key overrides for locating formulas in the schema.\n * @returns An array of {@link FormulaField} descriptors, one per computed field found.\n *\n * @example\n * ```ts\n * import { analyzeSchema } from '@a-ludi/rjsf-formulas'\n *\n * const fields = analyzeSchema({\n * type: 'object',\n * properties: {\n * price: { type: 'number' },\n * total: { type: 'number', 'x-formula': 'price * 2' },\n * },\n * })\n * // fields[0].path => ['total']\n * // fields[0].formula => 'price * 2'\n * ```\n */\nexport function analyzeSchema(\n schema: RJSFSchema,\n options?: AnalyzeSchemaOptions\n): FormulaField[] {\n const formulaKey = options?.formulaKey ?? 'x-formula'\n const formulaContextKey = options?.formulaContextKey ?? 'x-formula-context'\n const formulaConflictBehavior = options?.formulaConflictBehavior ?? 'warn'\n const fields: FormulaField[] = []\n traverse(schema, [], fields, formulaKey, formulaContextKey, formulaConflictBehavior, true, schema)\n return fields\n}\n\n/**\n * Compose an ambient condition with a new branch schema.\n *\n * - If `ambient === true`: returns `branch` directly (no wrapping needed).\n * - If `ambient` already has an `allOf`: appends `branch` to that array.\n * - Otherwise: wraps both in `{ allOf: [ambient, branch] }`.\n */\nfunction composeCondition(ambient: RJSFSchema | true, branch: RJSFSchema): RJSFSchema {\n if (ambient === true) return branch\n const ambientAny = ambient as Record<string, unknown>\n if (Array.isArray(ambientAny['allOf'])) {\n return { allOf: [...(ambientAny['allOf'] as RJSFSchema[]), branch] }\n }\n return { allOf: [ambient, branch] }\n}\n\nfunction resolveContextMode(\n value: unknown,\n path: (string | number | ArrayIndex)[]\n): ContextMode {\n if (value === undefined || value === 'siblings') return 'siblings'\n if (value === 'extended') return 'extended'\n console.warn(\n `[rjsf-formulas] Unknown x-formula-context value \"${value}\" at path [${formatPath(path)}], treating as \"siblings\"`\n )\n return 'siblings'\n}\n\nfunction formatPath(path: (string | number | ArrayIndex)[]): string {\n return path.map(s => (typeof s === 'symbol' ? '[*]' : String(s))).join(', ')\n}\n\nfunction pathKey(path: (string | number | ArrayIndex)[]): string {\n return path.map(s => (typeof s === 'symbol' ? '[*]' : String(s))).join('.')\n}\n\nfunction applyConflictBehavior(\n existing: FormulaField,\n incoming: FormulaField,\n behavior: 'ignore' | 'warn' | 'error'\n): void {\n const key = pathKey(existing.path)\n if (behavior === 'error') {\n throw new TypeError(\n `[rjsf-formulas] Formula conflict at path [${formatPath(existing.path)}]: \"${existing.formula}\" vs \"${incoming.formula}\". Resolve the conflict or set formulaConflictBehavior to 'ignore' or 'warn'.`\n )\n }\n if (behavior === 'warn') {\n console.warn(\n `[rjsf-formulas] Formula conflict at path [${key}]: \"${existing.formula}\" (earlier allOf branch) is overridden by \"${incoming.formula}\" (later allOf branch).`\n )\n }\n}\n\nfunction mergeFields(\n base: FormulaField[],\n incoming: FormulaField[],\n behavior: 'ignore' | 'warn' | 'error'\n): void {\n for (const field of incoming) {\n const key = pathKey(field.path)\n const existingIndex = base.findIndex(f => pathKey(f.path) === key)\n if (existingIndex !== -1) {\n applyConflictBehavior(base[existingIndex], field, behavior)\n base[existingIndex] = field\n } else {\n base.push(field)\n }\n }\n}\n\nfunction traverse(\n schema: RJSFSchema,\n path: (string | number | ArrayIndex)[],\n fields: FormulaField[],\n formulaKey: string,\n formulaContextKey: string,\n formulaConflictBehavior: 'ignore' | 'warn' | 'error',\n ambientCondition: RJSFSchema | true,\n rootSchema: RJSFSchema\n): void {\n const schemaAny = schema as Record<string, unknown>\n\n // $ref — resolve and continue traversal with the same ambientCondition\n if (typeof schemaAny['$ref'] === 'string') {\n const resolved = findSchemaDefinition(schemaAny['$ref'] as string, rootSchema)\n traverse(resolved, path, fields, formulaKey, formulaContextKey, formulaConflictBehavior, ambientCondition, rootSchema)\n return\n }\n\n // Rule 1: computed field — record and stop\n if (formulaKey in schema) {\n const formula = schemaAny[formulaKey]\n if (typeof formula !== 'string') {\n console.warn(\n `[rjsf-formulas] Formula at path [${formatPath(path)}] is not a string (got ${typeof formula}), skipping.`\n )\n return\n }\n fields.push({\n path,\n formula,\n contextMode: resolveContextMode(schemaAny[formulaContextKey], path),\n condition: ambientCondition,\n })\n return\n }\n\n // Rule 2: object — recurse into properties (type: 'object' is implicit when properties are present)\n const isArray = schema.type === 'array' ||\n (schema.type == null && (Array.isArray(schemaAny['prefixItems']) || schema.items != null))\n if (schema.properties && !isArray) {\n for (const [key, propSchema] of Object.entries(schema.properties)) {\n traverse(\n propSchema as RJSFSchema,\n [...path, key],\n fields,\n formulaKey,\n formulaContextKey,\n formulaConflictBehavior,\n ambientCondition,\n rootSchema\n )\n }\n }\n\n // Rule 3: array — recurse into prefixItems and/or items (type: 'array' is implicit when items/prefixItems are present)\n if (isArray) {\n // Rule 3a: prefixItems (tuple positions with static indices)\n if (Array.isArray(schemaAny['prefixItems'])) {\n const prefixItems = schemaAny['prefixItems'] as RJSFSchema[]\n prefixItems.forEach((itemSchema, index) => {\n traverse(itemSchema, [...path, index], fields, formulaKey, formulaContextKey, formulaConflictBehavior, ambientCondition, rootSchema)\n })\n }\n\n // Rule 3b: items as array (legacy draft-07 tuple — positional schemas, equivalent to prefixItems)\n if (Array.isArray(schema.items)) {\n (schema.items as RJSFSchema[]).forEach((itemSchema, index) => {\n traverse(itemSchema, [...path, index], fields, formulaKey, formulaContextKey, formulaConflictBehavior, ambientCondition, rootSchema)\n });\n\n if (schema.additionalItems && typeof schema.additionalItems === 'object') {\n traverse(schema.additionalItems, [...path, ARRAY_INDEX], fields, formulaKey, formulaContextKey, formulaConflictBehavior, ambientCondition, rootSchema);\n }\n }\n\n // Rule 3c: items as object (uniform array — all elements share one schema)\n if (schema.items && !Array.isArray(schema.items)) {\n traverse(\n schema.items as RJSFSchema,\n [...path, ARRAY_INDEX],\n fields,\n formulaKey,\n formulaContextKey,\n formulaConflictBehavior,\n ambientCondition,\n rootSchema\n )\n }\n }\n\n // Rule 4: allOf — recurse into each branch, then merge with conflict detection\n // allOf does not add to the condition — branches are always active within their parent's condition\n if (Array.isArray(schemaAny['allOf'])) {\n const allOfBranches = schemaAny['allOf'] as RJSFSchema[]\n for (const branch of allOfBranches) {\n const branchFields: FormulaField[] = []\n traverse(branch, path, branchFields, formulaKey, formulaContextKey, formulaConflictBehavior, ambientCondition, rootSchema)\n mergeFields(fields, branchFields, formulaConflictBehavior)\n }\n }\n\n // Rule 5: oneOf / anyOf — recurse each branch with a composed condition\n for (const compositionKey of ['oneOf', 'anyOf'] as const) {\n if (Array.isArray(schemaAny[compositionKey])) {\n const branches = schemaAny[compositionKey] as RJSFSchema[]\n for (const branch of branches) {\n const branchCondition = composeCondition(ambientCondition, branch)\n traverse(branch, path, fields, formulaKey, formulaContextKey, formulaConflictBehavior, branchCondition, rootSchema)\n }\n }\n }\n\n // Rule 6: if/then/else — traverse then/else with appropriate conditions; warn if formula found in if\n if ('if' in schemaAny) {\n const ifSchema = schemaAny['if'] as RJSFSchema\n const thenSchema = schemaAny['then'] as RJSFSchema | undefined\n const elseSchema = schemaAny['else'] as RJSFSchema | undefined\n\n // Warn if the if schema itself contains a formula key (it is never rendered by RJSF)\n if (formulaKey in (ifSchema as Record<string, unknown>)) {\n console.warn(\n `[rjsf-formulas] Formula key \"${formulaKey}\" found inside an \"if\" schema at path [${formatPath(path)}]. The \"if\" schema is a validation predicate and is never rendered — the formula will be ignored.`\n )\n }\n\n if (thenSchema !== undefined) {\n const thenCondition = composeCondition(ambientCondition, ifSchema)\n traverse(thenSchema, path, fields, formulaKey, formulaContextKey, formulaConflictBehavior, thenCondition, rootSchema)\n }\n\n if (elseSchema !== undefined) {\n const elseCondition = composeCondition(ambientCondition, { not: ifSchema })\n traverse(elseSchema, path, fields, formulaKey, formulaContextKey, formulaConflictBehavior, elseCondition, rootSchema)\n }\n }\n}\n","'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n","import type { FormulaField } from './analyzeSchema'\n\nexport type BuildContextOptions = {\n formulaDataKey: string\n formulaPathKey: string\n}\n\nexport function buildContext(\n field: FormulaField,\n resolvedPath: (string | number)[],\n candidateFormData: unknown,\n options: BuildContextOptions\n): object {\n const parentPath = resolvedPath.slice(0, -1)\n const parent = parentPath.reduce<unknown>((curr, key) => {\n if (curr == null || typeof curr !== 'object') return undefined\n return (curr as Record<string | number, unknown>)[key]\n }, candidateFormData)\n\n const siblings =\n parent != null && typeof parent === 'object' && !Array.isArray(parent)\n ? { ...(parent as object) }\n : {}\n\n if (field.contextMode === 'extended') {\n if (options.formulaDataKey in siblings || options.formulaPathKey in siblings) {\n console.warn(\n `[rjsf-formulas] Extended context key collision: sibling field named \"${\n options.formulaDataKey in siblings ? options.formulaDataKey : options.formulaPathKey\n }\" will be overwritten by the injected context. Use formulaDataKey/formulaPathKey props to choose a different key.`\n )\n }\n return {\n ...siblings,\n [options.formulaDataKey]: candidateFormData,\n [options.formulaPathKey]: [...resolvedPath],\n }\n }\n\n return siblings\n}\n","import equal from 'fast-deep-equal'\nimport type { RJSFSchema } from '@rjsf/utils'\nimport type { FormulaField, ArrayIndex } from './analyzeSchema'\nimport { ARRAY_INDEX } from './analyzeSchema'\nimport { buildContext } from './buildContext'\nimport type { BuildContextOptions } from './buildContext'\n\nexport { ARRAY_INDEX }\n\nfunction formatPath(path: (string | number | ArrayIndex)[]): string {\n return path.map(s => (typeof s === 'symbol' ? '[*]' : String(s))).join(', ')\n}\n\nexport function getAt(data: unknown, path: (string | number)[]): unknown {\n return path.reduce<unknown>((curr, key) => {\n if (curr == null || typeof curr !== 'object') return undefined\n return (curr as Record<string | number, unknown>)[key]\n }, data)\n}\n\nexport function setAt(data: unknown, path: (string | number)[], value: unknown): void {\n if (path.length === 0) return\n const parent = getAt(data, path.slice(0, -1))\n if (parent != null && typeof parent === 'object') {\n ;(parent as Record<string | number, unknown>)[path[path.length - 1]] = value\n }\n}\n\nexport function expandPaths(\n templatePath: (string | number | ArrayIndex)[],\n data: unknown,\n currentPath: (string | number)[] = []\n): (string | number)[][] {\n if (templatePath.length === 0) return [currentPath]\n const [head, ...rest] = templatePath\n if (head === ARRAY_INDEX) {\n const arr = getAt(data, currentPath)\n if (!Array.isArray(arr)) return []\n const results: (string | number)[][] = []\n for (let i = 0; i < arr.length; i++) {\n results.push(...expandPaths(rest, data, [...currentPath, i]))\n }\n return results\n }\n return expandPaths(rest, data, [...currentPath, head as string | number])\n}\n\nexport function deepEqual(a: unknown, b: unknown): boolean {\n return equal(a, b)\n}\n\ntype EvalTask = { field: FormulaField; concretePath: (string | number)[]; context: object }\n\ninterface PassResult {\n data: unknown\n errors: Array<{ path: (string | number)[]; error: Error }>\n}\n\nasync function applyAllFormulas(\n formData: unknown,\n formulaFields: FormulaField[],\n evaluator: (formula: string, context: object) => unknown | Promise<unknown>,\n contextOptions: BuildContextOptions\n): Promise<PassResult> {\n const result = structuredClone(formData)\n\n // Collect all tasks from the snapshot before any evaluation\n const tasks: EvalTask[] = []\n for (const field of formulaFields) {\n for (const concretePath of expandPaths(field.path, result)) {\n const context = buildContext(field, concretePath, result, contextOptions)\n tasks.push({ field, concretePath, context })\n }\n }\n\n // Evaluate all formulas in parallel; new Promise() executor is try-catched, catching sync throws\n const settled = await Promise.allSettled(\n tasks.map(({ field, context }) => new Promise<unknown>(resolve => resolve(evaluator(field.formula, context))))\n )\n\n // Apply results\n const errors: Array<{ path: (string | number)[]; error: Error }> = []\n for (let i = 0; i < tasks.length; i++) {\n const { concretePath } = tasks[i]\n const outcome = settled[i]\n if (outcome.status === 'fulfilled') {\n setAt(result, concretePath, outcome.value)\n } else {\n const err = outcome.reason instanceof Error\n ? outcome.reason\n : new Error(String(outcome.reason))\n errors.push({ path: concretePath, error: err })\n setAt(result, concretePath, undefined)\n }\n }\n\n return { data: result, errors }\n}\n\nfunction allConverged(\n prev: unknown,\n next: unknown,\n formulaFields: FormulaField[],\n convergenceKey: (value: unknown, path: (string | number)[]) => unknown\n): boolean {\n for (const field of formulaFields) {\n for (const concretePath of expandPaths(field.path, next)) {\n if (!deepEqual(\n convergenceKey(getAt(prev, concretePath), concretePath),\n convergenceKey(getAt(next, concretePath), concretePath)\n )) {\n return false\n }\n }\n }\n return true\n}\n\nexport async function enrich(\n formData: unknown,\n formulaFields: FormulaField[],\n evaluator: (formula: string, context: object) => unknown | Promise<unknown>,\n maxConvergencePasses: number,\n onFormulaError: ((path: (string | number)[], error: Error) => void) | undefined,\n formulaDataKey: string,\n formulaPathKey: string,\n checkCondition: (condition: RJSFSchema, formData: unknown) => boolean,\n formulaConflictBehavior: 'ignore' | 'warn' | 'error',\n convergenceKey: (value: unknown, path: (string | number)[]) => unknown = v => v\n): Promise<unknown> {\n // Filter to only active fields based on condition\n const activeFields = formulaFields.filter(field =>\n field.condition === true || checkCondition(field.condition as RJSFSchema, formData)\n )\n\n if (activeFields.length === 0) return formData\n\n // Detect runtime conflicts among active fields with the same template path\n const pathSeen = new Map<string, FormulaField>()\n const deduped: FormulaField[] = []\n for (const field of activeFields) {\n const key = JSON.stringify(field.path)\n if (pathSeen.has(key)) {\n if (formulaConflictBehavior === 'error') {\n throw new TypeError(\n `[rjsf-formulas] Formula conflict: two active fields share path [${formatPath(field.path)}]`\n )\n } else if (formulaConflictBehavior === 'warn') {\n console.warn(\n `[rjsf-formulas] Formula conflict: two active fields share path [${formatPath(field.path)}]; taking last`\n )\n }\n // Replace the previous entry with the last one (take last)\n const idx = deduped.indexOf(pathSeen.get(key)!)\n deduped[idx] = field\n pathSeen.set(key, field)\n } else {\n pathSeen.set(key, field)\n deduped.push(field)\n }\n }\n\n const contextOptions: BuildContextOptions = { formulaDataKey, formulaPathKey }\n let current = formData\n\n for (let pass = 0; pass < maxConvergencePasses; pass++) {\n const { data: candidate, errors } = await applyAllFormulas(current, deduped, evaluator, contextOptions)\n if (allConverged(current, candidate, deduped, convergenceKey)) {\n // Stable — emit error callbacks now that we know this is the final result\n for (const { path, error } of errors) {\n onFormulaError?.(path, error)\n }\n return candidate\n }\n current = candidate\n }\n\n // maxConvergencePasses exceeded — identify and report non-converging fields\n const { data: candidate } = await applyAllFormulas(current, deduped, evaluator, contextOptions)\n const result = structuredClone(candidate)\n\n for (const field of deduped) {\n for (const concretePath of expandPaths(field.path, candidate)) {\n if (!deepEqual(\n convergenceKey(getAt(current, concretePath), concretePath),\n convergenceKey(getAt(candidate, concretePath), concretePath)\n )) {\n onFormulaError?.(\n concretePath,\n new Error(\n `[rjsf-formulas] Formula at [${concretePath.join(', ')}] did not converge after ${maxConvergencePasses} passes`\n )\n )\n setAt(result, concretePath, undefined)\n }\n }\n }\n\n return result\n}\n","import { useState, useRef, useEffect, useCallback } from 'react'\nimport type { FormulaField } from './analyzeSchema'\nimport { expandPaths, enrich, deepEqual } from './enrich'\nimport type { BuildContextOptions } from './buildContext'\nimport type { RJSFSchema } from '@rjsf/utils'\n\ntype FieldState = 'idle' | 'running' | 'dirty'\n\nfunction pathKey(path: (string | number)[]): string {\n return JSON.stringify(path)\n}\n\nexport function useAsyncFormulas(\n formData: unknown,\n formulaFields: FormulaField[],\n evaluator: (formula: string, context: object) => unknown | Promise<unknown>,\n debounceMs: number,\n maxConvergencePasses: number,\n onFormulaError: ((path: (string | number)[], error: Error) => void) | undefined,\n onLoadingChange: ((loadingPaths: (string | number)[][]) => void) | undefined,\n contextOptions: BuildContextOptions,\n checkCondition: (condition: RJSFSchema, formData: unknown) => boolean,\n formulaConflictBehavior: 'ignore' | 'warn' | 'error',\n initialComputationMode: 'always' | 'skip' | 'silent',\n convergenceKey: (value: unknown, path: (string | number)[]) => unknown\n): { enrichedFormData: unknown; handleInput: (newFormData: unknown) => void } {\n const [enrichedFormData, setEnrichedFormData] = useState<unknown>(formData)\n\n const pendingInputRef = useRef<unknown>(formData)\n const lastExternalFormDataRef = useRef<unknown>(formData)\n const fieldStateRef = useRef<Map<string, FieldState>>(new Map())\n const debounceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)\n const runningRef = useRef(false)\n\n // Stable refs so callbacks/config don't require restarting the debounce\n const onFormulaErrorRef = useRef(onFormulaError)\n const onLoadingChangeRef = useRef(onLoadingChange)\n const evaluatorRef = useRef(evaluator)\n const formulaFieldsRef = useRef(formulaFields)\n const maxPassesRef = useRef(maxConvergencePasses)\n const contextOptionsRef = useRef(contextOptions)\n const checkConditionRef = useRef(checkCondition)\n const formulaConflictBehaviorRef = useRef(formulaConflictBehavior)\n const convergenceKeyRef = useRef(convergenceKey)\n\n useEffect(() => { onFormulaErrorRef.current = onFormulaError }, [onFormulaError])\n useEffect(() => { onLoadingChangeRef.current = onLoadingChange }, [onLoadingChange])\n useEffect(() => { evaluatorRef.current = evaluator }, [evaluator])\n useEffect(() => { formulaFieldsRef.current = formulaFields }, [formulaFields])\n useEffect(() => { maxPassesRef.current = maxConvergencePasses }, [maxConvergencePasses])\n useEffect(() => { contextOptionsRef.current = contextOptions }, [contextOptions])\n useEffect(() => { checkConditionRef.current = checkCondition }, [checkCondition])\n useEffect(() => { formulaConflictBehaviorRef.current = formulaConflictBehavior }, [formulaConflictBehavior])\n useEffect(() => { convergenceKeyRef.current = convergenceKey }, [convergenceKey])\n\n // startSequence reads all config from refs so it is stable across renders\n const startSequence = useCallback(() => {\n if (runningRef.current) return\n\n const run = async () => {\n runningRef.current = true\n\n try {\n while (true) {\n const input = pendingInputRef.current\n const fields = formulaFieldsRef.current\n\n // Only report loading for fields whose condition is currently active\n const activeFields = fields.filter(f =>\n f.condition === true || checkConditionRef.current(f.condition as any, input)\n )\n\n // Collect concrete paths for loading reporting\n const concretePaths: (string | number)[][] = []\n for (const field of activeFields) {\n for (const cp of expandPaths(field.path, input)) {\n concretePaths.push(cp)\n }\n }\n\n // Mark all fields running\n const stateMap = fieldStateRef.current\n stateMap.clear()\n for (const cp of concretePaths) stateMap.set(pathKey(cp), 'running')\n if (concretePaths.length > 0) onLoadingChangeRef.current?.(concretePaths)\n\n const result = await enrich(\n input,\n fields,\n evaluatorRef.current,\n maxPassesRef.current,\n onFormulaErrorRef.current,\n contextOptionsRef.current.formulaDataKey,\n contextOptionsRef.current.formulaPathKey,\n checkConditionRef.current,\n formulaConflictBehaviorRef.current,\n convergenceKeyRef.current\n )\n\n if (isUnmountedRef.current) break\n\n const anyDirty = [...stateMap.values()].some(s => s === 'dirty')\n stateMap.clear()\n\n if (!anyDirty) {\n setEnrichedFormData(result)\n if (concretePaths.length > 0) onLoadingChangeRef.current?.([])\n break\n }\n // New input arrived while evaluating — re-run with pendingInputRef.current\n }\n } finally {\n runningRef.current = false\n }\n }\n\n run()\n }, []) // stable: all dependencies accessed via refs\n\n const handleInput = useCallback(\n (newFormData: unknown) => {\n pendingInputRef.current = newFormData\n setEnrichedFormData(newFormData)\n\n // Flip any running fields to dirty\n const stateMap = fieldStateRef.current\n for (const [key, state] of stateMap) {\n if (state === 'running') stateMap.set(key, 'dirty')\n }\n\n // Only manage debounce when no sequence is in flight;\n // the while loop picks up dirty fields automatically\n if (!runningRef.current) {\n if (debounceTimerRef.current !== null) clearTimeout(debounceTimerRef.current)\n debounceTimerRef.current = setTimeout(() => {\n debounceTimerRef.current = null\n startSequence()\n }, debounceMs)\n }\n },\n [debounceMs, startSequence]\n )\n\n // React to external formData prop changes.\n // We use a no-dependency effect that runs every render but guards with deep equality\n // to avoid spurious re-evaluations when the parent re-renders with a new object\n // reference but the same value. On first render this always fires (initialises evaluation).\n const hasMountedRef = useRef(false)\n const isUnmountedRef = useRef(false)\n useEffect(() => {\n if (!hasMountedRef.current) {\n hasMountedRef.current = true\n lastExternalFormDataRef.current = formData\n // Read from param directly (not a ref) — this branch only executes once on mount.\n if (initialComputationMode !== 'skip') {\n handleInput(formData)\n }\n } else if (!deepEqual(formData, lastExternalFormDataRef.current)) {\n // Subsequent renders: only trigger on actual value change\n lastExternalFormDataRef.current = formData\n handleInput(formData)\n }\n }) // runs every render — guarded by deep equality\n\n // Reset lifecycle sentinels on every (re)mount; clean up on unmount.\n // The setup body runs before any debounce fires, so isUnmountedRef is false\n // by the time startSequence checks it.\n useEffect(() => {\n isUnmountedRef.current = false\n return () => {\n isUnmountedRef.current = true\n hasMountedRef.current = false // allow re-init on next mount (React StrictMode)\n if (debounceTimerRef.current !== null) clearTimeout(debounceTimerRef.current)\n }\n }, [])\n\n return { enrichedFormData, handleInput }\n}\n","import type { FormulaField, ArrayIndex } from './analyzeSchema'\nimport { ARRAY_INDEX } from './analyzeSchema'\n\ntype UiSchema = Record<string, unknown>\n\nexport function mergeReadOnly(\n uiSchema: UiSchema | undefined,\n formulaFields: FormulaField[]\n): UiSchema {\n const result: UiSchema = structuredClone(uiSchema ?? {})\n const mixedArrayPaths = findMixedArrayPaths(formulaFields)\n\n for (const field of formulaFields) {\n setReadOnly(result, field.path, mixedArrayPaths)\n }\n\n return result\n}\n\n// Returns a set of serialized parent paths for arrays that have both integer\n// (prefixItems) and ARRAY_INDEX (items) formula fields at the same depth.\nfunction findMixedArrayPaths(formulaFields: FormulaField[]): Set<string> {\n const mixed = new Set<string>()\n\n for (let i = 0; i < formulaFields.length; i++) {\n const path = formulaFields[i].path\n\n for (let depth = 0; depth < path.length; depth++) {\n const seg = path[depth]\n if (typeof seg !== 'number' && seg !== ARRAY_INDEX) continue\n\n const parentKey = serializePath(path.slice(0, depth))\n const isInt = typeof seg === 'number'\n\n const hasSibling = formulaFields.some((f, j) => {\n if (j === i) return false\n if (f.path.length <= depth) return false\n if (serializePath(f.path.slice(0, depth)) !== parentKey) return false\n const sibling = f.path[depth]\n return isInt ? sibling === ARRAY_INDEX : typeof sibling === 'number'\n })\n\n if (hasSibling) mixed.add(parentKey)\n }\n }\n\n return mixed\n}\n\nfunction serializePath(path: (string | number | ArrayIndex)[]): string {\n return JSON.stringify(path.map(s => (typeof s === 'symbol' ? '__ARRAY_INDEX__' : s)))\n}\n\nfunction setReadOnly(\n uiSchema: UiSchema,\n path: (string | number | ArrayIndex)[],\n mixedArrayPaths: Set<string>,\n traversedPath: (string | number | ArrayIndex)[] = []\n): void {\n if (path.length === 0) {\n uiSchema['ui:readonly'] = true\n return\n }\n\n const [head, ...tail] = path\n\n if (typeof head === 'string') {\n if (!uiSchema[head] || typeof uiSchema[head] !== 'object' || Array.isArray(uiSchema[head])) {\n uiSchema[head] = {}\n }\n setReadOnly(uiSchema[head] as UiSchema, tail, mixedArrayPaths, [...traversedPath, head])\n return\n }\n\n if (typeof head === 'number') {\n // prefixItems tuple slot — use items as array\n if (uiSchema['items'] !== undefined && !Array.isArray(uiSchema['items'])) {\n console.warn('[rjsf-formulas] mergeReadOnly: cannot inject ui:readonly at tuple index because existing uiSchema has items as an object. Skipping.')\n return\n }\n if (!Array.isArray(uiSchema['items'])) {\n uiSchema['items'] = []\n }\n const items = uiSchema['items'] as unknown[]\n if (!items[head] || typeof items[head] !== 'object') {\n items[head] = {}\n }\n setReadOnly(items[head] as UiSchema, tail, mixedArrayPaths, [...traversedPath, head])\n return\n }\n\n // head === ARRAY_INDEX\n const parentKey = serializePath(traversedPath)\n const isMixed = mixedArrayPaths.has(parentKey)\n\n if (isMixed) {\n // Mixed array: ARRAY_INDEX → additionalItems\n if (!uiSchema['additionalItems'] || typeof uiSchema['additionalItems'] !== 'object') {\n uiSchema['additionalItems'] = {}\n }\n setReadOnly(uiSchema['additionalItems'] as UiSchema, tail, mixedArrayPaths, [...traversedPath, head])\n } else {\n // Uniform array: ARRAY_INDEX → items as object\n if (Array.isArray(uiSchema['items'])) {\n console.warn('[rjsf-formulas] mergeReadOnly: cannot inject ui:readonly for uniform array because existing uiSchema has items as an array. Skipping.')\n return\n }\n if (!uiSchema['items'] || typeof uiSchema['items'] !== 'object') {\n uiSchema['items'] = {}\n }\n setReadOnly(uiSchema['items'] as UiSchema, tail, mixedArrayPaths, [...traversedPath, head])\n }\n}\n","import React, { useMemo, useEffect, useRef, useCallback, forwardRef } from 'react'\nimport Form from '@rjsf/core'\nimport type { FormProps, IChangeEvent } from '@rjsf/core'\nimport type { StrictRJSFSchema, RJSFSchema, FormContextType } from '@rjsf/utils'\nimport { analyzeSchema } from './analyzeSchema'\nimport type { FormulaField } from './analyzeSchema'\nimport { useAsyncFormulas } from './useAsyncFormulas'\nimport { mergeReadOnly } from './mergeReadOnly'\nimport type { BuildContextOptions } from './buildContext'\n\n/**\n * Props accepted by {@link FormulaForm}.\n *\n * Extends all standard RJSF `FormProps` with formula-specific configuration.\n * All formula-specific props are optional except `evaluator`.\n */\nexport type FormulaFormProps<\n T = any,\n S extends StrictRJSFSchema = RJSFSchema,\n F extends FormContextType = any\n> = FormProps<T, S, F> & {\n /**\n * Evaluates a formula string against a context object and returns the computed value.\n *\n * @remarks\n * May return a plain value or a `Promise`. For user-supplied formulas, **do not use `eval`**\n * — it allows arbitrary code execution. Prefer a sandboxed evaluator such as\n * [`expr-eval`](https://github.com/silentmatt/expr-eval) or\n * [`mathjs`](https://mathjs.org/). For additional isolation, run the evaluator in a Web Worker.\n *\n * @param formula - The formula string from the schema.\n * @param context - Sibling field values, or full form data in extended mode.\n * @returns The computed value, or a Promise resolving to it.\n */\n evaluator: (formula: string, context: object) => unknown | Promise<unknown>\n\n /**\n * Inner RJSF `Form` component to render.\n * Defaults to `Form` from `@rjsf/core`. Swap to use a themed form\n * (e.g. `Form` from `@rjsf/bootstrap-4`).\n */\n Form?: React.ComponentType<FormProps<T, S, F>>\n\n /** Schema key that marks a field as computed. Defaults to `'x-formula'`. */\n formulaKey?: string\n\n /** Schema key that selects the context mode for a field. Defaults to `'x-formula-context'`. */\n formulaContextKey?: string\n\n /**\n * Key injected into the extended context carrying the full form data.\n * Defaults to `'__formData__'`. Override if a sibling field uses the same name.\n */\n formulaDataKey?: string\n\n /**\n * Key injected into the extended context carrying the field's resolved path.\n * Defaults to `'__path__'`. Override if a sibling field uses the same name.\n */\n formulaPathKey?: string\n\n /**\n * Maximum number of re-evaluation passes triggered by a single input event.\n * Guards against infinite loops from circular formula dependencies. Defaults to `10`.\n */\n maxConvergencePasses?: number\n\n /**\n * Milliseconds to debounce formula evaluation after a user input event. Defaults to `300`.\n * Set to `0` to disable the debounce delay and evaluate on the next event loop tick.\n */\n debounceMs?: number\n\n /**\n * Called when a formula throws during evaluation.\n * @param path - JSON path of the field whose formula failed.\n * @param error - The error thrown by the evaluator.\n */\n onFormulaError?: (path: (string | number)[], error: Error) => void\n\n /**\n * Called whenever the set of currently-evaluating fields changes.\n * Useful for showing per-field loading indicators.\n * @param loadingPaths - Paths of all fields whose evaluations are in progress.\n */\n onLoadingChange?: (loadingPaths: (string | number)[][]) => void\n\n /**\n * What to do when multiple branches of a composition operator (`allOf` at schema-analysis\n * time, or simultaneously-active `oneOf`/`anyOf` branches at evaluation time) define a\n * formula for the same field path.\n * - `'ignore'` — silently take the last definition.\n * - `'warn'` (default) — emit `console.warn` and take the last definition.\n * - `'error'` — throw a `TypeError` synchronously (useful during development).\n */\n formulaConflictBehavior?: 'ignore' | 'warn' | 'error'\n\n /**\n * Controls what happens when the component mounts and runs its first formula evaluation pass.\n *\n * - `'always'` (default): evaluate on mount and call `onChange` with the enriched result.\n * - `'skip'`: skip evaluation on mount entirely; the form renders with the initial `formData` values as-is.\n * - `'silent'`: evaluate on mount (so the UI shows correct values), but do not call `onChange`.\n * User edits trigger `onChange` normally from that point on.\n *\n * `onFormulaError` and `onLoadingChange` fire normally regardless of mode.\n */\n initialComputationMode?: 'always' | 'skip' | 'silent'\n\n /**\n * Extracts a comparable key from a computed field value for convergence checking.\n * Two values are considered converged when their keys are deeply equal.\n * Defaults to the identity function — full deep equality of the computed value.\n *\n * Useful when a formula returns a compound value that includes non-deterministic parts\n * (e.g. a timestamp) that should not prevent convergence.\n *\n * @param value - The computed field's value from a convergence pass.\n * @param path - The concrete path of the computed field.\n * @returns The value to use for convergence comparison.\n */\n convergenceKey?: (value: unknown, path: (string | number)[]) => unknown\n}\n\n/**\n * Drop-in replacement for RJSF's `<Form>` with support for computed fields.\n *\n * @remarks\n * Fields marked with a formula key in the JSON schema are evaluated automatically\n * on every data change and rendered as read-only. The `evaluator` prop receives\n * the formula string and a context object, and returns the computed value.\n *\n * @example\n * ```tsx\n * import { FormulaForm } from '@a-ludi/rjsf-formulas'\n * import validator from '@rjsf/validator-ajv8'\n * import { Parser } from 'expr-eval'\n *\n * const parser = new Parser()\n *\n * const schema = {\n * type: 'object' as const,\n * properties: {\n * price: { type: 'number' as const },\n * quantity: { type: 'number' as const },\n * total: { type: 'number' as const, 'x-formula': 'price * quantity' },\n * },\n * }\n *\n * function MyForm() {\n * return (\n * <FormulaForm\n * schema={schema}\n * validator={validator}\n * evaluator={(formula, ctx) => parser.evaluate(formula, ctx)}\n * />\n * )\n * }\n * ```\n */\nfunction FormulaFormImpl<\n T = any,\n S extends StrictRJSFSchema = RJSFSchema,\n F extends FormContextType = any\n>(props: FormulaFormProps<T, S, F>, ref: React.Ref<Form<T, S, F>>): JSX.Element {\n const {\n schema,\n formData,\n validator,\n uiSchema,\n evaluator,\n Form: InnerForm = Form as React.ComponentType<FormProps<T, S, F>>,\n formulaKey = 'x-formula',\n formulaContextKey = 'x-formula-context',\n formulaDataKey = '__formData__',\n formulaPathKey = '__path__',\n maxConvergencePasses = 10,\n debounceMs = 300,\n onFormulaError,\n onLoadingChange,\n formulaConflictBehavior = 'warn',\n initialComputationMode = 'always',\n convergenceKey = (v: unknown) => v,\n onChange,\n ...rest\n } = props\n\n const formulaFields: FormulaField[] = useMemo(\n () => analyzeSchema(schema as RJSFSchema, { formulaKey, formulaContextKey }),\n [schema, formulaKey, formulaContextKey]\n )\n\n const contextOptions: BuildContextOptions = useMemo(\n () => ({ formulaDataKey, formulaPathKey }),\n [formulaDataKey, formulaPathKey]\n )\n\n const mergedUiSchema = useMemo(\n () => mergeReadOnly(uiSchema as Record<string, unknown> | undefined, formulaFields),\n [uiSchema, formulaFields]\n )\n\n const checkCondition = useCallback(\n (condition: RJSFSchema, formData: unknown) =>\n validator.isValid(condition as any, formData as any, schema as any),\n [validator, schema]\n )\n\n const suppressCount =\n initialComputationMode === 'always' ? 0 :\n initialComputationMode === 'skip' ? 1 : 2\n\n const suppressCountRef = useRef(suppressCount)\n\n // Reset the suppression counter on every (re)mount. This runs before the\n // enrichedFormData effect (React fires effects in source order), so the\n // counter is always fresh when the enrichedFormData effect reads it.\n // The cleanup restores it on StrictMode's simulated unmount so the\n // re-mount phase starts with a full count.\n useEffect(() => {\n suppressCountRef.current = suppressCount\n return () => { suppressCountRef.current = suppressCount }\n }, []) // eslint-disable-line react-hooks/exhaustive-deps\n\n const { enrichedFormData, handleInput } = useAsyncFormulas(\n formData,\n formulaFields,\n evaluator,\n debounceMs,\n maxConvergencePasses,\n onFormulaError,\n onLoadingChange,\n contextOptions,\n checkCondition,\n formulaConflictBehavior,\n initialComputationMode,\n convergenceKey\n )\n\n const onChangeRef = useRef(onChange)\n useEffect(() => { onChangeRef.current = onChange }, [onChange])\n\n // handleChange fires onChange immediately with raw input and then calls handleInput,\n // which now also calls setEnrichedFormData (optimistic update). That state change would\n // re-trigger the effect below — a duplicate onChange with the same raw data. This flag\n // suppresses exactly that one echo call; it is cleared by the effect after consuming it.\n const skipNextOnChangeRef = useRef(false)\n\n useEffect(() => {\n if (formulaFields.length === 0) return\n if (skipNextOnChangeRef.current) {\n skipNextOnChangeRef.current = false\n return\n }\n if (suppressCountRef.current > 0) {\n suppressCountRef.current--\n return\n }\n onChangeRef.current?.({ formData: enrichedFormData as T } as IChangeEvent<T, S, F>, undefined)\n }, [enrichedFormData]) // eslint-disable-line react-hooks/exhaustive-deps\n\n const handleChange = (data: IChangeEvent<T, S, F>, id?: string) => {\n skipNextOnChangeRef.current = true\n handleInput(data.formData)\n onChange?.(data, id)\n }\n\n return (\n <InnerForm\n ref={ref as any}\n {...rest}\n schema={schema}\n validator={validator}\n formData={enrichedFormData as T}\n uiSchema={mergedUiSchema as any}\n onChange={handleChange}\n />\n )\n}\n\nexport const FormulaForm = forwardRef(FormulaFormImpl) as <\n T = any,\n S extends StrictRJSFSchema = RJSFSchema,\n F extends FormContextType = any\n>(props: FormulaFormProps<T, S, F>) => JSX.Element\n"],"names":["ARRAY_INDEX","analyzeSchema","schema","options","formulaKey","formulaContextKey","formulaConflictBehavior","fields","traverse","composeCondition","ambient","branch","ambientAny","resolveContextMode","value","path","formatPath","s","pathKey","applyConflictBehavior","existing","incoming","behavior","key","mergeFields","base","field","existingIndex","f","ambientCondition","rootSchema","schemaAny","resolved","findSchemaDefinition","formula","isArray","propSchema","itemSchema","index","allOfBranches","branchFields","compositionKey","branches","branchCondition","ifSchema","thenSchema","elseSchema","thenCondition","elseCondition","fastDeepEqual","equal","a","b","length","i","keys","buildContext","resolvedPath","candidateFormData","parent","curr","siblings","getAt","data","setAt","expandPaths","templatePath","currentPath","head","rest","arr","results","deepEqual","applyAllFormulas","formData","formulaFields","evaluator","contextOptions","result","tasks","concretePath","context","settled","resolve","errors","outcome","err","allConverged","prev","next","convergenceKey","enrich","maxConvergencePasses","onFormulaError","formulaDataKey","formulaPathKey","checkCondition","v","activeFields","pathSeen","deduped","idx","current","pass","candidate","error","useAsyncFormulas","debounceMs","onLoadingChange","initialComputationMode","enrichedFormData","setEnrichedFormData","useState","pendingInputRef","useRef","lastExternalFormDataRef","fieldStateRef","debounceTimerRef","runningRef","onFormulaErrorRef","onLoadingChangeRef","evaluatorRef","formulaFieldsRef","maxPassesRef","contextOptionsRef","checkConditionRef","formulaConflictBehaviorRef","convergenceKeyRef","useEffect","startSequence","useCallback","input","concretePaths","cp","stateMap","_a","isUnmountedRef","anyDirty","_b","handleInput","newFormData","state","hasMountedRef","mergeReadOnly","uiSchema","mixedArrayPaths","findMixedArrayPaths","setReadOnly","mixed","depth","seg","parentKey","serializePath","isInt","j","sibling","traversedPath","tail","items","FormulaFormImpl","props","ref","validator","InnerForm","Form","onChange","useMemo","mergedUiSchema","condition","suppressCount","suppressCountRef","onChangeRef","skipNextOnChangeRef","jsx","id","FormulaForm","forwardRef"],"mappings":";;;;AAOO,MAAMA,IAA6B,OAAO,YAAY;AAmFtD,SAASC,GACdC,GACAC,GACgB;AAChB,QAAMC,KAAaD,KAAA,gBAAAA,EAAS,eAAc,aACpCE,KAAoBF,KAAA,gBAAAA,EAAS,sBAAqB,qBAClDG,KAA0BH,KAAA,gBAAAA,EAAS,4BAA2B,QAC9DI,IAAyB,CAAA;AAC/B,SAAAC,EAASN,GAAQ,CAAA,GAAIK,GAAQH,GAAYC,GAAmBC,GAAyB,IAAMJ,CAAM,GAC1FK;AACT;AASA,SAASE,EAAiBC,GAA4BC,GAAgC;AACpF,MAAID,MAAY,GAAM,QAAOC;AAC7B,QAAMC,IAAaF;AACnB,SAAI,MAAM,QAAQE,EAAW,KAAQ,IAC5B,EAAE,OAAO,CAAC,GAAIA,EAAW,OAA2BD,CAAM,EAAA,IAE5D,EAAE,OAAO,CAACD,GAASC,CAAM,EAAA;AAClC;AAEA,SAASE,GACPC,GACAC,GACa;AACb,SAAID,MAAU,UAAaA,MAAU,aAAmB,aACpDA,MAAU,aAAmB,cACjC,QAAQ;AAAA,IACN,oDAAoDA,CAAK,cAAcE,EAAWD,CAAI,CAAC;AAAA,EAA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