@defra/forms-engine-plugin 5.0.0-alpha.24 → 5.0.0-alpha.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/.public/javascripts/shared.min.js +1 -1
  2. package/.public/javascripts/shared.min.js.map +1 -1
  3. package/.server/client/javascripts/geospatial-map.d.ts +6 -0
  4. package/.server/client/javascripts/geospatial-map.js +2 -2
  5. package/.server/client/javascripts/geospatial-map.js.map +1 -1
  6. package/.server/client/javascripts/geospatial-map.test.js +152 -0
  7. package/.server/client/javascripts/geospatial-map.test.js.map +1 -0
  8. package/.server/client/javascripts/map.d.ts +2 -2
  9. package/.server/client/javascripts/map.js +0 -1
  10. package/.server/client/javascripts/map.js.map +1 -1
  11. package/.server/server/plugins/engine/components/ComponentCollection.js +1 -1
  12. package/.server/server/plugins/engine/components/ComponentCollection.js.map +1 -1
  13. package/.server/server/plugins/engine/components/helpers/geospatial.js +4 -4
  14. package/.server/server/plugins/engine/components/helpers/geospatial.js.map +1 -1
  15. package/.server/server/plugins/map/routes/index.d.ts +4 -0
  16. package/.server/server/plugins/map/routes/index.js +12 -4
  17. package/.server/server/plugins/map/routes/index.js.map +1 -1
  18. package/.server/server/plugins/map/routes/vts/README.md +38 -0
  19. package/.server/server/plugins/map/routes/vts/countries-5dp.geojson +4 -0
  20. package/.server/server/plugins/map/routes/vts/countries.geojson +10 -39283
  21. package/.server/server/plugins/map/types.d.ts +24 -2
  22. package/.server/server/plugins/map/types.js +9 -2
  23. package/.server/server/plugins/map/types.js.map +1 -1
  24. package/.server/server/plugins/nunjucks/enviroment.test.js +11 -4
  25. package/.server/server/plugins/nunjucks/enviroment.test.js.map +1 -1
  26. package/.server/server/plugins/postcode-lookup/models/index.js +16 -3
  27. package/.server/server/plugins/postcode-lookup/models/index.js.map +1 -1
  28. package/.server/server/plugins/postcode-lookup/routes/index.js +17 -3
  29. package/.server/server/plugins/postcode-lookup/routes/index.js.map +1 -1
  30. package/.server/typings/geodesy/index.d.js +2 -0
  31. package/.server/typings/geodesy/index.d.js.map +1 -0
  32. package/package.json +1 -1
  33. package/src/client/javascripts/geospatial-map.js +2 -2
  34. package/src/client/javascripts/map.js +0 -1
  35. package/src/server/plugins/engine/components/ComponentCollection.ts +1 -4
  36. package/src/server/plugins/engine/components/helpers/geospatial.ts +6 -6
  37. package/src/server/plugins/map/routes/index.js +26 -4
  38. package/src/server/plugins/map/routes/vts/README.md +38 -0
  39. package/src/server/plugins/map/routes/vts/countries-5dp.geojson +4 -0
  40. package/src/server/plugins/map/routes/vts/countries.geojson +10 -39283
  41. package/src/server/plugins/map/types.js +9 -2
  42. package/src/server/plugins/postcode-lookup/models/index.js +16 -3
  43. package/src/server/plugins/postcode-lookup/routes/index.js +23 -8
  44. package/src/typings/geodesy/index.d.ts +18 -0
