@dwp/govuk-casa 7.0.6 → 8.0.0-beta1

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 (228) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/README.md +22 -17
  3. package/dist/{casa → assets}/css/casa-ie8.css +1 -1
  4. package/dist/assets/css/casa.css +1 -0
  5. package/dist/casa.d.ts +11 -0
  6. package/dist/casa.js +46 -0
  7. package/dist/lib/CasaTemplateLoader.d.ts +29 -0
  8. package/dist/lib/CasaTemplateLoader.js +74 -0
  9. package/dist/lib/JourneyContext.d.ts +297 -0
  10. package/dist/lib/JourneyContext.js +581 -0
  11. package/dist/lib/MutableRouter.d.ts +155 -0
  12. package/dist/lib/MutableRouter.js +277 -0
  13. package/dist/lib/Plan.d.ts +154 -0
  14. package/dist/lib/Plan.js +442 -0
  15. package/dist/lib/ValidationError.d.ts +74 -0
  16. package/dist/lib/ValidationError.js +159 -0
  17. package/dist/lib/ValidatorFactory.d.ts +83 -0
  18. package/dist/lib/ValidatorFactory.js +106 -0
  19. package/dist/lib/configuration-ingestor.d.ts +262 -0
  20. package/dist/lib/configuration-ingestor.js +490 -0
  21. package/dist/lib/configure.d.ts +90 -0
  22. package/dist/lib/configure.js +192 -0
  23. package/dist/lib/dirname.cjs +1 -0
  24. package/dist/lib/dirname.d.cts +2 -0
  25. package/dist/lib/end-session.d.ts +13 -0
  26. package/dist/lib/end-session.js +43 -0
  27. package/dist/lib/field.d.ts +77 -0
  28. package/dist/lib/field.js +255 -0
  29. package/dist/lib/index.d.ts +14 -0
  30. package/dist/lib/index.js +54 -0
  31. package/dist/lib/logger.d.ts +9 -0
  32. package/dist/lib/logger.js +18 -0
  33. package/dist/lib/nunjucks-filters.d.ts +26 -0
  34. package/dist/lib/nunjucks-filters.js +90 -0
  35. package/dist/lib/nunjucks.d.ts +23 -0
  36. package/dist/lib/nunjucks.js +49 -0
  37. package/dist/lib/utils.d.ts +48 -0
  38. package/dist/lib/utils.js +111 -0
  39. package/dist/lib/validators/dateObject.d.ts +4 -0
  40. package/dist/lib/validators/dateObject.js +135 -0
  41. package/dist/lib/validators/email.d.ts +4 -0
  42. package/dist/lib/validators/email.js +46 -0
  43. package/dist/lib/validators/inArray.d.ts +4 -0
  44. package/dist/lib/validators/inArray.js +60 -0
  45. package/dist/lib/validators/index.d.ts +21 -0
  46. package/dist/lib/validators/index.js +47 -0
  47. package/dist/lib/validators/nino.d.ts +4 -0
  48. package/dist/lib/validators/nino.js +46 -0
  49. package/dist/lib/validators/postalAddressObject.d.ts +4 -0
  50. package/dist/lib/validators/postalAddressObject.js +123 -0
  51. package/dist/lib/validators/regex.d.ts +4 -0
  52. package/dist/lib/validators/regex.js +40 -0
  53. package/dist/lib/validators/required.d.ts +4 -0
  54. package/dist/lib/validators/required.js +56 -0
  55. package/dist/lib/validators/strlen.d.ts +4 -0
  56. package/dist/lib/validators/strlen.js +51 -0
  57. package/dist/lib/validators/wordCount.d.ts +5 -0
  58. package/dist/lib/validators/wordCount.js +54 -0
  59. package/dist/lib/waypoint-url.d.ts +23 -0
  60. package/dist/lib/waypoint-url.js +52 -0
  61. package/dist/middleware/body-parser.d.ts +1 -0
  62. package/dist/middleware/body-parser.js +24 -0
  63. package/dist/middleware/csrf.d.ts +1 -0
  64. package/dist/middleware/csrf.js +31 -0
  65. package/dist/middleware/data.d.ts +5 -0
  66. package/dist/middleware/data.js +53 -0
  67. package/dist/middleware/dirname.cjs +1 -0
  68. package/dist/middleware/dirname.d.cts +2 -0
  69. package/dist/middleware/gather-fields.d.ts +6 -0
  70. package/dist/middleware/gather-fields.js +48 -0
  71. package/dist/middleware/i18n.d.ts +4 -0
  72. package/dist/middleware/i18n.js +88 -0
  73. package/dist/middleware/post.d.ts +3 -0
  74. package/dist/middleware/post.js +57 -0
  75. package/dist/middleware/pre.d.ts +3 -0
  76. package/dist/middleware/pre.js +51 -0
  77. package/dist/middleware/progress-journey.d.ts +6 -0
  78. package/dist/middleware/progress-journey.js +80 -0
  79. package/dist/middleware/sanitise-fields.d.ts +5 -0
  80. package/dist/middleware/sanitise-fields.js +53 -0
  81. package/dist/middleware/session.d.ts +11 -0
  82. package/dist/middleware/session.js +121 -0
  83. package/dist/middleware/skip-waypoint.d.ts +5 -0
  84. package/dist/middleware/skip-waypoint.js +43 -0
  85. package/dist/middleware/steer-journey.d.ts +7 -0
  86. package/dist/middleware/steer-journey.js +62 -0
  87. package/dist/middleware/validate-fields.d.ts +7 -0
  88. package/dist/middleware/validate-fields.js +67 -0
  89. package/dist/mjs/esm-wrapper.js +11 -0
  90. package/dist/mjs/package.json +3 -0
  91. package/dist/package.json +3 -0
  92. package/dist/routes/ancillary.d.ts +11 -0
  93. package/dist/routes/ancillary.js +27 -0
  94. package/dist/routes/dirname.cjs +1 -0
  95. package/dist/routes/dirname.d.cts +2 -0
  96. package/dist/routes/journey.d.ts +8 -0
  97. package/dist/routes/journey.js +127 -0
  98. package/dist/routes/static.d.ts +26 -0
  99. package/dist/routes/static.js +68 -0
  100. package/package.json +64 -89
  101. package/views/casa/components/checkboxes/template.njk +4 -1
  102. package/views/casa/components/date-input/template.njk +3 -3
  103. package/views/casa/components/journey-form/README.md +3 -1
  104. package/views/casa/components/journey-form/template.njk +1 -1
  105. package/views/casa/components/postal-address-object/template.njk +5 -5
  106. package/views/casa/components/radios/template.njk +1 -1
  107. package/views/casa/errors/static.njk +11 -0
  108. package/views/casa/layouts/journey.njk +26 -9
  109. package/views/casa/layouts/main.njk +7 -20
  110. package/views/casa/partials/scripts.njk +8 -3
  111. package/views/casa/partials/styles.njk +2 -2
  112. package/casa.js +0 -208
  113. package/definitions/review-page.js +0 -60
  114. package/dist/casa/css/casa.css +0 -1
  115. package/dist/casa/js/casa.js +0 -1
  116. package/index.d.ts +0 -121
  117. package/lib/ConfigIngestor.js +0 -588
  118. package/lib/GatherModifier.js +0 -14
  119. package/lib/I18n.js +0 -160
  120. package/lib/JourneyContext.d.ts +0 -97
  121. package/lib/JourneyContext.js +0 -552
  122. package/lib/JourneyMap.js +0 -233
  123. package/lib/JourneyRoad.js +0 -330
  124. package/lib/Logger.js +0 -59
  125. package/lib/PageDictionary.d.ts +0 -11
  126. package/lib/PageDirectory.js +0 -77
  127. package/lib/Plan.js +0 -423
  128. package/lib/RoadConverter.js +0 -153
  129. package/lib/UserJourney.js +0 -8
  130. package/lib/Util.js +0 -227
  131. package/lib/Validation.js +0 -20
  132. package/lib/bootstrap/end-session.js +0 -44
  133. package/lib/bootstrap/load-definitions.js +0 -64
  134. package/lib/commonBodyParser.js +0 -15
  135. package/lib/enums.js +0 -6
  136. package/lib/gather-modifiers/index.js +0 -7
  137. package/lib/gather-modifiers/trimPostalAddressObject.js +0 -75
  138. package/lib/gather-modifiers/trimWhitespace.js +0 -16
  139. package/lib/utils/createGetRequest.d.ts +0 -5
  140. package/lib/utils/createGetRequest.js +0 -59
  141. package/lib/utils/index.js +0 -11
  142. package/lib/utils/parseRequest.d.ts +0 -5
  143. package/lib/utils/parseRequest.js +0 -72
  144. package/lib/utils/sanitise.js +0 -74
  145. package/lib/utils/validate.js +0 -32
  146. package/lib/validation/ArrayObjectField.js +0 -49
  147. package/lib/validation/ObjectField.js +0 -53
  148. package/lib/validation/SimpleField.d.ts +0 -11
  149. package/lib/validation/SimpleField.js +0 -46
  150. package/lib/validation/ValidationError.d.ts +0 -14
  151. package/lib/validation/ValidationError.js +0 -170
  152. package/lib/validation/ValidatorFactory.d.ts +0 -32
  153. package/lib/validation/ValidatorFactory.js +0 -91
  154. package/lib/validation/index.js +0 -22
  155. package/lib/validation/processor/flattenErrorArray.js +0 -24
  156. package/lib/validation/processor/queue.js +0 -214
  157. package/lib/validation/processor.js +0 -84
  158. package/lib/validation/rules/README.md +0 -3
  159. package/lib/validation/rules/ValidationRules.d.ts +0 -22
  160. package/lib/validation/rules/dateObject.js +0 -156
  161. package/lib/validation/rules/email.js +0 -44
  162. package/lib/validation/rules/inArray.js +0 -61
  163. package/lib/validation/rules/index.js +0 -23
  164. package/lib/validation/rules/nino.js +0 -48
  165. package/lib/validation/rules/optional.js +0 -14
  166. package/lib/validation/rules/postalAddressObject.js +0 -142
  167. package/lib/validation/rules/regex.js +0 -39
  168. package/lib/validation/rules/required.js +0 -57
  169. package/lib/validation/rules/strlen.js +0 -57
  170. package/lib/validation/rules/wordCount.js +0 -61
  171. package/lib/view-filters/formatDateObject.js +0 -35
  172. package/lib/view-filters/includes.js +0 -10
  173. package/lib/view-filters/index.js +0 -23
  174. package/lib/view-filters/mergeObjectsDeep.js +0 -21
  175. package/lib/view-filters/renderAsAttributes.js +0 -33
  176. package/middleware/errors/404.js +0 -12
  177. package/middleware/errors/catch-all.js +0 -27
  178. package/middleware/errors/index.js +0 -9
  179. package/middleware/headers/config-defaults.js +0 -57
  180. package/middleware/headers/headers.js +0 -40
  181. package/middleware/headers/index.js +0 -9
  182. package/middleware/i18n/i18n.js +0 -56
  183. package/middleware/i18n/index.js +0 -16
  184. package/middleware/index.js +0 -55
  185. package/middleware/mount/index.js +0 -9
  186. package/middleware/mount/mount.js +0 -10
  187. package/middleware/nunjucks/environment.js +0 -57
  188. package/middleware/nunjucks/index.js +0 -8
  189. package/middleware/page/csrf.js +0 -37
  190. package/middleware/page/edit-mode.js +0 -52
  191. package/middleware/page/gather.js +0 -75
  192. package/middleware/page/index.js +0 -103
  193. package/middleware/page/journey-continue.js +0 -157
  194. package/middleware/page/journey-rails.js +0 -102
  195. package/middleware/page/prepare-request.js +0 -77
  196. package/middleware/page/render.js +0 -75
  197. package/middleware/page/skip.js +0 -72
  198. package/middleware/page/utils.js +0 -206
  199. package/middleware/page/validate.js +0 -67
  200. package/middleware/session/expiry.js +0 -95
  201. package/middleware/session/genid.js +0 -18
  202. package/middleware/session/index.js +0 -18
  203. package/middleware/session/init.js +0 -25
  204. package/middleware/session/seed.js +0 -50
  205. package/middleware/session/timeout.js +0 -5
  206. package/middleware/static/asset-versions.js +0 -23
  207. package/middleware/static/index.js +0 -104
  208. package/middleware/static/prepare-assets.js +0 -51
  209. package/middleware/static/serve-assets.js +0 -58
  210. package/middleware/variables/index.js +0 -12
  211. package/middleware/variables/variables.js +0 -35
  212. package/src/browserconfig.xml +0 -5
  213. package/src/js/casa.js +0 -132
  214. package/src/scss/_casaElements.scss +0 -11
  215. package/src/scss/_casaGovukTemplateJinjaPolyfill.scss +0 -39
  216. package/src/scss/_casaMountUrl.scss +0 -8
  217. package/src/scss/casa-ie8.scss +0 -3
  218. package/src/scss/casa.scss +0 -14
  219. package/test/unit/templates/README.md +0 -5
  220. package/test/utils/BaseTestWaypoint.js +0 -106
  221. package/test/utils/concatWaypoints.js +0 -26
  222. package/test/utils/index.js +0 -6
  223. package/test/utils/testTraversal.js +0 -90
  224. package/views/casa/partials/cookie_message.njk +0 -3
  225. package/views/casa/partials/phase_banner_alpha.njk +0 -8
  226. package/views/casa/partials/phase_banner_beta.njk +0 -8
  227. package/views/casa/review/page-block.njk +0 -8
  228. package/views/casa/review/review.njk +0 -47
