@defra/forms-engine-plugin 5.0.0-alpha.20 → 5.0.0-alpha.22
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/.server/server/plugins/engine/helpers.d.ts +1 -0
- package/.server/server/plugins/engine/models/FormModel.js +16 -6
- package/.server/server/plugins/engine/models/FormModel.js.map +1 -1
- package/.server/server/plugins/engine/models/types.d.ts +28 -1
- package/.server/server/plugins/engine/models/types.js.map +1 -1
- package/.server/server/plugins/engine/options.js +2 -1
- package/.server/server/plugins/engine/options.js.map +1 -1
- package/.server/server/plugins/engine/outputFormatters/adapter/v1.js +11 -1
- package/.server/server/plugins/engine/outputFormatters/adapter/v1.js.map +1 -1
- package/.server/server/plugins/engine/pageControllers/helpers/submission.d.ts +34 -1
- package/.server/server/plugins/engine/pageControllers/helpers/submission.js +97 -0
- package/.server/server/plugins/engine/pageControllers/helpers/submission.js.map +1 -1
- package/.server/server/plugins/engine/plugin.js +3 -0
- package/.server/server/plugins/engine/plugin.js.map +1 -1
- package/.server/server/plugins/engine/referenceNumbers.d.ts +1 -0
- package/.server/server/plugins/engine/referenceNumbers.js +1 -0
- package/.server/server/plugins/engine/referenceNumbers.js.map +1 -1
- package/.server/server/plugins/engine/routes/index.js +9 -4
- package/.server/server/plugins/engine/routes/index.js.map +1 -1
- package/.server/server/plugins/engine/types/enums.d.ts +3 -3
- package/.server/server/plugins/engine/types/enums.js +5 -4
- package/.server/server/plugins/engine/types/enums.js.map +1 -1
- package/.server/server/plugins/engine/types/schema.js +9 -3
- package/.server/server/plugins/engine/types/schema.js.map +1 -1
- package/.server/server/plugins/engine/types.d.ts +15 -2
- package/.server/server/plugins/engine/types.js.map +1 -1
- package/.server/typings/hapi/index.d.js.map +1 -1
- package/package.json +2 -2
- package/src/server/plugins/engine/models/FormModel.ts +25 -6
- package/src/server/plugins/engine/models/types.ts +31 -0
- package/src/server/plugins/engine/options.js +2 -1
- package/src/server/plugins/engine/outputFormatters/adapter/v1.ts +15 -1
- package/src/server/plugins/engine/pageControllers/helpers/submission.ts +137 -1
- package/src/server/plugins/engine/plugin.ts +6 -0
- package/src/server/plugins/engine/referenceNumbers.ts +2 -0
- package/src/server/plugins/engine/routes/index.ts +9 -3
- package/src/server/plugins/engine/types/enums.ts +4 -3
- package/src/server/plugins/engine/types/schema.ts +16 -4
- package/src/server/plugins/engine/types.ts +19 -1
- package/src/typings/hapi/index.d.ts +2 -0
|
@@ -70,6 +70,7 @@ export declare function getPluginOptions(server: Server): {
|
|
|
70
70
|
getLanguage?: import("../../../server/plugins/engine/types.js").PluginOptions["getLanguage"];
|
|
71
71
|
baseUrl: string;
|
|
72
72
|
services: import("../../../server/plugins/engine/types.js").PluginOptions["services"];
|
|
73
|
+
generateReferenceNumber: import("../../../server/plugins/engine/types.js").GenerateReferenceNumberHandler;
|
|
73
74
|
};
|
|
74
75
|
/**
|
|
75
76
|
* Handles logging and issuing a permanent redirect for legacy routes.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { ComponentType, ConditionsModel, ControllerPath, ControllerType, SchemaVersion, convertConditionWrapperFromV2, formDefinitionSchema, formDefinitionV2Schema, generateConditionAlias, hasComponents, hasComponentsEvenIfNoNext, hasRepeater, isConditionWrapperV2, yesNoListId, yesNoListName } from '@defra/forms-model';
|
|
1
|
+
import { ComponentType, ConditionEvaluationOutcome, ConditionsModel, ControllerPath, ControllerType, SchemaVersion, convertConditionWrapperFromV2, formDefinitionSchema, formDefinitionV2Schema, generateConditionAlias, getErrorMessage, hasComponents, hasComponentsEvenIfNoNext, hasRepeater, isConditionWrapperV2, yesNoListId, yesNoListName } from '@defra/forms-model';
|
|
2
2
|
import { add, format } from 'date-fns';
|
|
3
3
|
import { Parser } from 'expr-eval-fork';
|
|
4
4
|
import joi from 'joi';
|
|
@@ -189,20 +189,30 @@ export class FormModel {
|
|
|
189
189
|
cause
|
|
190
190
|
});
|
|
191
191
|
}
|
|
192
|
-
const
|
|
192
|
+
const evaluate = evaluationState => {
|
|
193
193
|
const ctx = this.toConditionContext(evaluationState, this.conditions);
|
|
194
194
|
try {
|
|
195
|
-
return
|
|
196
|
-
|
|
197
|
-
|
|
195
|
+
return {
|
|
196
|
+
outcome: expr.evaluate(ctx) ? ConditionEvaluationOutcome.True : ConditionEvaluationOutcome.False
|
|
197
|
+
};
|
|
198
|
+
} catch (err) {
|
|
199
|
+
return {
|
|
200
|
+
outcome: ConditionEvaluationOutcome.Error,
|
|
201
|
+
error: getErrorMessage(err)
|
|
202
|
+
};
|
|
198
203
|
}
|
|
199
204
|
};
|
|
205
|
+
|
|
206
|
+
// A failed evaluation continues to route as `false`. `evaluate` exists so
|
|
207
|
+
// that the two can be told apart when recording outcomes for submission.
|
|
208
|
+
const fn = evaluationState => evaluate(evaluationState).outcome === ConditionEvaluationOutcome.True;
|
|
200
209
|
return {
|
|
201
210
|
name,
|
|
202
211
|
displayName,
|
|
203
212
|
value,
|
|
204
213
|
expr,
|
|
205
|
-
fn
|
|
214
|
+
fn,
|
|
215
|
+
evaluate
|
|
206
216
|
};
|
|
207
217
|
}
|
|
208
218
|
toConditionContext(evaluationState, conditions) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"FormModel.js","names":["ComponentType","ConditionsModel","ControllerPath","ControllerType","SchemaVersion","convertConditionWrapperFromV2","formDefinitionSchema","formDefinitionV2Schema","generateConditionAlias","hasComponents","hasComponentsEvenIfNoNext","hasRepeater","isConditionWrapperV2","yesNoListId","yesNoListName","add","format","Parser","joi","logger","EN_GB","hasListFormField","todayAsDateOnly","ConditionBuildError","SchemaValidationError","findPage","getError","getPage","loadFormTranslations","createTranslator","extractBaseTranslations","createFormI18nInstance","getAvailableLanguages","createPage","validationOptions","opts","defaultServices","FormAction","merge","FormModel","engine","schemaVersion","def","lists","sections","name","formId","values","basePath","ordnanceSurveyApiKey","conditions","pages","services","i18nInstance","controllers","pageDefMap","listDefMap","listDefIdMap","componentDefMap","componentDefIdMap","pageMap","componentMap","constructor","options","schema","V1","warn","result","validate","abortEarly","error","structuredClone","value","baseTranslations","push","id","title","type","items","text","moreThanOnePaymentQuestion","Error","Map","map","page","path","list","filter","flatMap","components","component","forEach","conditionDef","condition","makeCondition","pageDef","some","controller","Status","collection","language","metadata","translations","makeFilteredSchema","relevantPages","object","required","concat","stateSchema","parser","operators","logical","Object","assign","functions","dateForComparison","timePeriod","timeUnit","displayName","expr","toConditionExpression","cause","fn","evaluationState","ctx","toConditionContext","evaluate","context","conditionId","propertyName","V2","defineProperty","get","from","parse","toExpression","getList","nameOrId","find","getSection","section","getFormContext","request","state","errors","translator","query","currentPath","startPath","getStartPath","isForceAccess","relevantState","payload","getFormDataFromState","paths","data","referenceNumber","getReferenceNumber","languages","validateFormPayload","nextPage","initialiseContext","assignEvaluationState","assignRelevantState","pageStateIsInvalid","getNextPath","validateFormState","assignPaths","emptyState","freeze","getContextValueFromState","key","keys","listFields","fields","field","undefined","YesNoField","hasOptionalItems","item","length","fieldStateIsInvalid","validValues","fieldState","getFormValueFromState","isInvalid","isArray","Array","every","includes","t","href","getComponentById","componentId","getListById","listId","getConditionById","numOfPaymentFields","comp","PaymentField","action","getFormParams","Validate","startsWith","External","update","CheckboxesField","formState","getStateFromValidForm","previousPages","relevantPage","model","stripUnknown","errorsState","details","$$__referenceNumber"],"sources":["../../../../../src/server/plugins/engine/models/FormModel.ts"],"sourcesContent":["import {\n ComponentType,\n ConditionsModel,\n ControllerPath,\n ControllerType,\n SchemaVersion,\n convertConditionWrapperFromV2,\n formDefinitionSchema,\n formDefinitionV2Schema,\n generateConditionAlias,\n hasComponents,\n hasComponentsEvenIfNoNext,\n hasRepeater,\n isConditionWrapperV2,\n yesNoListId,\n yesNoListName,\n type ComponentDef,\n type ConditionWrapper,\n type ConditionWrapperV2,\n type ConditionsModelData,\n type DateUnits,\n type Engine,\n type FormDefinition,\n type List,\n type Page,\n type Section\n} from '@defra/forms-model'\nimport { add, format } from 'date-fns'\nimport { Parser, type Value } from 'expr-eval-fork'\nimport { type i18n } from 'i18next'\nimport joi from 'joi'\n\nimport { logger } from '~/src/server/common/helpers/logging/logger.js'\nimport { EN_GB } from '~/src/server/constants.js'\nimport { type ListFormComponent } from '~/src/server/plugins/engine/components/ListFormComponent.js'\nimport {} from '~/src/server/plugins/engine/components/YesNoField.js'\nimport {\n hasListFormField,\n type Component\n} from '~/src/server/plugins/engine/components/helpers/components.js'\nimport { todayAsDateOnly } from '~/src/server/plugins/engine/date-helper.js'\nimport {\n ConditionBuildError,\n SchemaValidationError\n} from '~/src/server/plugins/engine/errors.js'\nimport {\n findPage,\n getError,\n getPage\n} from '~/src/server/plugins/engine/helpers.js'\nimport { loadFormTranslations } from '~/src/server/plugins/engine/i18n/createFormTranslator.js'\nimport { createTranslator } from '~/src/server/plugins/engine/i18n/createTranslator.js'\nimport { extractBaseTranslations } from '~/src/server/plugins/engine/i18n/extractBaseTranslations.js'\nimport { createFormI18nInstance } from '~/src/server/plugins/engine/i18n/index.js'\nimport { getAvailableLanguages } from '~/src/server/plugins/engine/i18n/languages.js'\nimport { type Translator } from '~/src/server/plugins/engine/i18n/types.js'\nimport { type ExecutableCondition } from '~/src/server/plugins/engine/models/types.js'\nimport { type PageController } from '~/src/server/plugins/engine/pageControllers/PageController.js'\nimport {\n createPage,\n type PageControllerClass\n} from '~/src/server/plugins/engine/pageControllers/helpers/pages.js'\nimport { validationOptions as opts } from '~/src/server/plugins/engine/pageControllers/validationOptions.js'\nimport * as defaultServices from '~/src/server/plugins/engine/services/index.js'\nimport {\n type FormContext,\n type FormContextRequest,\n type FormState,\n type FormSubmissionError,\n type FormSubmissionState\n} from '~/src/server/plugins/engine/types.js'\nimport { FormAction } from '~/src/server/routes/types.js'\nimport { merge } from '~/src/server/services/cacheService.js'\nimport { type Services } from '~/src/server/types.js'\n\nexport class FormModel {\n /** The runtime engine that should be used */\n engine?: Engine\n\n schemaVersion: SchemaVersion\n\n /** the entire form JSON as an object */\n def: FormDefinition\n\n lists: FormDefinition['lists']\n sections: FormDefinition['sections'] = []\n name: string\n formId: string\n values: FormDefinition\n basePath: string\n ordnanceSurveyApiKey?: string\n conditions: Partial<Record<string, ExecutableCondition>>\n pages: PageControllerClass[]\n services: Services\n private readonly i18nInstance: i18n\n\n controllers?: Record<string, typeof PageController>\n pageDefMap: Map<string, Page>\n\n listDefMap: Map<string, List>\n listDefIdMap: Map<string, List>\n\n componentDefMap: Map<string, ComponentDef>\n componentDefIdMap: Map<string, ComponentDef>\n\n pageMap: Map<string, PageControllerClass>\n componentMap: Map<string, Component>\n\n constructor(\n def: typeof this.def,\n options: {\n basePath: string\n ordnanceSurveyApiKey?: string\n formId?: string\n },\n services: Services = defaultServices,\n controllers?: Record<string, typeof PageController>\n ) {\n let schema = formDefinitionV2Schema\n\n if (!def.schema || def.schema === SchemaVersion.V1) {\n logger.warn(\n `[DEPRECATION NOTICE] Form \"${def.name}\" constructed with legacy V1 schema. See https://defra.github.io/forms-engine-plugin/schemas/form-definition-schema.html.`\n )\n schema = formDefinitionSchema\n }\n\n const result = schema.validate(def, { abortEarly: false })\n\n if (result.error) {\n throw new SchemaValidationError(result.error)\n }\n\n // Make a clone of the shallow copy returned\n // by joi so as not to change the source data.\n def = structuredClone(result.value)\n\n const baseTranslations = extractBaseTranslations(def)\n this.i18nInstance = createFormI18nInstance(baseTranslations)\n loadFormTranslations(def, this.i18nInstance)\n\n // Add default lists. Yes/No text stored as i18n key constants so they\n // resolve to the user's language at render time via the translator.\n def.lists.push({\n id: def.schema === SchemaVersion.V1 ? yesNoListName : yesNoListId,\n name: '__yesNo',\n title: 'Yes/No',\n type: 'boolean',\n items: [\n {\n id: '02900d42-83d1-4c72-a719-c4e8228952fa',\n text: 'components.yesNoField.yes',\n value: true\n },\n {\n id: 'f39000eb-c51b-4019-8f82-bbda0423f04d',\n text: 'components.yesNoField.no',\n value: false\n }\n ]\n })\n\n this.engine = def.engine\n this.schemaVersion = def.schema ?? SchemaVersion.V1\n this.def = def\n this.lists = def.lists\n this.sections = def.sections\n this.name = def.name ?? ''\n this.formId = options.formId ?? ''\n this.values = result.value\n this.basePath = options.basePath\n this.ordnanceSurveyApiKey = options.ordnanceSurveyApiKey\n this.conditions = {}\n this.services = services\n this.controllers = controllers\n\n // Assert that there is only one payment question (if any)\n if (this.moreThanOnePaymentQuestion()) {\n throw new Error(\n 'Invalid form definition: Only one payment question is allowed per form'\n )\n }\n\n this.pageDefMap = new Map(def.pages.map((page) => [page.path, page]))\n this.listDefMap = new Map(def.lists.map((list) => [list.name, list]))\n this.listDefIdMap = new Map(\n def.lists\n .filter((list) => list.id) // Skip lists without an ID\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n .map((list) => [list.id as string, list])\n )\n this.componentDefMap = new Map(\n def.pages\n .filter(hasComponents)\n .flatMap((page) =>\n page.components.map((component) => [component.name, component])\n )\n )\n this.componentDefIdMap = new Map(\n def.pages.filter(hasComponents).flatMap((page) =>\n page.components\n .filter((component) => component.id) // Skip components without an ID\n .map((component) => {\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n return [component.id as string, component]\n })\n )\n )\n\n def.conditions.forEach((conditionDef) => {\n const condition = this.makeCondition(\n isConditionWrapperV2(conditionDef)\n ? convertConditionWrapperFromV2(conditionDef, this)\n : conditionDef\n )\n this.conditions[condition.name] = condition\n })\n\n this.pages = def.pages.map((pageDef) => createPage(this, pageDef))\n\n if (\n !def.pages.some(\n ({ controller }) =>\n // Check for user-provided status page (optional)\n controller === ControllerType.Status\n )\n ) {\n this.pages.push(\n createPage(this, {\n title: 'pages.confirmation.formSubmitted',\n path: ControllerPath.Status,\n controller: ControllerType.Status\n })\n )\n }\n\n this.pageMap = new Map(this.pages.map((page) => [page.path, page]))\n this.componentMap = new Map(\n this.pages.flatMap((page) =>\n page.collection.components.map((component) => [\n component.name,\n component\n ])\n )\n )\n }\n\n /** Returns a scoped translator pair for the given language. */\n createTranslator(language = EN_GB): Translator {\n // @ts-expect-error - dynamic language lookup\n if (!this.def.metadata?.translations?.[language]) {\n // If not translations defined in the FormDefinition, always default to English\n language = EN_GB\n }\n return createTranslator(this.i18nInstance, language)\n }\n\n /**\n * build the entire model schema from individual pages/sections and filter out answers\n * for pages which are no longer accessible due to an answer that has been changed\n */\n makeFilteredSchema(relevantPages: PageControllerClass[]) {\n // Build the entire model schema\n // from the individual pages/sections\n let schema = joi.object<FormSubmissionState>().required()\n\n relevantPages.forEach((page) => {\n schema = schema.concat(page.collection.stateSchema)\n })\n\n return schema\n }\n\n /**\n * Instantiates a Condition based on {@link ConditionWrapper}\n * @param condition\n */\n makeCondition(condition: ConditionWrapper): ExecutableCondition {\n const parser = new Parser({\n operators: {\n logical: true\n }\n })\n\n Object.assign(parser.functions, {\n dateForComparison(timePeriod: number, timeUnit: DateUnits) {\n // The time element must be stripped (hence using startOfDay() which has no time element),\n // then formatted as YYYY-MM-DD otherwise we can hit time element and BST issues giving the\n // wrong date to compare against.\n // Do not use .toISOString() to format the date as that introduces BST errors.\n return format(\n add(todayAsDateOnly(), { [timeUnit]: timePeriod }),\n 'yyyy-MM-dd'\n )\n }\n })\n\n const { name, displayName, value } = condition\n\n let expr\n try {\n expr = this.toConditionExpression(value, parser)\n } catch (cause) {\n throw new ConditionBuildError(displayName, { cause })\n }\n\n const fn = (evaluationState: FormState) => {\n const ctx = this.toConditionContext(evaluationState, this.conditions)\n try {\n return expr.evaluate(ctx) as boolean\n } catch {\n return false\n }\n }\n\n return {\n name,\n displayName,\n value,\n expr,\n fn\n }\n }\n\n toConditionContext(\n evaluationState: FormState,\n conditions: Partial<Record<string, ExecutableCondition>>\n ) {\n const context = { ...evaluationState }\n\n for (const conditionId in conditions) {\n const propertyName =\n this.schemaVersion === SchemaVersion.V2\n ? generateConditionAlias(conditionId)\n : conditionId\n\n Object.defineProperty(context, propertyName, {\n get() {\n return conditions[conditionId]?.fn(evaluationState)\n }\n })\n }\n\n return context as Extract<Value, Record<string, Value>>\n }\n\n toConditionExpression(value: ConditionsModelData, parser: Parser) {\n const conditions = ConditionsModel.from(value)\n return parser.parse(conditions.toExpression())\n }\n\n getList(nameOrId: string): List | undefined {\n return this.schemaVersion === SchemaVersion.V1\n ? this.lists.find((list) => list.name === nameOrId)\n : this.lists.find((list) => list.id === nameOrId)\n }\n\n getSection(nameOrId: string): Section | undefined {\n return this.schemaVersion === SchemaVersion.V1\n ? this.sections.find((section) => section.name === nameOrId)\n : this.sections.find((section) => section.id === nameOrId)\n }\n\n /**\n * Form context for the current page\n */\n getFormContext(\n request: FormContextRequest,\n state: FormSubmissionState,\n errors?: FormSubmissionError[],\n translator?: Translator\n ): FormContext {\n const { query } = request\n\n const page = getPage(this, request)\n\n // Determine form paths\n const currentPath = page.path\n const startPath = page.getStartPath()\n\n // Preview URL direct access is allowed\n const isForceAccess = 'force' in query\n\n let context: FormContext = {\n evaluationState: {},\n relevantState: {},\n relevantPages: [],\n payload: page.getFormDataFromState(request, state),\n state,\n paths: [],\n errors,\n isForceAccess,\n data: {},\n pageDefMap: this.pageDefMap,\n listDefMap: this.listDefMap,\n componentDefMap: this.componentDefMap,\n pageMap: this.pageMap,\n componentMap: this.componentMap,\n referenceNumber: getReferenceNumber(state),\n languages: getAvailableLanguages(this.def),\n translator\n }\n\n // Validate current page\n context = validateFormPayload(request, page, context, translator)\n\n // Find start page\n let nextPage = findPage(this, startPath)\n\n this.initialiseContext(context)\n\n // Walk form pages from start\n while (nextPage) {\n // Add page to context\n context.relevantPages.push(nextPage)\n\n this.assignEvaluationState(context, nextPage)\n\n this.assignRelevantState(context, nextPage)\n\n // Stop at current page\n if (\n this.pageStateIsInvalid(context, nextPage, translator) ||\n nextPage.path === currentPath\n ) {\n break\n }\n\n // Apply conditions to determine next page\n nextPage = findPage(this, nextPage.getNextPath(context))\n }\n\n // Validate form state\n context = validateFormState(request, page, context)\n\n // Add paths for navigation\n this.assignPaths(context)\n\n return context\n }\n\n private initialiseContext(context: FormContext) {\n // Initialise `evaluationState` for all keys using empty state.\n // This is because the current condition evaluation library (eval-expr)\n // will throw if an expression uses a key that is undefined.\n const emptyState = Object.freeze({})\n\n for (const page of this.pages) {\n const { collection, pageDef } = page\n\n if (!hasRepeater(pageDef)) {\n Object.assign(\n context.evaluationState,\n collection.getContextValueFromState(emptyState)\n )\n }\n }\n }\n\n private assignEvaluationState(\n context: FormContext,\n page: PageControllerClass\n ) {\n const { collection, pageDef } = page\n // Skip evaluation state for repeater pages\n\n if (!hasRepeater(pageDef)) {\n Object.assign(\n context.evaluationState,\n collection.getContextValueFromState(context.state)\n )\n }\n }\n\n private assignRelevantState(context: FormContext, page: PageControllerClass) {\n // Copy relevant state by expected keys\n for (const key of page.keys) {\n if (typeof context.state[key] !== 'undefined') {\n context.relevantState[key] = context.state[key]\n }\n }\n }\n\n private pageStateIsInvalid(\n context: FormContext,\n page: PageControllerClass,\n translator?: Translator\n ) {\n // Get any list-bound fields on the page\n const listFields = page.collection.fields.filter(hasListFormField)\n\n // For each list field that is bound to a list that contains any conditional items,\n // we need to check any answers are still valid. Do this by evaluating the conditions\n // and ensuring any current answers are all included in the set of valid answers\n for (const field of listFields) {\n const list = field.list\n\n // Filter out YesNo as they can't be conditional\n if (list !== undefined && field.type !== ComponentType.YesNoField) {\n const hasOptionalItems =\n list.items.filter((item) => item.condition).length > 0\n\n if (hasOptionalItems) {\n return this.fieldStateIsInvalid(context, field, list, translator)\n }\n }\n }\n }\n\n private fieldStateIsInvalid(\n context: FormContext,\n field: ListFormComponent,\n list: List,\n translator?: Translator\n ) {\n const { evaluationState, state } = context\n\n const validValues = list.items\n .filter((item) =>\n item.condition\n ? this.conditions[item.condition]?.fn(evaluationState)\n : true\n )\n .map((item) => item.value)\n\n // Get the field state\n const fieldState = field.getFormValueFromState(state)\n\n if (fieldState !== undefined) {\n let isInvalid = false\n const isArray = Array.isArray(fieldState)\n\n // Check if any saved state value(s) are still valid\n // and return true if any are invalid\n if (isArray) {\n isInvalid = !fieldState.every((item) => validValues.includes(item))\n } else {\n isInvalid = !validValues.includes(fieldState)\n }\n\n if (isInvalid) {\n context.errors ??= []\n\n const text = (translator ?? this.createTranslator('en-GB')).t(\n 'errors.optionsMismatch'\n )\n\n context.errors.push({\n text,\n name: field.name,\n href: `#${field.name}`,\n path: [`#${field.name}`]\n })\n }\n\n return isInvalid\n }\n }\n\n private assignPaths(context: FormContext) {\n for (const { keys, path } of context.relevantPages) {\n context.paths.push(path)\n\n // Stop at page with errors\n if (\n context.errors?.some(({ name, path }) => {\n return keys.includes(name) || keys.some((key) => path.includes(key))\n })\n ) {\n break\n }\n }\n }\n\n getComponentById(componentId: string): ComponentDef | undefined {\n return this.componentDefIdMap.get(componentId)\n }\n\n getListById(listId: string): List | undefined {\n return this.listDefIdMap.get(listId)\n }\n\n /**\n * Returns a condition by its ID. O(n) lookup time.\n * @param conditionId\n * @returns\n */\n getConditionById(conditionId: string): ConditionWrapperV2 | undefined {\n return this.def.conditions\n .filter(isConditionWrapperV2)\n .find((condition) => condition.id === conditionId)\n }\n\n /**\n * Checks that only one payment field exists (if any payments fields exist)\n */\n moreThanOnePaymentQuestion() {\n const numOfPaymentFields = this.def.pages\n .flatMap((page) =>\n hasComponentsEvenIfNoNext(page) ? page.components : []\n )\n .filter((comp) => comp.type === ComponentType.PaymentField).length\n return numOfPaymentFields > 1\n }\n}\n\n/**\n * Validate current page only\n */\nfunction validateFormPayload(\n request: FormContextRequest,\n page: PageControllerClass,\n context: FormContext,\n translator?: Translator\n): FormContext {\n const { collection } = page\n const { payload, state } = context\n\n const { action } = page.getFormParams(request)\n\n // Skip validation GET requests or other actions\n if (\n !request.payload ||\n (action &&\n action !== FormAction.Validate &&\n !action.startsWith(FormAction.External))\n ) {\n return context\n }\n\n // For checkbox fields missing in the payload (i.e. unchecked),\n // explicitly set their value to undefined so that any previously\n // stored value is cleared and required field validation is enforced.\n const update = { ...request.payload }\n collection.fields.forEach((field) => {\n if (\n field.type === ComponentType.CheckboxesField &&\n !(field.name in update)\n ) {\n update[field.name] = undefined\n }\n })\n\n const { value, errors } = collection.validate(\n { ...payload, ...update },\n translator\n )\n\n // Add sanitised payload (ready to save)\n const formState = page.getStateFromValidForm(request, state, value)\n\n return {\n ...context,\n payload: merge(payload, value),\n state: merge(state, formState),\n errors\n }\n}\n\n/**\n * Validate entire form state\n */\nfunction validateFormState(\n request: FormContextRequest,\n page: PageControllerClass,\n context: FormContext\n): FormContext {\n const { errors = [], relevantPages, relevantState } = context\n\n // Exclude current page\n const previousPages = relevantPages.filter(\n (relevantPage) => relevantPage !== page\n )\n\n // Validate relevant state\n const { error } = page.model\n .makeFilteredSchema(previousPages)\n .validate(relevantState, { ...opts, stripUnknown: true })\n\n // Add relevant state errors\n if (error) {\n const errorsState = error.details.map((item) => getError(EN_GB, item))\n return { ...context, errors: errors.concat(errorsState) }\n }\n\n return context\n}\n\nfunction getReferenceNumber(state: FormSubmissionState): string {\n if (\n !state.$$__referenceNumber ||\n typeof state.$$__referenceNumber !== 'string'\n ) {\n throw Error('Reference number not found in form state')\n }\n\n return state.$$__referenceNumber\n}\n"],"mappings":"AAAA,SACEA,aAAa,EACbC,eAAe,EACfC,cAAc,EACdC,cAAc,EACdC,aAAa,EACbC,6BAA6B,EAC7BC,oBAAoB,EACpBC,sBAAsB,EACtBC,sBAAsB,EACtBC,aAAa,EACbC,yBAAyB,EACzBC,WAAW,EACXC,oBAAoB,EACpBC,WAAW,EACXC,aAAa,QAWR,oBAAoB;AAC3B,SAASC,GAAG,EAAEC,MAAM,QAAQ,UAAU;AACtC,SAASC,MAAM,QAAoB,gBAAgB;AAEnD,OAAOC,GAAG,MAAM,KAAK;AAErB,SAASC,MAAM;AACf,SAASC,KAAK;AAEd;AACA,SACEC,gBAAgB;AAGlB,SAASC,eAAe;AACxB,SACEC,mBAAmB,EACnBC,qBAAqB;AAEvB,SACEC,QAAQ,EACRC,QAAQ,EACRC,OAAO;AAET,SAASC,oBAAoB;AAC7B,SAASC,gBAAgB;AACzB,SAASC,uBAAuB;AAChC,SAASC,sBAAsB;AAC/B,SAASC,q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AEA,SAAS8B,kBAAkBA,CAACd,KAA0B,EAAU;EAC9D,IACE,CAACA,KAAK,CAACwE,mBAAmB,IAC1B,OAAOxE,KAAK,CAACwE,mBAAmB,KAAK,QAAQ,EAC7C;IACA,MAAMtI,KAAK,CAAC,0CAA0C,CAAC;EACzD;EAEA,OAAO8D,KAAK,CAACwE,mBAAmB;AAClC","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"FormModel.js","names":["ComponentType","ConditionEvaluationOutcome","ConditionsModel","ControllerPath","ControllerType","SchemaVersion","convertConditionWrapperFromV2","formDefinitionSchema","formDefinitionV2Schema","generateConditionAlias","getErrorMessage","hasComponents","hasComponentsEvenIfNoNext","hasRepeater","isConditionWrapperV2","yesNoListId","yesNoListName","add","format","Parser","joi","logger","EN_GB","hasListFormField","todayAsDateOnly","ConditionBuildError","SchemaValidationError","findPage","getError","getPage","loadFormTranslations","createTranslator","extractBaseTranslations","createFormI18nInstance","getAvailableLanguages","createPage","validationOptions","opts","defaultServices","FormAction","merge","FormModel","engine","schemaVersion","def","lists","sections","name","formId","values","basePath","ordnanceSurveyApiKey","conditions","pages","services","i18nInstance","controllers","pageDefMap","listDefMap","listDefIdMap","componentDefMap","componentDefIdMap","pageMap","componentMap","constructor","options","schema","V1","warn","result","validate","abortEarly","error","structuredClone","value","baseTranslations","push","id","title","type","items","text","moreThanOnePaymentQuestion","Error","Map","map","page","path","list","filter","flatMap","components","component","forEach","conditionDef","condition","makeCondition","pageDef","some","controller","Status","collection","language","metadata","translations","makeFilteredSchema","relevantPages","object","required","concat","stateSchema","parser","operators","logical","Object","assign","functions","dateForComparison","timePeriod","timeUnit","displayName","expr","toConditionExpression","cause","evaluate","evaluationState","ctx","toConditionContext","outcome","True","False","err","fn","context","conditionId","propertyName","V2","defineProperty","get","from","parse","toExpression","getList","nameOrId","find","getSection","section","getFormContext","request","state","errors","translator","query","currentPath","startPath","getStartPath","isForceAccess","relevantState","payload","getFormDataFromState","paths","data","referenceNumber","getReferenceNumber","languages","validateFormPayload","nextPage","initialiseContext","assignEvaluationState","assignRelevantState","pageStateIsInvalid","getNextPath","validateFormState","assignPaths","emptyState","freeze","getContextValueFromState","key","keys","listFields","fields","field","undefined","YesNoField","hasOptionalItems","item","length","fieldStateIsInvalid","validValues","fieldState","getFormValueFromState","isInvalid","isArray","Array","every","includes","t","href","getComponentById","componentId","getListById","listId","getConditionById","numOfPaymentFields","comp","PaymentField","action","getFormParams","Validate","startsWith","External","update","CheckboxesField","formState","getStateFromValidForm","previousPages","relevantPage","model","stripUnknown","errorsState","details","$$__referenceNumber"],"sources":["../../../../../src/server/plugins/engine/models/FormModel.ts"],"sourcesContent":["import {\n ComponentType,\n ConditionEvaluationOutcome,\n ConditionsModel,\n ControllerPath,\n ControllerType,\n SchemaVersion,\n convertConditionWrapperFromV2,\n formDefinitionSchema,\n formDefinitionV2Schema,\n generateConditionAlias,\n getErrorMessage,\n hasComponents,\n hasComponentsEvenIfNoNext,\n hasRepeater,\n isConditionWrapperV2,\n yesNoListId,\n yesNoListName,\n type ComponentDef,\n type ConditionWrapper,\n type ConditionWrapperV2,\n type ConditionsModelData,\n type DateUnits,\n type Engine,\n type FormDefinition,\n type List,\n type Page,\n type Section\n} from '@defra/forms-model'\nimport { add, format } from 'date-fns'\nimport { Parser, type Value } from 'expr-eval-fork'\nimport { type i18n } from 'i18next'\nimport joi from 'joi'\n\nimport { logger } from '~/src/server/common/helpers/logging/logger.js'\nimport { EN_GB } from '~/src/server/constants.js'\nimport { type ListFormComponent } from '~/src/server/plugins/engine/components/ListFormComponent.js'\nimport {} from '~/src/server/plugins/engine/components/YesNoField.js'\nimport {\n hasListFormField,\n type Component\n} from '~/src/server/plugins/engine/components/helpers/components.js'\nimport { todayAsDateOnly } from '~/src/server/plugins/engine/date-helper.js'\nimport {\n ConditionBuildError,\n SchemaValidationError\n} from '~/src/server/plugins/engine/errors.js'\nimport {\n findPage,\n getError,\n getPage\n} from '~/src/server/plugins/engine/helpers.js'\nimport { loadFormTranslations } from '~/src/server/plugins/engine/i18n/createFormTranslator.js'\nimport { createTranslator } from '~/src/server/plugins/engine/i18n/createTranslator.js'\nimport { extractBaseTranslations } from '~/src/server/plugins/engine/i18n/extractBaseTranslations.js'\nimport { createFormI18nInstance } from '~/src/server/plugins/engine/i18n/index.js'\nimport { getAvailableLanguages } from '~/src/server/plugins/engine/i18n/languages.js'\nimport { type Translator } from '~/src/server/plugins/engine/i18n/types.js'\nimport {\n type ConditionEvaluation,\n type ExecutableCondition\n} from '~/src/server/plugins/engine/models/types.js'\nimport { type PageController } from '~/src/server/plugins/engine/pageControllers/PageController.js'\nimport {\n createPage,\n type PageControllerClass\n} from '~/src/server/plugins/engine/pageControllers/helpers/pages.js'\nimport { validationOptions as opts } from '~/src/server/plugins/engine/pageControllers/validationOptions.js'\nimport * as defaultServices from '~/src/server/plugins/engine/services/index.js'\nimport {\n type FormContext,\n type FormContextRequest,\n type FormState,\n type FormSubmissionError,\n type FormSubmissionState\n} from '~/src/server/plugins/engine/types.js'\nimport { FormAction } from '~/src/server/routes/types.js'\nimport { merge } from '~/src/server/services/cacheService.js'\nimport { type Services } from '~/src/server/types.js'\n\nexport class FormModel {\n /** The runtime engine that should be used */\n engine?: Engine\n\n schemaVersion: SchemaVersion\n\n /** the entire form JSON as an object */\n def: FormDefinition\n\n lists: FormDefinition['lists']\n sections: FormDefinition['sections'] = []\n name: string\n formId: string\n values: FormDefinition\n basePath: string\n ordnanceSurveyApiKey?: string\n conditions: Partial<Record<string, ExecutableCondition>>\n pages: PageControllerClass[]\n services: Services\n private readonly i18nInstance: i18n\n\n controllers?: Record<string, typeof PageController>\n pageDefMap: Map<string, Page>\n\n listDefMap: Map<string, List>\n listDefIdMap: Map<string, List>\n\n componentDefMap: Map<string, ComponentDef>\n componentDefIdMap: Map<string, ComponentDef>\n\n pageMap: Map<string, PageControllerClass>\n componentMap: Map<string, Component>\n\n constructor(\n def: typeof this.def,\n options: {\n basePath: string\n ordnanceSurveyApiKey?: string\n formId?: string\n },\n services: Services = defaultServices,\n controllers?: Record<string, typeof PageController>\n ) {\n let schema = formDefinitionV2Schema\n\n if (!def.schema || def.schema === SchemaVersion.V1) {\n logger.warn(\n `[DEPRECATION NOTICE] Form \"${def.name}\" constructed with legacy V1 schema. See https://defra.github.io/forms-engine-plugin/schemas/form-definition-schema.html.`\n )\n schema = formDefinitionSchema\n }\n\n const result = schema.validate(def, { abortEarly: false })\n\n if (result.error) {\n throw new SchemaValidationError(result.error)\n }\n\n // Make a clone of the shallow copy returned\n // by joi so as not to change the source data.\n def = structuredClone(result.value)\n\n const baseTranslations = extractBaseTranslations(def)\n this.i18nInstance = createFormI18nInstance(baseTranslations)\n loadFormTranslations(def, this.i18nInstance)\n\n // Add default lists. Yes/No text stored as i18n key constants so they\n // resolve to the user's language at render time via the translator.\n def.lists.push({\n id: def.schema === SchemaVersion.V1 ? yesNoListName : yesNoListId,\n name: '__yesNo',\n title: 'Yes/No',\n type: 'boolean',\n items: [\n {\n id: '02900d42-83d1-4c72-a719-c4e8228952fa',\n text: 'components.yesNoField.yes',\n value: true\n },\n {\n id: 'f39000eb-c51b-4019-8f82-bbda0423f04d',\n text: 'components.yesNoField.no',\n value: false\n }\n ]\n })\n\n this.engine = def.engine\n this.schemaVersion = def.schema ?? SchemaVersion.V1\n this.def = def\n this.lists = def.lists\n this.sections = def.sections\n this.name = def.name ?? ''\n this.formId = options.formId ?? ''\n this.values = result.value\n this.basePath = options.basePath\n this.ordnanceSurveyApiKey = options.ordnanceSurveyApiKey\n this.conditions = {}\n this.services = services\n this.controllers = controllers\n\n // Assert that there is only one payment question (if any)\n if (this.moreThanOnePaymentQuestion()) {\n throw new Error(\n 'Invalid form definition: Only one payment question is allowed per form'\n )\n }\n\n this.pageDefMap = new Map(def.pages.map((page) => [page.path, page]))\n this.listDefMap = new Map(def.lists.map((list) => [list.name, list]))\n this.listDefIdMap = new Map(\n def.lists\n .filter((list) => list.id) // Skip lists without an ID\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n .map((list) => [list.id as string, list])\n )\n this.componentDefMap = new Map(\n def.pages\n .filter(hasComponents)\n .flatMap((page) =>\n page.components.map((component) => [component.name, component])\n )\n )\n this.componentDefIdMap = new Map(\n def.pages.filter(hasComponents).flatMap((page) =>\n page.components\n .filter((component) => component.id) // Skip components without an ID\n .map((component) => {\n // eslint-disable-next-line @typescript-eslint/non-nullable-type-assertion-style\n return [component.id as string, component]\n })\n )\n )\n\n def.conditions.forEach((conditionDef) => {\n const condition = this.makeCondition(\n isConditionWrapperV2(conditionDef)\n ? convertConditionWrapperFromV2(conditionDef, this)\n : conditionDef\n )\n this.conditions[condition.name] = condition\n })\n\n this.pages = def.pages.map((pageDef) => createPage(this, pageDef))\n\n if (\n !def.pages.some(\n ({ controller }) =>\n // Check for user-provided status page (optional)\n controller === ControllerType.Status\n )\n ) {\n this.pages.push(\n createPage(this, {\n title: 'pages.confirmation.formSubmitted',\n path: ControllerPath.Status,\n controller: ControllerType.Status\n })\n )\n }\n\n this.pageMap = new Map(this.pages.map((page) => [page.path, page]))\n this.componentMap = new Map(\n this.pages.flatMap((page) =>\n page.collection.components.map((component) => [\n component.name,\n component\n ])\n )\n )\n }\n\n /** Returns a scoped translator pair for the given language. */\n createTranslator(language = EN_GB): Translator {\n // @ts-expect-error - dynamic language lookup\n if (!this.def.metadata?.translations?.[language]) {\n // If not translations defined in the FormDefinition, always default to English\n language = EN_GB\n }\n return createTranslator(this.i18nInstance, language)\n }\n\n /**\n * build the entire model schema from individual pages/sections and filter out answers\n * for pages which are no longer accessible due to an answer that has been changed\n */\n makeFilteredSchema(relevantPages: PageControllerClass[]) {\n // Build the entire model schema\n // from the individual pages/sections\n let schema = joi.object<FormSubmissionState>().required()\n\n relevantPages.forEach((page) => {\n schema = schema.concat(page.collection.stateSchema)\n })\n\n return schema\n }\n\n /**\n * Instantiates a Condition based on {@link ConditionWrapper}\n * @param condition\n */\n makeCondition(condition: ConditionWrapper): ExecutableCondition {\n const parser = new Parser({\n operators: {\n logical: true\n }\n })\n\n Object.assign(parser.functions, {\n dateForComparison(timePeriod: number, timeUnit: DateUnits) {\n // The time element must be stripped (hence using startOfDay() which has no time element),\n // then formatted as YYYY-MM-DD otherwise we can hit time element and BST issues giving the\n // wrong date to compare against.\n // Do not use .toISOString() to format the date as that introduces BST errors.\n return format(\n add(todayAsDateOnly(), { [timeUnit]: timePeriod }),\n 'yyyy-MM-dd'\n )\n }\n })\n\n const { name, displayName, value } = condition\n\n let expr\n try {\n expr = this.toConditionExpression(value, parser)\n } catch (cause) {\n throw new ConditionBuildError(displayName, { cause })\n }\n\n const evaluate = (evaluationState: FormState): ConditionEvaluation => {\n const ctx = this.toConditionContext(evaluationState, this.conditions)\n\n try {\n return {\n outcome: (expr.evaluate(ctx) as boolean)\n ? ConditionEvaluationOutcome.True\n : ConditionEvaluationOutcome.False\n }\n } catch (err) {\n return {\n outcome: ConditionEvaluationOutcome.Error,\n error: getErrorMessage(err)\n }\n }\n }\n\n // A failed evaluation continues to route as `false`. `evaluate` exists so\n // that the two can be told apart when recording outcomes for submission.\n const fn = (evaluationState: FormState) =>\n evaluate(evaluationState).outcome === ConditionEvaluationOutcome.True\n\n return {\n name,\n displayName,\n value,\n expr,\n fn,\n evaluate\n }\n }\n\n toConditionContext(\n evaluationState: FormState,\n conditions: Partial<Record<string, ExecutableCondition>>\n ) {\n const context = { ...evaluationState }\n\n for (const conditionId in conditions) {\n const propertyName =\n this.schemaVersion === SchemaVersion.V2\n ? generateConditionAlias(conditionId)\n : conditionId\n\n Object.defineProperty(context, propertyName, {\n get() {\n return conditions[conditionId]?.fn(evaluationState)\n }\n })\n }\n\n return context as Extract<Value, Record<string, Value>>\n }\n\n toConditionExpression(value: ConditionsModelData, parser: Parser) {\n const conditions = ConditionsModel.from(value)\n return parser.parse(conditions.toExpression())\n }\n\n getList(nameOrId: string): List | undefined {\n return this.schemaVersion === SchemaVersion.V1\n ? this.lists.find((list) => list.name === nameOrId)\n : this.lists.find((list) => list.id === nameOrId)\n }\n\n getSection(nameOrId: string): Section | undefined {\n return this.schemaVersion === SchemaVersion.V1\n ? this.sections.find((section) => section.name === nameOrId)\n : this.sections.find((section) => section.id === nameOrId)\n }\n\n /**\n * Form context for the current page\n */\n getFormContext(\n request: FormContextRequest,\n state: FormSubmissionState,\n errors?: FormSubmissionError[],\n translator?: Translator\n ): FormContext {\n const { query } = request\n\n const page = getPage(this, request)\n\n // Determine form paths\n const currentPath = page.path\n const startPath = page.getStartPath()\n\n // Preview URL direct access is allowed\n const isForceAccess = 'force' in query\n\n let context: FormContext = {\n evaluationState: {},\n relevantState: {},\n relevantPages: [],\n payload: page.getFormDataFromState(request, state),\n state,\n paths: [],\n errors,\n isForceAccess,\n data: {},\n pageDefMap: this.pageDefMap,\n listDefMap: this.listDefMap,\n componentDefMap: this.componentDefMap,\n pageMap: this.pageMap,\n componentMap: this.componentMap,\n referenceNumber: getReferenceNumber(state),\n languages: getAvailableLanguages(this.def),\n translator\n }\n\n // Validate current page\n context = validateFormPayload(request, page, context, translator)\n\n // Find start page\n let nextPage = findPage(this, startPath)\n\n this.initialiseContext(context)\n\n // Walk form pages from start\n while (nextPage) {\n // Add page to context\n context.relevantPages.push(nextPage)\n\n this.assignEvaluationState(context, nextPage)\n\n this.assignRelevantState(context, nextPage)\n\n // Stop at current page\n if (\n this.pageStateIsInvalid(context, nextPage, translator) ||\n nextPage.path === currentPath\n ) {\n break\n }\n\n // Apply conditions to determine next page\n nextPage = findPage(this, nextPage.getNextPath(context))\n }\n\n // Validate form state\n context = validateFormState(request, page, context)\n\n // Add paths for navigation\n this.assignPaths(context)\n\n return context\n }\n\n private initialiseContext(context: FormContext) {\n // Initialise `evaluationState` for all keys using empty state.\n // This is because the current condition evaluation library (eval-expr)\n // will throw if an expression uses a key that is undefined.\n const emptyState = Object.freeze({})\n\n for (const page of this.pages) {\n const { collection, pageDef } = page\n\n if (!hasRepeater(pageDef)) {\n Object.assign(\n context.evaluationState,\n collection.getContextValueFromState(emptyState)\n )\n }\n }\n }\n\n private assignEvaluationState(\n context: FormContext,\n page: PageControllerClass\n ) {\n const { collection, pageDef } = page\n // Skip evaluation state for repeater pages\n\n if (!hasRepeater(pageDef)) {\n Object.assign(\n context.evaluationState,\n collection.getContextValueFromState(context.state)\n )\n }\n }\n\n private assignRelevantState(context: FormContext, page: PageControllerClass) {\n // Copy relevant state by expected keys\n for (const key of page.keys) {\n if (typeof context.state[key] !== 'undefined') {\n context.relevantState[key] = context.state[key]\n }\n }\n }\n\n private pageStateIsInvalid(\n context: FormContext,\n page: PageControllerClass,\n translator?: Translator\n ) {\n // Get any list-bound fields on the page\n const listFields = page.collection.fields.filter(hasListFormField)\n\n // For each list field that is bound to a list that contains any conditional items,\n // we need to check any answers are still valid. Do this by evaluating the conditions\n // and ensuring any current answers are all included in the set of valid answers\n for (const field of listFields) {\n const list = field.list\n\n // Filter out YesNo as they can't be conditional\n if (list !== undefined && field.type !== ComponentType.YesNoField) {\n const hasOptionalItems =\n list.items.filter((item) => item.condition).length > 0\n\n if (hasOptionalItems) {\n return this.fieldStateIsInvalid(context, field, list, translator)\n }\n }\n }\n }\n\n private fieldStateIsInvalid(\n context: FormContext,\n field: ListFormComponent,\n list: List,\n translator?: Translator\n ) {\n const { evaluationState, state } = context\n\n const validValues = list.items\n .filter((item) =>\n item.condition\n ? this.conditions[item.condition]?.fn(evaluationState)\n : true\n )\n .map((item) => item.value)\n\n // Get the field state\n const fieldState = field.getFormValueFromState(state)\n\n if (fieldState !== undefined) {\n let isInvalid = false\n const isArray = Array.isArray(fieldState)\n\n // Check if any saved state value(s) are still valid\n // and return true if any are invalid\n if (isArray) {\n isInvalid = !fieldState.every((item) => validValues.includes(item))\n } else {\n isInvalid = !validValues.includes(fieldState)\n }\n\n if (isInvalid) {\n context.errors ??= []\n\n const text = (translator ?? this.createTranslator('en-GB')).t(\n 'errors.optionsMismatch'\n )\n\n context.errors.push({\n text,\n name: field.name,\n href: `#${field.name}`,\n path: [`#${field.name}`]\n })\n }\n\n return isInvalid\n }\n }\n\n private assignPaths(context: FormContext) {\n for (const { keys, path } of context.relevantPages) {\n context.paths.push(path)\n\n // Stop at page with errors\n if (\n context.errors?.some(({ name, path }) => {\n return keys.includes(name) || keys.some((key) => path.includes(key))\n })\n ) {\n break\n }\n }\n }\n\n getComponentById(componentId: string): ComponentDef | undefined {\n return this.componentDefIdMap.get(componentId)\n }\n\n getListById(listId: string): List | undefined {\n return this.listDefIdMap.get(listId)\n }\n\n /**\n * Returns a condition by its ID. O(n) lookup time.\n * @param conditionId\n * @returns\n */\n getConditionById(conditionId: string): ConditionWrapperV2 | undefined {\n return this.def.conditions\n .filter(isConditionWrapperV2)\n .find((condition) => condition.id === conditionId)\n }\n\n /**\n * Checks that only one payment field exists (if any payments fields exist)\n */\n moreThanOnePaymentQuestion() {\n const numOfPaymentFields = this.def.pages\n .flatMap((page) =>\n hasComponentsEvenIfNoNext(page) ? page.components : []\n )\n .filter((comp) => comp.type === ComponentType.PaymentField).length\n return numOfPaymentFields > 1\n }\n}\n\n/**\n * Validate current page only\n */\nfunction validateFormPayload(\n request: FormContextRequest,\n page: PageControllerClass,\n context: FormContext,\n translator?: Translator\n): FormContext {\n const { collection } = page\n const { payload, state } = context\n\n const { action } = page.getFormParams(request)\n\n // Skip validation GET requests or other actions\n if (\n !request.payload ||\n (action &&\n action !== FormAction.Validate &&\n !action.startsWith(FormAction.External))\n ) {\n return context\n }\n\n // For checkbox fields missing in the payload (i.e. unchecked),\n // explicitly set their value to undefined so that any previously\n // stored value is cleared and required field validation is enforced.\n const update = { ...request.payload }\n collection.fields.forEach((field) => {\n if (\n field.type === ComponentType.CheckboxesField &&\n !(field.name in update)\n ) {\n update[field.name] = undefined\n }\n })\n\n const { value, errors } = collection.validate(\n { ...payload, ...update },\n translator\n )\n\n // Add sanitised payload (ready to save)\n const formState = page.getStateFromValidForm(request, state, value)\n\n return {\n ...context,\n payload: merge(payload, value),\n state: merge(state, formState),\n errors\n }\n}\n\n/**\n * Validate entire form state\n */\nfunction validateFormState(\n request: FormContextRequest,\n page: PageControllerClass,\n context: FormContext\n): FormContext {\n const { errors = [], relevantPages, relevantState } = context\n\n // Exclude current page\n const previousPages = relevantPages.filter(\n (relevantPage) => relevantPage !== page\n )\n\n // Validate relevant state\n const { error } = page.model\n .makeFilteredSchema(previousPages)\n .validate(relevantState, { ...opts, stripUnknown: true })\n\n // Add relevant state errors\n if (error) {\n const errorsState = error.details.map((item) => getError(EN_GB, item))\n return { ...context, errors: errors.concat(errorsState) }\n }\n\n return context\n}\n\nfunction getReferenceNumber(state: FormSubmissionState): string {\n if (\n !state.$$__referenceNumber ||\n typeof state.$$__referenceNumber !== 'string'\n ) {\n throw Error('Reference number not found in form state')\n }\n\n return state.$$__referenceNumber\n}\n"],"mappings":"AAAA,SACEA,aAAa,EACbC,0BAA0B,EAC1BC,eAAe,EACfC,cAAc,EACdC,cAAc,EACdC,aAAa,EACbC,6BAA6B,EAC7BC,oBAAoB,EACpBC,sBAAsB,EACtBC,sBAAsB,EACtBC,eAAe,EACfC,aAAa,EACbC,yBAAyB,EACzBC,WAAW,EACXC,oBAAoB,EACpBC,WAAW,EACXC,aAAa,QAWR,oBAAoB;AAC3B,SAASC,GAAG,EAAEC,MAAM,QAAQ,UAAU;AACtC,SAASC,MAAM,QAAoB,gBAAgB;AAEnD,OAAOC,GAAG,MAAM,KAAK;AAErB,SAASC,MAAM;AACf,SAASC,KAAK;AAEd;AACA,SACEC,gBAAgB;AAGlB,SAASC,eAAe;AACxB,SACEC,mBAAmB,EACnBC,qBAAqB;AAEvB,SACEC,QAAQ,EACRC,QAAQ,EACRC,OAAO;AAET,SAASC,oBAAoB;AAC7B,SAASC,gBAAgB;AACzB,SAASC,uBAAuB;AAChC,SAASC,sBAAsB;AAC/B,SAASC,qBAAqB;AAO9B,SACEC,UAAU;AAGZ,SAASC,iBAAiB,IAAIC,IAAI;AAClC,OAAO,KAAKC,eAAe;AAQ3B,SAASC,UAAU;AACnB,SAASC,K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ACvI,GAAG,CAAEoG,IAAI,IAAK7J,QAAQ,CAACN,KAAK,EAAEmK,IAAI,CAAC,CAAC;IACtE,OAAO;MAAE,GAAGpD,OAAO;MAAEiB,MAAM,EAAEA,MAAM,CAACzC,MAAM,CAAC8G,WAAW;IAAE,CAAC;EAC3D;EAEA,OAAOtF,OAAO;AAChB;AAEA,SAAS8B,kBAAkBA,CAACd,KAA0B,EAAU;EAC9D,IACE,CAACA,KAAK,CAACwE,mBAAmB,IAC1B,OAAOxE,KAAK,CAACwE,mBAAmB,KAAK,QAAQ,EAC7C;IACA,MAAM1I,KAAK,CAAC,0CAA0C,CAAC;EACzD;EAEA,OAAOkE,KAAK,CAACwE,mBAAmB;AAClC","ignoreList":[]}
|
|
@@ -1,12 +1,39 @@
|
|
|
1
|
-
import { type ConditionWrapper, type Section } from '@defra/forms-model';
|
|
1
|
+
import { type ConditionEvaluationOutcome, type ConditionWrapper, type Section } from '@defra/forms-model';
|
|
2
2
|
import { type Expression } from 'expr-eval-fork';
|
|
3
3
|
import { type Field } from '../../../../server/plugins/engine/components/helpers/components.js';
|
|
4
4
|
import { type RepeatPageController } from '../../../../server/plugins/engine/pageControllers/RepeatPageController.js';
|
|
5
5
|
import { type PageControllerClass } from '../../../../server/plugins/engine/pageControllers/helpers/pages.js';
|
|
6
6
|
import { type FormState, type FormSubmissionError } from '../../../../server/plugins/engine/types.js';
|
|
7
|
+
/**
|
|
8
|
+
* The result of evaluating a condition, keeping a failed evaluation distinct
|
|
9
|
+
* from one that legitimately returned `false`.
|
|
10
|
+
* @see {@link ExecutableCondition.evaluate}
|
|
11
|
+
*/
|
|
12
|
+
export interface ConditionEvaluation {
|
|
13
|
+
outcome: ConditionEvaluationOutcome;
|
|
14
|
+
error?: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* A form condition paired with the parsed expression and callbacks needed to
|
|
18
|
+
* run it against a form submission state
|
|
19
|
+
* Created by `FormModel.makeCondition`
|
|
20
|
+
*/
|
|
7
21
|
export type ExecutableCondition = ConditionWrapper & {
|
|
22
|
+
/**
|
|
23
|
+
* Parsed expression for the condition's {@link ConditionWrapper.value},
|
|
24
|
+
* evaluated against a context built from the submission state
|
|
25
|
+
*/
|
|
8
26
|
expr: Expression;
|
|
27
|
+
/**
|
|
28
|
+
* Evaluates the condition, used for page routing and component visibility
|
|
29
|
+
* A failed evaluation is reported as `false`
|
|
30
|
+
*/
|
|
9
31
|
fn: (evaluationState: FormState) => boolean;
|
|
32
|
+
/**
|
|
33
|
+
* As `fn`, but reports whether evaluation failed rather than defaulting a
|
|
34
|
+
* failure to `false`. Used to record condition outcomes on submission.
|
|
35
|
+
*/
|
|
36
|
+
evaluate: (evaluationState: FormState) => ConditionEvaluation;
|
|
10
37
|
};
|
|
11
38
|
/**
|
|
12
39
|
* Used to render a row on a Summary List (check your answers)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":[],"sources":["../../../../../src/server/plugins/engine/models/types.ts"],"sourcesContent":["import {\n type ConditionWrapper,\n type FormComponentsDef,\n type Section\n} from '@defra/forms-model'\nimport { type Expression } from 'expr-eval-fork'\n\nimport {\n getAnswer,\n type Field\n} from '~/src/server/plugins/engine/components/helpers/components.js'\nimport { type RepeatPageController } from '~/src/server/plugins/engine/pageControllers/RepeatPageController.js'\nimport { type PageControllerClass } from '~/src/server/plugins/engine/pageControllers/helpers/pages.js'\nimport {\n type FormState,\n type FormSubmissionError\n} from '~/src/server/plugins/engine/types.js'\n\nexport type ExecutableCondition = ConditionWrapper & {\n expr: Expression\n fn: (evaluationState: FormState) => boolean\n}\n\n/**\n * Used to render a row on a Summary List (check your answers)\n */\nexport interface DetailItemBase {\n /**\n * Name of the component defined in the JSON\n * @see {@link FormComponentsDef.name}\n */\n name: string\n\n /**\n * Field label, used for change link visually hidden text\n * @see {@link FormComponentsDef.title}\n */\n label: string\n\n /**\n * Field change link\n */\n href: string\n\n /**\n * Form submission state (or repeat state for sub items)\n */\n state: FormState\n\n /**\n * Field submission state error, used to flag unanswered questions\n * Shown as 'Complete all unanswered questions before submitting the form'\n */\n error?: FormSubmissionError\n}\n\nexport interface DetailItemField extends DetailItemBase {\n /**\n * Field page controller instance\n */\n page: Exclude<PageControllerClass, RepeatPageController>\n\n /**\n * Check answers summary list key\n * For example, 'Date of birth'\n */\n title: string\n\n /**\n * Check answers summary list value, formatted by {@link getAnswer}\n * For example, date fields formatted as '25 December 2022'\n */\n value: string\n\n /**\n * Field component instance\n */\n field: Field\n}\n\nexport interface DetailItemRepeat extends DetailItemBase {\n /**\n * Repeat page controller instance\n */\n page: RepeatPageController\n\n /**\n * Check answers summary list key\n * For example, 'Pizza' or 'Pizza added'\n */\n title: string\n\n /**\n * Check answers summary list value\n * For example, 'You added 2 Pizzas'\n */\n value: string\n\n /**\n * Repeater field detail items\n */\n subItems: DetailItemField[][]\n}\n\nexport type DetailItem = DetailItemField | DetailItemRepeat\n\n/**\n * Used to render a row on a Summary List (check your answers)\n */\nexport interface Detail {\n name?: Section['name']\n title?: Section['title']\n items: DetailItem[]\n}\n"],"mappings":"","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../../../../src/server/plugins/engine/models/types.ts"],"sourcesContent":["import {\n type ConditionEvaluationOutcome,\n type ConditionWrapper,\n type FormComponentsDef,\n type Section\n} from '@defra/forms-model'\nimport { type Expression } from 'expr-eval-fork'\n\nimport {\n getAnswer,\n type Field\n} from '~/src/server/plugins/engine/components/helpers/components.js'\nimport { type RepeatPageController } from '~/src/server/plugins/engine/pageControllers/RepeatPageController.js'\nimport { type PageControllerClass } from '~/src/server/plugins/engine/pageControllers/helpers/pages.js'\nimport {\n type FormState,\n type FormSubmissionError\n} from '~/src/server/plugins/engine/types.js'\n\n/**\n * The result of evaluating a condition, keeping a failed evaluation distinct\n * from one that legitimately returned `false`.\n * @see {@link ExecutableCondition.evaluate}\n */\nexport interface ConditionEvaluation {\n outcome: ConditionEvaluationOutcome\n error?: string\n}\n\n/**\n * A form condition paired with the parsed expression and callbacks needed to\n * run it against a form submission state\n * Created by `FormModel.makeCondition`\n */\nexport type ExecutableCondition = ConditionWrapper & {\n /**\n * Parsed expression for the condition's {@link ConditionWrapper.value},\n * evaluated against a context built from the submission state\n */\n expr: Expression\n\n /**\n * Evaluates the condition, used for page routing and component visibility\n * A failed evaluation is reported as `false`\n */\n fn: (evaluationState: FormState) => boolean\n\n /**\n * As `fn`, but reports whether evaluation failed rather than defaulting a\n * failure to `false`. Used to record condition outcomes on submission.\n */\n evaluate: (evaluationState: FormState) => ConditionEvaluation\n}\n\n/**\n * Used to render a row on a Summary List (check your answers)\n */\nexport interface DetailItemBase {\n /**\n * Name of the component defined in the JSON\n * @see {@link FormComponentsDef.name}\n */\n name: string\n\n /**\n * Field label, used for change link visually hidden text\n * @see {@link FormComponentsDef.title}\n */\n label: string\n\n /**\n * Field change link\n */\n href: string\n\n /**\n * Form submission state (or repeat state for sub items)\n */\n state: FormState\n\n /**\n * Field submission state error, used to flag unanswered questions\n * Shown as 'Complete all unanswered questions before submitting the form'\n */\n error?: FormSubmissionError\n}\n\nexport interface DetailItemField extends DetailItemBase {\n /**\n * Field page controller instance\n */\n page: Exclude<PageControllerClass, RepeatPageController>\n\n /**\n * Check answers summary list key\n * For example, 'Date of birth'\n */\n title: string\n\n /**\n * Check answers summary list value, formatted by {@link getAnswer}\n * For example, date fields formatted as '25 December 2022'\n */\n value: string\n\n /**\n * Field component instance\n */\n field: Field\n}\n\nexport interface DetailItemRepeat extends DetailItemBase {\n /**\n * Repeat page controller instance\n */\n page: RepeatPageController\n\n /**\n * Check answers summary list key\n * For example, 'Pizza' or 'Pizza added'\n */\n title: string\n\n /**\n * Check answers summary list value\n * For example, 'You added 2 Pizzas'\n */\n value: string\n\n /**\n * Repeater field detail items\n */\n subItems: DetailItemField[][]\n}\n\nexport type DetailItem = DetailItemField | DetailItemRepeat\n\n/**\n * Used to render a row on a Summary List (check your answers)\n */\nexport interface Detail {\n name?: Section['name']\n title?: Section['title']\n items: DetailItem[]\n}\n"],"mappings":"","ignoreList":[]}
|
|
@@ -21,7 +21,8 @@ const pluginRegistrationOptionsSchema = Joi.object({
|
|
|
21
21
|
saveAndExit: Joi.function().optional(),
|
|
22
22
|
ordnanceSurveyApiKey: Joi.string().optional(),
|
|
23
23
|
ordnanceSurveyApiSecret: Joi.string().optional(),
|
|
24
|
-
getLanguage: Joi.function().optional()
|
|
24
|
+
getLanguage: Joi.function().optional(),
|
|
25
|
+
generateReferenceNumber: Joi.function().optional()
|
|
25
26
|
});
|
|
26
27
|
|
|
27
28
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"options.js","names":["getErrorMessage","Joi","logger","CacheService","pluginRegistrationOptionsSchema","object","model","optional","services","controllers","pattern","string","any","cache","alternatives","try","instance","globals","filters","pluginPath","nunjucks","baseLayoutPath","required","paths","array","items","viewContext","function","preparePageEventRequestOptions","onRequest","baseUrl","uri","saveAndExit","ordnanceSurveyApiKey","ordnanceSurveyApiSecret","getLanguage","validatePluginOptions","options","result","validate","abortEarly","error","Error","value"],"sources":["../../../../src/server/plugins/engine/options.js"],"sourcesContent":["import { getErrorMessage } from '@defra/forms-model'\nimport Joi from 'joi'\n\nimport { logger } from '~/src/server/common/helpers/logging/logger.js'\nimport { CacheService } from '~/src/server/services/index.js'\n\nconst pluginRegistrationOptionsSchema = Joi.object({\n model: Joi.object().optional(),\n services: Joi.object().optional(),\n controllers: Joi.object().pattern(Joi.string(), Joi.any()).optional(),\n cache: Joi.alternatives().try(\n Joi.object().instance(CacheService),\n Joi.string()\n ),\n globals: Joi.object().pattern(Joi.string(), Joi.any()).optional(),\n filters: Joi.object().pattern(Joi.string(), Joi.any()).optional(),\n pluginPath: Joi.string().optional(),\n nunjucks: Joi.object({\n baseLayoutPath: Joi.string().required(),\n paths: Joi.array().items(Joi.string()).required()\n }).required(),\n viewContext: Joi.function().required(),\n preparePageEventRequestOptions: Joi.function().optional(),\n onRequest: Joi.function().optional(),\n baseUrl: Joi.string().uri().required(),\n saveAndExit: Joi.function().optional(),\n ordnanceSurveyApiKey: Joi.string().optional(),\n ordnanceSurveyApiSecret: Joi.string().optional(),\n getLanguage: Joi.function().optional()\n})\n\n/**\n * Validates the plugin options against the schema and returns the validated value.\n * @param {PluginOptions} options\n * @returns {PluginOptions}\n */\nexport function validatePluginOptions(options) {\n const result = pluginRegistrationOptionsSchema.validate(options, {\n abortEarly: false\n })\n\n if (result.error) {\n logger.error(\n result.error,\n `Missing required properties in plugin options: ${getErrorMessage(result.error)}`\n )\n throw new Error('Invalid plugin options', result.error)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return result.value\n}\n\n/**\n * @import { PluginOptions } from '~/src/server/plugins/engine/types.js'\n */\n"],"mappings":"AAAA,SAASA,eAAe,QAAQ,oBAAoB;AACpD,OAAOC,GAAG,MAAM,KAAK;AAErB,SAASC,MAAM;AACf,SAASC,YAAY;AAErB,MAAMC,+BAA+B,GAAGH,GAAG,CAACI,MAAM,CAAC;EACjDC,KAAK,EAAEL,GAAG,CAACI,MAAM,CAAC,CAAC,CAACE,QAAQ,CAAC,CAAC;EAC9BC,QAAQ,EAAEP,GAAG,CAACI,MAAM,CAAC,CAAC,CAACE,QAAQ,CAAC,CAAC;EACjCE,WAAW,EAAER,GAAG,CAACI,MAAM,CAAC,CAAC,CAACK,OAAO,CAACT,GAAG,CAACU,MAAM,CAAC,CAAC,EAAEV,GAAG,CAACW,GAAG,CAAC,CAAC,CAAC,CAACL,QAAQ,CAAC,CAAC;EACrEM,KAAK,EAAEZ,GAAG,CAACa,YAAY,CAAC,CAAC,CAACC,GAAG,CAC3Bd,GAAG,CAACI,MAAM,CAAC,CAAC,CAACW,QAAQ,CAACb,YAAY,CAAC,EACnCF,GAAG,CAACU,MAAM,CAAC,CACb,CAAC;EACDM,OAAO,EAAEhB,GAAG,CAACI,MAAM,CAAC,CAAC,CAACK,OAAO,CAACT,GAAG,CAACU,MAAM,CAAC,CA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GAAG,CAAC0B,QAAQ,CAAC,CAAC,CAACpB,QAAQ,CAAC;
|
|
1
|
+
{"version":3,"file":"options.js","names":["getErrorMessage","Joi","logger","CacheService","pluginRegistrationOptionsSchema","object","model","optional","services","controllers","pattern","string","any","cache","alternatives","try","instance","globals","filters","pluginPath","nunjucks","baseLayoutPath","required","paths","array","items","viewContext","function","preparePageEventRequestOptions","onRequest","baseUrl","uri","saveAndExit","ordnanceSurveyApiKey","ordnanceSurveyApiSecret","getLanguage","generateReferenceNumber","validatePluginOptions","options","result","validate","abortEarly","error","Error","value"],"sources":["../../../../src/server/plugins/engine/options.js"],"sourcesContent":["import { getErrorMessage } from '@defra/forms-model'\nimport Joi from 'joi'\n\nimport { logger } from '~/src/server/common/helpers/logging/logger.js'\nimport { CacheService } from '~/src/server/services/index.js'\n\nconst pluginRegistrationOptionsSchema = Joi.object({\n model: Joi.object().optional(),\n services: Joi.object().optional(),\n controllers: Joi.object().pattern(Joi.string(), Joi.any()).optional(),\n cache: Joi.alternatives().try(\n Joi.object().instance(CacheService),\n Joi.string()\n ),\n globals: Joi.object().pattern(Joi.string(), Joi.any()).optional(),\n filters: Joi.object().pattern(Joi.string(), Joi.any()).optional(),\n pluginPath: Joi.string().optional(),\n nunjucks: Joi.object({\n baseLayoutPath: Joi.string().required(),\n paths: Joi.array().items(Joi.string()).required()\n }).required(),\n viewContext: Joi.function().required(),\n preparePageEventRequestOptions: Joi.function().optional(),\n onRequest: Joi.function().optional(),\n baseUrl: Joi.string().uri().required(),\n saveAndExit: Joi.function().optional(),\n ordnanceSurveyApiKey: Joi.string().optional(),\n ordnanceSurveyApiSecret: Joi.string().optional(),\n getLanguage: Joi.function().optional(),\n generateReferenceNumber: Joi.function().optional()\n})\n\n/**\n * Validates the plugin options against the schema and returns the validated value.\n * @param {PluginOptions} options\n * @returns {PluginOptions}\n */\nexport function validatePluginOptions(options) {\n const result = pluginRegistrationOptionsSchema.validate(options, {\n abortEarly: false\n })\n\n if (result.error) {\n logger.error(\n result.error,\n `Missing required properties in plugin options: ${getErrorMessage(result.error)}`\n )\n throw new Error('Invalid plugin options', result.error)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return result.value\n}\n\n/**\n * @import { PluginOptions } from '~/src/server/plugins/engine/types.js'\n */\n"],"mappings":"AAAA,SAASA,eAAe,QAAQ,oBAAoB;AACpD,OAAOC,GAAG,MAAM,KAAK;AAErB,SAASC,MAAM;AACf,SAASC,YAAY;AAErB,MAAMC,+BAA+B,GAAGH,GAAG,CAACI,MAAM,CAAC;EACjDC,KAAK,EAAEL,GAAG,CAACI,MAAM,CAAC,CAAC,CAACE,QAAQ,CAAC,CAAC;EAC9BC,QAAQ,EAAEP,GAAG,CAACI,MAAM,CAAC,CAAC,CAACE,QAAQ,CAAC,CAAC;EACjCE,WAAW,EAAER,GAAG,CAACI,MAAM,CAAC,CAAC,CAACK,OAAO,CAACT,GAAG,CAACU,MAAM,CAAC,CAAC,EAAEV,GAAG,CAACW,GAAG,CAAC,CAAC,CAAC,CAACL,QAAQ,CAAC,CAAC;EACrEM,KAAK,EAAEZ,GAAG,CAACa,YAAY,CAAC,CAAC,CAACC,GAAG,CAC3Bd,GAAG,CAACI,MAAM,CAAC,CAAC,CAACW,QAAQ,CAACb,YAAY,CAAC,EACnCF,GAAG,CAACU,MAAM,CAAC,CACb,CAAC;EACDM,OAAO,EAAEhB,GAAG,CAACI,MAAM,CAAC,CAAC,CAACK,OAAO,CAACT,GAAG,CAACU,MAAM,CAAC,CAAC,EAAEV,GAAG,CAACW,GAAG,CAAC,CAAC,CAAC,CAACL,QAAQ,CAAC,CAAC;EACjEW,OAAO,EAAEjB,GAAG,CAACI,MAAM,CAAC,CAAC,CAACK,OAAO,CAACT,GAAG,CAACU,MAAM,CAAC,CAAC,EAAEV,GAAG,CAACW,GAAG,CAAC,CAAC,CAAC,CAACL,QAAQ,CAAC,CAAC;EACjEY,UAAU,EAAElB,GAAG,CAACU,MAAM,CAAC,CAAC,CAACJ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AE;IAC/DG,UAAU,EAAE;EACd,CAAC,CAAC;EAEF,IAAIF,MAAM,CAACG,KAAK,EAAE;IAChBxC,MAAM,CAACwC,KAAK,CACVH,MAAM,CAACG,KAAK,EACZ,kDAAkD1C,eAAe,CAACuC,MAAM,CAACG,KAAK,CAAC,EACjF,CAAC;IACD,MAAM,IAAIC,KAAK,CAAC,wBAAwB,EAAEJ,MAAM,CAACG,KAAK,CAAC;EACzD;;EAEA;EACA,OAAOH,MAAM,CAACK,KAAK;AACrB;;AAEA;AACA;AACA","ignoreList":[]}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { Engine } from '@defra/forms-model';
|
|
1
2
|
import { EN_GB } from "../../../../constants.js";
|
|
2
3
|
import { getFormVersion } from "../../helpers.js";
|
|
3
4
|
import { categoriseData } from "../machine/v2.js";
|
|
5
|
+
import { buildConditionEvaluations } from "../../pageControllers/helpers/submission.js";
|
|
4
6
|
import { FormAdapterSubmissionSchemaVersion } from "../../types/enums.js";
|
|
5
7
|
export function format(context, items, model, submitResponse, formStatus, formMetadata) {
|
|
6
8
|
const csvFiles = extractCsvFiles(submitResponse);
|
|
@@ -40,7 +42,15 @@ export function format(context, items, model, submitResponse, formStatus, formMe
|
|
|
40
42
|
const payload = {
|
|
41
43
|
meta,
|
|
42
44
|
data,
|
|
43
|
-
result
|
|
45
|
+
result,
|
|
46
|
+
// Recorded here because only the engine holds the walked evaluation state
|
|
47
|
+
// the conditions were judged against; forms-notify-listener receives the
|
|
48
|
+
// flat submitted answers and resolves the outputs that qualify from these
|
|
49
|
+
// outcomes alone. Condition ids are only stable in V2, so a V1 definition
|
|
50
|
+
// has nothing to report - the property is still emitted, because its
|
|
51
|
+
// absence is what marks a message as predating this and sends the listener
|
|
52
|
+
// down its legacy path.
|
|
53
|
+
conditionEvaluations: model.engine === Engine.V2 ? buildConditionEvaluations(model, context) : []
|
|
44
54
|
};
|
|
45
55
|
return JSON.stringify(payload);
|
|
46
56
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"v1.js","names":["EN_GB","getFormVersion","categoriseData","FormAdapterSubmissionSchemaVersion","format","context","items","model","submitResponse","formStatus","formMetadata","csvFiles","extractCsvFiles","main","v2Main","v2Data","versionMetadata","def","meta","schemaVersion","V1","timestamp","Date","referenceNumber","formName","name","formId","id","formSlug","slug","status","state","isPreview","notificationEmail","language","translator","Object","fromEntries","entries","map","key","value","undefined","data","result","files","payload","JSON","stringify","repeaters"],"sources":["../../../../../../src/server/plugins/engine/outputFormatters/adapter/v1.ts"],"sourcesContent":["import {\n type FormMetadata,\n type SubmitResponsePayload\n} from '@defra/forms-model'\n\nimport { EN_GB } from '~/src/server/constants.js'\nimport {\n getFormVersion,\n type checkFormStatus\n} from '~/src/server/plugins/engine/helpers.js'\nimport { type FormModel } from '~/src/server/plugins/engine/models/FormModel.js'\nimport { type DetailItem } from '~/src/server/plugins/engine/models/types.js'\nimport { categoriseData } from '~/src/server/plugins/engine/outputFormatters/machine/v2.js'\nimport { FormAdapterSubmissionSchemaVersion } from '~/src/server/plugins/engine/types/enums.js'\nimport {\n type FormAdapterSubmissionMessageData,\n type FormAdapterSubmissionMessageMeta,\n type FormAdapterSubmissionMessagePayload,\n type FormAdapterSubmissionMessageResult,\n type FormContext\n} from '~/src/server/plugins/engine/types.js'\n\nexport function format(\n context: FormContext,\n items: DetailItem[],\n model: FormModel,\n submitResponse: SubmitResponsePayload,\n formStatus: ReturnType<typeof checkFormStatus>,\n formMetadata?: FormMetadata\n): string {\n const csvFiles = extractCsvFiles(submitResponse)\n\n const { main: v2Main, ...v2Data } = categoriseData(items)\n\n const versionMetadata = getFormVersion(model.def)\n\n const meta: FormAdapterSubmissionMessageMeta = {\n schemaVersion: FormAdapterSubmissionSchemaVersion.V1,\n timestamp: new Date(),\n referenceNumber: context.referenceNumber,\n formName: model.name,\n formId: formMetadata?.id ?? '',\n formSlug: formMetadata?.slug ?? '',\n status: formStatus.state,\n isPreview: formStatus.isPreview,\n notificationEmail: formMetadata?.notificationEmail ?? '',\n language: context.translator?.language ?? EN_GB\n }\n\n if (versionMetadata) {\n meta.versionMetadata = versionMetadata\n }\n\n const main = Object.fromEntries(\n Object.entries(v2Main).map(([key, value]) => {\n if (value === undefined) {\n return [key, null]\n }\n\n return [key, value]\n })\n )\n\n const data: FormAdapterSubmissionMessageData = {\n main,\n ...v2Data\n }\n\n const result: FormAdapterSubmissionMessageResult = {\n files: csvFiles\n }\n\n const payload: FormAdapterSubmissionMessagePayload = {\n meta,\n data,\n result\n }\n\n return JSON.stringify(payload)\n}\n\nfunction extractCsvFiles(\n submitResponse: SubmitResponsePayload\n): FormAdapterSubmissionMessageResult['files'] {\n const result =\n submitResponse.result as Partial<FormAdapterSubmissionMessageResult>\n\n return {\n main: result.files?.main ?? '',\n repeaters: result.files?.repeaters ?? {}\n }\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"v1.js","names":["Engine","EN_GB","getFormVersion","categoriseData","buildConditionEvaluations","FormAdapterSubmissionSchemaVersion","format","context","items","model","submitResponse","formStatus","formMetadata","csvFiles","extractCsvFiles","main","v2Main","v2Data","versionMetadata","def","meta","schemaVersion","V1","timestamp","Date","referenceNumber","formName","name","formId","id","formSlug","slug","status","state","isPreview","notificationEmail","language","translator","Object","fromEntries","entries","map","key","value","undefined","data","result","files","payload","conditionEvaluations","engine","V2","JSON","stringify","repeaters"],"sources":["../../../../../../src/server/plugins/engine/outputFormatters/adapter/v1.ts"],"sourcesContent":["import {\n Engine,\n type FormMetadata,\n type SubmitResponsePayload\n} from '@defra/forms-model'\n\nimport { EN_GB } from '~/src/server/constants.js'\nimport {\n getFormVersion,\n type checkFormStatus\n} from '~/src/server/plugins/engine/helpers.js'\nimport { type FormModel } from '~/src/server/plugins/engine/models/FormModel.js'\nimport { type DetailItem } from '~/src/server/plugins/engine/models/types.js'\nimport { categoriseData } from '~/src/server/plugins/engine/outputFormatters/machine/v2.js'\nimport { buildConditionEvaluations } from '~/src/server/plugins/engine/pageControllers/helpers/submission.js'\nimport { FormAdapterSubmissionSchemaVersion } from '~/src/server/plugins/engine/types/enums.js'\nimport {\n type FormAdapterSubmissionMessageData,\n type FormAdapterSubmissionMessageMeta,\n type FormAdapterSubmissionMessagePayload,\n type FormAdapterSubmissionMessageResult,\n type FormContext\n} from '~/src/server/plugins/engine/types.js'\n\nexport function format(\n context: FormContext,\n items: DetailItem[],\n model: FormModel,\n submitResponse: SubmitResponsePayload,\n formStatus: ReturnType<typeof checkFormStatus>,\n formMetadata?: FormMetadata\n): string {\n const csvFiles = extractCsvFiles(submitResponse)\n\n const { main: v2Main, ...v2Data } = categoriseData(items)\n\n const versionMetadata = getFormVersion(model.def)\n\n const meta: FormAdapterSubmissionMessageMeta = {\n schemaVersion: FormAdapterSubmissionSchemaVersion.V1,\n timestamp: new Date(),\n referenceNumber: context.referenceNumber,\n formName: model.name,\n formId: formMetadata?.id ?? '',\n formSlug: formMetadata?.slug ?? '',\n status: formStatus.state,\n isPreview: formStatus.isPreview,\n notificationEmail: formMetadata?.notificationEmail ?? '',\n language: context.translator?.language ?? EN_GB\n }\n\n if (versionMetadata) {\n meta.versionMetadata = versionMetadata\n }\n\n const main = Object.fromEntries(\n Object.entries(v2Main).map(([key, value]) => {\n if (value === undefined) {\n return [key, null]\n }\n\n return [key, value]\n })\n )\n\n const data: FormAdapterSubmissionMessageData = {\n main,\n ...v2Data\n }\n\n const result: FormAdapterSubmissionMessageResult = {\n files: csvFiles\n }\n\n const payload: FormAdapterSubmissionMessagePayload = {\n meta,\n data,\n result,\n\n // Recorded here because only the engine holds the walked evaluation state\n // the conditions were judged against; forms-notify-listener receives the\n // flat submitted answers and resolves the outputs that qualify from these\n // outcomes alone. Condition ids are only stable in V2, so a V1 definition\n // has nothing to report - the property is still emitted, because its\n // absence is what marks a message as predating this and sends the listener\n // down its legacy path.\n conditionEvaluations:\n model.engine === Engine.V2\n ? buildConditionEvaluations(model, context)\n : []\n }\n\n return JSON.stringify(payload)\n}\n\nfunction extractCsvFiles(\n submitResponse: SubmitResponsePayload\n): FormAdapterSubmissionMessageResult['files'] {\n const result =\n submitResponse.result as Partial<FormAdapterSubmissionMessageResult>\n\n return {\n main: result.files?.main ?? '',\n repeaters: result.files?.repeaters ?? {}\n }\n}\n"],"mappings":"AAAA,SACEA,MAAM,QAGD,oBAAoB;AAE3B,SAASC,KAAK;AACd,SACEC,cAAc;AAKhB,SAASC,cAAc;AACvB,SAASC,yBAAyB;AAClC,SAASC,kCAAkC;AAS3C,OAAO,SAASC,MAAMA,CACpBC,OAAoB,EACpBC,KAAmB,EACnBC,KAAgB,EAChBC,cAAqC,EACrCC,UAA8C,EAC9CC,YAA2B,EACnB;EACR,MAAMC,QAAQ,GAAGC,eAAe,CAACJ,cAAc,CAAC;EAEhD,MAAM;IAAEK,IAAI,EAAEC,MAAM;IAAE,GAAGC;EAAO,CAAC,GAAGd,cAAc,CAACK,KAAK,CAAC;EAEzD,MAAMU,eAAe,GAAGhB,cAAc,CAACO,KAAK,CAACU,GAAG,CAAC;EAEjD,MAAMC,IAAsC,GAAG;IAC7CC,aAAa,EAAEhB,kCAAkC,CAACiB,EAAE;IACpDC,SAAS,EAAE,IAAIC,IAAI,CAAC,CAAC;IACrBC,eAAe,EAAElB,OAAO,CAACkB,eAAe;IACxCC,QAAQ,EAAEjB,KAAK,CAACkB,IAAI;IACpBC,MAAM,EAAEhB,YAAY,EAAEiB,EAAE,IAAI,EAAE;IAC9BC,QAAQ,EAAElB,YAAY,EAAEmB,IAAI,IAAI,EAAE;IAClCC,MAAM,EAAErB,UAAU,CAACsB,KAAK;IACxBC,SAAS,EAAEvB,UAAU,CAACuB,SAAS;IAC/BC,iBAAiB,EAAEvB,YAAY,EAAEuB,iBAAiB,IAAI,EAAE;IACxDC,QAAQ,EAAE7B,OAAO,CAAC8B,UAAU,EAAED,QAAQ,IAAInC;EAC5C,CAAC;EAED,IAAIiB,eAAe,EAAE;IACnBE,IAAI,CAACF,eAAe,GAAGA,eAAe;EACxC;EAEA,MAAMH,IAAI,GAAGuB,MAAM,CAACC,WAAW,CAC7BD,MAAM,CAACE,OAAO,CAACxB,MAAM,CAAC,CAACyB,GAAG,CAAC,CAAC,CAACC,GAAG,EAAEC,KAAK,CAAC,KAAK;IAC3C,IAAIA,KAAK,KAAKC,SAAS,EAAE;MACvB,OAAO,CAACF,GAAG,EAAE,IAAI,CAAC;IACpB;IAEA,OAAO,CAACA,GAAG,EAAEC,KAAK,CAAC;EACrB,CAAC,CACH,CAAC;EAED,MAAME,IAAsC,GAAG;IAC7C9B,IAAI;IACJ,GAAGE;EACL,CAAC;EAED,MAAM6B,MAA0C,GAAG;IACjDC,KAAK,EAAElC;EACT,CAAC;EAED,MAAMmC,OAA4C,GAAG;IACnD5B,IAAI;IACJyB,IAAI;IACJC,MAAM;IAEN;IACA;IACA;IACA;IACA;IACA;IACA;IACAG,oBAAoB,EAClBxC,KAAK,CAACyC,MAAM,KAAKlD,MAAM,CAACmD,EAAE,GACtB/C,yBAAyB,CAACK,KAAK,EAAEF,OAAO,CAAC,GACzC;EACR,CAAC;EAED,OAAO6C,IAAI,CAACC,SAAS,CAACL,OAAO,CAAC;AAChC;AAEA,SAASlC,eAAeA,CACtBJ,cAAqC,EACQ;EAC7C,MAAMoC,MAAM,GACVpC,cAAc,CAACoC,MAAqD;EAEtE,OAAO;IACL/B,IAAI,EAAE+B,MAAM,CAACC,KAAK,EAAEhC,IAAI,IAAI,EAAE;IAC9BuC,SAAS,EAAER,MAAM,CAACC,KAAK,EAAEO,SAAS,IAAI,CAAC;EACzC,CAAC;AACH","ignoreList":[]}
|
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import { type SubmitPayload } from '@defra/forms-model';
|
|
1
|
+
import { type SubmitConditionEvaluation, type SubmitPayload } from '@defra/forms-model';
|
|
2
2
|
import { type Translator } from '../../../../../server/plugins/engine/i18n/types.js';
|
|
3
|
+
import { type FormModel } from '../../../../../server/plugins/engine/models/FormModel.js';
|
|
3
4
|
import { type DetailItem, type DetailItemField } from '../../../../../server/plugins/engine/models/types.js';
|
|
5
|
+
import { type FormContext, type FormStateValue } from '../../../../../server/plugins/engine/types.js';
|
|
4
6
|
export interface SubmitRecord {
|
|
5
7
|
name: string;
|
|
6
8
|
title: string;
|
|
@@ -26,3 +28,34 @@ export declare function buildPaymentRecords(item: DetailItemField, translator: T
|
|
|
26
28
|
* Builds the repeater submission records from repeater items.
|
|
27
29
|
*/
|
|
28
30
|
export declare function buildRepeaterRecords(items: DetailItem[], translator: Translator): SubmitPayload['repeaters'];
|
|
31
|
+
/**
|
|
32
|
+
* Records the outcome of every condition in the form definition, evaluated
|
|
33
|
+
* against the answers as they stand at the point of submission.
|
|
34
|
+
*
|
|
35
|
+
* Evaluated here rather than by the consumer because only the engine holds
|
|
36
|
+
* the context to evaluate against: `evaluationState` is built by walking the
|
|
37
|
+
* form from its start page along the path taken, applying page conditions as
|
|
38
|
+
* it goes. A consumer receives the flat submitted answers, not that walked
|
|
39
|
+
* state, and reproducing the walk in a second codebase would leave two
|
|
40
|
+
* implementations of the same logic free to diverge.
|
|
41
|
+
*
|
|
42
|
+
* Each record carries the components the condition depends on and whether each
|
|
43
|
+
* was answered. An unanswered question still yields a boolean - negative
|
|
44
|
+
* operators such as "is not" return `true` against the seeded `null` - so the
|
|
45
|
+
* outcome alone cannot be read as evidence that the user gave that answer.
|
|
46
|
+
*
|
|
47
|
+
* V2 definitions only. `conditionId` is the V2 condition id, and the
|
|
48
|
+
* references are resolved from the component ids V2 conditions carry - V1
|
|
49
|
+
* conditions reference components by name, and V1 components need not have
|
|
50
|
+
* an id at all.
|
|
51
|
+
*/
|
|
52
|
+
export declare function buildConditionEvaluations(model: FormModel, context: FormContext): SubmitConditionEvaluation[];
|
|
53
|
+
/**
|
|
54
|
+
* Whether a component held an answer at the point a condition was evaluated.
|
|
55
|
+
*
|
|
56
|
+
* The engine seeds every component in `evaluationState` with `null` before the
|
|
57
|
+
* page walk begins, so an unanswered question is present but empty rather than
|
|
58
|
+
* absent.
|
|
59
|
+
* @see {@link FormModel.initialiseContext}
|
|
60
|
+
*/
|
|
61
|
+
export declare function isAnswered(value: FormStateValue | undefined): boolean;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isConditionWrapperV2 } from '@defra/forms-model';
|
|
1
2
|
import { GeospatialField } from "../../components/GeospatialField.js";
|
|
2
3
|
import { PaymentField } from "../../components/PaymentField.js";
|
|
3
4
|
import { getAnswer } from "../../components/helpers/components.js";
|
|
@@ -95,4 +96,100 @@ export function buildRepeaterRecords(items, translator) {
|
|
|
95
96
|
}))
|
|
96
97
|
}));
|
|
97
98
|
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Records the outcome of every condition in the form definition, evaluated
|
|
102
|
+
* against the answers as they stand at the point of submission.
|
|
103
|
+
*
|
|
104
|
+
* Evaluated here rather than by the consumer because only the engine holds
|
|
105
|
+
* the context to evaluate against: `evaluationState` is built by walking the
|
|
106
|
+
* form from its start page along the path taken, applying page conditions as
|
|
107
|
+
* it goes. A consumer receives the flat submitted answers, not that walked
|
|
108
|
+
* state, and reproducing the walk in a second codebase would leave two
|
|
109
|
+
* implementations of the same logic free to diverge.
|
|
110
|
+
*
|
|
111
|
+
* Each record carries the components the condition depends on and whether each
|
|
112
|
+
* was answered. An unanswered question still yields a boolean - negative
|
|
113
|
+
* operators such as "is not" return `true` against the seeded `null` - so the
|
|
114
|
+
* outcome alone cannot be read as evidence that the user gave that answer.
|
|
115
|
+
*
|
|
116
|
+
* V2 definitions only. `conditionId` is the V2 condition id, and the
|
|
117
|
+
* references are resolved from the component ids V2 conditions carry - V1
|
|
118
|
+
* conditions reference components by name, and V1 components need not have
|
|
119
|
+
* an id at all.
|
|
120
|
+
*/
|
|
121
|
+
export function buildConditionEvaluations(model, context) {
|
|
122
|
+
const {
|
|
123
|
+
evaluationState
|
|
124
|
+
} = context;
|
|
125
|
+
return model.def.conditions.filter(isConditionWrapperV2).flatMap(conditionDef => {
|
|
126
|
+
const condition = model.conditions[conditionDef.id];
|
|
127
|
+
if (!condition) {
|
|
128
|
+
return [];
|
|
129
|
+
}
|
|
130
|
+
const {
|
|
131
|
+
outcome
|
|
132
|
+
} = condition.evaluate(evaluationState);
|
|
133
|
+
const references = collectReferences(model, conditionDef, evaluationState);
|
|
134
|
+
return {
|
|
135
|
+
conditionId: conditionDef.id,
|
|
136
|
+
outcome,
|
|
137
|
+
references: [...references.values()]
|
|
138
|
+
};
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Whether a component held an answer at the point a condition was evaluated.
|
|
144
|
+
*
|
|
145
|
+
* The engine seeds every component in `evaluationState` with `null` before the
|
|
146
|
+
* page walk begins, so an unanswered question is present but empty rather than
|
|
147
|
+
* absent.
|
|
148
|
+
* @see {@link FormModel.initialiseContext}
|
|
149
|
+
*/
|
|
150
|
+
export function isAnswered(value) {
|
|
151
|
+
if (value === undefined || value === null) {
|
|
152
|
+
return false;
|
|
153
|
+
}
|
|
154
|
+
if (Array.isArray(value)) {
|
|
155
|
+
return value.length > 0;
|
|
156
|
+
}
|
|
157
|
+
return value !== '';
|
|
158
|
+
}
|
|
159
|
+
function isConditionDataV2(item) {
|
|
160
|
+
return 'componentId' in item;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Recursive function that collects every component a condition depends on, following nested condition
|
|
165
|
+
* references. Results are keyed by component id so a component referenced more
|
|
166
|
+
* than once is reported once.
|
|
167
|
+
*/
|
|
168
|
+
function collectReferences(model, conditionDef, evaluationState, references = new Map(), visited = new Set()) {
|
|
169
|
+
if (visited.has(conditionDef.id)) {
|
|
170
|
+
return references;
|
|
171
|
+
}
|
|
172
|
+
visited.add(conditionDef.id);
|
|
173
|
+
for (const item of conditionDef.items) {
|
|
174
|
+
if (isConditionDataV2(item)) {
|
|
175
|
+
const component = model.getComponentById(item.componentId);
|
|
176
|
+
|
|
177
|
+
// A condition referencing a component that no longer exists cannot be
|
|
178
|
+
// resolved to a name, so there is nothing meaningful to report for it
|
|
179
|
+
if (component) {
|
|
180
|
+
references.set(item.componentId, {
|
|
181
|
+
componentId: item.componentId,
|
|
182
|
+
componentName: component.name,
|
|
183
|
+
answered: isAnswered(evaluationState[component.name])
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
const referenced = model.getConditionById(item.conditionId);
|
|
189
|
+
if (referenced) {
|
|
190
|
+
collectReferences(model, referenced, evaluationState, references, visited);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
return references;
|
|
194
|
+
}
|
|
98
195
|
//# sourceMappingURL=submission.js.map
|