@@ -1 +1 @@
1
- {"version":3,"file":"map.js","names":["InteractiveMap","createInteractPlugin","createMapStylesPlugin","createScaleBarPlugin","createSearchPlugin","maplibreProvider","centroid","OsGridRef","LatLon","processGeospatial","processLocation","DEFAULT_LAT","DEFAULT_LONG","COMPANY_SYMBOL_CODE","defaultData","VTS_OUTDOOR_URL","VTS_DARK_URL","VTS_BLACK_AND_WHITE_URL","VTS_AERIAL_URL","latLongToEastingNorthing","lat","long","point","toOsGrid","eastingNorthingToLatLong","easting","northing","latLong","toLatLon","latitude","longitude","latLongToOsGridRef","toString","osGridRefToLatLong","osGridRef","parse","getCoordinateGridRef","feature","geometry","type","coordinates","getCentroidGridRef","centre","defaultConfig","zoom","center","EVENTS","mapReady","interactMarkerChange","drawReady","drawCreated","drawEdited","drawCancelled","formSubmitFactory","buttons","onFormSubmit","e","submitter","HTMLButtonElement","includes","preventDefault","initMaps","config","assetPath","apiPath","data","locations","document","querySelectorAll","geospatials","length","form","closest","Array","from","addEventListener","forEach","location","index","geospatial","makeTileRequestTransformer","transformTileRequest","url","resourceType","startsWith","replace","window","origin","headers","encodeURIComponent","spritesPath","path","substring","createMap","mapId","initConfig","mapsConfig","logoAltText","interactPlugin","markerColor","outdoor","dark","interactionModes","multiSelect","map","enableFullscreen","autoColorScheme","mapProvider","behaviour","minZoom","maxZoom","containerHeight","enableZoomControls","transformRequest","plugins","mapStyles","id","label","thumbnail","logo","attribution","String","fromCodePoint","Date","getFullYear","backgroundColor","mapColorScheme","appColorScheme","osNamesURL","width","showMarker","units","centerMap","addMarker","flyTo","essential","getMapLayers","layers","trimmed","trim","split","getMapCountryLayers","country","datasets","push","geojson","showInKey","showInMenu","style","stroke","strokeWidth","fill"],"sources":["../../../src/client/javascripts/map.js"],"sourcesContent":["// @ts-expect-error - no types\nimport InteractiveMap from '@defra/interactive-map'\n// @ts-expect-error - no types\nimport createInteractPlugin from '@defra/interactive-map/plugins/interact'\n// @ts-expect-error - no types\nimport createMapStylesPlugin from '@defra/interactive-map/plugins/map-styles'\n// @ts-expect-error - no types\nimport createScaleBarPlugin from '@defra/interactive-map/plugins/scale-bar'\n// @ts-expect-error - no types\nimport createSearchPlugin from '@defra/interactive-map/plugins/search'\n// @ts-expect-error - no types\nimport maplibreProvider from '@defra/interactive-map/providers/maplibre'\nimport { centroid } from '@turf/centroid'\n// @ts-expect-error - no types\nimport OsGridRef, { LatLon } from 'geodesy/osgridref.js'\n\nimport { processGeospatial } from '~/src/client/javascripts/geospatial-map.js'\nimport { processLocation } from '~/src/client/javascripts/location-map.js'\n\n// Center of UK\nconst DEFAULT_LAT = 53.825564\nconst DEFAULT_LONG = -2.421975\nconst COMPANY_SYMBOL_CODE = 169\n\nconst defaultData = {\n VTS_OUTDOOR_URL: '/api/maps/vts/OS_VTS_3857_Outdoor.json',\n VTS_DARK_URL: '/api/maps/vts/OS_VTS_3857_Dark.json',\n VTS_BLACK_AND_WHITE_URL: '/api/maps/vts/OS_VTS_3857_Black_and_White.json',\n VTS_AERIAL_URL: '/api/maps/vts/esri-aerial.json'\n}\n\n/**\n * Converts lat long to easting and northing\n * @param {object} param\n * @param {number} param.lat\n * @param {number} param.long\n * @returns {{ easting: number, northing: number }}\n */\nexport function latLongToEastingNorthing({ lat, long }) {\n const point = new LatLon(lat, long)\n\n return point.toOsGrid()\n}\n\n/**\n * Converts easting and northing to lat long\n * @param {object} param\n * @param {number} param.easting\n * @param {number} param.northing\n * @returns {{ lat: number, long: number }}\n */\nexport function eastingNorthingToLatLong({ easting, northing }) {\n const point = new OsGridRef(easting, northing)\n const latLong = point.toLatLon()\n\n return { lat: latLong.latitude, long: latLong.longitude }\n}\n\n/**\n * Converts lat long to an ordnance survey grid reference\n * @param {object} param\n * @param {number} param.lat\n * @param {number} param.long\n * @returns {string}\n */\nexport function latLongToOsGridRef({ lat, long }) {\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n}\n\n/**\n * Converts an ordnance survey grid reference to lat long\n * @param {string} osGridRef\n * @returns {{ lat: number, long: number }}\n */\nexport function osGridRefToLatLong(osGridRef) {\n const point = OsGridRef.parse(osGridRef)\n const latLong = point.toLatLon()\n\n return { lat: latLong.latitude, long: latLong.longitude }\n}\n\n/**\n * Get the grid ref from the first coordinate of a long/lat feature\n * @param {Feature} feature\n */\nexport function getCoordinateGridRef(feature) {\n if (feature.geometry.type === 'Point') {\n const [long, lat] = feature.geometry.coordinates\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n } else if (feature.geometry.type === 'LineString') {\n const [long, lat] = feature.geometry.coordinates[0]\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n } else {\n const [long, lat] = feature.geometry.coordinates[0][0]\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n }\n}\n\n/**\n * Get the centroid grid ref from a long/lat feature\n * @param {Feature} feature\n */\nexport function getCentroidGridRef(feature) {\n if (feature.geometry.type === 'Point') {\n const [long, lat] = feature.geometry.coordinates\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n } else {\n const centre = centroid(feature)\n const [long, lat] = centre.geometry.coordinates\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n }\n}\n\n/** @type {InteractiveMapInitConfig} */\nexport const defaultConfig = {\n zoom: '6',\n center: [DEFAULT_LONG, DEFAULT_LAT]\n}\n\nexport const EVENTS = {\n mapReady: 'map:ready',\n interactMarkerChange: 'interact:markerchange',\n drawReady: 'draw:ready',\n drawCreated: 'draw:created',\n drawEdited: 'draw:edited',\n drawCancelled: 'draw:cancelled'\n}\n\n/**\n * Make a form submit handler that only allows submissions from allowed buttons\n * @param {HTMLButtonElement[]} buttons - the form buttons to allow submissions\n */\nexport function formSubmitFactory(buttons) {\n /**\n * The submit handler\n * @param {SubmitEvent} e\n */\n const onFormSubmit = function (e) {\n if (\n !(e.submitter instanceof HTMLButtonElement) ||\n !buttons.includes(e.submitter)\n ) {\n e.preventDefault()\n }\n }\n\n return onFormSubmit\n}\n\n/**\n * Initialise location maps\n * @param {Partial<MapsEnvironmentConfig>} config - the map configuration\n */\nexport function initMaps(config = {}) {\n const {\n assetPath = '/assets',\n apiPath = '/form/api',\n data = defaultData\n } = config\n const locations = document.querySelectorAll('.app-location-field')\n const geospatials = document.querySelectorAll('.app-geospatial-field')\n\n // TODO: Fix this in `interactive-map`\n // If there are location components on the page fix up the main form submit\n // handler so it doesn't fire when using the integrated map search feature\n if (locations.length) {\n const form = locations[0].closest('form')\n\n if (form === null) {\n return\n }\n\n const buttons = Array.from(form.querySelectorAll('button'))\n form.addEventListener('submit', formSubmitFactory(buttons), false)\n }\n\n if (geospatials.length) {\n const form = geospatials[0].closest('form')\n\n if (form === null) {\n return\n }\n\n const buttons = Array.from(form.querySelectorAll('button'))\n form.addEventListener('submit', formSubmitFactory(buttons), false)\n }\n\n locations.forEach((location, index) => {\n processLocation({ assetPath, apiPath, data }, location, index)\n })\n\n geospatials.forEach((geospatial, index) => {\n processGeospatial({ assetPath, apiPath, data }, geospatial, index)\n })\n}\n\n/**\n * OS API request proxy factory\n * @param {string} apiPath - the root API path\n */\nexport function makeTileRequestTransformer(apiPath) {\n /**\n * Proxy OS API requests via our server\n * @param {string} url - the request URL\n * @param {string} resourceType - the resource type\n */\n return function transformTileRequest(url, resourceType) {\n if (url.startsWith('https://api.os.uk')) {\n if (resourceType === 'Tile') {\n return {\n url: url.replace(\n 'https://api.os.uk/maps/vector/v1/vts',\n `${window.location.origin}${apiPath}`\n ),\n headers: {}\n }\n }\n\n if (resourceType !== 'Style') {\n return {\n url: `${apiPath}/map-proxy?url=${encodeURIComponent(url)}`,\n headers: {}\n }\n }\n }\n\n const spritesPath =\n 'https://raw.githubusercontent.com/OrdnanceSurvey/OS-Vector-Tile-API-Stylesheets/main'\n\n // Proxy sprite requests\n if (url.startsWith(spritesPath)) {\n const path = url.substring(spritesPath.length)\n return {\n url: `${apiPath}/maps/vts${path}`,\n headers: {}\n }\n }\n\n return { url, headers: {} }\n }\n}\n\n/**\n * Create a Defra map instance\n * @param {string} mapId - the map id\n * @param {InteractiveMapInitConfig} initConfig - the map initial configuration\n * @param {MapsEnvironmentConfig} mapsConfig - the map environment params\n */\nexport function createMap(mapId, initConfig, mapsConfig) {\n const { assetPath, apiPath, data = defaultData } = mapsConfig\n const logoAltText = 'Ordnance survey logo'\n const interactPlugin = createInteractPlugin({\n markerColor: { outdoor: '#ff0000', dark: '#00ff00' },\n interactionModes: ['placeMarker'],\n multiSelect: false\n })\n\n /** @type {InteractiveMap} */\n const map = new InteractiveMap(mapId, {\n enableFullscreen: true,\n autoColorScheme: false,\n mapProvider: maplibreProvider(),\n behaviour: 'inline',\n minZoom: 6,\n maxZoom: 18,\n containerHeight: '400px',\n enableZoomControls: true,\n transformRequest: makeTileRequestTransformer(apiPath),\n ...initConfig,\n plugins: [\n createMapStylesPlugin({\n mapStyles: [\n {\n id: 'outdoor',\n label: 'Outdoor',\n url: data.VTS_OUTDOOR_URL,\n thumbnail: `${assetPath}/interactive-map/assets/images/outdoor-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`,\n backgroundColor: '#f5f5f0'\n },\n {\n id: 'dark',\n label: 'Dark',\n url: data.VTS_DARK_URL,\n mapColorScheme: 'dark',\n appColorScheme: 'dark',\n thumbnail: `${assetPath}/interactive-map/assets/images/dark-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo-white.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`\n },\n {\n id: 'black-and-white',\n label: 'Black/White',\n url: data.VTS_BLACK_AND_WHITE_URL,\n thumbnail: `${assetPath}/interactive-map/assets/images/black-and-white-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo-black.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`\n },\n {\n id: 'aerial',\n label: 'Aerial',\n url: data.VTS_AERIAL_URL,\n thumbnail: `${assetPath}/interactive-map/assets/images/aerial-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/esri-logo.png`,\n logoAltText: 'Powered by Esri',\n attribution: `Tiles ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community ${new Date().getFullYear()}`\n }\n ]\n }),\n interactPlugin,\n createSearchPlugin({\n osNamesURL: `${apiPath}/geocode-proxy?query={query}`,\n width: '300px',\n showMarker: false\n }),\n createScaleBarPlugin({\n units: 'metric'\n }),\n ...(initConfig.plugins ?? [])\n ]\n })\n\n return { map, interactPlugin }\n}\n\n/**\n * Updates the marker position and moves the map view port the new location\n * @param {InteractiveMap} map - the map component instance (of InteractiveMap)\n * @param {MapLibreMap} mapProvider - the map provider instance (of MapLibreMap)\n * @param {MapCenter} center - the point\n */\nexport function centerMap(map, mapProvider, center) {\n // Move the 'location' marker to the new point\n map.addMarker('location', center)\n\n // Pan & zoom the map to the new valid location\n mapProvider.flyTo({\n center,\n zoom: 14,\n essential: true\n })\n}\n\n/**\n * Parse CSV string layers\n * @param {string | undefined} layers\n * @returns {string[]}\n */\nexport function getMapLayers(layers) {\n const trimmed = layers?.trim()\n return trimmed ? trimmed.split(',') : []\n}\n\n/**\n * Adds the country layers to a datasets array\n * @param {string} apiPath\n * @param {string} [country]\n */\nexport function getMapCountryLayers(apiPath, country) {\n /** @type {any[]} */\n const datasets = []\n\n if (country) {\n // Add the country bounds to the datasets array to show the valid area on the map\n // and provide feedback to the user when they add features outside of the bounds.\n datasets.push(\n {\n id: 'invalid-area',\n label: 'Invalid areas',\n geojson: `${apiPath}/maps/countries.geojson?omit=${country}`,\n showInKey: false,\n showInMenu: false,\n style: {\n stroke: 'gray',\n strokeWidth: 1,\n fill: 'rgba(211,211,211,0.8)'\n }\n },\n {\n id: 'valid-area',\n label: 'Valid areas',\n geojson: `${apiPath}/maps/countries.geojson?only=${country}`,\n showInKey: false,\n showInMenu: false,\n style: {\n stroke: 'rgba(0,112,60,1)',\n strokeWidth: 1\n }\n }\n )\n }\n\n return datasets\n}\n\n/**\n * @typedef {object} InteractiveMap - an instance of a InteractiveMap\n * @property {Function} on - register callback listeners to map events\n * @property {Function} addPanel - adds a new panel to the map\n * @property {Function} addMarker - adds/updates a marker\n * @property {Function} removeMarker - removes a marker\n * @property {Function} addButton - adds/updates a button\n * @property {Function} toggleButtonState - toggle the state of a button\n */\n\n/**\n * @typedef {object} MapLibreMap\n * @property {Function} flyTo - pans/zooms to a new location\n * @property {Function} fitBounds - fits the my to the new bounds\n */\n\n/**\n * @typedef {[number, number]} MapCenter - Map center point as [long, lat]\n */\n\n/**\n * @typedef {object} InteractiveMapInitConfig - additional config that can be provided to InteractiveMap\n * @property {string} zoom - the zoom level of the map\n * @property {MapCenter} center - the center point of the map\n * @property {{ id: string, coords: MapCenter }[]} [markers] - the markers to add to the map\n * @property {any[]} [plugins] - additional plugins\n */\n\n/**\n * @typedef {object} TileData\n * @property {string} VTS_OUTDOOR_URL - the outdoor tile URL\n * @property {string} VTS_DARK_URL - the dark tile URL\n * @property {string} VTS_BLACK_AND_WHITE_URL - the black and white tile URL\n * @property {string} VTS_AERIAL_URL - the aerial tile URL\n */\n\n/**\n * @typedef {object} MapsEnvironmentConfig\n * @property {string} assetPath - the root asset path\n * @property {string} apiPath - the root API path\n * @property {TileData} data - the tile data config\n */\n\n/**\n * @typedef {object} UIManagerOptions\n * @property {string} [geometryTypes] - the CSV list of geometry types that a user can create\n */\n\n/**\n * @import { Feature } from '~/src/server/plugins/engine/types.js'\n */\n\n/**\n * Supported language codes\n * @typedef {('en-GB'|'cy')} LanguageCode\n */\n"],"mappings":"AAAA;AACA,OAAOA,cAAc,MAAM,wBAAwB;AACnD;AACA,OAAOC,oBAAoB,MAAM,yCAAyC;AAC1E;AACA,OAAOC,qBAAqB,MAAM,2CAA2C;AAC7E;AACA,OAAOC,oBAAoB,MAAM,0CAA0C;AAC3E;AACA,OAAOC,kBAAkB,MAAM,uCAAuC;AACtE;AACA,OAAOC,gBAAgB,MAAM,2CAA2C;AACxE,SAASC,QAAQ,QAAQ,gBAAgB;AACzC;AACA,OAAOC,SAAS,IAAIC,MAAM,QAAQ,sBAAsB;AAExD,SAASC,iBAAiB;AAC1B,SAASC,eAAe;;AAExB;AACA,MAAMC,WAAW,GAAG,SAAS;AAC7B,MAAMC,YAAY,GAAG,CAAC,QAAQ;AAC9B,MAAMC,mBAAmB,GAAG,GAAG;AAE/B,MAAMC,WAAW,GAAG;EAClBC,eAAe,EAAE,wCAAwC;EACzDC,YAAY,EAAE,qCAAqC;EACnDC,uBAAuB,EAAE,gDAAgD;EACzEC,cAAc,EAAE;AAClB,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,wBAAwBA,CAAC;EAAEC,GAAG;EAAEC;AAAK,CAAC,EAAE;EACtD,MAAMC,KAAK,GAAG,IAAId,MAAM,CAACY,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AAM,EAAE;EACnC,MAAMC,OAAO,GAAGD,MAAM,EAAEE,IAAI,CAAC,CAAC;EAC9B,OAAOD,OAAO,GAAGA,OAAO,CAACE,KAAK,CAAC,GAAG,CAAC,GAAG,EAAE;AAC1C;;AAEA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASC,mBAAmBA,CAAC7E,OAAO,EAAE8E,OAAO,EAAE;EACpD;EACA,MAAMC,QAAQ,GAAG,EAAE;EAEnB,IAAID,OAAO,EAAE;IACX;IACA;IACAC,QAAQ,CAACC,IAAI,CACX;MACE5B,EAAE,EAAE,cAAc;MAClBC,KAAK,EAAE,eAAe;MACtB4B,OAAO,EAAE,GAAGjF,OAAO,gCAAgC8E,OAAO,EAAE;MAC5DI,SAAS,EAAE,KAAK;MAChBC,UAAU,EAAE,KAAK;MACjBC,KAAK,EAAE;QACLC,MAAM,EAAE,MAAM;QACdC,WAAW,EAAE,CAAC;QACdC,IAAI,EAAE;MACR;IACF,CAAC,EACD;MACEnC,EAAE,EAAE,YAAY;MAChBC,KAAK,EAAE,aAAa;MACpB4B,OAAO,EAAE,GAAGjF,OAAO,gCAAgC8E,OAAO,EAAE;MAC5DI,SAAS,EAAE,KAAK;MAChBC,UAAU,EAAE,KAAK;MACjBC,KAAK,EAAE;QACLC,MAAM,EAAE,kBAAkB;QAC1BC,WAAW,EAAE;MACf;IACF,CACF,CAAC;EACH;EAEA,OAAOP,QAAQ;AACjB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA","ignoreList":[]}
1
+ {"version":3,"file":"map.js","names":["InteractiveMap","createInteractPlugin","createMapStylesPlugin","createScaleBarPlugin","createSearchPlugin","maplibreProvider","centroid","OsGridRef","LatLon","processGeospatial","processLocation","DEFAULT_LAT","DEFAULT_LONG","COMPANY_SYMBOL_CODE","defaultData","VTS_OUTDOOR_URL","VTS_DARK_URL","VTS_BLACK_AND_WHITE_URL","VTS_AERIAL_URL","latLongToEastingNorthing","lat","long","point","toOsGrid","eastingNorthingToLatLong","easting","northing","latLong","toLatLon","latitude","longitude","latLongToOsGridRef","toString","osGridRefToLatLong","osGridRef","parse","getCoordinateGridRef","feature","geometry","type","coordinates","getCentroidGridRef","centre","defaultConfig","zoom","center","EVENTS","mapReady","interactMarkerChange","drawReady","drawCreated","drawEdited","drawCancelled","formSubmitFactory","buttons","onFormSubmit","e","submitter","HTMLButtonElement","includes","preventDefault","initMaps","config","assetPath","apiPath","data","locations","document","querySelectorAll","geospatials","length","form","closest","Array","from","addEventListener","forEach","location","index","geospatial","makeTileRequestTransformer","transformTileRequest","url","resourceType","startsWith","replace","window","origin","headers","encodeURIComponent","spritesPath","path","substring","createMap","mapId","initConfig","mapsConfig","logoAltText","interactPlugin","markerColor","outdoor","dark","interactionModes","multiSelect","map","enableFullscreen","autoColorScheme","mapProvider","behaviour","minZoom","maxZoom","containerHeight","enableZoomControls","transformRequest","plugins","mapStyles","id","label","thumbnail","logo","attribution","String","fromCodePoint","Date","getFullYear","backgroundColor","mapColorScheme","appColorScheme","osNamesURL","width","showMarker","units","centerMap","addMarker","flyTo","essential","getMapLayers","layers","trimmed","trim","split","getMapCountryLayers","country","datasets","push","geojson","showInKey","showInMenu","style","stroke","strokeWidth","fill"],"sources":["../../../src/client/javascripts/map.js"],"sourcesContent":["// @ts-expect-error - no types\nimport InteractiveMap from '@defra/interactive-map'\n// @ts-expect-error - no types\nimport createInteractPlugin from '@defra/interactive-map/plugins/interact'\n// @ts-expect-error - no types\nimport createMapStylesPlugin from '@defra/interactive-map/plugins/map-styles'\n// @ts-expect-error - no types\nimport createScaleBarPlugin from '@defra/interactive-map/plugins/scale-bar'\n// @ts-expect-error - no types\nimport createSearchPlugin from '@defra/interactive-map/plugins/search'\n// @ts-expect-error - no types\nimport maplibreProvider from '@defra/interactive-map/providers/maplibre'\nimport { centroid } from '@turf/centroid'\nimport OsGridRef, { LatLon } from 'geodesy/osgridref.js'\n\nimport { processGeospatial } from '~/src/client/javascripts/geospatial-map.js'\nimport { processLocation } from '~/src/client/javascripts/location-map.js'\n\n// Center of UK\nconst DEFAULT_LAT = 53.825564\nconst DEFAULT_LONG = -2.421975\nconst COMPANY_SYMBOL_CODE = 169\n\nconst defaultData = {\n VTS_OUTDOOR_URL: '/api/maps/vts/OS_VTS_3857_Outdoor.json',\n VTS_DARK_URL: '/api/maps/vts/OS_VTS_3857_Dark.json',\n VTS_BLACK_AND_WHITE_URL: '/api/maps/vts/OS_VTS_3857_Black_and_White.json',\n VTS_AERIAL_URL: '/api/maps/vts/esri-aerial.json'\n}\n\n/**\n * Converts lat long to easting and northing\n * @param {object} param\n * @param {number} param.lat\n * @param {number} param.long\n * @returns {{ easting: number, northing: number }}\n */\nexport function latLongToEastingNorthing({ lat, long }) {\n const point = new LatLon(lat, long)\n\n return point.toOsGrid()\n}\n\n/**\n * Converts easting and northing to lat long\n * @param {object} param\n * @param {number} param.easting\n * @param {number} param.northing\n * @returns {{ lat: number, long: number }}\n */\nexport function eastingNorthingToLatLong({ easting, northing }) {\n const point = new OsGridRef(easting, northing)\n const latLong = point.toLatLon()\n\n return { lat: latLong.latitude, long: latLong.longitude }\n}\n\n/**\n * Converts lat long to an ordnance survey grid reference\n * @param {object} param\n * @param {number} param.lat\n * @param {number} param.long\n * @returns {string}\n */\nexport function latLongToOsGridRef({ lat, long }) {\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n}\n\n/**\n * Converts an ordnance survey grid reference to lat long\n * @param {string} osGridRef\n * @returns {{ lat: number, long: number }}\n */\nexport function osGridRefToLatLong(osGridRef) {\n const point = OsGridRef.parse(osGridRef)\n const latLong = point.toLatLon()\n\n return { lat: latLong.latitude, long: latLong.longitude }\n}\n\n/**\n * Get the grid ref from the first coordinate of a long/lat feature\n * @param {Feature} feature\n */\nexport function getCoordinateGridRef(feature) {\n if (feature.geometry.type === 'Point') {\n const [long, lat] = feature.geometry.coordinates\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n } else if (feature.geometry.type === 'LineString') {\n const [long, lat] = feature.geometry.coordinates[0]\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n } else {\n const [long, lat] = feature.geometry.coordinates[0][0]\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n }\n}\n\n/**\n * Get the centroid grid ref from a long/lat feature\n * @param {Feature} feature\n */\nexport function getCentroidGridRef(feature) {\n if (feature.geometry.type === 'Point') {\n const [long, lat] = feature.geometry.coordinates\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n } else {\n const centre = centroid(feature)\n const [long, lat] = centre.geometry.coordinates\n const point = new LatLon(lat, long)\n\n return point.toOsGrid().toString()\n }\n}\n\n/** @type {InteractiveMapInitConfig} */\nexport const defaultConfig = {\n zoom: '6',\n center: [DEFAULT_LONG, DEFAULT_LAT]\n}\n\nexport const EVENTS = {\n mapReady: 'map:ready',\n interactMarkerChange: 'interact:markerchange',\n drawReady: 'draw:ready',\n drawCreated: 'draw:created',\n drawEdited: 'draw:edited',\n drawCancelled: 'draw:cancelled'\n}\n\n/**\n * Make a form submit handler that only allows submissions from allowed buttons\n * @param {HTMLButtonElement[]} buttons - the form buttons to allow submissions\n */\nexport function formSubmitFactory(buttons) {\n /**\n * The submit handler\n * @param {SubmitEvent} e\n */\n const onFormSubmit = function (e) {\n if (\n !(e.submitter instanceof HTMLButtonElement) ||\n !buttons.includes(e.submitter)\n ) {\n e.preventDefault()\n }\n }\n\n return onFormSubmit\n}\n\n/**\n * Initialise location maps\n * @param {Partial<MapsEnvironmentConfig>} config - the map configuration\n */\nexport function initMaps(config = {}) {\n const {\n assetPath = '/assets',\n apiPath = '/form/api',\n data = defaultData\n } = config\n const locations = document.querySelectorAll('.app-location-field')\n const geospatials = document.querySelectorAll('.app-geospatial-field')\n\n // TODO: Fix this in `interactive-map`\n // If there are location components on the page fix up the main form submit\n // handler so it doesn't fire when using the integrated map search feature\n if (locations.length) {\n const form = locations[0].closest('form')\n\n if (form === null) {\n return\n }\n\n const buttons = Array.from(form.querySelectorAll('button'))\n form.addEventListener('submit', formSubmitFactory(buttons), false)\n }\n\n if (geospatials.length) {\n const form = geospatials[0].closest('form')\n\n if (form === null) {\n return\n }\n\n const buttons = Array.from(form.querySelectorAll('button'))\n form.addEventListener('submit', formSubmitFactory(buttons), false)\n }\n\n locations.forEach((location, index) => {\n processLocation({ assetPath, apiPath, data }, location, index)\n })\n\n geospatials.forEach((geospatial, index) => {\n processGeospatial({ assetPath, apiPath, data }, geospatial, index)\n })\n}\n\n/**\n * OS API request proxy factory\n * @param {string} apiPath - the root API path\n */\nexport function makeTileRequestTransformer(apiPath) {\n /**\n * Proxy OS API requests via our server\n * @param {string} url - the request URL\n * @param {string} resourceType - the resource type\n */\n return function transformTileRequest(url, resourceType) {\n if (url.startsWith('https://api.os.uk')) {\n if (resourceType === 'Tile') {\n return {\n url: url.replace(\n 'https://api.os.uk/maps/vector/v1/vts',\n `${window.location.origin}${apiPath}`\n ),\n headers: {}\n }\n }\n\n if (resourceType !== 'Style') {\n return {\n url: `${apiPath}/map-proxy?url=${encodeURIComponent(url)}`,\n headers: {}\n }\n }\n }\n\n const spritesPath =\n 'https://raw.githubusercontent.com/OrdnanceSurvey/OS-Vector-Tile-API-Stylesheets/main'\n\n // Proxy sprite requests\n if (url.startsWith(spritesPath)) {\n const path = url.substring(spritesPath.length)\n return {\n url: `${apiPath}/maps/vts${path}`,\n headers: {}\n }\n }\n\n return { url, headers: {} }\n }\n}\n\n/**\n * Create a Defra map instance\n * @param {string} mapId - the map id\n * @param {InteractiveMapInitConfig} initConfig - the map initial configuration\n * @param {MapsEnvironmentConfig} mapsConfig - the map environment params\n */\nexport function createMap(mapId, initConfig, mapsConfig) {\n const { assetPath, apiPath, data = defaultData } = mapsConfig\n const logoAltText = 'Ordnance survey logo'\n const interactPlugin = createInteractPlugin({\n markerColor: { outdoor: '#ff0000', dark: '#00ff00' },\n interactionModes: ['placeMarker'],\n multiSelect: false\n })\n\n /** @type {InteractiveMap} */\n const map = new InteractiveMap(mapId, {\n enableFullscreen: true,\n autoColorScheme: false,\n mapProvider: maplibreProvider(),\n behaviour: 'inline',\n minZoom: 6,\n maxZoom: 18,\n containerHeight: '400px',\n enableZoomControls: true,\n transformRequest: makeTileRequestTransformer(apiPath),\n ...initConfig,\n plugins: [\n createMapStylesPlugin({\n mapStyles: [\n {\n id: 'outdoor',\n label: 'Outdoor',\n url: data.VTS_OUTDOOR_URL,\n thumbnail: `${assetPath}/interactive-map/assets/images/outdoor-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`,\n backgroundColor: '#f5f5f0'\n },\n {\n id: 'dark',\n label: 'Dark',\n url: data.VTS_DARK_URL,\n mapColorScheme: 'dark',\n appColorScheme: 'dark',\n thumbnail: `${assetPath}/interactive-map/assets/images/dark-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo-white.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`\n },\n {\n id: 'black-and-white',\n label: 'Black/White',\n url: data.VTS_BLACK_AND_WHITE_URL,\n thumbnail: `${assetPath}/interactive-map/assets/images/black-and-white-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/os-logo-black.svg`,\n logoAltText,\n attribution: `Contains OS data ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Crown copyright and database rights ${new Date().getFullYear()}`\n },\n {\n id: 'aerial',\n label: 'Aerial',\n url: data.VTS_AERIAL_URL,\n thumbnail: `${assetPath}/interactive-map/assets/images/aerial-map-thumb.jpg`,\n logo: `${assetPath}/interactive-map/assets/images/esri-logo.png`,\n logoAltText: 'Powered by Esri',\n attribution: `Tiles ${String.fromCodePoint(COMPANY_SYMBOL_CODE)} Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community ${new Date().getFullYear()}`\n }\n ]\n }),\n interactPlugin,\n createSearchPlugin({\n osNamesURL: `${apiPath}/geocode-proxy?query={query}`,\n width: '300px',\n showMarker: false\n }),\n createScaleBarPlugin({\n units: 'metric'\n }),\n ...(initConfig.plugins ?? [])\n ]\n })\n\n return { map, interactPlugin }\n}\n\n/**\n * Updates the marker position and moves the map view port the new location\n * @param {InteractiveMap} map - the map component instance (of InteractiveMap)\n * @param {MapLibreMap} mapProvider - the map provider instance (of MapLibreMap)\n * @param {MapCenter} center - the point\n */\nexport function centerMap(map, mapProvider, center) {\n // Move the 'location' marker to the new point\n map.addMarker('location', center)\n\n // Pan & zoom the map to the new valid location\n mapProvider.flyTo({\n center,\n zoom: 14,\n essential: true\n })\n}\n\n/**\n * Parse CSV string layers\n * @param {string | undefined} layers\n * @returns {string[]}\n */\nexport function getMapLayers(layers) {\n const trimmed = layers?.trim()\n return trimmed ? trimmed.split(',') : []\n}\n\n/**\n * Adds the country layers to a datasets array\n * @param {string} apiPath\n * @param {string} [country]\n */\nexport function getMapCountryLayers(apiPath, country) {\n /** @type {any[]} */\n const datasets = []\n\n if (country) {\n // Add the country bounds to the datasets array to show the valid area on the map\n // and provide feedback to the user when they add features outside of the bounds.\n datasets.push(\n {\n id: 'invalid-area',\n label: 'Invalid areas',\n geojson: `${apiPath}/maps/countries.geojson?omit=${country}`,\n showInKey: false,\n showInMenu: false,\n style: {\n stroke: 'gray',\n strokeWidth: 1,\n fill: 'rgba(211,211,211,0.8)'\n }\n },\n {\n id: 'valid-area',\n label: 'Valid areas',\n geojson: `${apiPath}/maps/countries.geojson?only=${country}`,\n showInKey: false,\n showInMenu: false,\n style: {\n stroke: 'rgba(0,112,60,1)',\n strokeWidth: 1\n }\n }\n )\n }\n\n return datasets\n}\n\n/**\n * @typedef {object} InteractiveMap - an instance of a InteractiveMap\n * @property {Function} on - register callback listeners to map events\n * @property {Function} addPanel - adds a new panel to the map\n * @property {Function} addMarker - adds/updates a marker\n * @property {Function} removeMarker - removes a marker\n * @property {Function} addButton - adds/updates a button\n * @property {Function} toggleButtonState - toggle the state of a button\n */\n\n/**\n * @typedef {object} MapLibreMap\n * @property {Function} flyTo - pans/zooms to a new location\n * @property {Function} fitBounds - fits the my to the new bounds\n */\n\n/**\n * @typedef {[number, number]} MapCenter - Map center point as [long, lat]\n */\n\n/**\n * @typedef {object} InteractiveMapInitConfig - additional config that can be provided to InteractiveMap\n * @property {string} zoom - the zoom level of the map\n * @property {MapCenter} center - the center point of the map\n * @property {{ id: string, coords: MapCenter }[]} [markers] - the markers to add to the map\n * @property {any[]} [plugins] - additional plugins\n */\n\n/**\n * @typedef {object} TileData\n * @property {string} VTS_OUTDOOR_URL - the outdoor tile URL\n * @property {string} VTS_DARK_URL - the dark tile URL\n * @property {string} VTS_BLACK_AND_WHITE_URL - the black and white tile URL\n * @property {string} VTS_AERIAL_URL - the aerial tile URL\n */\n\n/**\n * @typedef {object} MapsEnvironmentConfig\n * @property {string} assetPath - the root asset path\n * @property {string} apiPath - the root API path\n * @property {TileData} data - the tile data config\n */\n\n/**\n * @typedef {object} UIManagerOptions\n * @property {string} [geometryTypes] - the CSV list of geometry types that a user can create\n */\n\n/**\n * @import { Feature } from '~/src/server/plugins/engine/types.js'\n */\n\n/**\n * Supported language codes\n * @typedef {('en-GB'|'cy')} LanguageCode\n */\n"],"mappings":"AAAA;AACA,OAAOA,cAAc,MAAM,wBAAwB;AACnD;AACA,OAAOC,oBAAoB,MAAM,yCAAyC;AAC1E;AACA,OAAOC,qBAAqB,MAAM,2CAA2C;AAC7E;AACA,OAAOC,oBAAoB,MAAM,0CAA0C;AAC3E;AACA,OAAOC,kB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K,EAAE,aAAa;MACpB4B,OAAO,EAAE,GAAGjF,OAAO,gCAAgC8E,OAAO,EAAE;MAC5DI,SAAS,EAAE,KAAK;MAChBC,UAAU,EAAE,KAAK;MACjBC,KAAK,EAAE;QACLC,MAAM,EAAE,kBAAkB;QAC1BC,WAAW,EAAE;MACf;IACF,CACF,CAAC;EACH;EAEA,OAAOP,QAAQ;AACjB;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;;AAEA;AACA;AACA;AACA;;AAEA;AACA;AACA;;AAEA;AACA;AACA;AACA","ignoreList":[]}
@@ -171,7 +171,7 @@ export class ComponentCollection {
171
171
 
172
172
  // Update error with parent title
173
173
  if (translator && parent) {
174
- error.local.title ??= translator.tComponent(parent, 'title');
174
+ error.local.title ??= getTranslatedLabel(parent.def, translator);
175
175
  } else {
176
176
  error.local.title ??= parent?.label;
177
177
  }
@@ -1 +1 @@
1
- {"version":3,"file":"ComponentCollection.js","names":["joi","isFormState","isFormValue","createComponent","getTranslatedLabel","getErrors","buildLanguageMessages","validationOptions","opts","ComponentCollection","page","parent","components","fields","guidance","formSchema","stateSchema","constructor","defs","props","schema","map","def","filter","component","isFormComponent","object","required","field","collection","name","concat","keys","peers","and","isPresent","custom","flatMap","getFormDataFromState","state","payload","forEach","Object","assign","getFormValueFromState","value","entries","key","split","pop","getStateFromValidForm","getContextValueFromState","context","translator","errors","getFieldErrors","getViewErrors","getViewModel","result","type","model","overrideParentTitle","error","isErrorContext","local","title","missing","path","find","item","shift","child","label","length","tComponent","validate","messages","t","undefined","labelOverrides","messagesOverride","getValidationMessagesOverride","subField","translatedSubLabel","patchedSchema","subFieldMessages","fieldDef","translatedLabel","fieldMessages","details","language","callback","list","fieldErrors","push"],"sources":["../../../../../src/server/plugins/engine/components/ComponentCollection.ts"],"sourcesContent":["import { type ComponentDef } from '@defra/forms-model'\nimport joi, {\n type CustomValidator,\n type ErrorReportCollection,\n type ObjectSchema\n} from 'joi'\n\nimport {\n isFormState,\n isFormValue\n} from '~/src/server/plugins/engine/components/FormComponent.js'\nimport {\n createComponent,\n type Component,\n type Field,\n type Guidance\n} from '~/src/server/plugins/engine/components/helpers/components.js'\nimport { getTranslatedLabel } from '~/src/server/plugins/engine/components/helpers/index.js'\nimport {\n type ComponentViewModel,\n type RenderContext\n} from '~/src/server/plugins/engine/components/types.js'\nimport { getErrors } from '~/src/server/plugins/engine/helpers.js'\nimport { type Translator } from '~/src/server/plugins/engine/i18n/types.js'\nimport { type FormModel } from '~/src/server/plugins/engine/models/index.js'\nimport { type PageControllerClass } from '~/src/server/plugins/engine/pageControllers/helpers/pages.js'\nimport {\n buildLanguageMessages,\n validationOptions as opts\n} from '~/src/server/plugins/engine/pageControllers/validationOptions.js'\nimport {\n type FormPayload,\n type FormState,\n type FormSubmissionError,\n type FormSubmissionState,\n type FormValidationResult\n} from '~/src/server/plugins/engine/types.js'\n\nexport class ComponentCollection {\n page?: PageControllerClass\n parent?: Component\n\n components: Component[]\n fields: Field[]\n guidance: Guidance[]\n\n formSchema: ObjectSchema<FormPayload>\n stateSchema: ObjectSchema<FormSubmissionState>\n\n constructor(\n defs: ComponentDef[],\n props: {\n page?: PageControllerClass\n parent?: Component\n model: FormModel\n },\n schema?: {\n /**\n * Defines an all-or-nothing relationship between keys where if one\n * of the peers is present, all of them are required as well\n */\n peers?: string[]\n\n /**\n * Defines a custom validation rule for the object schema\n */\n custom?: CustomValidator\n }\n ) {\n const components = defs.map((def) => createComponent(def, props))\n\n const fields = components.filter(\n (component): component is Field => component.isFormComponent\n )\n\n const guidance = components.filter(\n (component): component is Guidance => !component.isFormComponent\n )\n\n let formSchema = joi.object<FormPayload>().required()\n let stateSchema = joi.object<FormSubmissionState>().required()\n\n // Add each field or concat collection\n for (const field of fields) {\n const { collection, name } = field\n\n formSchema = collection\n ? formSchema.concat(collection.formSchema)\n : formSchema.keys({ [name]: field.formSchema })\n\n stateSchema = collection\n ? stateSchema.concat(collection.stateSchema)\n : stateSchema.keys({ [name]: field.stateSchema })\n }\n\n if (schema?.peers) {\n formSchema = formSchema.and(...schema.peers, {\n isPresent: isFormValue\n })\n }\n\n if (schema?.custom) {\n formSchema = formSchema.custom(schema.custom)\n }\n\n this.page = props.page\n this.parent = props.parent\n\n this.components = components\n this.fields = fields\n this.guidance = guidance\n\n this.formSchema = formSchema\n this.stateSchema = stateSchema\n }\n\n get keys() {\n return this.fields.flatMap((field) => {\n const { name, collection } = field\n\n if (collection) {\n const { fields } = collection\n return [name, ...fields.map(({ name }) => name)]\n }\n\n return [name]\n })\n }\n\n getFormDataFromState(state: FormSubmissionState) {\n const payload: FormPayload = {}\n\n this.fields.forEach((component) => {\n Object.assign(payload, component.getFormDataFromState(state))\n })\n\n return payload\n }\n\n getFormValueFromState(state: FormSubmissionState) {\n const payload: FormPayload = {}\n\n // Remove name prefix for formatted value\n for (const [name, value] of Object.entries(\n this.getFormDataFromState(state)\n )) {\n const key = name.split('__').pop()\n if (!key) {\n continue\n }\n\n payload[key] = value\n }\n\n return payload\n }\n\n getStateFromValidForm(payload: FormPayload) {\n const state: FormState = {}\n\n this.fields.forEach((component) => {\n Object.assign(state, component.getStateFromValidForm(payload))\n })\n\n return state\n }\n\n getContextValueFromState(state: FormSubmissionState) {\n const context: FormState = {}\n\n for (const component of this.fields) {\n context[component.name] = component.getContextValueFromState(state)\n }\n\n return context\n }\n\n /**\n * Get all errors for all fields in this collection\n */\n getErrors(\n translator: Translator,\n errors?: FormSubmissionError[]\n ): FormSubmissionError[] | undefined {\n return this.getFieldErrors(\n (field) => field.getErrors(translator, errors),\n errors\n )\n }\n\n /**\n * Get view errors for all fields in this collection.\n * For most fields this means filtering to the first error in the list.\n * Composite fields like UKAddress can choose to return more than one error.\n */\n getViewErrors(\n translator: Translator,\n errors?: FormSubmissionError[]\n ): FormSubmissionError[] | undefined {\n return this.getFieldErrors(\n (field) => field.getViewErrors(translator, errors),\n errors\n )\n }\n\n getViewModel(context: RenderContext) {\n const { components } = this\n\n const result: ComponentViewModel[] = components.map((component) => {\n const { isFormComponent, type } = component\n\n const model = component.getViewModel(context)\n\n return { type, isFormComponent, model }\n })\n\n return result\n }\n\n overrideParentTitle(\n formSchema: joi.ObjectSchema<FormPayload>,\n translator: Translator | undefined\n ) {\n // Add parent field title to collection field errors\n return formSchema.error((errors) => {\n return errors.flatMap((error) => {\n if (!isErrorContext(error.local) || error.local.title) {\n return error\n }\n\n // Use field key or first missing child field\n let { missing, key = missing?.[0] } = error.local\n\n // But avoid numeric key used by array payloads\n if (typeof key === 'number') {\n key = error.path[0]\n }\n\n // Find the parent field\n const parent = this.fields.find(\n (item) => item.name === key?.split('__').shift()\n )\n\n // Find the child field\n const child = (parent?.collection?.fields ?? this.fields).find(\n (item) => item.name === key\n )\n\n // Update error with child label\n if (child && (!error.local.label || error.local.label === 'value')) {\n error.local.label = child.title\n }\n\n // Fix error summary links for missing fields\n if (missing?.length) {\n error.path = missing\n error.local.key = missing[0]\n }\n\n // Update error with parent title\n if (translator && parent) {\n error.local.title ??= translator.tComponent(\n parent as ComponentDef,\n 'title'\n )\n } else {\n error.local.title ??= parent?.label\n }\n\n return error\n })\n })\n }\n\n /**\n * Validate form payload\n */\n validate(\n value: FormPayload = {},\n translator?: Translator\n ): FormValidationResult<FormPayload> {\n const messages = translator\n ? buildLanguageMessages(translator.t)\n : undefined\n\n // When translating, override Joi labels (and custom schema messages where\n // needed) so #label/#title in message templates resolve in the correct language.\n let schema = this.formSchema\n // Add parent field title to collection field errors\n schema = this.overrideParentTitle(schema, translator)\n\n if (translator) {\n const { t } = translator\n const labelOverrides: Record<string, joi.Schema> = {}\n\n for (const field of this.fields) {\n if (field.collection) {\n // Composite field: translate each sub-field's label using the key constant\n // (e.g. 'components.addressField.line1' → \"Llinell cyfeiriad 1\") and apply\n // any field-type-specific message overrides (e.g. objectMissing for dates).\n const messagesOverride =\n field.getValidationMessagesOverride(translator)\n for (const subField of field.collection.fields) {\n const translatedSubLabel = t(subField.title) || subField.label\n let patchedSchema = subField.formSchema.label(translatedSubLabel)\n const subFieldMessages = messagesOverride\n ? messagesOverride[subField.name]\n : undefined\n if (subFieldMessages) {\n patchedSchema = patchedSchema.messages(subFieldMessages)\n }\n labelOverrides[subField.name] = patchedSchema\n }\n } else {\n const fieldDef = field.def\n const translatedLabel = getTranslatedLabel(fieldDef, translator)\n const messagesOverride =\n field.getValidationMessagesOverride(translator)\n let patchedSchema = field.formSchema\n if (translatedLabel && translatedLabel !== field.label) {\n patchedSchema = patchedSchema.label(translatedLabel)\n }\n const fieldMessages = messagesOverride\n ? messagesOverride[field.name]\n : undefined\n if (fieldMessages) {\n patchedSchema = patchedSchema.messages(fieldMessages)\n }\n if (patchedSchema !== field.formSchema) {\n labelOverrides[field.name] = patchedSchema\n }\n }\n }\n\n if (Object.keys(labelOverrides).length) {\n schema = schema.keys(labelOverrides)\n }\n }\n\n const result = schema.validate(value, {\n ...opts,\n ...(messages && { messages })\n })\n\n const details = result.error?.details\n const language = translator?.language\n\n return {\n value: (result.value ?? {}) as typeof value,\n errors:\n this.page?.getErrors(details, language) ?? getErrors(language, details)\n }\n }\n\n /**\n * Helper to get errors from all fields\n */\n private getFieldErrors(\n callback: (field: Field) => FormSubmissionError[] | undefined,\n errors?: FormSubmissionError[]\n ): FormSubmissionError[] | undefined {\n const { fields } = this\n\n if (!errors?.length) {\n return\n }\n\n const list: FormSubmissionError[] = []\n\n for (const field of fields) {\n const fieldErrors = callback(field)\n\n if (fieldErrors?.length) {\n list.push(...fieldErrors)\n }\n }\n\n if (!list.length) {\n return\n }\n\n return list\n }\n}\n\n/**\n * Check for field local state\n */\nexport function isErrorContext(\n value?: unknown\n): value is ErrorReportCollection['local'] {\n return isFormState(value) && typeof value.label === 'string'\n}\n"],"mappings":"AACA,OAAOA,GAAG,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;IAEA,IAAI,CAACD,IAAI,CAACnB,MAAM,EAAE;MAChB;IACF;IAEA,OAAOmB,IAAI;EACb;AACF;;AAEA;AACA;AACA;AACA,OAAO,SAAS7B,cAAcA,CAC5BlB,KAAe,EAC0B;EACzC,OAAO5C,WAAW,CAAC4C,KAAK,CAAC,IAAI,OAAOA,KAAK,CAAC2B,KAAK,KAAK,QAAQ;AAC9D","ignoreList":[]}
1
+ {"version":3,"file":"ComponentCollection.js","names":["joi","isFormState","isFormValue","createComponent","getTranslatedLabel","getErrors","buildLanguageMessages","validationOptions","opts","ComponentCollection","page","parent","components","fields","guidance","formSchema","stateSchema","constructor","defs","props","schema","map","def","filter","component","isFormComponent","object","required","field","collection","name","concat","keys","peers","and","isPresent","custom","flatMap","getFormDataFromState","state","payload","forEach","Object","assign","getFormValueFromState","value","entries","key","split","pop","getStateFromValidForm","getContextValueFromState","context","translator","errors","getFieldErrors","getViewErrors","getViewModel","result","type","model","overrideParentTitle","error","isErrorContext","local","title","missing","path","find","item","shift","child","label","length","validate","messages","t","undefined","labelOverrides","messagesOverride","getValidationMessagesOverride","subField","translatedSubLabel","patchedSchema","subFieldMessages","fieldDef","translatedLabel","fieldMessages","details","language","callback","list","fieldErrors","push"],"sources":["../../../../../src/server/plugins/engine/components/ComponentCollection.ts"],"sourcesContent":["import { type ComponentDef } from '@defra/forms-model'\nimport joi, {\n type CustomValidator,\n type ErrorReportCollection,\n type ObjectSchema\n} from 'joi'\n\nimport {\n isFormState,\n isFormValue\n} from '~/src/server/plugins/engine/components/FormComponent.js'\nimport {\n createComponent,\n type Component,\n type Field,\n type Guidance\n} from '~/src/server/plugins/engine/components/helpers/components.js'\nimport { getTranslatedLabel } from '~/src/server/plugins/engine/components/helpers/index.js'\nimport {\n type ComponentViewModel,\n type RenderContext\n} from '~/src/server/plugins/engine/components/types.js'\nimport { getErrors } from '~/src/server/plugins/engine/helpers.js'\nimport { type Translator } from '~/src/server/plugins/engine/i18n/types.js'\nimport { type FormModel } from '~/src/server/plugins/engine/models/index.js'\nimport { type PageControllerClass } from '~/src/server/plugins/engine/pageControllers/helpers/pages.js'\nimport {\n buildLanguageMessages,\n validationOptions as opts\n} from '~/src/server/plugins/engine/pageControllers/validationOptions.js'\nimport {\n type FormPayload,\n type FormState,\n type FormSubmissionError,\n type FormSubmissionState,\n type FormValidationResult\n} from '~/src/server/plugins/engine/types.js'\n\nexport class ComponentCollection {\n page?: PageControllerClass\n parent?: Component\n\n components: Component[]\n fields: Field[]\n guidance: Guidance[]\n\n formSchema: ObjectSchema<FormPayload>\n stateSchema: ObjectSchema<FormSubmissionState>\n\n constructor(\n defs: ComponentDef[],\n props: {\n page?: PageControllerClass\n parent?: Component\n model: FormModel\n },\n schema?: {\n /**\n * Defines an all-or-nothing relationship between keys where if one\n * of the peers is present, all of them are required as well\n */\n peers?: string[]\n\n /**\n * Defines a custom validation rule for the object schema\n */\n custom?: CustomValidator\n }\n ) {\n const components = defs.map((def) => createComponent(def, props))\n\n const fields = components.filter(\n (component): component is Field => component.isFormComponent\n )\n\n const guidance = components.filter(\n (component): component is Guidance => !component.isFormComponent\n )\n\n let formSchema = joi.object<FormPayload>().required()\n let stateSchema = joi.object<FormSubmissionState>().required()\n\n // Add each field or concat collection\n for (const field of fields) {\n const { collection, name } = field\n\n formSchema = collection\n ? formSchema.concat(collection.formSchema)\n : formSchema.keys({ [name]: field.formSchema })\n\n stateSchema = collection\n ? stateSchema.concat(collection.stateSchema)\n : stateSchema.keys({ [name]: field.stateSchema })\n }\n\n if (schema?.peers) {\n formSchema = formSchema.and(...schema.peers, {\n isPresent: isFormValue\n })\n }\n\n if (schema?.custom) {\n formSchema = formSchema.custom(schema.custom)\n }\n\n this.page = props.page\n this.parent = props.parent\n\n this.components = components\n this.fields = fields\n this.guidance = guidance\n\n this.formSchema = formSchema\n this.stateSchema = stateSchema\n }\n\n get keys() {\n return this.fields.flatMap((field) => {\n const { name, collection } = field\n\n if (collection) {\n const { fields } = collection\n return [name, ...fields.map(({ name }) => name)]\n }\n\n return [name]\n })\n }\n\n getFormDataFromState(state: FormSubmissionState) {\n const payload: FormPayload = {}\n\n this.fields.forEach((component) => {\n Object.assign(payload, component.getFormDataFromState(state))\n })\n\n return payload\n }\n\n getFormValueFromState(state: FormSubmissionState) {\n const payload: FormPayload = {}\n\n // Remove name prefix for formatted value\n for (const [name, value] of Object.entries(\n this.getFormDataFromState(state)\n )) {\n const key = name.split('__').pop()\n if (!key) {\n continue\n }\n\n payload[key] = value\n }\n\n return payload\n }\n\n getStateFromValidForm(payload: FormPayload) {\n const state: FormState = {}\n\n this.fields.forEach((component) => {\n Object.assign(state, component.getStateFromValidForm(payload))\n })\n\n return state\n }\n\n getContextValueFromState(state: FormSubmissionState) {\n const context: FormState = {}\n\n for (const component of this.fields) {\n context[component.name] = component.getContextValueFromState(state)\n }\n\n return context\n }\n\n /**\n * Get all errors for all fields in this collection\n */\n getErrors(\n translator: Translator,\n errors?: FormSubmissionError[]\n ): FormSubmissionError[] | undefined {\n return this.getFieldErrors(\n (field) => field.getErrors(translator, errors),\n errors\n )\n }\n\n /**\n * Get view errors for all fields in this collection.\n * For most fields this means filtering to the first error in the list.\n * Composite fields like UKAddress can choose to return more than one error.\n */\n getViewErrors(\n translator: Translator,\n errors?: FormSubmissionError[]\n ): FormSubmissionError[] | undefined {\n return this.getFieldErrors(\n (field) => field.getViewErrors(translator, errors),\n errors\n )\n }\n\n getViewModel(context: RenderContext) {\n const { components } = this\n\n const result: ComponentViewModel[] = components.map((component) => {\n const { isFormComponent, type } = component\n\n const model = component.getViewModel(context)\n\n return { type, isFormComponent, model }\n })\n\n return result\n }\n\n overrideParentTitle(\n formSchema: joi.ObjectSchema<FormPayload>,\n translator: Translator | undefined\n ) {\n // Add parent field title to collection field errors\n return formSchema.error((errors) => {\n return errors.flatMap((error) => {\n if (!isErrorContext(error.local) || error.local.title) {\n return error\n }\n\n // Use field key or first missing child field\n let { missing, key = missing?.[0] } = error.local\n\n // But avoid numeric key used by array payloads\n if (typeof key === 'number') {\n key = error.path[0]\n }\n\n // Find the parent field\n const parent = this.fields.find(\n (item) => item.name === key?.split('__').shift()\n )\n\n // Find the child field\n const child = (parent?.collection?.fields ?? this.fields).find(\n (item) => item.name === key\n )\n\n // Update error with child label\n if (child && (!error.local.label || error.local.label === 'value')) {\n error.local.label = child.title\n }\n\n // Fix error summary links for missing fields\n if (missing?.length) {\n error.path = missing\n error.local.key = missing[0]\n }\n\n // Update error with parent title\n if (translator && parent) {\n error.local.title ??= getTranslatedLabel(parent.def, translator)\n } else {\n error.local.title ??= parent?.label\n }\n\n return error\n })\n })\n }\n\n /**\n * Validate form payload\n */\n validate(\n value: FormPayload = {},\n translator?: Translator\n ): FormValidationResult<FormPayload> {\n const messages = translator\n ? buildLanguageMessages(translator.t)\n : undefined\n\n // When translating, override Joi labels (and custom schema messages where\n // needed) so #label/#title in message templates resolve in the correct language.\n let schema = this.formSchema\n // Add parent field title to collection field errors\n schema = this.overrideParentTitle(schema, translator)\n\n if (translator) {\n const { t } = translator\n const labelOverrides: Record<string, joi.Schema> = {}\n\n for (const field of this.fields) {\n if (field.collection) {\n // Composite field: translate each sub-field's label using the key constant\n // (e.g. 'components.addressField.line1' → \"Llinell cyfeiriad 1\") and apply\n // any field-type-specific message overrides (e.g. objectMissing for dates).\n const messagesOverride =\n field.getValidationMessagesOverride(translator)\n for (const subField of field.collection.fields) {\n const translatedSubLabel = t(subField.title) || subField.label\n let patchedSchema = subField.formSchema.label(translatedSubLabel)\n const subFieldMessages = messagesOverride\n ? messagesOverride[subField.name]\n : undefined\n if (subFieldMessages) {\n patchedSchema = patchedSchema.messages(subFieldMessages)\n }\n labelOverrides[subField.name] = patchedSchema\n }\n } else {\n const fieldDef = field.def\n const translatedLabel = getTranslatedLabel(fieldDef, translator)\n const messagesOverride =\n field.getValidationMessagesOverride(translator)\n let patchedSchema = field.formSchema\n if (translatedLabel && translatedLabel !== field.label) {\n patchedSchema = patchedSchema.label(translatedLabel)\n }\n const fieldMessages = messagesOverride\n ? messagesOverride[field.name]\n : undefined\n if (fieldMessages) {\n patchedSchema = patchedSchema.messages(fieldMessages)\n }\n if (patchedSchema !== field.formSchema) {\n labelOverrides[field.name] = patchedSchema\n }\n }\n }\n\n if (Object.keys(labelOverrides).length) {\n schema = schema.keys(labelOverrides)\n }\n }\n\n const result = schema.validate(value, {\n ...opts,\n ...(messages && { messages })\n })\n\n const details = result.error?.details\n const language = translator?.language\n\n return {\n value: (result.value ?? {}) as typeof value,\n errors:\n this.page?.getErrors(details, language) ?? getErrors(language, details)\n }\n }\n\n /**\n * Helper to get errors from all fields\n */\n private getFieldErrors(\n callback: (field: Field) => FormSubmissionError[] | undefined,\n errors?: FormSubmissionError[]\n ): FormSubmissionError[] | undefined {\n const { fields } = this\n\n if (!errors?.length) {\n return\n }\n\n const list: FormSubmissionError[] = []\n\n for (const field of fields) {\n const fieldErrors = callback(field)\n\n if (fieldErrors?.length) {\n list.push(...fieldErrors)\n }\n }\n\n if (!list.length) {\n return\n }\n\n return list\n }\n}\n\n/**\n * Check for field local state\n */\nexport function isErrorContext(\n value?: unknown\n): value is ErrorReportCollection['local'] {\n return isFormState(value) && typeof value.label === 'string'\n}\n"],"mappings":"AACA,OAAOA,GAAG,MAIH,KAAK;AAEZ,SACEC,WAAW,EACXC,WAAW;AAEb,SACEC,eAAe;AAKjB,SAASC,kBAAkB;AAK3B,SAASC,SAAS;AAIlB,SACEC,qBAAqB,EACrBC,iBAAiB,IAAIC,IAAI;AAU3B,OAAO,MAAMC,mBAAmB,CAAC;EAC/BC,IAAI;EACJC,MAAM;EAENC,UAAU;EACVC,MAAM;EACNC,QAAQ;EAERC,UAAU;EACVC,WAAW;EAEXC,WAAWA,CACTC,IAAoB,EACpBC,KAIC,EACDC,MAWC,EACD;IACA,MAAMR,UAAU,GAAGM,IAAI,CAACG,GAAG,CAAEC,GAAG,IAAKnB,eAAe,CAACmB,GAAG,EAAEH,KAAK,CAAC,CAAC;IAEjE,MAAMN,MAAM,GAAG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,CAAC;IAC9B,CAAC,CAAC;IAEF,MAAMa,OAAO,GAAG9B,MAAM,CAACI,KAAK,EAAE0B,OAAO;IACrC,MAAMC,QAAQ,GAAGpC,UAAU,EAAEoC,QAAQ;IAErC,OAAO;MACL5C,KAAK,EAAGa,MAAM,CAACb,KAAK,IAAI,CAAC,CAAkB;MAC3CS,MAAM,EACJ,IAAI,CAAC5C,IAAI,EAAEL,SAAS,CAACmF,OAAO,EAAEC,QAAQ,CAAC,IAAIpF,SAAS,CAACoF,QAAQ,EAAED,OAAO;IAC1E,CAAC;EACH;;EAEA;AACF;AACA;EACUjC,cAAcA,CACpBmC,QAA6D,EAC7DpC,MAA8B,EACK;IACnC,MAAM;MAAEzC;IAAO,CAAC,GAAG,IAAI;IAEvB,IAAI,CAACyC,MAAM,EAAEmB,MAAM,EAAE;MACnB;IACF;IAEA,MAAMkB,IAA2B,GAAG,EAAE;IAEtC,KAAK,MAAM/D,KAAK,IAAIf,MAAM,EAAE;MAC1B,MAAM+E,WAAW,GAAGF,QAAQ,CAAC9D,KAAK,CAAC;MAEnC,IAAIgE,WAAW,EAAEnB,MAAM,EAAE;QACvBkB,IAAI,CAACE,IAAI,CAAC,GAAGD,WAAW,CAAC;MAC3B;IACF;IAEA,IAAI,CAACD,IAAI,CAAClB,MAAM,EAAE;MAChB;IACF;IAEA,OAAOkB,IAAI;EACb;AACF;;AAEA;AACA;AACA;AACA,OAAO,SAAS5B,cAAcA,CAC5BlB,KAAe,EAC0B;EACzC,OAAO5C,WAAW,CAAC4C,KAAK,CAAC,IAAI,OAAOA,KAAK,CAAC2B,KAAK,KAAK,QAAQ;AAC9D","ignoreList":[]}
@@ -1,10 +1,10 @@
1
1
  import Bourne from '@hapi/bourne';
2
2
  import { booleanWithin } from '@turf/boolean-within';
3
3
  import { point } from '@turf/helpers';
4
- // @ts-expect-error - no types
5
4
  import OsGridRef from 'geodesy/osgridref.js';
6
5
  import JoiBase from 'joi';
7
- import { countries } from "../../../map/routes/index.js";
6
+ import { countriesValidate } from "../../../map/routes/index.js";
7
+ import { CountryMap } from "../../../map/types.js";
8
8
  const Joi = JoiBase.extend({
9
9
  type: 'array',
10
10
  base: JoiBase.array(),
@@ -117,7 +117,7 @@ export function getGeospatialSchema(def) {
117
117
  return applySchemaConstraints(Joi.array().items(featureSchema).unique('id'), def);
118
118
  }
119
119
  const validateCountryBounds = (value, helpers) => {
120
- const countryFeature = countries.features.find(feature => feature.id === country);
120
+ const countryFeature = countriesValidate.features.find(feature => feature.id === CountryMap[country]);
121
121
  if (!countryFeature) {
122
122
  // eslint-disable-next-line @typescript-eslint/no-unsafe-return
123
123
  return value;
@@ -136,7 +136,7 @@ export function getGeospatialSchema(def) {
136
136
  }
137
137
  export function getEastingNorthingCountryValidator(field, country) {
138
138
  const validateCountryBounds = (value, helpers) => {
139
- const countryFeature = countries.features.find(feature => feature.id === country);
139
+ const countryFeature = countriesValidate.features.find(feature => feature.id === CountryMap[country]);
140
140
  if (!countryFeature) {
141
141
  // eslint-disable-next-line @typescript-eslint/no-unsafe-return
142
142
  return value;
@@ -1 +1 @@
1
- {"version":3,"file":"geospatial.js","names":["Bourne","booleanWithin","point","OsGridRef","JoiBase","countries","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","determineLimits","def","isOptional","schema","constraints","limits","length","max","applySchemaConstraints","options","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 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 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\nexport function determineLimits(\n def: GeospatialFieldComponent,\n isOptional: boolean\n) {\n const { schema: constraints } = def\n const limits: { min?: number; max?: number; length?: number } = {}\n if (typeof constraints?.length === 'number') {\n limits.length = constraints.length\n } else {\n if (typeof constraints?.min === 'number') {\n limits.min = constraints.min\n } else if (!isOptional) {\n limits.min = 1\n }\n\n limits.max = typeof constraints?.max === 'number' ? constraints.max : 50\n }\n return limits\n}\n\nfunction applySchemaConstraints(\n schema: JoiBase.ArraySchema<Feature[]>,\n def: GeospatialFieldComponent\n) {\n const { options } = def\n const isOptional = options.required === false\n\n const limits = determineLimits(def, isOptional)\n\n if (limits.length !== undefined) {\n schema = schema.length(limits.length)\n }\n if (limits.min !== undefined) {\n schema = schema.min(limits.min)\n }\n if (limits.max !== undefined) {\n schema = schema.max(limits.max)\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\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\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":"AAIA,OAAOA,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,GAAG,GAAGF,OAAO,CAACG,MAAM,CAAC;EACzBC,IAAI,EAAE,OAAO;EACbC,IAAI,EAAEL,OAAO,CAACM,KAAK,CAAC,CAAC;EACrBC,QAAQ,EAAE;IACR,oBAAoB,EAAE;EACxB,CAAC;EACDC,MAAM,EAAE;IACNC,IAAI,EAAE,QAAQ;IACdC,MAAMA,CAACC,KAAK,EAAEC,OAAO,EAAE;MACrB,IAAI,OAAOD,KAAK,KAAK,QAAQ,EAAE;QAC7B,MAAME,OAAO,GAAGF,KAAK,CAACG,IAAI,CAAC,CAAC;QAC5B,IAAID,OAAO,KAAK,EAAE,IAAIA,OAAO,KAAK,IAAI,EAAE;UACtC,OAAO;YACLF,KAAK,EAAEI;UACT,CAAC;QACH;QAEA,IAAI;UACF;UACA,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,GAAG,IAAIrE,SAAS,CAC3BmE,eAAe,CAACG,OAAO,EACvBH,eAAe,CAACI,QAClB,CAAC;IACD,MAAMC,OAAO,GAAGH,OAAO,CAACI,QAAQ,CAAC,CAAC;IAClC,MAAMC,KAAK,GAAG3E,KAAK,CAAC,CAACyE,OAAO,CAACG,SAAS,EAAEH,OAAO,CAACI,QAAQ,CAAC,CAAC;IAC1D,MAAMC,MAAM,GAAG/E,aAAa,CAAC4E,KAAK,EAAEd,cAAc,CAAC;IAEnD,IAAI,CAACiB,MAAM,EAAE;MACX,OAAOhE,OAAO,CAACO,KAAK,CAClB,YAAY,EACZ;QACEoC;MACF,CAAC,EACD;QAAEsB,IAAI,EAAE,CAACZ,KAAK,CAACa,IAAI;MAAE,CACvB,CAAC;IACH;;IAEA;IACA,OAAOnE,KAAK;EACd,CAAC;EAED,OAAO+C,qBAAqB;AAC9B","ignoreList":[]}
1
+ {"version":3,"file":"geospatial.js","names":["Bourne","booleanWithin","point","OsGridRef","JoiBase","countriesValidate","CountryMap","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","determineLimits","def","isOptional","schema","constraints","limits","length","max","applySchemaConstraints","options","optional","getGeospatialSchema","country","countries","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 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'\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 { countriesValidate } from '~/src/server/plugins/map/routes/index.js'\nimport { CountryMap } from '~/src/server/plugins/map/types.js'\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\nexport function determineLimits(\n def: GeospatialFieldComponent,\n isOptional: boolean\n) {\n const { schema: constraints } = def\n const limits: { min?: number; max?: number; length?: number } = {}\n if (typeof constraints?.length === 'number') {\n limits.length = constraints.length\n } else {\n if (typeof constraints?.min === 'number') {\n limits.min = constraints.min\n } else if (!isOptional) {\n limits.min = 1\n }\n\n limits.max = typeof constraints?.max === 'number' ? constraints.max : 50\n }\n return limits\n}\n\nfunction applySchemaConstraints(\n schema: JoiBase.ArraySchema<Feature[]>,\n def: GeospatialFieldComponent\n) {\n const { options } = def\n const isOptional = options.required === false\n\n const limits = determineLimits(def, isOptional)\n\n if (limits.length !== undefined) {\n schema = schema.length(limits.length)\n }\n if (limits.min !== undefined) {\n schema = schema.min(limits.min)\n }\n if (limits.max !== undefined) {\n schema = schema.max(limits.max)\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 = countriesValidate.features.find(\n (feature) => feature.id === CountryMap[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\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 = countriesValidate.features.find(\n (feature) => feature.id === CountryMap[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\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":"AAIA,OAAOA,MAAM,MAAM,cAAc;AACjC,SAASC,aAAa,QAAQ,sBAAsB;AACpD,SAASC,KAAK,QAAQ,eAAe;AACrC,OAAOC,SAAS,MAAM,sBAAsB;AAC5C,OAAOC,OAAO,MAAgC,KAAK;AAUnD,SAASC,iBAAiB;AAC1B,SAASC,UAAU;AAEnB,MAAMC,GAAG,GAAGH,OAAO,CAACI,MAAM,CAAC;EACzBC,IAAI,EAAE,OAAO;EACbC,IAAI,EAAEN,OAAO,CAACO,KAAK,CAAC,CAAC;EACrBC,QAAQ,EAAE;IACR,oBAAoB,EAAE;EACxB,CAAC;EACDC,MAAM,EAAE;IACNC,IAAI,EAAE,QAAQ;IACdC,MAAMA,CAACC,KAAK,EAAEC,OAAO,EAAE;MACrB,IAAI,OAAOD,KAAK,KAAK,QAAQ,EAAE;QAC7B,MAAME,OAAO,GAAGF,KAAK,CAACG,IAAI,CAAC,CAAC;QAC5B,IAAID,OAAO,KAAK,EAAE,IAAIA,OAAO,KAAK,IAAI,EAAE;UACtC,OAAO;YACLF,KAAK,EAAEI;UACT,CAAC;QACH;QAEA,IAAI;UACF;UACA,OAAO;YAAEJ,KAAK,EAAEhB,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0D,OAAO,GAAG,IAAIvE,SAAS,CAC3BqE,eAAe,CAACG,OAAO,EACvBH,eAAe,CAACI,QAClB,CAAC;IACD,MAAMC,OAAO,GAAGH,OAAO,CAACI,QAAQ,CAAC,CAAC;IAClC,MAAMC,KAAK,GAAG7E,KAAK,CAAC,CAAC2E,OAAO,CAACG,SAAS,EAAEH,OAAO,CAACI,QAAQ,CAAC,CAAC;IAC1D,MAAMC,MAAM,GAAGjF,aAAa,CAAC8E,KAAK,EAAEd,cAAc,CAAC;IAEnD,IAAI,CAACiB,MAAM,EAAE;MACX,OAAOjE,OAAO,CAACO,KAAK,CAClB,YAAY,EACZ;QACEoC;MACF,CAAC,EACD;QAAEuB,IAAI,EAAE,CAACZ,KAAK,CAACa,IAAI;MAAE,CACvB,CAAC;IACH;;IAEA;IACA,OAAOpE,KAAK;EACd,CAAC;EAED,OAAOgD,qBAAqB;AAC9B","ignoreList":[]}
@@ -7,6 +7,10 @@ export function getRoutes(options: MapConfiguration): (ServerRoute<MapProxyGetRe
7
7
  * @type {FeatureCollection}
8
8
  */
9
9
  export const countries: FeatureCollection;
10
+ /**
11
+ * @type {FeatureCollection}
12
+ */
13
+ export const countriesValidate: FeatureCollection;
10
14
  export const countrySchema: Joi.StringSchema<string>;
11
15
  import type { MapConfiguration } from '../../../../server/plugins/map/types.js';
12
16
  import type { MapProxyGetRequestRefs } from '../../../../server/plugins/map/types.js';
@@ -5,14 +5,22 @@ import { StatusCodes } from 'http-status-codes';
5
5
  import Joi from 'joi';
6
6
  import { getAccessToken } from "./get-os-token.js";
7
7
  import { find } from "../service.js";
8
+ import { CountryMap } from "../types.js";
8
9
  import { get, request as httpRequest } from "../../../services/httpService.js";
9
- const filePath = resolve(import.meta.dirname, './vts/countries.geojson');
10
+ const countriesDisplayFilePath = resolve(import.meta.dirname, './vts/countries.geojson');
11
+ const countriesValidateFilePath = resolve(import.meta.dirname, './vts/countries-5dp.geojson');
10
12
 
11
13
  /**
12
14
  * @type {FeatureCollection}
13
15
  */
14
16
  // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
15
- export const countries = JSON.parse(fs.readFileSync(filePath, 'utf8'));
17
+ export const countries = JSON.parse(fs.readFileSync(countriesDisplayFilePath, 'utf8'));
18
+
19
+ /**
20
+ * @type {FeatureCollection}
21
+ */
22
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
23
+ export const countriesValidate = JSON.parse(fs.readFileSync(countriesValidateFilePath, 'utf8'));
16
24
  export const countrySchema = Joi.string().valid(...Object.values(GeospatialFieldOptionsCountryEnum));
17
25
 
18
26
  /**
@@ -169,13 +177,13 @@ function getGeospatialCountries() {
169
177
  if (omit) {
170
178
  return {
171
179
  ...countries,
172
- features: countries.features.filter(feature => feature.id !== omit)
180
+ features: countries.features.filter(feature => feature.id !== CountryMap[omit])
173
181
  };
174
182
  }
175
183
  if (only) {
176
184
  return {
177
185
  ...countries,
178
- features: countries.features.filter(feature => feature.id === only)
186
+ features: countries.features.filter(feature => feature.id === CountryMap[only])
179
187
  };
180
188
  }
181
189
  return countries;
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["fs","resolve","GeospatialFieldOptionsCountryEnum","StatusCodes","Joi","getAccessToken","find","get","request","httpRequest","filePath","import","meta","dirname","countries","JSON","parse","readFileSync","countrySchema","string","valid","Object","values","getRoutes","options","mapStyleResourceRoutes","mapProxyRoute","tileProxyRoute","geocodeProxyRoute","getGeospatialCountries","method","path","handler","h","query","targetUrl","URL","decodeURIComponent","url","token","searchParams","set","proxyResponse","toString","headers","Authorization","buffer","payload","contentType","res","response","type","auth","validate","object","keys","required","optional","z","y","x","params","getBuffer","Accept","json","gunzip","statusCode","OK","valueOf","code","header","_h","data","ordnanceSurveyApiKey","directory","omit","only","features","filter","feature","id"],"sources":["../../../../../src/server/plugins/map/routes/index.js"],"sourcesContent":["import fs from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { GeospatialFieldOptionsCountryEnum } from '@defra/forms-model'\nimport { StatusCodes } from 'http-status-codes'\nimport Joi from 'joi'\n\nimport { getAccessToken } from '~/src/server/plugins/map/routes/get-os-token.js'\nimport { find } from '~/src/server/plugins/map/service.js'\nimport {\n get,\n request as httpRequest\n} from '~/src/server/services/httpService.js'\n\nconst filePath = resolve(import.meta.dirname, './vts/countries.geojson')\n\n/**\n * @type {FeatureCollection}\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\nexport const countries = JSON.parse(fs.readFileSync(filePath, 'utf8'))\n\nexport const countrySchema = Joi.string().valid(\n ...Object.values(GeospatialFieldOptionsCountryEnum)\n)\n\n/**\n * Gets the map support routes\n * @param {MapConfiguration} options - ordnance survey names api key\n */\nexport function getRoutes(options) {\n return [\n mapStyleResourceRoutes(),\n mapProxyRoute(options),\n tileProxyRoute(options),\n geocodeProxyRoute(options),\n getGeospatialCountries()\n ]\n}\n\n/**\n * Proxies ordnance survey requests from the front end to api.os.com\n * Used for the VTS map source by forwarding on the request\n * and adding the auth token and SRS (spatial reference system)\n * @param {MapConfiguration} options - the map options\n * @returns {ServerRoute<MapProxyGetRequestRefs>}\n */\nfunction mapProxyRoute(options) {\n return {\n method: 'GET',\n path: '/api/map-proxy',\n handler: async (request, h) => {\n const { query } = request\n const targetUrl = new URL(decodeURIComponent(query.url))\n const token = await getAccessToken(options)\n\n targetUrl.searchParams.set('srs', '3857')\n\n const proxyResponse = await httpRequest('get', targetUrl.toString(), {\n headers: {\n Authorization: `Bearer ${token}`\n }\n })\n const buffer = proxyResponse.payload\n const contentType = proxyResponse.res.headers['content-type']\n const response = h.response(buffer)\n\n if (contentType) {\n response.type(contentType)\n }\n\n return response\n },\n options: {\n auth: false,\n validate: {\n query: Joi.object()\n .keys({\n url: Joi.string().required()\n })\n .optional()\n }\n }\n }\n}\n\n/**\n * Proxies ordnance survey requests from the front end to api.os.uk\n * Used for VTS map tiles forwarding on the request and adding the auth token\n * @param {MapConfiguration} options - the map options\n * @returns {ServerRoute<MapProxyGetRequestRefs>}\n */\nfunction tileProxyRoute(options) {\n return {\n method: 'GET',\n path: '/api/tile/{z}/{y}/{x}.pbf',\n handler: async (request, h) => {\n const { z, y, x } = request.params\n const token = await getAccessToken(options)\n\n const url = `https://api.os.uk/maps/vector/v1/vts/tile/${z}/${y}/${x}.pbf?srs=3857`\n\n const getBuffer = /** @type {typeof get<Buffer>} */ (get)\n\n const { payload, res } = await getBuffer(url, {\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/x-protobuf'\n },\n json: false,\n gunzip: true\n })\n\n if (res.statusCode && res.statusCode !== StatusCodes.OK.valueOf()) {\n return h.response('Tile fetch failed').code(res.statusCode)\n }\n\n return h\n .response(payload)\n .type('application/x-protobuf')\n .header('Cache-Control', 'public, max-age=86400')\n },\n options: {\n auth: false\n }\n }\n}\n\n/**\n * Proxies ordnance survey geocode requests from the front end to api.os.uk\n * Used for the gazzeteer address lookup to find name from query strings like postcode and place names\n * @param {MapConfiguration} options - the map options\n * @returns {ServerRoute<MapGeocodeGetRequestRefs>}\n */\nfunction geocodeProxyRoute(options) {\n return {\n method: 'GET',\n path: '/api/geocode-proxy',\n async handler(request, _h) {\n const { query } = request\n const data = await find(query.query, options.ordnanceSurveyApiKey)\n\n return data\n },\n options: {\n auth: false,\n validate: {\n query: Joi.object()\n .keys({\n query: Joi.string().required()\n })\n .required()\n }\n }\n }\n}\n\n/**\n * Resource routes to return sprites and glyphs\n * @returns {ServerRoute<MapProxyGetRequestRefs>}\n */\nfunction mapStyleResourceRoutes() {\n return {\n method: 'GET',\n path: '/api/maps/vts/{path*}',\n options: {\n auth: false,\n handler: {\n directory: {\n path: resolve(import.meta.dirname, './vts')\n }\n }\n }\n }\n}\n\n/**\n * Resource routes to return sprites and glyphs\n * @returns {ServerRoute<GeospatialCountriesGetRequestRefs>}\n */\nfunction getGeospatialCountries() {\n return {\n method: 'GET',\n path: '/api/maps/countries.geojson',\n handler: (request) => {\n const { omit, only } = request.query\n\n if (omit) {\n return {\n ...countries,\n features: countries.features.filter((feature) => feature.id !== omit)\n }\n }\n\n if (only) {\n return {\n ...countries,\n features: countries.features.filter((feature) => feature.id === only)\n }\n }\n\n return countries\n },\n options: {\n auth: false,\n validate: {\n query: Joi.object()\n .keys({\n omit: countrySchema.optional(),\n only: countrySchema.optional()\n })\n .optional()\n }\n }\n }\n}\n\n/**\n * @import { ServerRoute } from '@hapi/hapi'\n * @import { FeatureCollection } from 'geojson'\n * @import { MapConfiguration, MapProxyGetRequestRefs, MapGeocodeGetRequestRefs, GeospatialCountriesGetRequestRefs } from '~/src/server/plugins/map/types.js'\n */\n"],"mappings":"AAAA,OAAOA,EAAE,MAAM,SAAS;AACxB,SAASC,OAAO,QAAQ,WAAW;AAEnC,SAASC,iCAAiC,QAAQ,oBAAoB;AACtE,SAASC,WAAW,QAAQ,mBAAmB;AAC/C,OAAOC,GAAG,MAAM,KAAK;AAErB,SAASC,cAAc;AACvB,SAASC,IAAI;AACb,SACEC,GAAG,EACHC,OAAO,IAAIC,WAAW;AAGxB,MAAMC,QAAQ,GAAGT,OAAO,CAACU,MAAM,CAACC,IAAI,CAACC,OAAO,EAAE,yBAAyB,CAAC;;AAExE;AACA;AACA;AACA;AACA,OAAO,MAAMC,SAAS,GAAGC,IAAI,CAACC,KAAK,CAAChB,EAAE,CAACiB,YAAY,CAACP,QAAQ,EAAE,MAAM,CAAC,CAAC;AAEtE,OAAO,MAAMQ,aAAa,GAAGd,GAAG,CAACe,MAAM,CAAC,CAAC,CAACC,KAAK,CAC7C,GAAGC,MAAM,CAACC,MAAM,CAACpB,iCAAiC,CACpD,CAAC;;AAED;AACA;AACA;AACA;AACA,OAAO,SAASqB,SAASA,CAACC,OAAO,EAAE;EACjC,OAAO,CACLC,sBAAsB,CAAC,CAAC,EACxBC,aAAa,CAACF,OAAO,CAAC,EACtBG,cAAc,CAACH,OAAO,CAAC,EACvBI,iBAAiB,CAACJ,OAAO,CAAC,EAC1BK,sBAAsB,CAAC,CAAC,CACzB;AACH;;AAEA;AACA;AACA;AACA;AACA;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,OAAO;UACL,GAAG9D,SAAS;UACZ+D,QAAQ,EAAE/D,SAAS,CAAC+D,QAAQ,CAACC,MAAM,CAAEC,OAAO,IAAKA,OAAO,CAACC,EAAE,KAAKJ,IAAI;QACtE,CAAC;MACH;MAEA,OAAO9D,SAAS;IAClB,CAAC;IACDU,OAAO,EAAE;MACP4B,IAAI,EAAE,KAAK;MACXC,QAAQ,EAAE;QACRnB,KAAK,EAAE9B,GAAG,CAACkD,MAAM,CAAC,CAAC,CAChBC,IAAI,CAAC;UACJoB,IAAI,EAAEzD,aAAa,CAACuC,QAAQ,CAAC,CAAC;UAC9BmB,IAAI,EAAE1D,aAAa,CAACuC,QAAQ,CAAC;QAC/B,CAAC,CAAC,CACDA,QAAQ,CAAC;MACd;IACF;EACF,CAAC;AACH;;AAEA;AACA;AACA;AACA;AACA","ignoreList":[]}
1
+ {"version":3,"file":"index.js","names":["fs","resolve","GeospatialFieldOptionsCountryEnum","StatusCodes","Joi","getAccessToken","find","CountryMap","get","request","httpRequest","countriesDisplayFilePath","import","meta","dirname","countriesValidateFilePath","countries","JSON","parse","readFileSync","countriesValidate","countrySchema","string","valid","Object","values","getRoutes","options","mapStyleResourceRoutes","mapProxyRoute","tileProxyRoute","geocodeProxyRoute","getGeospatialCountries","method","path","handler","h","query","targetUrl","URL","decodeURIComponent","url","token","searchParams","set","proxyResponse","toString","headers","Authorization","buffer","payload","contentType","res","response","type","auth","validate","object","keys","required","optional","z","y","x","params","getBuffer","Accept","json","gunzip","statusCode","OK","valueOf","code","header","_h","data","ordnanceSurveyApiKey","directory","omit","only","features","filter","feature","id"],"sources":["../../../../../src/server/plugins/map/routes/index.js"],"sourcesContent":["import fs from 'node:fs'\nimport { resolve } from 'node:path'\n\nimport { GeospatialFieldOptionsCountryEnum } from '@defra/forms-model'\nimport { StatusCodes } from 'http-status-codes'\nimport Joi from 'joi'\n\nimport { getAccessToken } from '~/src/server/plugins/map/routes/get-os-token.js'\nimport { find } from '~/src/server/plugins/map/service.js'\nimport { CountryMap } from '~/src/server/plugins/map/types.js'\nimport {\n get,\n request as httpRequest\n} from '~/src/server/services/httpService.js'\n\nconst countriesDisplayFilePath = resolve(\n import.meta.dirname,\n './vts/countries.geojson'\n)\nconst countriesValidateFilePath = resolve(\n import.meta.dirname,\n './vts/countries-5dp.geojson'\n)\n\n/**\n * @type {FeatureCollection}\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\nexport const countries = JSON.parse(\n fs.readFileSync(countriesDisplayFilePath, 'utf8')\n)\n\n/**\n * @type {FeatureCollection}\n */\n// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\nexport const countriesValidate = JSON.parse(\n fs.readFileSync(countriesValidateFilePath, 'utf8')\n)\n\nexport const countrySchema = Joi.string().valid(\n ...Object.values(GeospatialFieldOptionsCountryEnum)\n)\n\n/**\n * Gets the map support routes\n * @param {MapConfiguration} options - ordnance survey names api key\n */\nexport function getRoutes(options) {\n return [\n mapStyleResourceRoutes(),\n mapProxyRoute(options),\n tileProxyRoute(options),\n geocodeProxyRoute(options),\n getGeospatialCountries()\n ]\n}\n\n/**\n * Proxies ordnance survey requests from the front end to api.os.com\n * Used for the VTS map source by forwarding on the request\n * and adding the auth token and SRS (spatial reference system)\n * @param {MapConfiguration} options - the map options\n * @returns {ServerRoute<MapProxyGetRequestRefs>}\n */\nfunction mapProxyRoute(options) {\n return {\n method: 'GET',\n path: '/api/map-proxy',\n handler: async (request, h) => {\n const { query } = request\n const targetUrl = new URL(decodeURIComponent(query.url))\n const token = await getAccessToken(options)\n\n targetUrl.searchParams.set('srs', '3857')\n\n const proxyResponse = await httpRequest('get', targetUrl.toString(), {\n headers: {\n Authorization: `Bearer ${token}`\n }\n })\n const buffer = proxyResponse.payload\n const contentType = proxyResponse.res.headers['content-type']\n const response = h.response(buffer)\n\n if (contentType) {\n response.type(contentType)\n }\n\n return response\n },\n options: {\n auth: false,\n validate: {\n query: Joi.object()\n .keys({\n url: Joi.string().required()\n })\n .optional()\n }\n }\n }\n}\n\n/**\n * Proxies ordnance survey requests from the front end to api.os.uk\n * Used for VTS map tiles forwarding on the request and adding the auth token\n * @param {MapConfiguration} options - the map options\n * @returns {ServerRoute<MapProxyGetRequestRefs>}\n */\nfunction tileProxyRoute(options) {\n return {\n method: 'GET',\n path: '/api/tile/{z}/{y}/{x}.pbf',\n handler: async (request, h) => {\n const { z, y, x } = request.params\n const token = await getAccessToken(options)\n\n const url = `https://api.os.uk/maps/vector/v1/vts/tile/${z}/${y}/${x}.pbf?srs=3857`\n\n const getBuffer = /** @type {typeof get<Buffer>} */ (get)\n\n const { payload, res } = await getBuffer(url, {\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/x-protobuf'\n },\n json: false,\n gunzip: true\n })\n\n if (res.statusCode && res.statusCode !== StatusCodes.OK.valueOf()) {\n return h.response('Tile fetch failed').code(res.statusCode)\n }\n\n return h\n .response(payload)\n .type('application/x-protobuf')\n .header('Cache-Control', 'public, max-age=86400')\n },\n options: {\n auth: false\n }\n }\n}\n\n/**\n * Proxies ordnance survey geocode requests from the front end to api.os.uk\n * Used for the gazzeteer address lookup to find name from query strings like postcode and place names\n * @param {MapConfiguration} options - the map options\n * @returns {ServerRoute<MapGeocodeGetRequestRefs>}\n */\nfunction geocodeProxyRoute(options) {\n return {\n method: 'GET',\n path: '/api/geocode-proxy',\n async handler(request, _h) {\n const { query } = request\n const data = await find(query.query, options.ordnanceSurveyApiKey)\n\n return data\n },\n options: {\n auth: false,\n validate: {\n query: Joi.object()\n .keys({\n query: Joi.string().required()\n })\n .required()\n }\n }\n }\n}\n\n/**\n * Resource routes to return sprites and glyphs\n * @returns {ServerRoute<MapProxyGetRequestRefs>}\n */\nfunction mapStyleResourceRoutes() {\n return {\n method: 'GET',\n path: '/api/maps/vts/{path*}',\n options: {\n auth: false,\n handler: {\n directory: {\n path: resolve(import.meta.dirname, './vts')\n }\n }\n }\n }\n}\n\n/**\n * Resource routes to return sprites and glyphs\n * @returns {ServerRoute<GeospatialCountriesGetRequestRefs>}\n */\nfunction getGeospatialCountries() {\n return {\n method: 'GET',\n path: '/api/maps/countries.geojson',\n handler: (request) => {\n const { omit, only } = request.query\n\n if (omit) {\n return {\n ...countries,\n features: countries.features.filter(\n (feature) => feature.id !== CountryMap[omit]\n )\n }\n }\n\n if (only) {\n return {\n ...countries,\n features: countries.features.filter(\n (feature) => feature.id === CountryMap[only]\n )\n }\n }\n\n return countries\n },\n options: {\n auth: false,\n validate: {\n query: Joi.object()\n .keys({\n omit: countrySchema.optional(),\n only: countrySchema.optional()\n })\n .optional()\n }\n }\n }\n}\n\n/**\n * @import { ServerRoute } from '@hapi/hapi'\n * @import { FeatureCollection } from 'geojson'\n * @import { MapConfiguration, MapProxyGetRequestRefs, MapGeocodeGetRequestRefs, GeospatialCountriesGetRequestRefs } from '~/src/server/plugins/map/types.js'\n */\n"],"mappings":"AAAA,OAAOA,EAAE,MAAM,SAAS;AACxB,SAASC,OAAO,QAAQ,WAAW;AAEnC,SAASC,iCAAiC,QAAQ,oBAAoB;AACtE,SAASC,WAAW,QAAQ,mBAAmB;AAC/C,OAAOC,GAAG,MAAM,KAAK;AAErB,SAASC,cAAc;AACvB,SAASC,IAAI;AACb,SAASC,UAAU;AACnB,SACEC,GAAG,EACHC,OAAO,IAAIC,WAAW;AAGxB,MAAMC,wBAAwB,GAAGV,OAAO,CACtCW,MAAM,CAACC,IAAI,CAACC,OAAO,EACnB,yBACF,CAAC;AACD,MAAMC,yBAAyB,GAAGd,OAAO,CACvCW,MAAM,CAACC,IAAI,CAACC,OAAO,EACnB,6BACF,CAAC;;AAED;AACA;AACA;AACA;AACA,OAAO,MAAME,SAAS,GAAGC,IAAI,CAACC,KAAK,CACjClB,EAAE,CAACmB,YAAY,CAACR,wBAAwB,EAAE,MAAM,CAClD,CAAC;;AAED;AACA;AACA;AACA;AACA,OAAO,MAAMS,iBAAiB,GAAGH,IAAI,CAACC,KAAK,CACzClB,EAAE,CAACmB,YAAY,CAACJ,yBAAyB,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;AACA;AACA;AACA,SAASkB,sBAAsBA,CAAA,EAAG;EAChC,OAAO;IACLC,MAAM,EAAE,KAAK;IACbC,IAAI,EAAE,6BAA6B;IACnCC,OAAO,EAAG1B,OAAO,IAAK;MACpB,MAAM;QAAEqE,IAAI;QAAEC;MAAK,CAAC,GAAGtE,OAAO,CAAC4B,KAAK;MAEpC,IAAIyC,IAAI,EAAE;QACR,OAAO;UACL,GAAG9D,SAAS;UACZgE,QAAQ,EAAEhE,SAAS,CAACgE,QAAQ,CAACC,MAAM,CAChCC,OAAO,IAAKA,OAAO,CAACC,EAAE,KAAK5E,UAAU,CAACuE,IAAI,CAC7C;QACF,CAAC;MACH;MAEA,IAAIC,IAAI,EAAE;QACR,OAAO;UACL,GAAG/D,SAAS;UACZgE,QAAQ,EAAEhE,SAAS,CAACgE,QAAQ,CAACC,MAAM,CAChCC,OAAO,IAAKA,OAAO,CAACC,EAAE,KAAK5E,UAAU,CAACwE,IAAI,CAC7C;QACF,CAAC;MACH;MAEA,OAAO/D,SAAS;IAClB,CAAC;IACDW,OAAO,EAAE;MACP4B,IAAI,EAAE,KAAK;MACXC,QAAQ,EAAE;QACRnB,KAAK,EAAEjC,GAAG,CAACqD,MAAM,CAAC,CAAC,CAChBC,IAAI,CAAC;UACJoB,IAAI,EAAEzD,aAAa,CAACuC,QAAQ,CAAC,CAAC;UAC9BmB,IAAI,EAAE1D,aAAa,CAACuC,QAAQ,CAAC;QAC/B,CAAC,CAAC,CACDA,QAAQ,CAAC;MACd;IACF;EACF,CAAC;AACH;;AAEA;AACA;AACA;AACA;AACA","ignoreList":[]}
@@ -1,5 +1,43 @@
1
+ # VTS
2
+
1
3
  File in this directory are sourced from https://github.com/OrdnanceSurvey/OS-Vector-Tile-API-Stylesheets
2
4
 
3
5
  VTS_OUTDOOR_URL=https://raw.githubusercontent.com/OrdnanceSurvey/OS-Vector-Tile-API-Stylesheets/main/OS_VTS_3857_Outdoor.json
4
6
  VTS_DARK_URL=https://raw.githubusercontent.com/OrdnanceSurvey/OS-Vector-Tile-API-Stylesheets/main/OS_VTS_3857_Dark.json
5
7
  VTS_BLACK_AND_WHITE_URL=https://raw.githubusercontent.com/OrdnanceSurvey/OS-Vector-Tile-API-Stylesheets/main/OS_VTS_3857_Black_and_White.json
8
+
9
+ # Country boundaries
10
+
11
+ The [Office for National Statistics provides full-resolution boundaries](https://www.ons.gov.uk/methodology/geography/geographicalproducts/digitalboundaries) in two coastal forms.
12
+ We use "BFE" a full resolution — extent of the realm and generally extends to Mean Low Water rather than clipping at Mean High Water.
13
+
14
+ The latest version of the data is from 2025 and can be found at the following links:
15
+
16
+ https://geoportal.statistics.gov.uk/datasets/591803c2a3b94804a3d7895cc127d7c0_0/explore?location=50.529309%2C-4.098782%2C7
17
+
18
+ Download from: http://geoportal.statistics.gov.uk/ or https://geoportal.statistics.gov.uk/datasets/ons::countries-december-2025-boundaries-uk-bfe/about
19
+
20
+ The source data is for the 2025 revision is 179MB so needs to be reduced to allow rendering in a Web map and used for validation on the server. The downloaded file is named `boundaries-bfe.geojson`. `org2ogr` is used to produce two files:
21
+
22
+ ## Server-side validation (boundaries-bfe-5dp.geojson)
23
+
24
+ This is the full file but with coordinate precision reduced from 14 to 5 decimal places, resulting in a smaller file of 83.7MB.
25
+ This data is then used server-side to validate points, shapes and lines that include country restrictions.
26
+
27
+ `ogr2ogr --config OGR_GEOJSON_MAX_OBJ_SIZE 0 -f GeoJSON boundaries-bfe-5dp.geojson boundaries-bfe.geojson -lco COORDINATE_PRECISION=5`
28
+
29
+ ## Client-side display on map (boundaries-bfe-5dp.geojson)
30
+
31
+ To produce a file suitable for use in the map in the browser we use `ogr2ogr`'s `simplify` option.
32
+
33
+ `-simplify 0.001` uses the units of the input CRS. In EPSG:4326, that's degrees, not metres so a tolerance of 0.001° is roughly 111 metres north–south, which is quite a substantial simplification for coastal boundaries. For 0.001 to mean approximately one metre, we have to reproject to a suitable projected CRS (BNG, EPSG:27700) before simplifying:
34
+
35
+ The following command produces `boundaries-bng.geojson`, the source file reprojected to BNG.
36
+
37
+ `ogr2ogr --config OGR_GEOJSON_MAX_OBJ_SIZE 0 -f GeoJSON boundaries-bng.geojson boundaries-bfe.geojson -t_srs EPSG:27700`
38
+
39
+ We then use this to create a simplified dataset, `countries.geojson`, reprojected back in ESPG:4326:
40
+
41
+ `ogr2ogr --config OGR_GEOJSON_MAX_OBJ_SIZE 0 -f GeoJSON countries.geojson boundaries-bng.json -simplify 100 -t_srs EPSG:4326 -lco COORDINATE_PRECISION=5`
42
+
43
+ The result is a file of 940kB that is suitable to use in the web map.
@@ -0,0 +1,4 @@
1
+ [diffend] Oversized file quarantined before diffing.
2
+ name: package/.server/server/plugins/map/routes/vts/countries-5dp.geojson
3
+ size: 83733031 bytes
4
+ sha256: 032725bc5cedcee3aeba36dc8bc6aa987343635c199f5fe723dc8b0478ae5954