@@ -0,0 +1,581 @@
1
+ "use strict";
2
+ var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
3
+ if (kind === "m") throw new TypeError("Private method is not writable");
4
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
5
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
6
+ return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
7
+ };
8
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
9
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
10
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
11
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
12
+ };
13
+ var __rest = (this && this.__rest) || function (s, e) {
14
+ var t = {};
15
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
16
+ t[p] = s[p];
17
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
18
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
19
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
20
+ t[p[i]] = s[p[i]];
21
+ }
22
+ return t;
23
+ };
24
+ var __importDefault = (this && this.__importDefault) || function (mod) {
25
+ return (mod && mod.__esModule) ? mod : { "default": mod };
26
+ };
27
+ var _JourneyContext_data, _JourneyContext_validation, _JourneyContext_nav, _JourneyContext_identity, _JourneyContext_eventListeners, _JourneyContext_eventListenerPreState;
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ /**
30
+ * Represents the state of a user's journey through the Plan. It contains
31
+ * information about:
32
+ *
33
+ * - Data gathered during the journey
34
+ * - Validation errors on that data
35
+ * - Navigation information about how the user got where they are.
36
+ */
37
+ const uuid_1 = require("uuid");
38
+ const lodash_1 = __importDefault(require("lodash"));
39
+ const ValidationError_js_1 = __importDefault(require("./ValidationError.js"));
40
+ const logger_js_1 = __importDefault(require("./logger.js"));
41
+ const { cloneDeep, isPlainObject, isObject, has, isEqual, } = lodash_1.default; // CommonJS
42
+ const log = (0, logger_js_1.default)('class:journey-context');
43
+ /**
44
+ * @typedef {import('./configuration-ingestor').Page} Page
45
+ */
46
+ /**
47
+ * @callback ContextEventHandler
48
+ * @param {JourneyContext} journeyContext Context including changes
49
+ * @param {JourneyContext} previousContext Context prior to changes
50
+ * @returns {void}
51
+ */
52
+ /**
53
+ * @typedef {object} ContextEvent
54
+ * @property {string} waypoint Waypoint to watch for changes
55
+ * @property {string} [field] Field to watch for changes
56
+ * @property {ContextEventHandler} handler Handler to invoke when change happens
57
+ */
58
+ class JourneyContext {
59
+ /**
60
+ * Constructor.
61
+ *
62
+ * `data` is the "single source of truth" for all data gathered during the
63
+ * user's journey. This is referred to as the "canonical data model".
64
+ * Page-specific "views" of this data are generated at runtime in order to
65
+ * populate/validate specific form fields.
66
+ *
67
+ * `validation` holds the results of form field validation carried out when
68
+ * page forms are POSTed. These results are mapped directly to per-page,
69
+ * per-field.
70
+ *
71
+ * `nav` holds information about the current navigation state. Currently this
72
+ * comprises of the language in which the user is navigating the service.
73
+ *
74
+ * `identity` holds information that helps uniquely identify this context
75
+ * among a group of contexts stored in the session.
76
+ *
77
+ * @param {object} data Entire journey data.
78
+ * @param {object} validation Page errors (indexed by waypoint id).
79
+ * @param {object} nav Navigation context.
80
+ * @param {object} identity Some metadata for identifying this context among others.
81
+ */
82
+ constructor(data = {}, validation = {}, nav = {}, identity = {}) {
83
+ // Private properties
84
+ _JourneyContext_data.set(this, void 0);
85
+ _JourneyContext_validation.set(this, void 0);
86
+ _JourneyContext_nav.set(this, void 0);
87
+ _JourneyContext_identity.set(this, void 0);
88
+ _JourneyContext_eventListeners.set(this, void 0);
89
+ _JourneyContext_eventListenerPreState.set(this, void 0);
90
+ __classPrivateFieldSet(this, _JourneyContext_data, data, "f");
91
+ __classPrivateFieldSet(this, _JourneyContext_validation, validation, "f");
92
+ __classPrivateFieldSet(this, _JourneyContext_nav, nav, "f");
93
+ __classPrivateFieldSet(this, _JourneyContext_identity, identity, "f");
94
+ __classPrivateFieldSet(this, _JourneyContext_eventListeners, [], "f");
95
+ __classPrivateFieldSet(this, _JourneyContext_eventListenerPreState, null, "f");
96
+ }
97
+ /**
98
+ * Clone into an object that can be stringified.
99
+ *
100
+ * @returns {object} Plain object.
101
+ */
102
+ toObject() {
103
+ return Object.assign(Object.create(null), {
104
+ data: cloneDeep(__classPrivateFieldGet(this, _JourneyContext_data, "f")),
105
+ validation: cloneDeep(__classPrivateFieldGet(this, _JourneyContext_validation, "f")),
106
+ nav: cloneDeep(__classPrivateFieldGet(this, _JourneyContext_nav, "f")),
107
+ identity: cloneDeep(__classPrivateFieldGet(this, _JourneyContext_identity, "f")),
108
+ });
109
+ }
110
+ /**
111
+ * Create a new JourneyContext using the plain object.
112
+ *
113
+ * @param {object} obj Object.
114
+ * @param {object} obj.data Data
115
+ * @param {object} obj.validation Validation state
116
+ * @param {object} obj.nav Navigation meta
117
+ * @param {object} obj.identity Identity meta
118
+ * @returns {JourneyContext} Instance.
119
+ */
120
+ static fromObject({ data = Object.create(null), validation = Object.create(null), nav = Object.create(null), identity = Object.create(null), } = {}) {
121
+ return new JourneyContext(data, validation, nav, identity);
122
+ }
123
+ get data() {
124
+ return __classPrivateFieldGet(this, _JourneyContext_data, "f");
125
+ }
126
+ set data(value) {
127
+ __classPrivateFieldSet(this, _JourneyContext_data, value, "f");
128
+ }
129
+ get validation() {
130
+ return __classPrivateFieldGet(this, _JourneyContext_validation, "f");
131
+ }
132
+ get nav() {
133
+ return __classPrivateFieldGet(this, _JourneyContext_nav, "f");
134
+ }
135
+ get identity() {
136
+ return __classPrivateFieldGet(this, _JourneyContext_identity, "f");
137
+ }
138
+ /**
139
+ * Get data context for a specific a specific page.
140
+ *
141
+ * @param {string | Page} page Page waypoint ID, or Page object.
142
+ * @returns {object} Page data.
143
+ * @throws {TypeError} When page is invalid.
144
+ */
145
+ getDataForPage(page) {
146
+ if (typeof page === 'string') {
147
+ return __classPrivateFieldGet(this, _JourneyContext_data, "f")[page];
148
+ }
149
+ if (isPlainObject(page)) {
150
+ return __classPrivateFieldGet(this, _JourneyContext_data, "f")[page.waypoint];
151
+ }
152
+ throw new TypeError(`Page must be a string or Page object. Got ${typeof page}`);
153
+ }
154
+ getData() {
155
+ return __classPrivateFieldGet(this, _JourneyContext_data, "f");
156
+ }
157
+ /**
158
+ * Overwrite the data context with a new object.
159
+ *
160
+ * @param {object} data Data that will overwrite all existing data.
161
+ * @returns {JourneyContext} Chain.
162
+ */
163
+ setData(data) {
164
+ __classPrivateFieldSet(this, _JourneyContext_data, data, "f");
165
+ return this;
166
+ }
167
+ /**
168
+ * Write field form data from a page HTML form, into the `data` model.
169
+ *
170
+ * By default this will store the data as-is, keyed against the page's
171
+ * waypoint ID. However, when passing a `Page` instance, its
172
+ * `fieldWriter()` method will be called to transform the provided formData
173
+ * before storing in `data`
174
+ *
175
+ * @param {string | Page} page Page waypoint ID, or Page object
176
+ * @param {object} webFormData Data to overwrite with
177
+ * @returns {JourneyContext} Chain
178
+ * @throws {TypeError} When page is invalid.
179
+ */
180
+ setDataForPage(page, webFormData) {
181
+ if (typeof page === 'string') {
182
+ __classPrivateFieldGet(this, _JourneyContext_data, "f")[page] = webFormData;
183
+ }
184
+ else if (isPlainObject(page)) {
185
+ __classPrivateFieldGet(this, _JourneyContext_data, "f")[page.waypoint] = webFormData;
186
+ }
187
+ else {
188
+ throw new TypeError(`Page must be a string or Page object. Got ${typeof page}`);
189
+ }
190
+ return this;
191
+ }
192
+ /**
193
+ * Return validation errors for all pages.
194
+ *
195
+ * @returns {object} All page validation errors.
196
+ */
197
+ getValidationErrors() {
198
+ return __classPrivateFieldGet(this, _JourneyContext_validation, "f");
199
+ }
200
+ /**
201
+ * Removes any validation state for the given page. Clearing validation state
202
+ * completely will, by default, prevent onward traversal from this page. See
203
+ * the traversal logic in Plan class.
204
+ *
205
+ * @param {string} pageId Page ID.
206
+ * @returns {JourneyContext} Chain.
207
+ */
208
+ removeValidationStateForPage(pageId) {
209
+ const _a = __classPrivateFieldGet(this, _JourneyContext_validation, "f"), _b = pageId, dummy = _a[_b], remaining = __rest(_a, [typeof _b === "symbol" ? _b : _b + ""]);
210
+ __classPrivateFieldSet(this, _JourneyContext_validation, Object.assign({}, remaining), "f");
211
+ return this;
212
+ }
213
+ /**
214
+ * Clear any validation errors for the given page. This effectively declares
215
+ * that this page has been successfully validated, and so can be traversed. If
216
+ * you want to remove any knowledge of validation success/failure, use
217
+ * `removeValidationStateForPage()` instead.
218
+ *
219
+ * @param {string} pageId Page ID.
220
+ * @returns {JourneyContext} Chain.
221
+ */
222
+ clearValidationErrorsForPage(pageId) {
223
+ __classPrivateFieldGet(this, _JourneyContext_validation, "f")[pageId] = null;
224
+ return this;
225
+ }
226
+ /**
227
+ * Set validation errors for a page.
228
+ *
229
+ * @param {string} pageId Page ID.
230
+ * @param {ValidationError[]} errors Errors
231
+ * @returns {JourneyContext} Chain.
232
+ * @throws {SyntaxError} When errors are invalid.
233
+ */
234
+ setValidationErrorsForPage(pageId, errors = []) {
235
+ if (!Array.isArray(errors)) {
236
+ throw new SyntaxError(`Errors must be an Array. Received ${Object.prototype.toString.call(errors)}`);
237
+ }
238
+ errors.forEach((error) => {
239
+ if (!(error instanceof ValidationError_js_1.default)) {
240
+ throw new SyntaxError('Field errors must be a ValidationError');
241
+ }
242
+ });
243
+ __classPrivateFieldGet(this, _JourneyContext_validation, "f")[pageId] = errors;
244
+ return this;
245
+ }
246
+ /**
247
+ * Return the validation errors associated with the page's currently held data
248
+ * context (if any).
249
+ *
250
+ * @param {string} pageId Page ID.
251
+ * @returns {ValidationError[]} An array of errors
252
+ */
253
+ getValidationErrorsForPage(pageId) {
254
+ return __classPrivateFieldGet(this, _JourneyContext_validation, "f")[pageId] || [];
255
+ }
256
+ getValidationErrorsForPageByField(pageId) {
257
+ const errors = this.getValidationErrorsForPage(pageId);
258
+ const obj = Object.create(null);
259
+ for (let i = 0, l = errors.length; i < l; i++) {
260
+ if (!obj[errors[i].field]) {
261
+ obj[errors[i].field] = [];
262
+ }
263
+ obj[errors[i].field].push(errors[i]);
264
+ }
265
+ return obj;
266
+ }
267
+ /**
268
+ * Determine whether the specified page has any errors in its validation
269
+ * context.
270
+ *
271
+ * @param {string} pageId Page ID.
272
+ * @returns {boolean} Result.
273
+ */
274
+ hasValidationErrorsForPage(pageId) {
275
+ var _a, _b;
276
+ return ((_b = (_a = __classPrivateFieldGet(this, _JourneyContext_validation, "f")) === null || _a === void 0 ? void 0 : _a[pageId]) === null || _b === void 0 ? void 0 : _b.length) > 0;
277
+ }
278
+ /**
279
+ * Set language of the context.
280
+ *
281
+ * @param {string} language Language to set (ISO 639-1 2-letter code).
282
+ * @returns {JourneyContext} Chain.
283
+ */
284
+ setNavigationLanguage(language = 'en') {
285
+ __classPrivateFieldGet(this, _JourneyContext_nav, "f").language = language;
286
+ return this;
287
+ }
288
+ /**
289
+ * Convenience function to test if page is valid.
290
+ *
291
+ * @param {string} pageId Page ID.
292
+ * @returns {boolean} True if the page is valid.
293
+ */
294
+ isPageValid(pageId) {
295
+ return __classPrivateFieldGet(this, _JourneyContext_validation, "f")[pageId] === null;
296
+ }
297
+ /**
298
+ * Remove information about these waypoints.
299
+ *
300
+ * @param {string[]} waypoints Waypoints to be removed
301
+ */
302
+ purge(waypoints = []) {
303
+ const newData = Object.create(null);
304
+ const newValidation = Object.create(null);
305
+ const toKeep = Object.keys(this.data).filter((w) => !waypoints.includes(w));
306
+ for (let i = 0, l = toKeep.length; i < l; i++) {
307
+ newData[toKeep[i]] = __classPrivateFieldGet(this, _JourneyContext_data, "f")[toKeep[i]];
308
+ newValidation[toKeep[i]] = __classPrivateFieldGet(this, _JourneyContext_validation, "f")[toKeep[i]];
309
+ }
310
+ __classPrivateFieldSet(this, _JourneyContext_data, Object.assign({}, newData), "f");
311
+ __classPrivateFieldSet(this, _JourneyContext_validation, Object.assign({}, newValidation), "f");
312
+ }
313
+ /**
314
+ * Remove validation state from these waypoints. This is useful to quickly
315
+ * force the user to revisit some waypoints.
316
+ *
317
+ * @param {string[]} waypoints Waypoints to be invalidated
318
+ * @returns {void}
319
+ */
320
+ invalidate(waypoints = []) {
321
+ for (let i = 0, l = waypoints.length; i < l; i++) {
322
+ this.removeValidationStateForPage(waypoints[i]);
323
+ }
324
+ }
325
+ /**
326
+ * Event listeners are transient. They are not stored in session, and generally
327
+ * only apply for the current request.
328
+ *
329
+ * They also only act on a fixed snapshot of this context's state, which is
330
+ * taken at the point of attaching the listeners (in the "data" middleware).
331
+ * This is important because JourneyContext.putContext()` could be called many
332
+ * times during a request, so the context will be constantly changing.
333
+ *
334
+ * @param {ContextEvent[]} events Event listeners
335
+ * @returns {JourneyContext} Chain
336
+ */
337
+ addEventListeners(events) {
338
+ __classPrivateFieldSet(this, _JourneyContext_eventListeners, events, "f");
339
+ __classPrivateFieldSet(this, _JourneyContext_eventListenerPreState, this.toObject(), "f");
340
+ return this;
341
+ }
342
+ applyEventListeners({ event }) {
343
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
344
+ if (!__classPrivateFieldGet(this, _JourneyContext_eventListeners, "f").length) {
345
+ return this;
346
+ }
347
+ const previousContext = JourneyContext.fromObject(__classPrivateFieldGet(this, _JourneyContext_eventListenerPreState, "f"));
348
+ const listeners = __classPrivateFieldGet(this, _JourneyContext_eventListeners, "f").filter((l) => l.event === event);
349
+ for (let i = 0, l = listeners.length; i < l; i++) {
350
+ const { waypoint, field, handler } = listeners[i];
351
+ let logMessage;
352
+ let runHandler = false;
353
+ if (!waypoint && !field) {
354
+ logMessage = 'Calling generic event handler';
355
+ runHandler = true;
356
+ }
357
+ else if (waypoint && !field) {
358
+ logMessage = `Calling waypoint-specific event handler on "${waypoint}"`;
359
+ runHandler = ((_a = previousContext.data) === null || _a === void 0 ? void 0 : _a[waypoint]) !== undefined && !isEqual((_b = this.data) === null || _b === void 0 ? void 0 : _b[waypoint], (_c = previousContext.data) === null || _c === void 0 ? void 0 : _c[waypoint]);
360
+ }
361
+ else if (waypoint && field) {
362
+ logMessage = `Calling field-specific event handler on "${waypoint} : ${field}"`;
363
+ runHandler = ((_e = (_d = previousContext.data) === null || _d === void 0 ? void 0 : _d[waypoint]) === null || _e === void 0 ? void 0 : _e[field]) !== undefined && !isEqual((_g = (_f = this.data) === null || _f === void 0 ? void 0 : _f[waypoint]) === null || _g === void 0 ? void 0 : _g[field], (_j = (_h = previousContext.data) === null || _h === void 0 ? void 0 : _h[waypoint]) === null || _j === void 0 ? void 0 : _j[field]);
364
+ }
365
+ if (runHandler) {
366
+ log.trace(logMessage);
367
+ handler({ journeyContext: this, previousContext });
368
+ }
369
+ }
370
+ return this;
371
+ }
372
+ /* ----------------------------------------------- session context handling */
373
+ /**
374
+ * Construct a new JourneyContext instance frmo another instance.
375
+ *
376
+ * @param {JourneyContext} context Context to copy from
377
+ * @returns {JourneyContext} Constructed JourneyContext instance
378
+ * @throws {TypeError} When context is not a valid type
379
+ */
380
+ static fromContext(context) {
381
+ if (!(context instanceof JourneyContext)) {
382
+ throw new TypeError('Source context must be a JourneyContext');
383
+ }
384
+ const newContextObj = context.toObject();
385
+ newContextObj.identity.id = (0, uuid_1.v4)();
386
+ return JourneyContext.fromObject(newContextObj);
387
+ }
388
+ /**
389
+ * Convenience method to determine if this is the default context.
390
+ *
391
+ * @returns {boolean} True if this is the "default" journey context
392
+ */
393
+ isDefault() {
394
+ return __classPrivateFieldGet(this, _JourneyContext_identity, "f").id === JourneyContext.DEFAULT_CONTEXT_ID;
395
+ }
396
+ /**
397
+ * Initialise session with an empty entry for the "default" context.
398
+ *
399
+ * @param {object} session Request session
400
+ * @returns {void}
401
+ */
402
+ static initContextStore(session) {
403
+ if (!has(session, 'journeyContextList')) {
404
+ log.trace('Initialising session with a default journey context list');
405
+ /* eslint-disable-next-line no-param-reassign */
406
+ session.journeyContextList = Object.create(null);
407
+ const defaultContext = new JourneyContext();
408
+ defaultContext.identity.id = JourneyContext.DEFAULT_CONTEXT_ID;
409
+ JourneyContext.putContext(session, defaultContext);
410
+ }
411
+ }
412
+ /**
413
+ * Validate the format of a context ID, i.e. "default" or a uuid
414
+ * eg 00000000-0000-0000-0000-000000000000
415
+ * eg 123e4567-e89b-12d3-a456-426614174000
416
+ *
417
+ * @param {string} id Context ID
418
+ * @returns {string} Original ID if it's valid
419
+ * @throws {TypeError} When id is not a valid type
420
+ * @throws {SyntaxError} When id is not a valid uuid format
421
+ */
422
+ static validateContextId(id) {
423
+ if (id === JourneyContext.DEFAULT_CONTEXT_ID) {
424
+ return JourneyContext.DEFAULT_CONTEXT_ID;
425
+ }
426
+ if (typeof id !== 'string') {
427
+ throw new TypeError('Context ID must be a string');
428
+ }
429
+ else if (!(0, uuid_1.validate)(id)) {
430
+ throw new SyntaxError('Context ID is not in the correct uuid format');
431
+ }
432
+ return id;
433
+ }
434
+ /**
435
+ * Lookup context from session using the ID.
436
+ *
437
+ * @param {object} session Request session
438
+ * @param {string} id Context ID
439
+ * @returns {JourneyContext} The discovered JourneyContext instance
440
+ */
441
+ static getContextById(session, id) {
442
+ if (has(session === null || session === void 0 ? void 0 : session.journeyContextList, id)) {
443
+ return JourneyContext.fromObject(session.journeyContextList[id]);
444
+ }
445
+ return undefined;
446
+ }
447
+ /**
448
+ * Lookup context from session using the name.
449
+ *
450
+ * @param {object} session Request session
451
+ * @param {string} name Context name
452
+ * @returns {JourneyContext} The discovered JourneyContext instance
453
+ */
454
+ static getContextByName(session, name) {
455
+ if (session) {
456
+ const context = Object.values(session.journeyContextList).find((c) => (c.identity.name === name));
457
+ if (context) {
458
+ return JourneyContext.fromObject(context);
459
+ }
460
+ }
461
+ return undefined;
462
+ }
463
+ /**
464
+ * Lookup contexts from session using the tag.
465
+ *
466
+ * @param {object} session Request session
467
+ * @param {string} tag Context tag
468
+ * @returns {Array<JourneyContext>} The discovered JourneyContext instance
469
+ */
470
+ static getContextsByTag(session, tag) {
471
+ if (session) {
472
+ return Object.values(session.journeyContextList).filter((c) => { var _a; return ((_a = c.identity.tags) === null || _a === void 0 ? void 0 : _a.includes(tag)); }).map((c) => (JourneyContext.fromObject(c)));
473
+ }
474
+ return undefined;
475
+ }
476
+ /**
477
+ * Return all contexts currently stored in the session.
478
+ *
479
+ * @param {object} session Request session
480
+ * @returns {Array} Array of contexts
481
+ */
482
+ static getContexts(session) {
483
+ if (has(session, 'journeyContextList')) {
484
+ return Object.values(session.journeyContextList).map((contextObj) => (JourneyContext.fromObject(contextObj)));
485
+ }
486
+ return [];
487
+ }
488
+ /**
489
+ * Put context back into the session store.
490
+ *
491
+ * @param {object} session Request session
492
+ * @param {JourneyContext} context Context
493
+ * @returns {void}
494
+ * @throws {TypeError} When isession is not a valid type, or context has no ID
495
+ */
496
+ static putContext(session, context) {
497
+ if (!isObject(session)) {
498
+ throw new TypeError('Session must be an object');
499
+ }
500
+ else if (!(context instanceof JourneyContext)) {
501
+ throw new TypeError('Context must be a valid JourneyContext');
502
+ }
503
+ else if (context.identity.id === undefined) {
504
+ throw new TypeError('Context must have an ID before storing in session');
505
+ }
506
+ // Initialise the session if necessary
507
+ if (!has(session, 'journeyContextList')) {
508
+ JourneyContext.initContextStore(session);
509
+ }
510
+ // Apply context events
511
+ context.applyEventListeners({
512
+ event: 'waypoint-change',
513
+ previousContextObject: session.journeyContextList[context.identity.id],
514
+ });
515
+ context.applyEventListeners({
516
+ event: 'context-change',
517
+ previousContextObject: session.journeyContextList[context.identity.id],
518
+ });
519
+ /* eslint-disable-next-line no-param-reassign */
520
+ session.journeyContextList[context.identity.id] = context.toObject();
521
+ }
522
+ /**
523
+ * Remove a context from the session store.
524
+ *
525
+ * @param {object} session Request session
526
+ * @param {JourneyContext} context Context
527
+ * @returns {void}
528
+ */
529
+ static removeContext(session, context) {
530
+ if (context instanceof JourneyContext) {
531
+ JourneyContext.removeContextById(session, context.identity.id);
532
+ }
533
+ }
534
+ static removeContextById(session, id) {
535
+ if (session && has(session.journeyContextList, id)) {
536
+ /* eslint-disable-next-line no-param-reassign */
537
+ delete session.journeyContextList[id];
538
+ }
539
+ }
540
+ static removeContextByName(session, name) {
541
+ JourneyContext.removeContext(session, JourneyContext.getContextByName(session, name));
542
+ }
543
+ static removeContextsByTag(session, tag) {
544
+ JourneyContext.getContextsByTag(session, tag).forEach((c) => JourneyContext.removeContext(session, c));
545
+ }
546
+ static removeContexts(session) {
547
+ JourneyContext.getContexts(session).forEach((c) => JourneyContext.removeContext(session, c));
548
+ }
549
+ static extractContextFromRequest(req) {
550
+ JourneyContext.initContextStore(req.session);
551
+ let contextId;
552
+ if (has(req.query, 'contextid')) {
553
+ log.trace('Context ID found in req.query.contextid');
554
+ contextId = String(req.query.contextid);
555
+ }
556
+ else if (has(req === null || req === void 0 ? void 0 : req.body, 'contextid')) {
557
+ log.trace('Context ID found in req.body.contextid');
558
+ contextId = String(req.body.contextid);
559
+ }
560
+ else {
561
+ log.trace('Context ID not specified or not found; will attempt to use default');
562
+ contextId = JourneyContext.DEFAULT_CONTEXT_ID;
563
+ }
564
+ try {
565
+ contextId = JourneyContext.validateContextId(contextId);
566
+ const context = JourneyContext.getContextById(req.session, contextId);
567
+ if (!context) {
568
+ throw (new Error(`Could not find a context with id, ${contextId}`));
569
+ }
570
+ return context;
571
+ }
572
+ catch (err) {
573
+ log.debug(err.message);
574
+ log.trace('Falling back to default context');
575
+ return JourneyContext.getContextById(req.session, JourneyContext.DEFAULT_CONTEXT_ID);
576
+ }
577
+ }
578
+ }
579
+ exports.default = JourneyContext;
580
+ _JourneyContext_data = new WeakMap(), _JourneyContext_validation = new WeakMap(), _JourneyContext_nav = new WeakMap(), _JourneyContext_identity = new WeakMap(), _JourneyContext_eventListeners = new WeakMap(), _JourneyContext_eventListenerPreState = new WeakMap();
581
+ JourneyContext.DEFAULT_CONTEXT_ID = 'default';