@defra/forms-engine-plugin 5.0.0-alpha.1 → 5.0.0-alpha.11
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/.public/javascripts/application.min.js +1 -1
- package/.public/javascripts/application.min.js.LICENSE.txt +7 -0
- package/.public/javascripts/application.min.js.map +1 -1
- package/.public/javascripts/shared.min.js +1 -1
- package/.public/javascripts/shared.min.js.LICENSE.txt +7 -0
- package/.public/javascripts/shared.min.js.map +1 -1
- package/.public/stylesheets/application.min.css.map +1 -1
- package/.server/client/javascripts/file-upload.js +6 -3
- package/.server/client/javascripts/file-upload.js.map +1 -1
- package/.server/client/javascripts/geospatial-map.js +10 -31
- package/.server/client/javascripts/geospatial-map.js.map +1 -1
- package/.server/client/javascripts/govuk.js +2 -1
- package/.server/client/javascripts/govuk.js.map +1 -1
- package/.server/client/javascripts/location-map.js +11 -2
- package/.server/client/javascripts/location-map.js.map +1 -1
- package/.server/client/javascripts/map.d.ts +6 -0
- package/.server/client/javascripts/map.js +37 -0
- package/.server/client/javascripts/map.js.map +1 -1
- package/.server/client/javascripts/maps.d.ts +5 -0
- package/.server/client/javascripts/maps.js +6 -0
- package/.server/client/javascripts/maps.js.map +1 -0
- package/.server/client/javascripts/shared.d.ts +1 -3
- package/.server/client/javascripts/shared.js +1 -3
- package/.server/client/javascripts/shared.js.map +1 -1
- package/.server/client/javascripts/sssi-dataset.d.ts +18 -20
- package/.server/client/javascripts/sssi-dataset.js +37 -39
- package/.server/client/javascripts/sssi-dataset.js.map +1 -1
- package/.server/client/stylesheets/maps.scss +4 -0
- package/.server/client/stylesheets/shared.scss +1 -5
- package/.server/server/constants.d.ts +2 -0
- package/.server/server/constants.js +2 -0
- package/.server/server/constants.js.map +1 -1
- package/.server/server/plugins/engine/components/AutocompleteField.d.ts +9 -3
- package/.server/server/plugins/engine/components/AutocompleteField.js +12 -0
- package/.server/server/plugins/engine/components/AutocompleteField.js.map +1 -1
- package/.server/server/plugins/engine/components/CheckboxesField.d.ts +4 -1
- package/.server/server/plugins/engine/components/CheckboxesField.js +13 -0
- package/.server/server/plugins/engine/components/CheckboxesField.js.map +1 -1
- package/.server/server/plugins/engine/components/ComponentBase.d.ts +1 -0
- package/.server/server/plugins/engine/components/ComponentBase.js +2 -0
- package/.server/server/plugins/engine/components/ComponentBase.js.map +1 -1
- package/.server/server/plugins/engine/components/ComponentCollection.js +11 -6
- package/.server/server/plugins/engine/components/ComponentCollection.js.map +1 -1
- package/.server/server/plugins/engine/components/DatePartsField.d.ts +6 -3
- package/.server/server/plugins/engine/components/DatePartsField.js +12 -7
- package/.server/server/plugins/engine/components/DatePartsField.js.map +1 -1
- package/.server/server/plugins/engine/components/DeclarationField.d.ts +5 -2
- package/.server/server/plugins/engine/components/DeclarationField.js +6 -4
- package/.server/server/plugins/engine/components/DeclarationField.js.map +1 -1
- package/.server/server/plugins/engine/components/Details.d.ts +1 -0
- package/.server/server/plugins/engine/components/EastingNorthingField.d.ts +29 -2
- package/.server/server/plugins/engine/components/EastingNorthingField.js +110 -54
- package/.server/server/plugins/engine/components/EastingNorthingField.js.map +1 -1
- package/.server/server/plugins/engine/components/EmailAddressField.d.ts +4 -1
- package/.server/server/plugins/engine/components/EmailAddressField.js +2 -1
- package/.server/server/plugins/engine/components/EmailAddressField.js.map +1 -1
- package/.server/server/plugins/engine/components/FileUploadField.d.ts +12 -0
- package/.server/server/plugins/engine/components/FileUploadField.js +23 -3
- package/.server/server/plugins/engine/components/FileUploadField.js.map +1 -1
- package/.server/server/plugins/engine/components/FormComponent.d.ts +5 -1
- package/.server/server/plugins/engine/components/FormComponent.js +5 -2
- package/.server/server/plugins/engine/components/FormComponent.js.map +1 -1
- package/.server/server/plugins/engine/components/GeospatialField.d.ts +1 -0
- package/.server/server/plugins/engine/components/GeospatialField.js +1 -1
- package/.server/server/plugins/engine/components/GeospatialField.js.map +1 -1
- package/.server/server/plugins/engine/components/Html.d.ts +1 -0
- package/.server/server/plugins/engine/components/InsetText.d.ts +1 -0
- package/.server/server/plugins/engine/components/LatLongField.d.ts +28 -2
- package/.server/server/plugins/engine/components/LatLongField.js +85 -48
- package/.server/server/plugins/engine/components/LatLongField.js.map +1 -1
- package/.server/server/plugins/engine/components/List.d.ts +1 -0
- package/.server/server/plugins/engine/components/ListFormComponent.d.ts +1 -0
- package/.server/server/plugins/engine/components/LocationFieldBase.d.ts +8 -2
- package/.server/server/plugins/engine/components/LocationFieldBase.js +18 -5
- package/.server/server/plugins/engine/components/LocationFieldBase.js.map +1 -1
- package/.server/server/plugins/engine/components/LocationFieldHelpers.d.ts +8 -3
- package/.server/server/plugins/engine/components/LocationFieldHelpers.js +13 -12
- package/.server/server/plugins/engine/components/LocationFieldHelpers.js.map +1 -1
- package/.server/server/plugins/engine/components/Markdown.d.ts +1 -0
- package/.server/server/plugins/engine/components/Markdown.js +1 -1
- package/.server/server/plugins/engine/components/Markdown.js.map +1 -1
- package/.server/server/plugins/engine/components/MonthYearField.d.ts +5 -2
- package/.server/server/plugins/engine/components/MonthYearField.js +13 -9
- package/.server/server/plugins/engine/components/MonthYearField.js.map +1 -1
- package/.server/server/plugins/engine/components/MultilineTextField.d.ts +1 -0
- package/.server/server/plugins/engine/components/NationalGridFieldNumberField.d.ts +2 -1
- package/.server/server/plugins/engine/components/NationalGridFieldNumberField.js +4 -3
- package/.server/server/plugins/engine/components/NationalGridFieldNumberField.js.map +1 -1
- package/.server/server/plugins/engine/components/NotificationBanner.d.ts +1 -0
- package/.server/server/plugins/engine/components/NumberField.d.ts +5 -0
- package/.server/server/plugins/engine/components/NumberField.js +16 -0
- package/.server/server/plugins/engine/components/NumberField.js.map +1 -1
- package/.server/server/plugins/engine/components/OsGridRefField.d.ts +2 -1
- package/.server/server/plugins/engine/components/OsGridRefField.js +4 -3
- package/.server/server/plugins/engine/components/OsGridRefField.js.map +1 -1
- package/.server/server/plugins/engine/components/PaymentField.d.ts +3 -0
- package/.server/server/plugins/engine/components/PaymentField.js +17 -6
- package/.server/server/plugins/engine/components/PaymentField.js.map +1 -1
- package/.server/server/plugins/engine/components/SelectField.d.ts +1 -0
- package/.server/server/plugins/engine/components/SelectionControlField.d.ts +1 -0
- package/.server/server/plugins/engine/components/TelephoneNumberField.d.ts +1 -0
- package/.server/server/plugins/engine/components/UkAddressField.d.ts +1 -0
- package/.server/server/plugins/engine/components/UkAddressField.js +23 -8
- package/.server/server/plugins/engine/components/UkAddressField.js.map +1 -1
- package/.server/server/plugins/engine/components/YesNoField.d.ts +5 -2
- package/.server/server/plugins/engine/components/YesNoField.js +17 -8
- package/.server/server/plugins/engine/components/YesNoField.js.map +1 -1
- package/.server/server/plugins/engine/components/helpers/components.js +1 -2
- package/.server/server/plugins/engine/components/helpers/components.js.map +1 -1
- package/.server/server/plugins/engine/components/helpers/geospatial.d.ts +3 -1
- package/.server/server/plugins/engine/components/helpers/geospatial.js +32 -0
- package/.server/server/plugins/engine/components/helpers/geospatial.js.map +1 -1
- package/.server/server/plugins/engine/components/helpers/index.d.ts +7 -0
- package/.server/server/plugins/engine/components/helpers/index.js +13 -1
- package/.server/server/plugins/engine/components/helpers/index.js.map +1 -1
- package/.server/server/plugins/engine/components/types.d.ts +1 -0
- package/.server/server/plugins/engine/components/types.js.map +1 -1
- package/.server/server/plugins/engine/helpers.d.ts +22 -2
- package/.server/server/plugins/engine/helpers.js +44 -5
- package/.server/server/plugins/engine/helpers.js.map +1 -1
- package/.server/server/plugins/engine/i18n/buildValidationMessages.d.ts +3 -0
- package/.server/server/plugins/engine/i18n/buildValidationMessages.js +10 -7
- package/.server/server/plugins/engine/i18n/buildValidationMessages.js.map +1 -1
- package/.server/server/plugins/engine/i18n/createFormTranslator.d.ts +4 -4
- package/.server/server/plugins/engine/i18n/createFormTranslator.js +33 -4
- package/.server/server/plugins/engine/i18n/createFormTranslator.js.map +1 -1
- package/.server/server/plugins/engine/i18n/extractBaseTranslations.d.ts +1 -1
- package/.server/server/plugins/engine/i18n/extractBaseTranslations.js +9 -0
- package/.server/server/plugins/engine/i18n/extractBaseTranslations.js.map +1 -1
- package/.server/server/plugins/engine/i18n/form.d.ts +13 -0
- package/.server/server/plugins/engine/i18n/form.js +35 -0
- package/.server/server/plugins/engine/i18n/form.js.map +1 -0
- package/.server/server/plugins/engine/i18n/languages.d.ts +10 -0
- package/.server/server/plugins/engine/i18n/languages.js +19 -0
- package/.server/server/plugins/engine/i18n/languages.js.map +1 -0
- package/.server/server/plugins/engine/i18n/translations/cy.json +85 -8
- package/.server/server/plugins/engine/i18n/translations/en-GB.json +55 -6
- package/.server/server/plugins/engine/i18n/types.d.ts +2 -0
- package/.server/server/plugins/engine/i18n/types.js.map +1 -1
- package/.server/server/plugins/engine/index.d.ts +4 -0
- package/.server/server/plugins/engine/index.js +4 -0
- package/.server/server/plugins/engine/index.js.map +1 -1
- package/.server/server/plugins/engine/models/FormModel.d.ts +0 -4
- package/.server/server/plugins/engine/models/FormModel.js +9 -15
- package/.server/server/plugins/engine/models/FormModel.js.map +1 -1
- package/.server/server/plugins/engine/models/SummaryViewModel.js +9 -4
- package/.server/server/plugins/engine/models/SummaryViewModel.js.map +1 -1
- package/.server/server/plugins/engine/outputFormatters/adapter/v1.js +3 -5
- package/.server/server/plugins/engine/outputFormatters/adapter/v1.js.map +1 -1
- package/.server/server/plugins/engine/outputFormatters/human/v1.js +2 -1
- package/.server/server/plugins/engine/outputFormatters/human/v1.js.map +1 -1
- package/.server/server/plugins/engine/outputFormatters/machine/v2.d.ts +2 -0
- package/.server/server/plugins/engine/outputFormatters/machine/v2.js +2 -0
- package/.server/server/plugins/engine/outputFormatters/machine/v2.js.map +1 -1
- package/.server/server/plugins/engine/pageControllers/FileUploadPageController.d.ts +7 -1
- package/.server/server/plugins/engine/pageControllers/FileUploadPageController.js +56 -10
- package/.server/server/plugins/engine/pageControllers/FileUploadPageController.js.map +1 -1
- package/.server/server/plugins/engine/pageControllers/QuestionPageController.d.ts +1 -1
- package/.server/server/plugins/engine/pageControllers/QuestionPageController.js +7 -3
- package/.server/server/plugins/engine/pageControllers/QuestionPageController.js.map +1 -1
- package/.server/server/plugins/engine/pageControllers/RepeatPageController.js +3 -4
- package/.server/server/plugins/engine/pageControllers/RepeatPageController.js.map +1 -1
- package/.server/server/plugins/engine/pageControllers/SummaryPageController.js +10 -4
- package/.server/server/plugins/engine/pageControllers/SummaryPageController.js.map +1 -1
- package/.server/server/plugins/engine/pageControllers/helpers/submission.d.ts +1 -1
- package/.server/server/plugins/engine/pageControllers/helpers/submission.js +3 -3
- package/.server/server/plugins/engine/pageControllers/helpers/submission.js.map +1 -1
- package/.server/server/plugins/engine/pageControllers/validationOptions.js +23 -2
- package/.server/server/plugins/engine/pageControllers/validationOptions.js.map +1 -1
- package/.server/server/plugins/engine/types/schema.js +1 -0
- package/.server/server/plugins/engine/types/schema.js.map +1 -1
- package/.server/server/plugins/engine/types.d.ts +5 -0
- package/.server/server/plugins/engine/types.js.map +1 -1
- package/.server/server/plugins/engine/views/components/_location-field-base.html +2 -1
- package/.server/server/plugins/engine/views/components/fileuploadfield.html +1 -1
- package/.server/server/plugins/engine/views/components/multilinetextfield.html +12 -1
- package/.server/server/plugins/engine/views/components/paymentfield.html +1 -1
- package/.server/server/plugins/engine/views/components/ukaddressfield.html +1 -1
- package/.server/server/plugins/engine/views/file-upload.html +1 -1
- package/.server/server/plugins/engine/views/partials/preview-banner.html +3 -1
- package/.server/server/plugins/nunjucks/filters/applyUrlParam.d.ts +9 -0
- package/.server/server/plugins/nunjucks/filters/applyUrlParam.js +17 -0
- package/.server/server/plugins/nunjucks/filters/applyUrlParam.js.map +1 -0
- package/.server/server/plugins/nunjucks/filters/applyUrlParam.test.js +17 -0
- package/.server/server/plugins/nunjucks/filters/applyUrlParam.test.js.map +1 -0
- package/.server/server/plugins/nunjucks/filters/field.d.ts +1 -1
- package/.server/server/plugins/nunjucks/filters/index.d.ts +1 -0
- package/.server/server/plugins/nunjucks/filters/index.js +1 -0
- package/.server/server/plugins/nunjucks/filters/index.js.map +1 -1
- package/.server/server/plugins/payment/helper.d.ts +11 -1
- package/.server/server/plugins/payment/helper.js +18 -2
- package/.server/server/plugins/payment/helper.js.map +1 -1
- package/.server/server/plugins/payment/helper.test.js +2 -1
- package/.server/server/plugins/payment/helper.test.js.map +1 -1
- package/.server/server/plugins/payment/service.d.ts +2 -1
- package/.server/server/plugins/payment/service.js +5 -2
- package/.server/server/plugins/payment/service.js.map +1 -1
- package/.server/server/plugins/payment/service.test.js +7 -3
- package/.server/server/plugins/payment/service.test.js.map +1 -1
- package/.server/server/plugins/payment/types.d.ts +4 -0
- package/.server/server/plugins/payment/types.js +1 -0
- package/.server/server/plugins/payment/types.js.map +1 -1
- package/.server/server/plugins/postcode-lookup/models/index.d.ts +249 -3
- package/.server/server/plugins/postcode-lookup/models/index.js +87 -33
- package/.server/server/plugins/postcode-lookup/models/index.js.map +1 -1
- package/.server/server/plugins/postcode-lookup/routes/index.d.ts +15 -1
- package/.server/server/plugins/postcode-lookup/routes/index.js +47 -15
- package/.server/server/plugins/postcode-lookup/routes/index.js.map +1 -1
- package/.server/server/plugins/postcode-lookup/routes/index.test.js +84 -0
- package/.server/server/plugins/postcode-lookup/routes/index.test.js.map +1 -0
- package/.server/server/plugins/postcode-lookup/types.d.ts +12 -0
- package/.server/server/plugins/postcode-lookup/types.js +6 -1
- package/.server/server/plugins/postcode-lookup/types.js.map +1 -1
- package/.server/server/plugins/postcode-lookup/views/postcode-lookup-details.html +3 -3
- package/.server/server/utils/type-utils.d.ts +1 -2
- package/.server/server/utils/type-utils.js +0 -3
- package/.server/server/utils/type-utils.js.map +1 -1
- package/.server/server/utils/utils.d.ts +6 -0
- package/.server/server/utils/utils.js +18 -1
- package/.server/server/utils/utils.js.map +1 -1
- package/.server/server/utils/utils.test.js +21 -1
- package/.server/server/utils/utils.test.js.map +1 -1
- package/package.json +9 -2
- package/src/client/javascripts/file-upload.js +11 -3
- package/src/client/javascripts/geospatial-map.js +7 -34
- package/src/client/javascripts/govuk.js +2 -0
- package/src/client/javascripts/location-map.js +9 -1
- package/src/client/javascripts/map.js +42 -0
- package/src/client/javascripts/maps.js +5 -0
- package/src/client/javascripts/shared.js +1 -3
- package/src/client/javascripts/sssi-dataset.js +39 -41
- package/src/client/stylesheets/maps.scss +4 -0
- package/src/client/stylesheets/shared.scss +1 -5
- package/src/server/constants.js +2 -0
- package/src/server/plugins/engine/components/AutocompleteField.ts +13 -0
- package/src/server/plugins/engine/components/CheckboxesField.ts +13 -1
- package/src/server/plugins/engine/components/ComponentBase.ts +2 -0
- package/src/server/plugins/engine/components/ComponentCollection.ts +16 -11
- package/src/server/plugins/engine/components/DatePartsField.ts +20 -9
- package/src/server/plugins/engine/components/DeclarationField.ts +7 -6
- package/src/server/plugins/engine/components/EastingNorthingField.ts +185 -89
- package/src/server/plugins/engine/components/EmailAddressField.ts +2 -1
- package/src/server/plugins/engine/components/FileUploadField.ts +24 -3
- package/src/server/plugins/engine/components/FormComponent.ts +6 -5
- package/src/server/plugins/engine/components/GeospatialField.ts +6 -1
- package/src/server/plugins/engine/components/LatLongField.ts +128 -58
- package/src/server/plugins/engine/components/LocationFieldBase.ts +23 -6
- package/src/server/plugins/engine/components/LocationFieldHelpers.ts +20 -13
- package/src/server/plugins/engine/components/Markdown.ts +2 -3
- package/src/server/plugins/engine/components/MonthYearField.ts +20 -15
- package/src/server/plugins/engine/components/NationalGridFieldNumberField.ts +9 -3
- package/src/server/plugins/engine/components/NumberField.ts +21 -1
- package/src/server/plugins/engine/components/OsGridRefField.ts +9 -3
- package/src/server/plugins/engine/components/PaymentField.ts +15 -5
- package/src/server/plugins/engine/components/UkAddressField.ts +30 -7
- package/src/server/plugins/engine/components/YesNoField.ts +17 -9
- package/src/server/plugins/engine/components/helpers/components.ts +1 -2
- package/src/server/plugins/engine/components/helpers/geospatial.ts +53 -0
- package/src/server/plugins/engine/components/helpers/index.ts +19 -0
- package/src/server/plugins/engine/components/types.ts +1 -0
- package/src/server/plugins/engine/helpers.ts +52 -5
- package/src/server/plugins/engine/i18n/buildValidationMessages.ts +10 -7
- package/src/server/plugins/engine/i18n/createFormTranslator.ts +62 -11
- package/src/server/plugins/engine/i18n/extractBaseTranslations.ts +7 -1
- package/src/server/plugins/engine/i18n/form.ts +54 -0
- package/src/server/plugins/engine/i18n/languages.ts +19 -0
- package/src/server/plugins/engine/i18n/translations/cy.json +85 -8
- package/src/server/plugins/engine/i18n/translations/en-GB.json +55 -6
- package/src/server/plugins/engine/i18n/types.ts +2 -0
- package/src/server/plugins/engine/index.ts +7 -0
- package/src/server/plugins/engine/models/FormModel.ts +9 -15
- package/src/server/plugins/engine/models/SummaryViewModel.ts +6 -5
- package/src/server/plugins/engine/outputFormatters/adapter/v1.ts +3 -6
- package/src/server/plugins/engine/outputFormatters/human/v1.ts +2 -1
- package/src/server/plugins/engine/outputFormatters/machine/v2.ts +3 -0
- package/src/server/plugins/engine/pageControllers/FileUploadPageController.ts +60 -9
- package/src/server/plugins/engine/pageControllers/QuestionPageController.ts +10 -5
- package/src/server/plugins/engine/pageControllers/RepeatPageController.ts +2 -2
- package/src/server/plugins/engine/pageControllers/SummaryPageController.ts +15 -4
- package/src/server/plugins/engine/pageControllers/helpers/submission.ts +6 -3
- package/src/server/plugins/engine/pageControllers/validationOptions.ts +27 -2
- package/src/server/plugins/engine/types/schema.ts +1 -0
- package/src/server/plugins/engine/types.ts +5 -0
- package/src/server/plugins/engine/views/components/_location-field-base.html +2 -1
- package/src/server/plugins/engine/views/components/fileuploadfield.html +1 -1
- package/src/server/plugins/engine/views/components/multilinetextfield.html +12 -1
- package/src/server/plugins/engine/views/components/paymentfield.html +1 -1
- package/src/server/plugins/engine/views/components/ukaddressfield.html +1 -1
- package/src/server/plugins/engine/views/file-upload.html +1 -1
- package/src/server/plugins/engine/views/partials/preview-banner.html +3 -1
- package/src/server/plugins/nunjucks/filters/applyUrlParam.js +17 -0
- package/src/server/plugins/nunjucks/filters/index.js +1 -0
- package/src/server/plugins/payment/helper.js +22 -2
- package/src/server/plugins/payment/service.js +6 -2
- package/src/server/plugins/payment/types.js +1 -0
- package/src/server/plugins/postcode-lookup/models/index.js +75 -43
- package/src/server/plugins/postcode-lookup/routes/index.js +73 -16
- package/src/server/plugins/postcode-lookup/types.js +6 -1
- package/src/server/plugins/postcode-lookup/views/postcode-lookup-details.html +3 -3
- package/src/server/utils/type-utils.ts +1 -11
- package/src/server/utils/utils.js +19 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"geospatial.js","names":["GeospatialFieldOptionsCountryEnum","Bourne","booleanWithin","JoiBase","countries","countriesDesc","England","NorthernIreland","Scotland","Wales","Joi","extend","type","base","array","messages","coerce","from","method","value","helpers","trimmed","trim","undefined","parse","result","errors","error","coordinatesSchema","items","number","required","featurePropertiesSchema","object","keys","description","string","coordinateGridReference","centroidGridReference","featureGeometrySchema","valid","coordinates","when","switch","is","then","min","featureSchema","id","properties","geometry","applySchemaConstraints","schema","def","options","constraints","isOptional","length","max","optional","getGeospatialSchema","country","at","unique","validateCountryBounds","countryFeature","features","find","feature","custom"],"sources":["../../../../../../src/server/plugins/engine/components/helpers/geospatial.ts"],"sourcesContent":["import {\n GeospatialFieldOptionsCountryEnum,\n type GeospatialFieldComponent,\n type GeospatialFieldOptionsCountry\n} from '@defra/forms-model'\nimport Bourne from '@hapi/bourne'\nimport { booleanWithin } from '@turf/boolean-within'\nimport JoiBase, { type CustomValidator } from 'joi'\n\nimport {\n type Coordinates,\n type Feature,\n type FeatureProperties,\n type Geometry\n} from '~/src/server/plugins/engine/types.js'\nimport { countries } from '~/src/server/plugins/map/routes/index.js'\n\nconst countriesDesc: Record<GeospatialFieldOptionsCountryEnum, string> = {\n [GeospatialFieldOptionsCountryEnum.England]: 'England',\n [GeospatialFieldOptionsCountryEnum.NorthernIreland]: 'Northern Ireland',\n [GeospatialFieldOptionsCountryEnum.Scotland]: 'Scotland',\n [GeospatialFieldOptionsCountryEnum.Wales]: 'Wales'\n}\n\nconst Joi = JoiBase.extend({\n type: 'array',\n base: JoiBase.array(),\n messages: {\n 'object.invalidjson': '{{#label}} must be a valid json array string'\n },\n coerce: {\n from: 'string',\n method(value, helpers) {\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (trimmed === '' || trimmed === '[]') {\n return {\n value: undefined\n }\n }\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n return { value: Bourne.parse(value) }\n } catch {\n const result = {\n value,\n errors: [helpers.error('object.invalidjson')]\n }\n\n return result\n }\n } else {\n return {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n value\n }\n }\n }\n }\n}) as JoiBase.Root\n\nconst coordinatesSchema = Joi.array<Coordinates[]>()\n .items(Joi.number().required(), Joi.number().required())\n .required()\n\nconst featurePropertiesSchema = Joi.object<FeatureProperties>()\n .keys({\n description: Joi.string().required(),\n coordinateGridReference: Joi.string().required(),\n centroidGridReference: Joi.string().required()\n })\n .required()\n\nconst featureGeometrySchema = Joi.object<Geometry>().keys({\n type: Joi.string().valid('Point', 'LineString', 'Polygon').required(),\n coordinates: Joi.array()\n .when('type', {\n switch: [\n { is: 'Point', then: coordinatesSchema },\n {\n is: 'LineString',\n then: Joi.array().items(coordinatesSchema).min(2)\n },\n {\n is: 'Polygon',\n then: Joi.array().items(Joi.array().items(coordinatesSchema).min(3))\n }\n ]\n })\n .required()\n})\n\nconst featureSchema = Joi.object<Feature>().keys({\n id: Joi.string().required(),\n type: Joi.string().valid('Feature').required(),\n properties: featurePropertiesSchema,\n geometry: featureGeometrySchema\n})\n\nfunction applySchemaConstraints(\n schema: JoiBase.ArraySchema<Feature[]>,\n def: GeospatialFieldComponent\n) {\n const { options, schema: constraints } = def\n const isOptional = options.required === false\n\n if (typeof constraints?.length === 'number') {\n schema = schema.length(constraints.length)\n } else {\n if (typeof constraints?.min === 'number') {\n schema = schema.min(constraints.min)\n } else if (!isOptional) {\n schema = schema.min(1)\n }\n\n schema = schema.max(\n typeof constraints?.max === 'number' ? constraints.max : 50\n )\n }\n\n if (isOptional) {\n schema = schema.optional()\n } else {\n schema = schema.required()\n }\n\n return schema\n}\n\nexport function getGeospatialSchema(\n def: GeospatialFieldComponent\n): JoiBase.ArraySchema<Feature[]> {\n const { options = {} } = def\n const country: GeospatialFieldOptionsCountry | undefined =\n options.countries?.at(0)\n\n if (!country) {\n return applySchemaConstraints(\n Joi.array<Feature[]>().items(featureSchema).unique('id'),\n def\n )\n }\n\n const validateCountryBounds: CustomValidator = (value, helpers) => {\n const countryFeature = countries.features.find(\n (feature) => feature.id === country\n )\n\n if (!countryFeature) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value\n }\n\n const result = booleanWithin(value as Geometry | Feature, countryFeature)\n\n if (!result) {\n return helpers.error('any.custom', {\n country: countriesDesc[country as GeospatialFieldOptionsCountryEnum]\n })\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value\n }\n\n return applySchemaConstraints(\n Joi.array<Feature[]>()\n .items(featureSchema.custom(validateCountryBounds))\n .unique('id'),\n def\n )\n}\n"],"mappings":"AAAA,SACEA,iCAAiC,QAG5B,oBAAoB;AAC3B,OAAOC,MAAM,MAAM,cAAc;AACjC,SAASC,aAAa,QAAQ,sBAAsB;AACpD,OAAOC,OAAO,MAAgC,KAAK;AAQnD,SAASC,SAAS;AAElB,MAAMC,aAAgE,GAAG;EACvE,CAACL,iCAAiC,CAACM,OAAO,GAAG,SAAS;EACtD,CAACN,iCAAiC,CAACO,eAAe,GAAG,kBAAkB;EACvE,CAACP,iCAAiC,CAACQ,QAAQ,GAAG,UAAU;EACxD,CAACR,iCAAiC,CAACS,KAAK,GAAG;AAC7C,CAAC;AAED,MAAMC,GAAG,GAAGP,OAAO,CAACQ,MAAM,CAAC;EACzBC,IAAI,EAAE,OAAO;EACbC,IAAI,EAAEV,OAAO,CAACW,KAAK,CAAC,CAAC;EACrBC,QAAQ,EAAE;IACR,oBAAoB,EAAE;EACxB,CAAC;EACDC,MAAM,EAAE;IACNC,IAAI,EAAE,QAAQ;IAC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I,CAC3CC,OAAO,IAAKA,OAAO,CAACpB,EAAE,KAAKa,OAC9B,CAAC;IAED,IAAI,CAACI,cAAc,EAAE;MACnB;MACA,OAAO9C,KAAK;IACd;IAEA,MAAMM,MAAM,GAAGvB,aAAa,CAACiB,KAAK,EAAwB8C,cAAc,CAAC;IAEzE,IAAI,CAACxC,MAAM,EAAE;MACX,OAAOL,OAAO,CAACO,KAAK,CAAC,YAAY,EAAE;QACjCkC,OAAO,EAAExD,aAAa,CAACwD,OAAO;MAChC,CAAC,CAAC;IACJ;;IAEA;IACA,OAAO1C,KAAK;EACd,CAAC;EAED,OAAOgC,sBAAsB,CAC3BzC,GAAG,CAACI,KAAK,CAAY,CAAC,CACnBe,KAAK,CAACkB,aAAa,CAACsB,MAAM,CAACL,qBAAqB,CAAC,CAAC,CAClDD,MAAM,CAAC,IAAI,CAAC,EACfV,GACF,CAAC;AACH","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"geospatial.js","names":["GeospatialFieldOptionsCountryEnum","Bourne","booleanWithin","point","OsGridRef","JoiBase","countries","countriesDesc","England","NorthernIreland","Scotland","Wales","Joi","extend","type","base","array","messages","coerce","from","method","value","helpers","trimmed","trim","undefined","parse","result","errors","error","coordinatesSchema","items","number","required","featurePropertiesSchema","object","keys","description","string","coordinateGridReference","centroidGridReference","featureGeometrySchema","valid","coordinates","when","switch","is","then","min","featureSchema","id","properties","geometry","applySchemaConstraints","schema","def","options","constraints","isOptional","length","max","optional","getGeospatialSchema","country","at","unique","validateCountryBounds","countryFeature","features","find","feature","custom","getEastingNorthingCountryValidator","field","eastingNorthing","getFormValueFromState","gridRef","easting","northing","latLong","toLatLon","coord","longitude","latitude","within","path","name"],"sources":["../../../../../../src/server/plugins/engine/components/helpers/geospatial.ts"],"sourcesContent":["import {\n GeospatialFieldOptionsCountryEnum,\n type GeospatialFieldComponent,\n type GeospatialFieldOptionsCountry\n} from '@defra/forms-model'\nimport Bourne from '@hapi/bourne'\nimport { booleanWithin } from '@turf/boolean-within'\nimport { point } from '@turf/helpers'\n// @ts-expect-error - no types\nimport OsGridRef from 'geodesy/osgridref.js'\nimport JoiBase, { type CustomValidator } from 'joi'\n\nimport { type EastingNorthingField } from '~/src/server/plugins/engine/components/EastingNorthingField.js'\nimport { type EastingNorthingState } from '~/src/server/plugins/engine/components/types.js'\nimport {\n type Coordinates,\n type Feature,\n type FeatureProperties,\n type Geometry\n} from '~/src/server/plugins/engine/types.js'\nimport { countries } from '~/src/server/plugins/map/routes/index.js'\n\nconst countriesDesc: Record<GeospatialFieldOptionsCountryEnum, string> = {\n [GeospatialFieldOptionsCountryEnum.England]: 'England',\n [GeospatialFieldOptionsCountryEnum.NorthernIreland]: 'Northern Ireland',\n [GeospatialFieldOptionsCountryEnum.Scotland]: 'Scotland',\n [GeospatialFieldOptionsCountryEnum.Wales]: 'Wales'\n}\n\nconst Joi = JoiBase.extend({\n type: 'array',\n base: JoiBase.array(),\n messages: {\n 'object.invalidjson': '{{#label}} must be a valid json array string'\n },\n coerce: {\n from: 'string',\n method(value, helpers) {\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (trimmed === '' || trimmed === '[]') {\n return {\n value: undefined\n }\n }\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n return { value: Bourne.parse(value) }\n } catch {\n const result = {\n value,\n errors: [helpers.error('object.invalidjson')]\n }\n\n return result\n }\n } else {\n return {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n value\n }\n }\n }\n }\n}) as JoiBase.Root\n\nconst coordinatesSchema = Joi.array<Coordinates[]>()\n .items(Joi.number().required(), Joi.number().required())\n .required()\n\nconst featurePropertiesSchema = Joi.object<FeatureProperties>()\n .keys({\n description: Joi.string().required(),\n coordinateGridReference: Joi.string().required(),\n centroidGridReference: Joi.string().required()\n })\n .required()\n\nconst featureGeometrySchema = Joi.object<Geometry>().keys({\n type: Joi.string().valid('Point', 'LineString', 'Polygon').required(),\n coordinates: Joi.array()\n .when('type', {\n switch: [\n { is: 'Point', then: coordinatesSchema },\n {\n is: 'LineString',\n then: Joi.array().items(coordinatesSchema).min(2)\n },\n {\n is: 'Polygon',\n then: Joi.array().items(Joi.array().items(coordinatesSchema).min(3))\n }\n ]\n })\n .required()\n})\n\nconst featureSchema = Joi.object<Feature>().keys({\n id: Joi.string().required(),\n type: Joi.string().valid('Feature').required(),\n properties: featurePropertiesSchema,\n geometry: featureGeometrySchema\n})\n\nfunction applySchemaConstraints(\n schema: JoiBase.ArraySchema<Feature[]>,\n def: GeospatialFieldComponent\n) {\n const { options, schema: constraints } = def\n const isOptional = options.required === false\n\n if (typeof constraints?.length === 'number') {\n schema = schema.length(constraints.length)\n } else {\n if (typeof constraints?.min === 'number') {\n schema = schema.min(constraints.min)\n } else if (!isOptional) {\n schema = schema.min(1)\n }\n\n schema = schema.max(\n typeof constraints?.max === 'number' ? constraints.max : 50\n )\n }\n\n if (isOptional) {\n schema = schema.optional()\n } else {\n schema = schema.required()\n }\n\n return schema\n}\n\nexport function getGeospatialSchema(\n def: GeospatialFieldComponent\n): JoiBase.ArraySchema<Feature[]> {\n const { options = {} } = def\n const country: GeospatialFieldOptionsCountry | undefined =\n options.countries?.at(0)\n\n if (!country) {\n return applySchemaConstraints(\n Joi.array<Feature[]>().items(featureSchema).unique('id'),\n def\n )\n }\n\n const validateCountryBounds: CustomValidator = (value, helpers) => {\n const countryFeature = countries.features.find(\n (feature) => feature.id === country\n )\n\n if (!countryFeature) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value\n }\n\n const result = booleanWithin(value as Geometry | Feature, countryFeature)\n\n if (!result) {\n return helpers.error('any.custom', {\n country: countriesDesc[country as GeospatialFieldOptionsCountryEnum]\n })\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value\n }\n\n return applySchemaConstraints(\n Joi.array<Feature[]>()\n .items(featureSchema.custom(validateCountryBounds))\n .unique('id'),\n def\n )\n}\n\nexport function getEastingNorthingCountryValidator(\n field: EastingNorthingField,\n country: GeospatialFieldOptionsCountry\n) {\n const validateCountryBounds: CustomValidator = (value, helpers) => {\n const countryFeature = countries.features.find(\n (feature) => feature.id === country\n )\n\n if (!countryFeature) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value\n }\n\n const eastingNorthing = field.getFormValueFromState(\n value as EastingNorthingState\n )\n\n if (!eastingNorthing) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value\n }\n\n const gridRef = new OsGridRef(\n eastingNorthing.easting,\n eastingNorthing.northing\n )\n const latLong = gridRef.toLatLon()\n const coord = point([latLong.longitude, latLong.latitude])\n const within = booleanWithin(coord, countryFeature)\n\n if (!within) {\n return helpers.error(\n 'any.custom',\n {\n country: countriesDesc[country as GeospatialFieldOptionsCountryEnum]\n },\n { path: [field.name] }\n )\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return value\n }\n\n return validateCountryBounds\n}\n"],"mappings":"AAAA,SACEA,iCAAiC,QAG5B,oBAAoB;AAC3B,OAAOC,MAAM,MAAM,cAAc;AACjC,SAASC,aAAa,QAAQ,sBAAsB;AACpD,SAASC,KAAK,QAAQ,eAAe;AACrC;AACA,OAAOC,SAAS,MAAM,sBAAsB;AAC5C,OAAOC,OAAO,MAAgC,KAAK;AAUnD,SAASC,SAAS;AAElB,MAAMC,aAAgE,GAAG;EACvE,CAACP,iCAAiC,CAACQ,OAAO,GAAG,SAAS;EACtD,CAACR,iCAAiC,CAACS,eAAe,GAAG,kBAAkB;EACvE,CAACT,iCAAiC,CAACU,QAAQ,GAAG,UAAU;EACxD,CAACV,iCAAiC,CAACW,KAAK,GAAG;AAC7C,CAAC;AAED,MAAMC,GAAG,GAAGP,OAAO,CAACQ,MAAM,CAAC;EACzBC,IAAI,EAAE,OAAO;EACbC,IAAI,EAAEV,OAAO,CAACW,KAAK,CAAC,CAAC;EACrBC,QAAQ,EAAE;IACR,oBAAoB,EAAE;EACxB,CAAC;EACDC,MAAM,EAAE;IACNC,IAAI,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AAEH,OAAO,CAACI,QAAQ,CAAC,CAAC;IAC1D,MAAMC,MAAM,GAAGlF,aAAa,CAAC+E,KAAK,EAAEd,cAAc,CAAC;IAEnD,IAAI,CAACiB,MAAM,EAAE;MACX,OAAO9D,OAAO,CAACO,KAAK,CAClB,YAAY,EACZ;QACEkC,OAAO,EAAExD,aAAa,CAACwD,OAAO;MAChC,CAAC,EACD;QAAEsB,IAAI,EAAE,CAACZ,KAAK,CAACa,IAAI;MAAE,CACvB,CAAC;IACH;;IAEA;IACA,OAAOjE,KAAK;EACd,CAAC;EAED,OAAO6C,qBAAqB;AAC9B","ignoreList":[]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type ComponentDef } from '@defra/forms-model';
|
|
2
2
|
import { type JoiExpression, type ReferenceOptions } from 'joi';
|
|
3
|
+
import { type Translator } from '../../../../../server/plugins/engine/i18n/types.js';
|
|
3
4
|
/**
|
|
4
5
|
* Prevent Markdown formatting
|
|
5
6
|
* @see {@link https://pandoc.org/chunkedhtml-demo/8.11-backslash-escapes.html}
|
|
@@ -24,3 +25,9 @@ export declare const lowerFirstExpressionOptions: ReferenceOptions;
|
|
|
24
25
|
* Used for error messages in location field components
|
|
25
26
|
*/
|
|
26
27
|
export declare const createLowerFirstExpression: (template: string) => JoiExpression;
|
|
28
|
+
/**
|
|
29
|
+
* Translate a component label, in precedence order of errorDescription, then shortDesciption, then title
|
|
30
|
+
* @param {ComponentDef} component
|
|
31
|
+
* @param {Translator} translator
|
|
32
|
+
*/
|
|
33
|
+
export declare function getTranslatedLabel(component: ComponentDef, translator: Translator): string;
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import joi from 'joi';
|
|
2
2
|
import lowerFirst from 'lodash/lowerFirst.js';
|
|
3
|
-
|
|
4
3
|
/**
|
|
5
4
|
* Prevent Markdown formatting
|
|
6
5
|
* @see {@link https://pandoc.org/chunkedhtml-demo/8.11-backslash-escapes.html}
|
|
@@ -39,4 +38,17 @@ export const lowerFirstExpressionOptions = {
|
|
|
39
38
|
* Used for error messages in location field components
|
|
40
39
|
*/
|
|
41
40
|
export const createLowerFirstExpression = template => joi.expression(template, lowerFirstExpressionOptions);
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Translate a component label, in precedence order of errorDescription, then shortDesciption, then title
|
|
44
|
+
* @param {ComponentDef} component
|
|
45
|
+
* @param {Translator} translator
|
|
46
|
+
*/
|
|
47
|
+
export function getTranslatedLabel(component, translator) {
|
|
48
|
+
const {
|
|
49
|
+
tComponent
|
|
50
|
+
} = translator;
|
|
51
|
+
const translatedLabel = tComponent(component, 'errorDescription') || tComponent(component, 'shortDescription') || tComponent(component, 'title');
|
|
52
|
+
return translatedLabel;
|
|
53
|
+
}
|
|
42
54
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["joi","lowerFirst","escapeMarkdown","answer","punctuation","character","replaceAll","addClassOptionIfNone","options","className","classes","lowerFirstPreserveProperNouns","text","result","replace","lowerFirstExpressionOptions","functions","createLowerFirstExpression","template","expression"],"sources":["../../../../../../src/server/plugins/engine/components/helpers/index.ts"],"sourcesContent":["import { type ComponentDef } from '@defra/forms-model'\nimport joi, { type JoiExpression, type ReferenceOptions } from 'joi'\nimport lowerFirst from 'lodash/lowerFirst.js'\n\n/**\n * Prevent Markdown formatting\n * @see {@link https://pandoc.org/chunkedhtml-demo/8.11-backslash-escapes.html}\n */\nexport function escapeMarkdown(answer: string) {\n const punctuation = [\n '`',\n \"'\",\n '*',\n '_',\n '{',\n '}',\n '[',\n ']',\n '(',\n ')',\n '#',\n '+',\n '-',\n '.',\n '!'\n ]\n\n for (const character of punctuation) {\n answer = answer.replaceAll(character, `\\\\${character}`)\n }\n\n return answer\n}\n\nexport const addClassOptionIfNone = (\n options: Extract<ComponentDef, { options: { classes?: string } }>['options'],\n className: string\n) => {\n options.classes ??= className\n}\n\n/**\n * Applies lowerFirst but preserves capitalisation of proper nouns\n * like \"National Grid\", \"Ordnance Survey\" and \"OS\".\n */\nexport function lowerFirstPreserveProperNouns(text: string): string {\n const result = lowerFirst(text)\n return result\n .replace(/\\bnational [Gg]rid\\b/g, 'National Grid')\n .replace(/\\bordnance [Ss]urvey\\b/g, 'Ordnance Survey')\n .replace(/\\b[oO][sS]\\b/g, 'OS')\n}\n\n/**\n * Configuration for Joi expressions that use lowerFirst function\n */\nexport const lowerFirstExpressionOptions = {\n functions: {\n lowerFirst: lowerFirstPreserveProperNouns\n }\n} as ReferenceOptions\n\n/**\n * Creates a Joi expression with lowerFirst function support\n * Used for error messages in location field components\n */\nexport const createLowerFirstExpression = (template: string): JoiExpression =>\n joi.expression(template, lowerFirstExpressionOptions) as JoiExpression\n"],"mappings":"AACA,OAAOA,GAAG,MAAqD,KAAK;AACpE,OAAOC,UAAU,MAAM,sBAAsB
|
|
1
|
+
{"version":3,"file":"index.js","names":["joi","lowerFirst","escapeMarkdown","answer","punctuation","character","replaceAll","addClassOptionIfNone","options","className","classes","lowerFirstPreserveProperNouns","text","result","replace","lowerFirstExpressionOptions","functions","createLowerFirstExpression","template","expression","getTranslatedLabel","component","translator","tComponent","translatedLabel"],"sources":["../../../../../../src/server/plugins/engine/components/helpers/index.ts"],"sourcesContent":["import { type ComponentDef } from '@defra/forms-model'\nimport joi, { type JoiExpression, type ReferenceOptions } from 'joi'\nimport lowerFirst from 'lodash/lowerFirst.js'\n\nimport { type Translator } from '~/src/server/plugins/engine/i18n/types.js'\n\n/**\n * Prevent Markdown formatting\n * @see {@link https://pandoc.org/chunkedhtml-demo/8.11-backslash-escapes.html}\n */\nexport function escapeMarkdown(answer: string) {\n const punctuation = [\n '`',\n \"'\",\n '*',\n '_',\n '{',\n '}',\n '[',\n ']',\n '(',\n ')',\n '#',\n '+',\n '-',\n '.',\n '!'\n ]\n\n for (const character of punctuation) {\n answer = answer.replaceAll(character, `\\\\${character}`)\n }\n\n return answer\n}\n\nexport const addClassOptionIfNone = (\n options: Extract<ComponentDef, { options: { classes?: string } }>['options'],\n className: string\n) => {\n options.classes ??= className\n}\n\n/**\n * Applies lowerFirst but preserves capitalisation of proper nouns\n * like \"National Grid\", \"Ordnance Survey\" and \"OS\".\n */\nexport function lowerFirstPreserveProperNouns(text: string): string {\n const result = lowerFirst(text)\n return result\n .replace(/\\bnational [Gg]rid\\b/g, 'National Grid')\n .replace(/\\bordnance [Ss]urvey\\b/g, 'Ordnance Survey')\n .replace(/\\b[oO][sS]\\b/g, 'OS')\n}\n\n/**\n * Configuration for Joi expressions that use lowerFirst function\n */\nexport const lowerFirstExpressionOptions = {\n functions: {\n lowerFirst: lowerFirstPreserveProperNouns\n }\n} as ReferenceOptions\n\n/**\n * Creates a Joi expression with lowerFirst function support\n * Used for error messages in location field components\n */\nexport const createLowerFirstExpression = (template: string): JoiExpression =>\n joi.expression(template, lowerFirstExpressionOptions) as JoiExpression\n\n/**\n * Translate a component label, in precedence order of errorDescription, then shortDesciption, then title\n * @param {ComponentDef} component\n * @param {Translator} translator\n */\nexport function getTranslatedLabel(\n component: ComponentDef,\n translator: Translator\n) {\n const { tComponent } = translator\n const translatedLabel =\n tComponent(component, 'errorDescription') ||\n tComponent(component, 'shortDescription') ||\n tComponent(component, 'title')\n return translatedLabel\n}\n"],"mappings":"AACA,OAAOA,GAAG,MAAqD,KAAK;AACpE,OAAOC,UAAU,MAAM,sBAAsB;AAI7C;AACA;AACA;AACA;AACA,OAAO,SAASC,cAAcA,CAACC,MAAc,EAAE;EAC7C,MAAMC,WAAW,GAAG,CAClB,GAAG,EACH,GAAG,EACH,GAAG,EACH,GAAG,EACH,GAAG,EACH,GAAG,EACH,GAAG,EACH,GAAG,EACH,GAAG,EACH,GAAG,EACH,GAAG,EACH,GAAG,EACH,GAAG,EACH,GAAG,EACH,GAAG,CACJ;EAED,KAAK,MAAMC,SAAS,IAAID,WAAW,EAAE;IACnCD,MAAM,GAAGA,MAAM,CAACG,UAAU,CAACD,SAAS,EAAE,KAAKA,SAAS,EAAE,CAAC;EACzD;EAEA,OAAOF,MAAM;AACf;AAEA,OAAO,MAAMI,oBAAoB,GAAGA,CAClCC,OAA4E,EAC5EC,SAAiB,KACd;EACHD,OAAO,CAACE,OAAO,KAAKD,SAAS;AAC/B,CAAC;;AAED;AACA;AACA;AACA;AACA,OAAO,SAASE,6BAA6BA,CAACC,IAAY,EAAU;EAClE,MAAMC,MAAM,GAAGZ,UAAU,CAACW,IAAI,CAAC;EAC/B,OAAOC,MAAM,CACVC,OAAO,CAAC,uBAAuB,EAAE,eAAe,CAAC,CACjDA,OAAO,CAAC,yBAAyB,EAAE,iBAAiB,CAAC,CACrDA,OAAO,CAAC,eAAe,EAAE,IAAI,CAAC;AACnC;;AAEA;AACA;AACA;AACA,OAAO,MAAMC,2BAA2B,GAAG;EACzCC,SAAS,EAAE;IACTf,UAAU,EAAEU;EACd;AACF,CAAqB;;AAErB;AACA;AACA;AACA;AACA,OAAO,MAAMM,0BAA0B,GAAIC,QAAgB,IACzDlB,GAAG,CAACmB,UAAU,CAACD,QAAQ,EAAEH,2BAA2B,CAAkB;;AAExE;AACA;AACA;AACA;AACA;AACA,OAAO,SAASK,kBAAkBA,CAChCC,SAAuB,EACvBC,UAAsB,EACtB;EACA,MAAM;IAAEC;EAAW,CAAC,GAAGD,UAAU;EACjC,MAAME,eAAe,GACnBD,UAAU,CAACF,SAAS,EAAE,kBAAkB,CAAC,IACzCE,UAAU,CAACF,SAAS,EAAE,kBAAkB,CAAC,IACzCE,UAAU,CAACF,SAAS,EAAE,OAAO,CAAC;EAChC,OAAOG,eAAe;AACxB","ignoreList":[]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","names":[],"sources":["../../../../../src/server/plugins/engine/components/types.ts"],"sourcesContent":["import { type ComponentType, type Item } from '@defra/forms-model'\n\nimport { type Translator } from '~/src/server/plugins/engine/i18n/types.js'\nimport {\n type FormPayload,\n type FormSubmissionError,\n type FormValue,\n type SummaryList\n} from '~/src/server/plugins/engine/types.js'\n\nexport interface RenderContext {\n payload: FormPayload\n errors: FormSubmissionError[] | undefined\n translator: Translator\n isForceAccess?: boolean\n}\n\nexport type ComponentText = {\n classes?: string\n attributes?: string | Record<string, string>\n} & (\n | {\n text: string\n html?: string\n }\n | {\n text?: string\n html: string\n }\n)\n\nexport interface Label {\n text: string\n classes?: string\n html?: string\n isPageHeading?: boolean\n}\n\nexport interface Content {\n title?: string\n text: string\n condition?: string\n}\n\nexport interface BackLink {\n text: string\n href: string\n}\n\nexport type ListItemLabel = Omit<Label, 'text' | 'isPageHeading'>\n\nexport interface ListItem {\n text?: string\n value?: Item['value']\n hint?: {\n id?: string\n text: string\n }\n checked?: boolean\n selected?: boolean\n label?: ListItemLabel\n condition?: string\n}\n\nexport interface DateInputItem {\n label?: Label\n type?: string\n id?: string\n name?: string\n value?: Item['value']\n classes?: string\n // Prefix/suffix are used by location fields (e.g., LatLong, EastingNorthing) for units like \"°\"\n // but not by date fields. This interface is reused by both component types.\n prefix?: ComponentText\n suffix?: ComponentText\n errorMessage?: {\n text: string\n }\n condition?: undefined\n}\n\nexport interface ViewModel extends Record<string, unknown> {\n label?: Label\n type?: string\n id?: string\n name?: string\n value?: FormValue\n hint?: {\n id?: string\n text: string\n }\n prefix?: ComponentText\n suffix?: ComponentText\n classes?: string\n condition?: string\n errors?: FormSubmissionError[]\n errorMessage?: {\n text: string\n }\n summaryHtml?: string\n html?: string\n attributes: {\n autocomplete?: string\n maxlength?: number\n multiple?: string\n accept?: string\n inputmode?: string\n }\n content?: Content | Content[] | string\n maxlength?: number\n maxwords?: number\n rows?: number\n items?: ListItem[] | DateInputItem[]\n fieldset?: {\n attributes?: string | Record<string, string>\n legend?: Label\n }\n formGroup?: {\n classes?: string\n attributes?: string | Record<string, string>\n }\n showFieldsetError?: boolean\n components?: ComponentViewModel[]\n upload?: {\n count: number\n summaryList: SummaryList\n }\n}\n\nexport interface ComponentViewModel {\n type: ComponentType\n isFormComponent: boolean\n model: ViewModel\n}\n\nexport interface DatePartsState extends Record<string, number> {\n day: number\n month: number\n year: number\n}\n\nexport interface MonthYearState extends Record<string, number> {\n month: number\n year: number\n}\n\nexport interface EastingNorthingState extends Record<string, number> {\n easting: number\n northing: number\n}\n\nexport interface LatLongState extends Record<string, number> {\n latitude: number\n longitude: number\n}\n"],"mappings":"","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"types.js","names":[],"sources":["../../../../../src/server/plugins/engine/components/types.ts"],"sourcesContent":["import { type ComponentType, type Item } from '@defra/forms-model'\n\nimport { type Translator } from '~/src/server/plugins/engine/i18n/types.js'\nimport {\n type FormPayload,\n type FormSubmissionError,\n type FormValue,\n type SummaryList\n} from '~/src/server/plugins/engine/types.js'\n\nexport interface RenderContext {\n payload: FormPayload\n errors: FormSubmissionError[] | undefined\n translator: Translator\n isForceAccess?: boolean\n}\n\nexport type ComponentText = {\n classes?: string\n attributes?: string | Record<string, string>\n} & (\n | {\n text: string\n html?: string\n }\n | {\n text?: string\n html: string\n }\n)\n\nexport interface Label {\n text: string\n classes?: string\n html?: string\n isPageHeading?: boolean\n}\n\nexport interface Content {\n title?: string\n text: string\n condition?: string\n}\n\nexport interface BackLink {\n text: string\n href: string\n}\n\nexport type ListItemLabel = Omit<Label, 'text' | 'isPageHeading'>\n\nexport interface ListItem {\n text?: string\n value?: Item['value']\n hint?: {\n id?: string\n text: string\n }\n checked?: boolean\n selected?: boolean\n label?: ListItemLabel\n condition?: string\n}\n\nexport interface DateInputItem {\n label?: Label\n type?: string\n id?: string\n name?: string\n value?: Item['value']\n classes?: string\n // Prefix/suffix are used by location fields (e.g., LatLong, EastingNorthing) for units like \"°\"\n // but not by date fields. This interface is reused by both component types.\n prefix?: ComponentText\n suffix?: ComponentText\n errorMessage?: {\n text: string\n }\n condition?: undefined\n}\n\nexport interface ViewModel extends Record<string, unknown> {\n label?: Label\n type?: string\n id?: string\n name?: string\n value?: FormValue\n hint?: {\n id?: string\n text: string\n }\n prefix?: ComponentText\n suffix?: ComponentText\n classes?: string\n condition?: string\n errors?: FormSubmissionError[]\n errorMessage?: {\n text: string\n }\n summaryHtml?: string\n html?: string\n attributes: {\n autocomplete?: string\n maxlength?: number\n multiple?: string\n accept?: string\n inputmode?: string\n }\n content?: Content | Content[] | string\n maxlength?: number\n maxwords?: number\n rows?: number\n items?: ListItem[] | DateInputItem[]\n fieldset?: {\n attributes?: string | Record<string, string>\n legend?: Label\n }\n formGroup?: {\n classes?: string\n attributes?: string | Record<string, string>\n }\n showFieldsetError?: boolean\n components?: ComponentViewModel[]\n upload?: {\n count: number\n summaryList: SummaryList\n uploadingLabel?: string\n }\n}\n\nexport interface ComponentViewModel {\n type: ComponentType\n isFormComponent: boolean\n model: ViewModel\n}\n\nexport interface DatePartsState extends Record<string, number> {\n day: number\n month: number\n year: number\n}\n\nexport interface MonthYearState extends Record<string, number> {\n month: number\n year: number\n}\n\nexport interface EastingNorthingState extends Record<string, number> {\n easting: number\n northing: number\n}\n\nexport interface LatLongState extends Record<string, number> {\n latitude: number\n longitude: number\n}\n"],"mappings":"","ignoreList":[]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type ComponentDef, type FormDefinition, type Page } from '@defra/forms-model';
|
|
2
2
|
import { type ResponseToolkit, type Server } from '@hapi/hapi';
|
|
3
|
+
import { type Locale } from 'date-fns';
|
|
3
4
|
import { type ValidationErrorItem } from 'joi';
|
|
4
5
|
import { Liquid } from 'liquidjs';
|
|
5
6
|
import { type FormModel } from '../../../server/plugins/engine/models/FormModel.js';
|
|
@@ -41,10 +42,11 @@ export declare function checkFormStatus(params?: FormParams): {
|
|
|
41
42
|
export declare function checkEmailAddressForLiveFormSubmission(emailAddress: string | undefined, isPreview: boolean): void;
|
|
42
43
|
/**
|
|
43
44
|
* Parses the errors from {@link Schema.validate} so they can be rendered by govuk-frontend templates
|
|
45
|
+
* @param language - the target language for translations
|
|
44
46
|
* @param [details] - provided by {@link Schema.validate}
|
|
45
47
|
*/
|
|
46
|
-
export declare function getErrors(details?: ValidationErrorItem[]): FormSubmissionError[] | undefined;
|
|
47
|
-
export declare function getError(detail: ValidationErrorItem): FormSubmissionError;
|
|
48
|
+
export declare function getErrors(language: string | undefined, details?: ValidationErrorItem[]): FormSubmissionError[] | undefined;
|
|
49
|
+
export declare function getError(language: string | undefined, detail: ValidationErrorItem): FormSubmissionError;
|
|
48
50
|
export declare function createError(componentName: string, message: string): {
|
|
49
51
|
href: string;
|
|
50
52
|
name: string;
|
|
@@ -88,3 +90,21 @@ export interface FormVersionMetadata {
|
|
|
88
90
|
* Extracts form version metadata from a form definition
|
|
89
91
|
*/
|
|
90
92
|
export declare function getFormVersion(definition: Pick<FormDefinition, 'metadata'>): FormVersionMetadata | undefined;
|
|
93
|
+
/**
|
|
94
|
+
* Converts a BCP 47 language tag to the ISO 639-1 code GOV.UK Pay accepts.
|
|
95
|
+
* Defaults to English if the language is not supported.
|
|
96
|
+
* @param { string | undefined } language - BCP 47 language code
|
|
97
|
+
* @returns {string} language code required by GOV.UK Pay
|
|
98
|
+
*/
|
|
99
|
+
export declare function toPayLanguageCode(language: string | undefined): string;
|
|
100
|
+
/**
|
|
101
|
+
* Converts a BCP 47 language tag to the date-fns Locale (for date formatting).
|
|
102
|
+
* Defaults to English if the language is not supported.
|
|
103
|
+
* @param { string | undefined } language - BCP 47 language code
|
|
104
|
+
* @returns {Locale} language locale
|
|
105
|
+
*/
|
|
106
|
+
export declare function toLanguageLocale(language: string | undefined): Locale;
|
|
107
|
+
/**
|
|
108
|
+
* @import { FormsService } from '../../../server/types.js'
|
|
109
|
+
* @import { Locale } from 'date-fns/locale'
|
|
110
|
+
*/
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import { ControllerPath, Engine, getErrorMessage } from '@defra/forms-model';
|
|
2
2
|
import Boom from '@hapi/boom';
|
|
3
3
|
import { format, parseISO } from 'date-fns';
|
|
4
|
+
import { cy, enGB } from 'date-fns/locale';
|
|
4
5
|
import { StatusCodes } from 'http-status-codes';
|
|
5
6
|
import { Liquid } from 'liquidjs';
|
|
6
7
|
import { logger } from "../../common/helpers/logging/logger.js";
|
|
7
|
-
import { FORM_VERSION_METADATA_KEY } from "../../constants.js";
|
|
8
|
+
import { CY, EN_GB, FORM_VERSION_METADATA_KEY } from "../../constants.js";
|
|
8
9
|
import { getAnswer } from "./components/helpers/components.js";
|
|
9
10
|
import { stripParam } from "./pageControllers/helpers/state.js";
|
|
10
11
|
import { FormAction, FormStatus } from "../../routes/types.js";
|
|
@@ -194,15 +195,16 @@ export function checkEmailAddressForLiveFormSubmission(emailAddress, isPreview)
|
|
|
194
195
|
|
|
195
196
|
/**
|
|
196
197
|
* Parses the errors from {@link Schema.validate} so they can be rendered by govuk-frontend templates
|
|
198
|
+
* @param language - the target language for translations
|
|
197
199
|
* @param [details] - provided by {@link Schema.validate}
|
|
198
200
|
*/
|
|
199
|
-
export function getErrors(details) {
|
|
201
|
+
export function getErrors(language, details) {
|
|
200
202
|
if (!details?.length) {
|
|
201
203
|
return;
|
|
202
204
|
}
|
|
203
|
-
return details.map(getError);
|
|
205
|
+
return details.map(detail => getError(language, detail));
|
|
204
206
|
}
|
|
205
|
-
export function getError(detail) {
|
|
207
|
+
export function getError(language, detail) {
|
|
206
208
|
const {
|
|
207
209
|
context,
|
|
208
210
|
message,
|
|
@@ -210,7 +212,9 @@ export function getError(detail) {
|
|
|
210
212
|
} = detail;
|
|
211
213
|
const name = context?.key ?? '';
|
|
212
214
|
const href = `#${name}`;
|
|
213
|
-
const text = message.replace(/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/, text => format(parseISO(text), 'd MMMM yyyy'
|
|
215
|
+
const text = message.replace(/\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/, text => format(parseISO(text), 'd MMMM yyyy', {
|
|
216
|
+
locale: toLanguageLocale(language)
|
|
217
|
+
}));
|
|
214
218
|
return {
|
|
215
219
|
path,
|
|
216
220
|
href,
|
|
@@ -282,4 +286,39 @@ export function handleLegacyRedirect(h, targetUrl) {
|
|
|
282
286
|
export function getFormVersion(definition) {
|
|
283
287
|
return definition.metadata?.[FORM_VERSION_METADATA_KEY];
|
|
284
288
|
}
|
|
289
|
+
const payLanguageCodes = {
|
|
290
|
+
[EN_GB]: 'en',
|
|
291
|
+
[CY]: 'cy'
|
|
292
|
+
};
|
|
293
|
+
const languageLocales = {
|
|
294
|
+
[EN_GB]: enGB,
|
|
295
|
+
[CY]: cy
|
|
296
|
+
};
|
|
297
|
+
const defaultLanguageCode = 'en';
|
|
298
|
+
const defaultLanguageLocale = enGB;
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Converts a BCP 47 language tag to the ISO 639-1 code GOV.UK Pay accepts.
|
|
302
|
+
* Defaults to English if the language is not supported.
|
|
303
|
+
* @param { string | undefined } language - BCP 47 language code
|
|
304
|
+
* @returns {string} language code required by GOV.UK Pay
|
|
305
|
+
*/
|
|
306
|
+
export function toPayLanguageCode(language) {
|
|
307
|
+
return payLanguageCodes[language ?? 'unknown'] ?? defaultLanguageCode;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Converts a BCP 47 language tag to the date-fns Locale (for date formatting).
|
|
312
|
+
* Defaults to English if the language is not supported.
|
|
313
|
+
* @param { string | undefined } language - BCP 47 language code
|
|
314
|
+
* @returns {Locale} language locale
|
|
315
|
+
*/
|
|
316
|
+
export function toLanguageLocale(language) {
|
|
317
|
+
return languageLocales[language ?? 'unknown'] ?? defaultLanguageLocale;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* @import { FormsService } from '../../../server/types.js'
|
|
322
|
+
* @import { Locale } from 'date-fns/locale'
|
|
323
|
+
*/
|
|
285
324
|
//# sourceMappingURL=helpers.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"helpers.js","names":["ControllerPath","Engine","getErrorMessage","Boom","format","parseISO","StatusCodes","Liquid","logger","FORM_VERSION_METADATA_KEY","getAnswer","stripParam","FormAction","FormStatus","engine","outputEscape","jsTruthy","ownPropertyOnly","registerFilter","template","globals","context","evaluated","evaluateTemplate","path","pageDef","pages","get","query","page","pageMap","undefined","getPageHref","name","componentDef","components","component","componentMap","isFormComponent","field","translator","answer","relevantState","model","createTranslator","proceed","request","h","nextUrl","method","payload","returnUrl","isReturnAllowed","action","Continue","Validate","nextQuery","response","isPathRelative","redirect","redirectPath","code","SEE_OTHER","MOVED_TEMPORARILY","encodeUrl","link","URL","toString","err","error","pathOrQuery","queryOnly","Error","getHref","isRelative","params","Object","entries","filter","url","value","searchParams","set","pathname","search","href","startsWith","normalisePath","trim","replace","getPage","findPage","notFound","findPath","find","getStartPath","V2","startPath","def","at","Start","startPage","checkFormStatus","isPreview","state","Live","Draft","checkEmailAddressForLiveFormSubmission","emailAddress","internal","getErrors","details","length","map","getError","detail","message","key","text","createError","componentName","getExponentialBackoffDelay","depth","BASE_DELAY_MS","CAP_DELAY_MS","delay","Math","min","pageDefMap","componentDefMap","parseAndRenderSync","getCacheService","server","getPluginOptions","cacheService","getSaveAndExitHelpers","saveAndExit","plugins","handleLegacyRedirect","targetUrl","permanent","takeover","getFormVersion","definition","metadata"],"sources":["../../../../src/server/plugins/engine/helpers.ts"],"sourcesContent":["import {\n ControllerPath,\n Engine,\n getErrorMessage,\n type ComponentDef,\n type FormDefinition,\n type Page\n} from '@defra/forms-model'\nimport Boom from '@hapi/boom'\nimport { type ResponseToolkit, type Server } from '@hapi/hapi'\nimport { format, parseISO } from 'date-fns'\nimport { StatusCodes } from 'http-status-codes'\nimport { type Schema, type ValidationErrorItem } from 'joi'\nimport { Liquid } from 'liquidjs'\n\nimport { logger } from '~/src/server/common/helpers/logging/logger.js'\nimport { FORM_VERSION_METADATA_KEY } from '~/src/server/constants.js'\nimport {\n getAnswer,\n type Field\n} from '~/src/server/plugins/engine/components/helpers/components.js'\nimport { type FormModel } from '~/src/server/plugins/engine/models/FormModel.js'\nimport { type PageControllerClass } from '~/src/server/plugins/engine/pageControllers/helpers/pages.js'\nimport { stripParam } from '~/src/server/plugins/engine/pageControllers/helpers/state.js'\nimport {\n type FormContext,\n type FormContextRequest,\n type FormSubmissionError\n} from '~/src/server/plugins/engine/types.js'\nimport {\n FormAction,\n FormStatus,\n type FormParams,\n type FormQuery,\n type FormResponseToolkit\n} from '~/src/server/routes/types.js'\n\nexport const engine = new Liquid({\n outputEscape: 'escape',\n jsTruthy: true,\n ownPropertyOnly: false\n})\n\nexport interface GlobalScope {\n context: FormContext\n pages: Map<string, Page>\n components: Map<string, ComponentDef>\n}\n\nengine.registerFilter('evaluate', function (template?: string) {\n if (typeof template !== 'string') {\n return template\n }\n\n const globals = this.context.globals as GlobalScope\n const evaluated = evaluateTemplate(template, globals.context)\n\n return evaluated\n})\n\nengine.registerFilter('page', function (path?: string) {\n if (typeof path !== 'string') {\n return\n }\n\n const globals = this.context.globals as GlobalScope\n const pageDef = globals.pages.get(path)\n\n return pageDef\n})\n\nengine.registerFilter('href', function (path: string, query?: FormQuery) {\n if (typeof path !== 'string') {\n return\n }\n\n const globals = this.context.globals as GlobalScope\n const page = globals.context.pageMap.get(path)\n\n if (page === undefined) {\n return\n }\n\n return getPageHref(page, query)\n})\n\nengine.registerFilter('field', function (name: string) {\n if (typeof name !== 'string') {\n return\n }\n\n const globals = this.context.globals as GlobalScope\n const componentDef = globals.components.get(name)\n\n return componentDef\n})\n\nengine.registerFilter('answer', function (name: string) {\n if (typeof name !== 'string') {\n return\n }\n\n const globals = this.context.globals as GlobalScope\n const component = globals.context.componentMap.get(name)\n\n if (!component?.isFormComponent) {\n return\n }\n\n const field = component as Field\n const { translator } = globals.context\n const answer = getAnswer(\n field,\n globals.context.relevantState,\n translator ?? field.model.createTranslator(),\n {\n format: 'summary'\n }\n )\n\n return answer\n})\n\nexport function proceed(\n request: Pick<FormContextRequest, 'method' | 'payload' | 'query'>,\n h: FormResponseToolkit,\n nextUrl: string\n) {\n const { method, payload, query } = request\n const { returnUrl } = query\n\n const isReturnAllowed =\n payload && 'action' in payload\n ? payload.action === FormAction.Continue ||\n payload.action === FormAction.Validate\n : false\n\n // On POST, strip all query params to prevent them persisting across pages.\n // On GET, forward params (minus returnUrl) so pre-population query params\n // survive dispatch redirects (e.g. ?formId= reaching the start page).\n const nextQuery =\n method === 'get' ? stripParam(query, 'returnUrl') : undefined\n\n // Redirect to return location (optional)\n const response =\n isReturnAllowed && isPathRelative(returnUrl)\n ? h.redirect(returnUrl)\n : h.redirect(redirectPath(nextUrl, nextQuery))\n\n // Redirect POST to GET to avoid resubmission\n return method === 'post'\n ? response.code(StatusCodes.SEE_OTHER)\n : response.code(StatusCodes.MOVED_TEMPORARILY)\n}\n\n/**\n * Encodes a URL, returning undefined if the process fails.\n */\nexport function encodeUrl(link?: string) {\n if (link) {\n try {\n return new URL(link).toString() // escape the search params without breaking the ? and & reserved characters in rfc2368\n } catch (err) {\n logger.error(\n err,\n `[urlEncodingFailed] Failed to encode URL: ${link} - ${getErrorMessage(err)}`\n )\n throw err\n }\n }\n}\n\n/**\n * Get page href\n */\nexport function getPageHref(\n page: PageControllerClass,\n query?: FormQuery\n): string\n\n/**\n * Get page href by path\n */\nexport function getPageHref(\n page: PageControllerClass,\n path: string,\n query?: FormQuery\n): string\n\nexport function getPageHref(\n page: PageControllerClass,\n pathOrQuery?: string | FormQuery,\n queryOnly: FormQuery = {}\n) {\n const path = typeof pathOrQuery === 'string' ? pathOrQuery : page.path\n const query = typeof pathOrQuery === 'object' ? pathOrQuery : queryOnly\n\n if (!isPathRelative(path)) {\n throw Error(`Only relative URLs are allowed: ${path}`)\n }\n\n // Return path with page href as base\n return redirectPath(page.getHref(path), query)\n}\n\n/**\n * Get redirect path with optional query params\n */\nexport function redirectPath(nextUrl: string, query: FormQuery = {}) {\n const isRelative = isPathRelative(nextUrl)\n\n // Filter string query params only\n const params = Object.entries(query).filter(\n (query): query is [string, string] => typeof query[1] === 'string'\n )\n\n // Build URL with relative path support\n const url = isRelative\n ? new URL(nextUrl, 'http://example.com')\n : new URL(nextUrl)\n\n // Append query params\n for (const [name, value] of params) {\n url.searchParams.set(name, value)\n }\n\n if (isRelative) {\n return `${url.pathname}${url.search}`\n }\n\n return url.href\n}\n\nexport function isPathRelative(path?: string) {\n return (path ?? '').startsWith('/')\n}\n\nexport function normalisePath(path = '') {\n return path\n .trim() // Trim empty spaces\n .replace(/^\\//, '') // Remove leading slash\n .replace(/\\/$/, '') // Remove trailing slash\n}\n\nexport function getPage(\n model: FormModel | undefined,\n request: FormContextRequest\n) {\n const { params } = request\n\n const page = findPage(model, `/${params.path}`)\n\n if (!page) {\n throw Boom.notFound(`No page found for /${params.path}`)\n }\n\n return page\n}\n\nexport function findPage(model: FormModel | undefined, path?: string) {\n const findPath = `/${normalisePath(path)}`\n return model?.pages.find(({ path }) => path === findPath)\n}\n\nexport function getStartPath(model?: FormModel) {\n if (model?.engine === Engine.V2) {\n const startPath = normalisePath(model.def.pages.at(0)?.path)\n return startPath ? `/${startPath}` : ControllerPath.Start\n }\n\n const startPath = normalisePath(model?.def.startPage)\n return startPath ? `/${startPath}` : ControllerPath.Start\n}\n\nexport function checkFormStatus(params?: FormParams) {\n const isPreview = !!params?.state\n\n let state = FormStatus.Live\n\n if (isPreview && params.state === FormStatus.Draft) {\n state = FormStatus.Draft\n }\n\n return {\n isPreview,\n state\n }\n}\n\nexport function checkEmailAddressForLiveFormSubmission(\n emailAddress: string | undefined,\n isPreview: boolean\n) {\n if (!emailAddress && !isPreview) {\n throw Boom.internal(\n 'An email address is required to complete the form submission'\n )\n }\n}\n\n/**\n * Parses the errors from {@link Schema.validate} so they can be rendered by govuk-frontend templates\n * @param [details] - provided by {@link Schema.validate}\n */\nexport function getErrors(\n details?: ValidationErrorItem[]\n): FormSubmissionError[] | undefined {\n if (!details?.length) {\n return\n }\n\n return details.map(getError)\n}\n\nexport function getError(detail: ValidationErrorItem): FormSubmissionError {\n const { context, message, path } = detail\n\n const name = context?.key ?? ''\n const href = `#${name}`\n\n const text = message.replace(\n /\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z)/,\n (text) => format(parseISO(text), 'd MMMM yyyy')\n )\n\n return {\n path,\n href,\n name,\n text,\n context\n }\n}\n\nexport function createError(componentName: string, message: string) {\n return {\n href: `#${componentName}`,\n name: componentName,\n text: message\n }\n}\n\n/**\n * Calculates an exponential backoff delay (in milliseconds) based on the current retry depth,\n * using a base delay of 2000ms (2 seconds) and doubling for each additional depth, while capping the delay at 25,000ms (25 seconds).\n * @param depth - The current retry depth (1, 2, 3, …)\n * @returns The calculated delay in milliseconds.\n */\nexport function getExponentialBackoffDelay(depth: number): number {\n const BASE_DELAY_MS = 2000 // 2 seconds initial delay\n const CAP_DELAY_MS = 25000 // cap each delay to 25 seconds\n const delay = BASE_DELAY_MS * 2 ** (depth - 1)\n return Math.min(delay, CAP_DELAY_MS)\n}\n\nexport function evaluateTemplate(\n template: string,\n context: FormContext\n): string {\n const globals: GlobalScope = {\n context,\n pages: context.pageDefMap,\n components: context.componentDefMap\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return engine.parseAndRenderSync(template, context.relevantState, {\n globals\n })\n}\n\nexport function getCacheService(server: Server) {\n return getPluginOptions(server).cacheService\n}\n\nexport function getSaveAndExitHelpers(server: Server) {\n return getPluginOptions(server).saveAndExit\n}\n\nexport function getPluginOptions(server: Server) {\n return server.plugins['forms-engine-plugin']\n}\n\n/**\n * Handles logging and issuing a permanent redirect for legacy routes.\n * @param h - The Hapi response toolkit.\n * @param targetUrl - The URL to redirect to.\n * @returns The Hapi response object configured for permanent redirect.\n */\nexport function handleLegacyRedirect(h: ResponseToolkit, targetUrl: string) {\n return h.redirect(targetUrl).permanent().takeover()\n}\n\n/**\n * If the page doesn't have a title, set it from the title of the first form component\n * @param def - the form definition\n */\nexport interface FormVersionMetadata {\n versionNumber: number\n createdAt: Date\n}\n\n/**\n * Extracts form version metadata from a form definition\n */\nexport function getFormVersion(\n definition: Pick<FormDefinition, 'metadata'>\n): FormVersionMetadata | undefined {\n return definition.metadata?.[FORM_VERSION_METADATA_KEY] as\n | FormVersionMetadata\n | undefined\n}\n"],"mappings":"AAAA,SACEA,cAAc,EACdC,MAAM,EACNC,eAAe,QAIV,oBAAoB;AAC3B,OAAOC,IAAI,MAAM,YAAY;AAE7B,SAASC,MAAM,EAAEC,QAAQ,QAAQ,UAAU;AAC3C,SAASC,WAAW,QAAQ,mBAAmB;AAE/C,SAASC,MAAM,QAAQ,UAAU;AAEjC,SAASC,MAAM;AACf,SAASC,yBAAyB;AAClC,SACEC,SAAS;AAKX,SAASC,UAAU;AAMnB,SACEC,UAAU,EACVC,UAAU;AAMZ,OAAO,MAAMC,MAAM,GAAG,IAAIP,MAAM,CAAC;EAC/BQ,YAAY,EAAE,QAAQ;EACtBC,QAAQ,EAAE,IAAI;EACdC,eAAe,EAAE;AACnB,CAAC,CAAC;AAQFH,MAAM,CAACI,cAAc,CAAC,UAAU,EAAE,UAAUC,QAAiB,EAAE;EAC7D,IAAI,OAAOA,QAAQ,KAAK,QAAQ,EAAE;IAChC,OAAOA,QAAQ;EACjB;EAEA,MAAMC,OAAO,GAAG,IAAI,CAACC,OAAO,CAACD,OAAsB;EACnD,MAAME,SAAS,GAAGC,gBAAgB,CAACJ,QAAQ,EAAEC,OAAO,CAACC,OAAO,CAAC;EAE7D,OAAOC,SAAS;AAClB,CAAC,CAAC;AAEFR,MAAM,CAACI,cAAc,CAAC,MAAM,EAAE,UAAUM,IAAa,EAAE;EACrD,IAAI,OAAOA,IAAI,KAAK,QAAQ,EAAE;IAC5B;EACF;EAEA,MAAMJ,OAAO,GAAG,IAAI,CAACC,OAAO,CAACD,OAAsB;EACnD,MAAMK,OAAO,GAAGL,OAAO,CAACM,KAAK,CAACC,GAAG,CAACH,IAAI,CAAC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;AAC7C;AAEA,OAAO,SAASH,gBAAgBA,CAACD,MAAc,EAAE;EAC/C,OAAOA,MAAM,CAACK,OAAO,CAAC,qBAAqB,CAAC;AAC9C;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,oBAAoBA,CAAC3F,CAAkB,EAAE4F,SAAiB,EAAE;EAC1E,OAAO5F,CAAC,CAACY,QAAQ,CAACgF,SAAS,CAAC,CAACC,SAAS,CAAC,CAAC,CAACC,QAAQ,CAAC,CAAC;AACrD;;AAEA;AACA;AACA;AACA;;AAMA;AACA;AACA;AACA,OAAO,SAASC,cAAcA,CAC5BC,UAA4C,EACX;EACjC,OAAOA,UAAU,CAACC,QAAQ,GAAGvI,yBAAyB,CAAC;AAGzD","ignoreList":[]}
|
|
1
|
+
{"version":3,"file":"helpers.js","names":["ControllerPath","Engine","getErrorMessage","Boom","format","parseISO","cy","enGB","StatusCodes","Liquid","logger","CY","EN_GB","FORM_VERSION_METADATA_KEY","getAnswer","stripParam","FormAction","FormStatus","engine","outputEscape","jsTruthy","ownPropertyOnly","registerFilter","template","globals","context","evaluated","evaluateTemplate","path","pageDef","pages","get","query","page","pageMap","undefined","getPageHref","name","componentDef","components","component","componentMap","isFormComponent","field","translator","answer","relevantState","model","createTranslator","proceed","request","h","nextUrl","method","payload","returnUrl","isReturnAllowed","action","Continue","Validate","nextQuery","response","isPathRelative","redirect","redirectPath","code","SEE_OTHER","MOVED_TEMPORARILY","encodeUrl","link","URL","toString","err","error","pathOrQuery","queryOnly","Error","getHref","isRelative","params","Object","entries","filter","url","value","searchParams","set","pathname","search","href","startsWith","normalisePath","trim","replace","getPage","findPage","notFound","findPath","find","getStartPath","V2","startPath","def","at","Start","startPage","checkFormStatus","isPreview","state","Live","Draft","checkEmailAddressForLiveFormSubmission","emailAddress","internal","getErrors","language","details","length","map","detail","getError","message","key","text","locale","toLanguageLocale","createError","componentName","getExponentialBackoffDelay","depth","BASE_DELAY_MS","CAP_DELAY_MS","delay","Math","min","pageDefMap","componentDefMap","parseAndRenderSync","getCacheService","server","getPluginOptions","cacheService","getSaveAndExitHelpers","saveAndExit","plugins","handleLegacyRedirect","targetUrl","permanent","takeover","getFormVersion","definition","metadata","payLanguageCodes","languageLocales","defaultLanguageCode","defaultLanguageLocale","toPayLanguageCode"],"sources":["../../../../src/server/plugins/engine/helpers.ts"],"sourcesContent":["import {\n ControllerPath,\n Engine,\n getErrorMessage,\n type ComponentDef,\n type FormDefinition,\n type Page\n} from '@defra/forms-model'\nimport Boom from '@hapi/boom'\nimport { type ResponseToolkit, type Server } from '@hapi/hapi'\nimport { format, parseISO, type Locale } from 'date-fns'\nimport { cy, enGB } from 'date-fns/locale'\nimport { StatusCodes } from 'http-status-codes'\nimport { type Schema, type ValidationErrorItem } from 'joi'\nimport { Liquid } from 'liquidjs'\n\nimport { logger } from '~/src/server/common/helpers/logging/logger.js'\nimport { CY, EN_GB, FORM_VERSION_METADATA_KEY } from '~/src/server/constants.js'\nimport {\n getAnswer,\n type Field\n} from '~/src/server/plugins/engine/components/helpers/components.js'\nimport { type FormModel } from '~/src/server/plugins/engine/models/FormModel.js'\nimport { type PageControllerClass } from '~/src/server/plugins/engine/pageControllers/helpers/pages.js'\nimport { stripParam } from '~/src/server/plugins/engine/pageControllers/helpers/state.js'\nimport {\n type FormContext,\n type FormContextRequest,\n type FormSubmissionError\n} from '~/src/server/plugins/engine/types.js'\nimport {\n FormAction,\n FormStatus,\n type FormParams,\n type FormQuery,\n type FormResponseToolkit\n} from '~/src/server/routes/types.js'\n\nexport const engine = new Liquid({\n outputEscape: 'escape',\n jsTruthy: true,\n ownPropertyOnly: false\n})\n\nexport interface GlobalScope {\n context: FormContext\n pages: Map<string, Page>\n components: Map<string, ComponentDef>\n}\n\nengine.registerFilter('evaluate', function (template?: string) {\n if (typeof template !== 'string') {\n return template\n }\n\n const globals = this.context.globals as GlobalScope\n const evaluated = evaluateTemplate(template, globals.context)\n\n return evaluated\n})\n\nengine.registerFilter('page', function (path?: string) {\n if (typeof path !== 'string') {\n return\n }\n\n const globals = this.context.globals as GlobalScope\n const pageDef = globals.pages.get(path)\n\n return pageDef\n})\n\nengine.registerFilter('href', function (path: string, query?: FormQuery) {\n if (typeof path !== 'string') {\n return\n }\n\n const globals = this.context.globals as GlobalScope\n const page = globals.context.pageMap.get(path)\n\n if (page === undefined) {\n return\n }\n\n return getPageHref(page, query)\n})\n\nengine.registerFilter('field', function (name: string) {\n if (typeof name !== 'string') {\n return\n }\n\n const globals = this.context.globals as GlobalScope\n const componentDef = globals.components.get(name)\n\n return componentDef\n})\n\nengine.registerFilter('answer', function (name: string) {\n if (typeof name !== 'string') {\n return\n }\n\n const globals = this.context.globals as GlobalScope\n const component = globals.context.componentMap.get(name)\n\n if (!component?.isFormComponent) {\n return\n }\n\n const field = component as Field\n const { translator } = globals.context\n const answer = getAnswer(\n field,\n globals.context.relevantState,\n translator ?? field.model.createTranslator(),\n {\n format: 'summary'\n }\n )\n\n return answer\n})\n\nexport function proceed(\n request: Pick<FormContextRequest, 'method' | 'payload' | 'query'>,\n h: FormResponseToolkit,\n nextUrl: string\n) {\n const { method, payload, query } = request\n const { returnUrl } = query\n\n const isReturnAllowed =\n payload && 'action' in payload\n ? payload.action === FormAction.Continue ||\n payload.action === FormAction.Validate\n : false\n\n // On POST, strip all query params to prevent them persisting across pages.\n // On GET, forward params (minus returnUrl) so pre-population query params\n // survive dispatch redirects (e.g. ?formId= reaching the start page).\n const nextQuery =\n method === 'get' ? stripParam(query, 'returnUrl') : undefined\n\n // Redirect to return location (optional)\n const response =\n isReturnAllowed && isPathRelative(returnUrl)\n ? h.redirect(returnUrl)\n : h.redirect(redirectPath(nextUrl, nextQuery))\n\n // Redirect POST to GET to avoid resubmission\n return method === 'post'\n ? response.code(StatusCodes.SEE_OTHER)\n : response.code(StatusCodes.MOVED_TEMPORARILY)\n}\n\n/**\n * Encodes a URL, returning undefined if the process fails.\n */\nexport function encodeUrl(link?: string) {\n if (link) {\n try {\n return new URL(link).toString() // escape the search params without breaking the ? and & reserved characters in rfc2368\n } catch (err) {\n logger.error(\n err,\n `[urlEncodingFailed] Failed to encode URL: ${link} - ${getErrorMessage(err)}`\n )\n throw err\n }\n }\n}\n\n/**\n * Get page href\n */\nexport function getPageHref(\n page: PageControllerClass,\n query?: FormQuery\n): string\n\n/**\n * Get page href by path\n */\nexport function getPageHref(\n page: PageControllerClass,\n path: string,\n query?: FormQuery\n): string\n\nexport function getPageHref(\n page: PageControllerClass,\n pathOrQuery?: string | FormQuery,\n queryOnly: FormQuery = {}\n) {\n const path = typeof pathOrQuery === 'string' ? pathOrQuery : page.path\n const query = typeof pathOrQuery === 'object' ? pathOrQuery : queryOnly\n\n if (!isPathRelative(path)) {\n throw Error(`Only relative URLs are allowed: ${path}`)\n }\n\n // Return path with page href as base\n return redirectPath(page.getHref(path), query)\n}\n\n/**\n * Get redirect path with optional query params\n */\nexport function redirectPath(nextUrl: string, query: FormQuery = {}) {\n const isRelative = isPathRelative(nextUrl)\n\n // Filter string query params only\n const params = Object.entries(query).filter(\n (query): query is [string, string] => typeof query[1] === 'string'\n )\n\n // Build URL with relative path support\n const url = isRelative\n ? new URL(nextUrl, 'http://example.com')\n : new URL(nextUrl)\n\n // Append query params\n for (const [name, value] of params) {\n url.searchParams.set(name, value)\n }\n\n if (isRelative) {\n return `${url.pathname}${url.search}`\n }\n\n return url.href\n}\n\nexport function isPathRelative(path?: string) {\n return (path ?? '').startsWith('/')\n}\n\nexport function normalisePath(path = '') {\n return path\n .trim() // Trim empty spaces\n .replace(/^\\//, '') // Remove leading slash\n .replace(/\\/$/, '') // Remove trailing slash\n}\n\nexport function getPage(\n model: FormModel | undefined,\n request: FormContextRequest\n) {\n const { params } = request\n\n const page = findPage(model, `/${params.path}`)\n\n if (!page) {\n throw Boom.notFound(`No page found for /${params.path}`)\n }\n\n return page\n}\n\nexport function findPage(model: FormModel | undefined, path?: string) {\n const findPath = `/${normalisePath(path)}`\n return model?.pages.find(({ path }) => path === findPath)\n}\n\nexport function getStartPath(model?: FormModel) {\n if (model?.engine === Engine.V2) {\n const startPath = normalisePath(model.def.pages.at(0)?.path)\n return startPath ? `/${startPath}` : ControllerPath.Start\n }\n\n const startPath = normalisePath(model?.def.startPage)\n return startPath ? `/${startPath}` : ControllerPath.Start\n}\n\nexport function checkFormStatus(params?: FormParams) {\n const isPreview = !!params?.state\n\n let state = FormStatus.Live\n\n if (isPreview && params.state === FormStatus.Draft) {\n state = FormStatus.Draft\n }\n\n return {\n isPreview,\n state\n }\n}\n\nexport function checkEmailAddressForLiveFormSubmission(\n emailAddress: string | undefined,\n isPreview: boolean\n) {\n if (!emailAddress && !isPreview) {\n throw Boom.internal(\n 'An email address is required to complete the form submission'\n )\n }\n}\n\n/**\n * Parses the errors from {@link Schema.validate} so they can be rendered by govuk-frontend templates\n * @param language - the target language for translations\n * @param [details] - provided by {@link Schema.validate}\n */\nexport function getErrors(\n language: string | undefined,\n details?: ValidationErrorItem[]\n): FormSubmissionError[] | undefined {\n if (!details?.length) {\n return\n }\n\n return details.map((detail) => getError(language, detail))\n}\n\nexport function getError(\n language: string | undefined,\n detail: ValidationErrorItem\n): FormSubmissionError {\n const { context, message, path } = detail\n\n const name = context?.key ?? ''\n const href = `#${name}`\n\n const text = message.replace(\n /\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z)/,\n (text) =>\n format(parseISO(text), 'd MMMM yyyy', {\n locale: toLanguageLocale(language)\n })\n )\n\n return {\n path,\n href,\n name,\n text,\n context\n }\n}\n\nexport function createError(componentName: string, message: string) {\n return {\n href: `#${componentName}`,\n name: componentName,\n text: message\n }\n}\n\n/**\n * Calculates an exponential backoff delay (in milliseconds) based on the current retry depth,\n * using a base delay of 2000ms (2 seconds) and doubling for each additional depth, while capping the delay at 25,000ms (25 seconds).\n * @param depth - The current retry depth (1, 2, 3, …)\n * @returns The calculated delay in milliseconds.\n */\nexport function getExponentialBackoffDelay(depth: number): number {\n const BASE_DELAY_MS = 2000 // 2 seconds initial delay\n const CAP_DELAY_MS = 25000 // cap each delay to 25 seconds\n const delay = BASE_DELAY_MS * 2 ** (depth - 1)\n return Math.min(delay, CAP_DELAY_MS)\n}\n\nexport function evaluateTemplate(\n template: string,\n context: FormContext\n): string {\n const globals: GlobalScope = {\n context,\n pages: context.pageDefMap,\n components: context.componentDefMap\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n return engine.parseAndRenderSync(template, context.relevantState, {\n globals\n })\n}\n\nexport function getCacheService(server: Server) {\n return getPluginOptions(server).cacheService\n}\n\nexport function getSaveAndExitHelpers(server: Server) {\n return getPluginOptions(server).saveAndExit\n}\n\nexport function getPluginOptions(server: Server) {\n return server.plugins['forms-engine-plugin']\n}\n\n/**\n * Handles logging and issuing a permanent redirect for legacy routes.\n * @param h - The Hapi response toolkit.\n * @param targetUrl - The URL to redirect to.\n * @returns The Hapi response object configured for permanent redirect.\n */\nexport function handleLegacyRedirect(h: ResponseToolkit, targetUrl: string) {\n return h.redirect(targetUrl).permanent().takeover()\n}\n\n/**\n * If the page doesn't have a title, set it from the title of the first form component\n * @param def - the form definition\n */\nexport interface FormVersionMetadata {\n versionNumber: number\n createdAt: Date\n}\n\n/**\n * Extracts form version metadata from a form definition\n */\nexport function getFormVersion(\n definition: Pick<FormDefinition, 'metadata'>\n): FormVersionMetadata | undefined {\n return definition.metadata?.[FORM_VERSION_METADATA_KEY] as\n | FormVersionMetadata\n | undefined\n}\n\nconst payLanguageCodes = {\n [EN_GB]: 'en',\n [CY]: 'cy'\n} as Record<string, string>\n\nconst languageLocales = {\n [EN_GB]: enGB,\n [CY]: cy\n} as Record<string, Locale>\n\nconst defaultLanguageCode = 'en'\nconst defaultLanguageLocale = enGB\n\n/**\n * Converts a BCP 47 language tag to the ISO 639-1 code GOV.UK Pay accepts.\n * Defaults to English if the language is not supported.\n * @param { string | undefined } language - BCP 47 language code\n * @returns {string} language code required by GOV.UK Pay\n */\nexport function toPayLanguageCode(language: string | undefined): string {\n return payLanguageCodes[language ?? 'unknown'] ?? defaultLanguageCode\n}\n\n/**\n * Converts a BCP 47 language tag to the date-fns Locale (for date formatting).\n * Defaults to English if the language is not supported.\n * @param { string | undefined } language - BCP 47 language code\n * @returns {Locale} language locale\n */\nexport function toLanguageLocale(language: string | undefined): Locale {\n return languageLocales[language ?? 'unknown'] ?? defaultLanguageLocale\n}\n\n/**\n * @import { FormsService } from '~/src/server/types.js'\n * @import { Locale } from 'date-fns/locale'\n */\n"],"mappings":"AAAA,SACEA,cAAc,EACdC,MAAM,EACNC,eAAe,QAIV,oBAAoB;AAC3B,OAAOC,IAAI,MAAM,YAAY;AAE7B,SAASC,MAAM,EAAEC,QAAQ,QAAqB,UAAU;AACxD,SAASC,EAAE,EAAEC,IAAI,QAAQ,iBAAiB;AAC1C,SAASC,WAAW,QAAQ,mBAAmB;AAE/C,SAASC,MAAM,QAAQ,UAAU;AAEjC,SAASC,MAAM;AACf,SAASC,EAAE,EAAEC,KAAK,EAAEC,yBAAyB;AAC7C,SACEC,SAAS;AAKX,SAASC,UAAU;AAMnB,SACEC,UAAU,EACVC,UAAU;AAMZ,OAAO,MAAMC,MAAM,GAAG,IAAIT,MAAM,CAAC;EAC/BU,YAAY,EAAE,QAAQ;EACtBC,QAAQ,EAAE,IAAI;EACdC,eAAe,EAAE;AACnB,CAAC,CAAC;AAQFH,MAAM,CAACI,cAAc,CAAC,UAAU,EAAE,UAAUC,QAAiB,EAAE;EAC7D,IAAI,OAAOA,QAAQ,KAAK,QAAQ,EAAE;IAChC,OAAOA,QAAQ;EACjB;EAEA,MAAMC,OAAO,GAAG,IAAI,CAACC,OAAO,CAACD,OAAsB;EACnD,MAAME,SAAS,GAAGC,gBAAgB,CAACJ,QAAQ,EAAEC,OAAO,CAACC,OAAO,CAAC;EAE7D,OAAOC,SAAS;AAClB,CAAC,CAAC;AAEFR,MAAM,CAACI,cAAc,CAAC,MAAM,EAAE,UAA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AACvE;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAAS7B,gBAAgBA,CAACV,QAA4B,EAAU;EACrE,OAAOsC,eAAe,CAACtC,QAAQ,IAAI,SAAS,CAAC,IAAIwC,qBAAqB;AACxE;;AAEA;AACA;AACA;AACA","ignoreList":[]}
|
|
@@ -35,5 +35,8 @@ export declare function buildValidationMessages(t: (key: string) => string): {
|
|
|
35
35
|
featuresMin: string;
|
|
36
36
|
featuresMax: string;
|
|
37
37
|
featuresLength: string;
|
|
38
|
+
filesMin: string;
|
|
39
|
+
filesMax: string;
|
|
40
|
+
filesLength: string;
|
|
38
41
|
};
|
|
39
42
|
export type ValidationMessages = ReturnType<typeof buildValidationMessages>;
|
|
@@ -38,13 +38,16 @@ export function buildValidationMessages(t) {
|
|
|
38
38
|
dateFormat: t('components.dateField.validation.dateFormat'),
|
|
39
39
|
dateMin: t('components.dateField.validation.dateMin'),
|
|
40
40
|
dateMax: t('components.dateField.validation.dateMax'),
|
|
41
|
-
unicode: 'validation.unicode',
|
|
42
|
-
arrayMin: 'validation.
|
|
43
|
-
arrayMax: 'validation.
|
|
44
|
-
arrayLength: 'validation.
|
|
45
|
-
featuresMin: 'validation.
|
|
46
|
-
featuresMax: 'validation.
|
|
47
|
-
featuresLength: 'validation.
|
|
41
|
+
unicode: t('validation.unicode'),
|
|
42
|
+
arrayMin: t('validation.arrayMin'),
|
|
43
|
+
arrayMax: t('validation.arrayMax'),
|
|
44
|
+
arrayLength: t('validation.arrayLength'),
|
|
45
|
+
featuresMin: t('validation.featuresMin'),
|
|
46
|
+
featuresMax: t('validation.featuresMax'),
|
|
47
|
+
featuresLength: t('validation.featuresLength'),
|
|
48
|
+
filesMin: t('validation.filesMin'),
|
|
49
|
+
filesMax: t('validation.filesMax'),
|
|
50
|
+
filesLength: t('validation.filesLength')
|
|
48
51
|
};
|
|
49
52
|
}
|
|
50
53
|
//# sourceMappingURL=buildValidationMessages.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"buildValidationMessages.js","names":["joi","lowerFirstPreserveProperNouns","opts","functions","lowerFirst","buildValidationMessages","t","required","expression","selectRequired","pattern","format","declarationRequired","objectRequired","objectMissing","selectYesNoRequired","max","min","minMax","number","numberPrecision","numberInteger","numberMin","numberMax","maxWords","dateFormat","dateMin","dateMax","unicode","arrayMin","arrayMax","arrayLength","featuresMin","featuresMax","featuresLength"],"sources":["../../../../../src/server/plugins/engine/i18n/buildValidationMessages.ts"],"sourcesContent":["import joi, { type JoiExpression, type ReferenceOptions } from 'joi'\n\nimport { lowerFirstPreserveProperNouns } from '~/src/server/plugins/engine/components/helpers/index.js'\n\nconst opts = {\n functions: {\n lowerFirst: lowerFirstPreserveProperNouns\n }\n} as ReferenceOptions\n\n/**\n * Builds a set of translated Joi message templates for a given language.\n * Called once per FormModel at construction time.\n *\n * Strings containing {{lowerFirst(#label)}} must be wrapped in joi.expression()\n * because Joi cannot resolve custom functions from a plain string.\n * Plain strings with only built-in tokens ({{#label}}, {{#limit}}) work without wrapping.\n */\nexport function buildValidationMessages(t: (key: string) => string) {\n return {\n // Expressions — contain lowerFirst custom function\n required: joi.expression(t('validation.required'), opts) as JoiExpression,\n selectRequired: joi.expression(\n t('validation.selectRequired'),\n opts\n ) as JoiExpression,\n pattern: joi.expression(t('validation.pattern'), opts) as JoiExpression,\n format: joi.expression(t('validation.format'), opts) as JoiExpression,\n declarationRequired: joi.expression(\n t('components.declarationField.validation.declarationRequired'),\n opts\n ) as JoiExpression,\n objectRequired: joi.expression(\n t('validation.objectRequired'),\n opts\n ) as JoiExpression,\n objectMissing: joi.expression(\n t('validation.objectMissing'),\n opts\n ) as JoiExpression,\n\n // Plain Joi template strings — no lowerFirst\n selectYesNoRequired: t(\n 'components.yesNoField.validation.selectYesNoRequired'\n ),\n max: t('validation.max'),\n min: t('validation.min'),\n minMax: t('validation.minMax'),\n number: t('validation.number'),\n numberPrecision: t('validation.numberPrecision'),\n numberInteger: t('validation.numberInteger'),\n numberMin: t('validation.numberMin'),\n numberMax: t('validation.numberMax'),\n maxWords: t('validation.maxWords'),\n dateFormat: t('components.dateField.validation.dateFormat'),\n dateMin: t('components.dateField.validation.dateMin'),\n dateMax: t('components.dateField.validation.dateMax'),\n\n unicode: 'validation.unicode',\n arrayMin: 'validation.
|
|
1
|
+
{"version":3,"file":"buildValidationMessages.js","names":["joi","lowerFirstPreserveProperNouns","opts","functions","lowerFirst","buildValidationMessages","t","required","expression","selectRequired","pattern","format","declarationRequired","objectRequired","objectMissing","selectYesNoRequired","max","min","minMax","number","numberPrecision","numberInteger","numberMin","numberMax","maxWords","dateFormat","dateMin","dateMax","unicode","arrayMin","arrayMax","arrayLength","featuresMin","featuresMax","featuresLength","filesMin","filesMax","filesLength"],"sources":["../../../../../src/server/plugins/engine/i18n/buildValidationMessages.ts"],"sourcesContent":["import joi, { type JoiExpression, type ReferenceOptions } from 'joi'\n\nimport { lowerFirstPreserveProperNouns } from '~/src/server/plugins/engine/components/helpers/index.js'\n\nconst opts = {\n functions: {\n lowerFirst: lowerFirstPreserveProperNouns\n }\n} as ReferenceOptions\n\n/**\n * Builds a set of translated Joi message templates for a given language.\n * Called once per FormModel at construction time.\n *\n * Strings containing {{lowerFirst(#label)}} must be wrapped in joi.expression()\n * because Joi cannot resolve custom functions from a plain string.\n * Plain strings with only built-in tokens ({{#label}}, {{#limit}}) work without wrapping.\n */\nexport function buildValidationMessages(t: (key: string) => string) {\n return {\n // Expressions — contain lowerFirst custom function\n required: joi.expression(t('validation.required'), opts) as JoiExpression,\n selectRequired: joi.expression(\n t('validation.selectRequired'),\n opts\n ) as JoiExpression,\n pattern: joi.expression(t('validation.pattern'), opts) as JoiExpression,\n format: joi.expression(t('validation.format'), opts) as JoiExpression,\n declarationRequired: joi.expression(\n t('components.declarationField.validation.declarationRequired'),\n opts\n ) as JoiExpression,\n objectRequired: joi.expression(\n t('validation.objectRequired'),\n opts\n ) as JoiExpression,\n objectMissing: joi.expression(\n t('validation.objectMissing'),\n opts\n ) as JoiExpression,\n\n // Plain Joi template strings — no lowerFirst\n selectYesNoRequired: t(\n 'components.yesNoField.validation.selectYesNoRequired'\n ),\n max: t('validation.max'),\n min: t('validation.min'),\n minMax: t('validation.minMax'),\n number: t('validation.number'),\n numberPrecision: t('validation.numberPrecision'),\n numberInteger: t('validation.numberInteger'),\n numberMin: t('validation.numberMin'),\n numberMax: t('validation.numberMax'),\n maxWords: t('validation.maxWords'),\n dateFormat: t('components.dateField.validation.dateFormat'),\n dateMin: t('components.dateField.validation.dateMin'),\n dateMax: t('components.dateField.validation.dateMax'),\n\n unicode: t('validation.unicode'),\n arrayMin: t('validation.arrayMin'),\n arrayMax: t('validation.arrayMax'),\n arrayLength: t('validation.arrayLength'),\n featuresMin: t('validation.featuresMin'),\n featuresMax: t('validation.featuresMax'),\n featuresLength: t('validation.featuresLength'),\n filesMin: t('validation.filesMin'),\n filesMax: t('validation.filesMax'),\n filesLength: t('validation.filesLength')\n }\n}\n\nexport type ValidationMessages = ReturnType<typeof buildValidationMessages>\n"],"mappings":"AAAA,OAAOA,GAAG,MAAqD,KAAK;AAEpE,SAASC,6BAA6B;AAEtC,MAAMC,IAAI,GAAG;EACXC,SAAS,EAAE;IACTC,UAAU,EAAEH;EACd;AACF,CAAqB;;AAErB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASI,uBAAuBA,CAACC,CAA0B,EAAE;EAClE,OAAO;IACL;IACAC,QAAQ,EAAEP,GAAG,CAACQ,UAAU,CAACF,CAAC,CAAC,qBAAqB,CAAC,EAAEJ,IAAI,CAAkB;IACzEO,cAAc,EAAET,GAAG,CAACQ,UAAU,CAC5BF,CAAC,CAAC,2BAA2B,CAAC,EAC9BJ,IACF,CAAkB;IAClBQ,OAAO,EAAEV,GAAG,CAACQ,UAAU,CAACF,CAAC,CAAC,oBAAoB,CAAC,EAAEJ,IAAI,CAAkB;IACvES,MAAM,EAAEX,GAAG,CAACQ,UAAU,CAACF,CAAC,CAA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B,CAAC,CAAC,wBAAwB,CAAC;IACxC4B,cAAc,EAAE5B,CAAC,CAAC,2BAA2B,CAAC;IAC9C6B,QAAQ,EAAE7B,CAAC,CAAC,qBAAqB,CAAC;IAClC8B,QAAQ,EAAE9B,CAAC,CAAC,qBAAqB,CAAC;IAClC+B,WAAW,EAAE/B,CAAC,CAAC,wBAAwB;EACzC,CAAC;AACH","ignoreList":[]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { type FormDefinition } from '@defra/forms-model';
|
|
1
|
+
import { type FormDefinition, type FormMetadata } from '@defra/forms-model';
|
|
2
2
|
import { type i18n } from 'i18next';
|
|
3
|
-
|
|
4
|
-
export declare function
|
|
5
|
-
export declare function
|
|
3
|
+
export declare function createFormTranslator(metadata: FormMetadata, definition: FormDefinition | undefined, language: string): import("../../../../server/plugins/engine/i18n/types.js").Translator;
|
|
4
|
+
export declare function loadFormTranslations(def: FormDefinition | undefined, i18nInstance: i18n): void;
|
|
5
|
+
export declare function extractMetadataBaseTranslations(metadata: FormMetadata | undefined, i18nInstance: i18n): void;
|
|
@@ -1,18 +1,47 @@
|
|
|
1
|
+
import { yesNoListNoItemId, yesNoListYesItemId } from '@defra/forms-model';
|
|
2
|
+
import { CY } from "../../../constants.js";
|
|
1
3
|
import { createTranslator } from "./createTranslator.js";
|
|
2
4
|
import { extractBaseTranslations } from "./extractBaseTranslations.js";
|
|
3
5
|
import { createFormI18nInstance } from "./index.js";
|
|
4
|
-
export function createFormTranslator(
|
|
5
|
-
const baseTranslations = extractBaseTranslations(
|
|
6
|
+
export function createFormTranslator(metadata, definition, language) {
|
|
7
|
+
const baseTranslations = extractBaseTranslations(definition);
|
|
6
8
|
const i18nInstance = createFormI18nInstance(baseTranslations);
|
|
7
|
-
loadFormTranslations(
|
|
8
|
-
|
|
9
|
+
loadFormTranslations(definition, i18nInstance);
|
|
10
|
+
extractMetadataBaseTranslations(metadata, i18nInstance);
|
|
11
|
+
const translator = createTranslator(i18nInstance, language);
|
|
12
|
+
return translator;
|
|
9
13
|
}
|
|
10
14
|
export function loadFormTranslations(def, i18nInstance) {
|
|
15
|
+
if (!def) {
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
11
18
|
const formTranslations = def.metadata?.translations;
|
|
12
19
|
if (formTranslations) {
|
|
13
20
|
for (const [lng, resources] of Object.entries(formTranslations)) {
|
|
14
21
|
i18nInstance.addResourceBundle(lng, 'form', resources, true, true);
|
|
22
|
+
|
|
23
|
+
// Temporary workaround - until we develop a better solution
|
|
24
|
+
if (lng === CY) {
|
|
25
|
+
i18nInstance.addResource(lng, 'form', `listItems.${yesNoListYesItemId}.text`, 'Ie');
|
|
26
|
+
i18nInstance.addResource(lng, 'form', `listItems.${yesNoListNoItemId}.text`, 'Nage');
|
|
27
|
+
}
|
|
15
28
|
}
|
|
16
29
|
}
|
|
17
30
|
}
|
|
31
|
+
export function extractMetadataBaseTranslations(metadata, i18nInstance) {
|
|
32
|
+
if (metadata) {
|
|
33
|
+
const translations = {
|
|
34
|
+
'form.title': metadata.title,
|
|
35
|
+
'form.contact.email.address': metadata.contact?.email?.address ?? '',
|
|
36
|
+
'form.contact.email.responseTime': metadata.contact?.email?.responseTime ?? '',
|
|
37
|
+
'form.contact.online.url': metadata.contact?.online?.url ?? '',
|
|
38
|
+
'form.contact.online.text': metadata.contact?.online?.text ?? '',
|
|
39
|
+
'form.contact.phone': metadata.contact?.phone ?? '',
|
|
40
|
+
'form.submissionGuidance': metadata.submissionGuidance ?? '',
|
|
41
|
+
'form.privacyNoticeText': metadata.privacyNoticeText ?? '',
|
|
42
|
+
'form.privacyNoticeUrl': metadata.privacyNoticeUrl ?? ''
|
|
43
|
+
};
|
|
44
|
+
i18nInstance.addResourceBundle('en-GB', 'form', translations, true, true);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
18
47
|
//# sourceMappingURL=createFormTranslator.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createFormTranslator.js","names":["createTranslator","extractBaseTranslations","createFormI18nInstance","createFormTranslator","
|
|
1
|
+
{"version":3,"file":"createFormTranslator.js","names":["yesNoListNoItemId","yesNoListYesItemId","CY","createTranslator","extractBaseTranslations","createFormI18nInstance","createFormTranslator","metadata","definition","language","baseTranslations","i18nInstance","loadFormTranslations","extractMetadataBaseTranslations","translator","def","formTranslations","translations","lng","resources","Object","entries","addResourceBundle","addResource","title","contact","email","address","responseTime","online","url","text","phone","submissionGuidance","privacyNoticeText","privacyNoticeUrl"],"sources":["../../../../../src/server/plugins/engine/i18n/createFormTranslator.ts"],"sourcesContent":["import {\n yesNoListNoItemId,\n yesNoListYesItemId,\n type FormDefinition,\n type FormMetadata\n} from '@defra/forms-model'\nimport { type i18n } from 'i18next'\n\nimport { CY } from '~/src/server/constants.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 { type FormDefinitionTranslations } from '~/src/server/plugins/engine/i18n/types.js'\n\nexport function createFormTranslator(\n metadata: FormMetadata,\n definition: FormDefinition | undefined,\n language: string\n) {\n const baseTranslations = extractBaseTranslations(definition)\n const i18nInstance = createFormI18nInstance(baseTranslations)\n loadFormTranslations(definition, i18nInstance)\n extractMetadataBaseTranslations(metadata, i18nInstance)\n\n const translator = createTranslator(i18nInstance, language)\n\n return translator\n}\n\nexport function loadFormTranslations(\n def: FormDefinition | undefined,\n i18nInstance: i18n\n) {\n if (!def) {\n return\n }\n\n const formTranslations = def.metadata?.translations as\n | FormDefinitionTranslations\n | undefined\n\n if (formTranslations) {\n for (const [lng, resources] of Object.entries(formTranslations)) {\n i18nInstance.addResourceBundle(lng, 'form', resources, true, true)\n\n // Temporary workaround - until we develop a better solution\n if (lng === CY) {\n i18nInstance.addResource(\n lng,\n 'form',\n `listItems.${yesNoListYesItemId}.text`,\n 'Ie'\n )\n i18nInstance.addResource(\n lng,\n 'form',\n `listItems.${yesNoListNoItemId}.text`,\n 'Nage'\n )\n }\n }\n }\n}\n\nexport function extractMetadataBaseTranslations(\n metadata: FormMetadata | undefined,\n i18nInstance: i18n\n) {\n if (metadata) {\n const translations = {\n 'form.title': metadata.title,\n 'form.contact.email.address': metadata.contact?.email?.address ?? '',\n 'form.contact.email.responseTime':\n metadata.contact?.email?.responseTime ?? '',\n 'form.contact.online.url': metadata.contact?.online?.url ?? '',\n 'form.contact.online.text': metadata.contact?.online?.text ?? '',\n 'form.contact.phone': metadata.contact?.phone ?? '',\n 'form.submissionGuidance': metadata.submissionGuidance ?? '',\n 'form.privacyNoticeText': metadata.privacyNoticeText ?? '',\n 'form.privacyNoticeUrl': metadata.privacyNoticeUrl ?? ''\n }\n i18nInstance.addResourceBundle('en-GB', 'form', translations, true, true)\n }\n}\n"],"mappings":"AAAA,SACEA,iBAAiB,EACjBC,kBAAkB,QAGb,oBAAoB;AAG3B,SAASC,EAAE;AACX,SAASC,gBAAgB;AACzB,SAASC,uBAAuB;AAChC,SAASC,sBAAsB;AAG/B,OAAO,SAASC,oBAAoBA,CAClCC,QAAsB,EACtBC,UAAsC,EACtCC,QAAgB,EAChB;EACA,MAAMC,gBAAgB,GAAGN,uBAAuB,CAACI,UAAU,CAAC;EAC5D,MAAMG,YAAY,GAAGN,sBAAsB,CAACK,gBAAgB,CAAC;EAC7DE,oBAAoB,CAACJ,UAAU,EAAEG,YAAY,CAAC;EAC9CE,+BAA+B,CAACN,QAAQ,EAAEI,YAAY,CAAC;EAEvD,MAAMG,UAAU,GAAGX,gBAAgB,CAACQ,YAAY,EAAEF,QAAQ,CAAC;EAE3D,OAAOK,UAAU;AACnB;AAEA,OAAO,SAASF,oBAAoBA,CAClCG,GAA+B,EAC/BJ,YAAkB,EAClB;EACA,IAAI,CAACI,GAAG,EAAE;IACR;EACF;EAEA,MAAMC,gBAAgB,GAAGD,GAAG,CAACR,QAAQ,EAAEU,YAE1B;EAEb,IAAID,gBAAg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EAAE,MAAM,EAAEL,YAAY,EAAE,IAAI,EAAE,IAAI,CAAC;EAC3E;AACF","ignoreList":[]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type FormDefinition } from '@defra/forms-model';
|
|
2
2
|
import { type FormDefinitionTranslations } from '../../../../server/plugins/engine/i18n/types.js';
|
|
3
3
|
type BaseTranslations = FormDefinitionTranslations[string];
|
|
4
|
-
export declare function extractBaseTranslations(def: FormDefinition): BaseTranslations;
|
|
4
|
+
export declare function extractBaseTranslations(def: FormDefinition | undefined): BaseTranslations;
|
|
5
5
|
export {};
|
|
@@ -5,6 +5,15 @@ export function extractBaseTranslations(def) {
|
|
|
5
5
|
const sections = {};
|
|
6
6
|
const listItems = {};
|
|
7
7
|
const form = {};
|
|
8
|
+
if (!def) {
|
|
9
|
+
return {
|
|
10
|
+
pages,
|
|
11
|
+
components,
|
|
12
|
+
sections,
|
|
13
|
+
listItems,
|
|
14
|
+
form
|
|
15
|
+
};
|
|
16
|
+
}
|
|
8
17
|
for (const page of def.pages) {
|
|
9
18
|
if (page.id && page.title) {
|
|
10
19
|
pages[page.id] = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extractBaseTranslations.js","names":["hasComponentsEvenIfNoNext","extractBaseTranslations","def","pages","components","sections","listItems","form","page","id","title","component","entry","hint","content","shortDescription","Object","keys","length","section","list","lists","item","items","text","name"],"sources":["../../../../../src/server/plugins/engine/i18n/extractBaseTranslations.ts"],"sourcesContent":["import {\n hasComponentsEvenIfNoNext,\n type FormDefinition\n} from '@defra/forms-model'\n\nimport { type FormDefinitionTranslations } from '~/src/server/plugins/engine/i18n/types.js'\n\ntype BaseTranslations = FormDefinitionTranslations[string]\n\nexport function extractBaseTranslations(def: FormDefinition): BaseTranslations {\n const pages: BaseTranslations['pages'] = {}\n const components: BaseTranslations['components'] = {}\n const sections: BaseTranslations['sections'] = {}\n const listItems: BaseTranslations['listItems'] = {}\n const form: BaseTranslations['form'] = {}\n\n for (const page of def.pages) {\n if (page.id && page.title) {\n pages[page.id] = { title: page.title }\n }\n\n if (hasComponentsEvenIfNoNext(page)) {\n for (const component of page.components) {\n if (!component.id) continue\n\n const entry: BaseTranslations['components'][string] = {}\n\n if (component.title) entry.title = component.title\n if ('hint' in component && component.hint) entry.hint = component.hint\n if ('content' in component && component.content) {\n entry.content = component.content\n }\n if ('shortDescription' in component && component.shortDescription) {\n entry.shortDescription = component.shortDescription\n }\n\n if (Object.keys(entry).length) {\n components[component.id] = entry\n }\n }\n }\n }\n\n for (const section of def.sections) {\n if (section.id && section.title) {\n sections[section.id] = { title: section.title }\n }\n }\n\n for (const list of def.lists) {\n for (const item of list.items) {\n if (item.id && item.text) {\n listItems[item.id] = { text: item.text }\n }\n }\n }\n\n form.title = def.name ?? ''\n\n return { pages, components, sections, listItems, form }\n}\n"],"mappings":"AAAA,SACEA,yBAAyB,QAEpB,oBAAoB;AAM3B,OAAO,SAASC,uBAAuBA,
|
|
1
|
+
{"version":3,"file":"extractBaseTranslations.js","names":["hasComponentsEvenIfNoNext","extractBaseTranslations","def","pages","components","sections","listItems","form","page","id","title","component","entry","hint","content","shortDescription","Object","keys","length","section","list","lists","item","items","text","name"],"sources":["../../../../../src/server/plugins/engine/i18n/extractBaseTranslations.ts"],"sourcesContent":["import {\n hasComponentsEvenIfNoNext,\n type FormDefinition\n} from '@defra/forms-model'\n\nimport { type FormDefinitionTranslations } from '~/src/server/plugins/engine/i18n/types.js'\n\ntype BaseTranslations = FormDefinitionTranslations[string]\n\nexport function extractBaseTranslations(\n def: FormDefinition | undefined\n): BaseTranslations {\n const pages: BaseTranslations['pages'] = {}\n const components: BaseTranslations['components'] = {}\n const sections: BaseTranslations['sections'] = {}\n const listItems: BaseTranslations['listItems'] = {}\n const form: BaseTranslations['form'] = {}\n\n if (!def) {\n return { pages, components, sections, listItems, form }\n }\n\n for (const page of def.pages) {\n if (page.id && page.title) {\n pages[page.id] = { title: page.title }\n }\n\n if (hasComponentsEvenIfNoNext(page)) {\n for (const component of page.components) {\n if (!component.id) continue\n\n const entry: BaseTranslations['components'][string] = {}\n\n if (component.title) entry.title = component.title\n if ('hint' in component && component.hint) entry.hint = component.hint\n if ('content' in component && component.content) {\n entry.content = component.content\n }\n if ('shortDescription' in component && component.shortDescription) {\n entry.shortDescription = component.shortDescription\n }\n\n if (Object.keys(entry).length) {\n components[component.id] = entry\n }\n }\n }\n }\n\n for (const section of def.sections) {\n if (section.id && section.title) {\n sections[section.id] = { title: section.title }\n }\n }\n\n for (const list of def.lists) {\n for (const item of list.items) {\n if (item.id && item.text) {\n listItems[item.id] = { text: item.text }\n }\n }\n }\n\n form.title = def.name ?? ''\n\n return { pages, components, sections, listItems, form }\n}\n"],"mappings":"AAAA,SACEA,yBAAyB,QAEpB,oBAAoB;AAM3B,OAAO,SAASC,uBAAuBA,CACrCC,GAA+B,EACb;EAClB,MAAMC,KAAgC,GAAG,CAAC,CAAC;EAC3C,MAAMC,UAA0C,GAAG,CAAC,CAAC;EACrD,MAAMC,QAAsC,GAAG,CAAC,CAAC;EACjD,MAAMC,SAAwC,GAAG,CAAC,CAAC;EACnD,MAAMC,IAA8B,GAAG,CAAC,CAAC;EAEzC,IAAI,CAACL,GAAG,EAAE;IACR,OAAO;MAAEC,KAAK;MAAEC,UAAU;MAAEC,QAAQ;MAAEC,SAAS;MAAEC;IAAK,CAAC;EACzD;EAEA,KAAK,MAAMC,IAAI,IAAIN,GAAG,CAACC,KAAK,EAAE;IAC5B,IAAIK,IAAI,CAACC,EAAE,IAAID,IAAI,CAACE,KAAK,EAAE;MACzBP,KAAK,CAACK,IAAI,CAACC,EAAE,CAAC,GAAG;QAAEC,KAAK,EAAEF,IAAI,CAACE;MAAM,CAAC;IACxC;IAEA,IAAIV,yBAAyB,CAACQ,IAAI,CAAC,EAAE;MACnC,KAAK,MAAMG,SAAS,IAAIH,IAAI,CAACJ,UAAU,EAAE;QACvC,IAAI,CAACO,SAAS,CAACF,EAAE,EAAE;QAEnB,MAAM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