@flarehr/apollo-super-selection 5.54.16008 → 5.56.16984

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 (75) hide show
  1. package/dist/lib/apollo-super-selection/apollo-super-selection.css +1 -1
  2. package/dist/lib/apollo-super-selection/apollo-super-selection.esm.js +1 -1
  3. package/dist/lib/apollo-super-selection/apollo-super-selection.js +1 -1
  4. package/dist/lib/apollo-super-selection/{p-ef3afa00.system.entry.js → p-22939048.system.entry.js} +1 -1
  5. package/dist/lib/apollo-super-selection/p-2590548f.system.js +1 -0
  6. package/dist/lib/apollo-super-selection/{p-02f24922.system.entry.js → p-2b42304a.system.entry.js} +1 -1
  7. package/dist/lib/apollo-super-selection/{p-9c855634.entry.js → p-33eca162.entry.js} +1 -1
  8. package/dist/lib/apollo-super-selection/p-3e16df95.system.entry.js +69 -0
  9. package/dist/lib/apollo-super-selection/p-40873393.entry.js +14 -0
  10. package/dist/lib/apollo-super-selection/p-4e871154.entry.js +1 -0
  11. package/dist/lib/apollo-super-selection/{p-6ac8791e.system.entry.js → p-53b231f0.system.entry.js} +1 -1
  12. package/dist/lib/apollo-super-selection/{p-b89b68db.entry.js → p-5c73c587.entry.js} +1 -1
  13. package/dist/lib/apollo-super-selection/p-645755ee.system.entry.js +1 -0
  14. package/dist/lib/apollo-super-selection/{p-fcb4050d.entry.js → p-69bbf1dd.entry.js} +1 -1
  15. package/dist/lib/apollo-super-selection/p-6b03f1b2.entry.js +1 -0
  16. package/dist/lib/apollo-super-selection/{p-44bec843.system.js → p-71ca4cf8.system.js} +1 -1
  17. package/dist/lib/apollo-super-selection/p-97188c78.system.js +1 -0
  18. package/dist/lib/apollo-super-selection/p-99266549.js +1 -0
  19. package/dist/lib/apollo-super-selection/{p-23cfdd82.entry.js → p-9d2a7c0e.entry.js} +1 -1
  20. package/dist/lib/apollo-super-selection/p-bd6e6a8f.system.js +1 -0
  21. package/dist/lib/apollo-super-selection/p-c775c0e4.system.entry.js +1 -0
  22. package/dist/lib/apollo-super-selection/{p-51c6dd08.js → p-db0bded8.js} +1 -1
  23. package/dist/lib/apollo-super-selection/{p-f29066b9.system.entry.js → p-e957b393.system.entry.js} +1 -1
  24. package/dist/lib/apollo-super-selection/{p-7a89efaf.js → p-fdadb647.js} +1 -1
  25. package/dist/lib/cjs/apollo-super-selection.cjs.js +1 -1
  26. package/dist/lib/cjs/custom-fund-choice.api-713823d3.js +3043 -0
  27. package/dist/lib/cjs/loader.cjs.js +1 -1
  28. package/dist/lib/cjs/{sss-button_33.cjs.entry.js → sss-button_31.cjs.entry.js} +395 -3566
  29. package/dist/lib/cjs/sss-super-byof-host.cjs.entry.js +94 -0
  30. package/dist/lib/collection/apollo-super-selection.css +1 -1
  31. package/dist/lib/collection/collection-manifest.json +1 -4
  32. package/dist/lib/collection/components/super-byof/super-byof-types.js +1 -0
  33. package/dist/lib/collection/components/super-byof/super-byof.form.js +1 -0
  34. package/dist/lib/collection/components/super-byof/super-byof.js +120 -0
  35. package/dist/lib/collection/components/super-selection-app/services/super-selection-app.routes.js +1 -1
  36. package/dist/lib/esm/{active-router-5e40c0f8.js → active-router-d18b36fb.js} +1 -1
  37. package/dist/lib/esm/apollo-super-selection.js +2 -2
  38. package/dist/lib/esm/context-consumer.entry.js +1 -1
  39. package/dist/lib/esm/custom-fund-choice.api-45fa478c.js +3022 -0
  40. package/dist/lib/esm/{index-189b2180.js → index-107d7c24.js} +1 -1
  41. package/dist/lib/esm/loader.js +2 -2
  42. package/dist/lib/esm/{sss-button_33.entry.js → sss-button_31.entry.js} +142 -3311
  43. package/dist/lib/esm/sss-super-byof-host.entry.js +90 -0
  44. package/dist/lib/esm/stencil-async-content.entry.js +1 -1
  45. package/dist/lib/esm/stencil-route-title.entry.js +2 -2
  46. package/dist/lib/esm/stencil-router-prompt.entry.js +2 -2
  47. package/dist/lib/esm/stencil-router-redirect.entry.js +2 -2
  48. package/dist/lib/esm-es5/{active-router-5e40c0f8.js → active-router-d18b36fb.js} +1 -1
  49. package/dist/lib/esm-es5/apollo-super-selection.js +1 -1
  50. package/dist/lib/esm-es5/context-consumer.entry.js +1 -1
  51. package/dist/lib/esm-es5/custom-fund-choice.api-45fa478c.js +1 -0
  52. package/dist/lib/esm-es5/{index-189b2180.js → index-107d7c24.js} +1 -1
  53. package/dist/lib/esm-es5/loader.js +1 -1
  54. package/dist/lib/esm-es5/sss-button_31.entry.js +69 -0
  55. package/dist/lib/esm-es5/sss-super-byof-host.entry.js +1 -0
  56. package/dist/lib/esm-es5/stencil-async-content.entry.js +1 -1
  57. package/dist/lib/esm-es5/stencil-route-title.entry.js +1 -1
  58. package/dist/lib/esm-es5/stencil-router-prompt.entry.js +1 -1
  59. package/dist/lib/esm-es5/stencil-router-redirect.entry.js +1 -1
  60. package/dist/lib/types/components/super-byof/super-byof-types.d.ts +26 -0
  61. package/dist/lib/types/components/super-byof/super-byof.d.ts +18 -0
  62. package/dist/lib/types/components/super-byof/super-byof.form.d.ts +6 -0
  63. package/dist/lib/types/components.d.ts +15 -34
  64. package/package.json +2 -1
  65. package/dist/lib/apollo-super-selection/p-071b8545.entry.js +0 -1
  66. package/dist/lib/apollo-super-selection/p-2298df79.system.entry.js +0 -69
  67. package/dist/lib/apollo-super-selection/p-51aefdb1.system.entry.js +0 -1
  68. package/dist/lib/apollo-super-selection/p-80178f87.system.js +0 -1
  69. package/dist/lib/apollo-super-selection/p-bdcfc026.system.js +0 -1
  70. package/dist/lib/apollo-super-selection/p-d7dbf362.entry.js +0 -14
  71. package/dist/lib/collection/components/super-selection-app/funds/custom-fund/my-own-fund/my-own-fund-inputs.js +0 -143
  72. package/dist/lib/collection/components/super-selection-app/funds/custom-fund/my-own-fund/my-own-fund.js +0 -123
  73. package/dist/lib/esm-es5/sss-button_33.entry.js +0 -69
  74. package/dist/lib/types/components/super-selection-app/funds/custom-fund/my-own-fund/my-own-fund-inputs.d.ts +0 -16
  75. package/dist/lib/types/components/super-selection-app/funds/custom-fund/my-own-fund/my-own-fund.d.ts +0 -13
@@ -0,0 +1,3043 @@
1
+ 'use strict';
2
+
3
+ const index = require('./index-eb4f212f.js');
4
+ const activeRouter = require('./active-router-1f555f75.js');
5
+
6
+ // -------------------------------------------------------------------------------------
7
+ // guards
8
+ // -------------------------------------------------------------------------------------
9
+ /**
10
+ * Returns `true` if the option is an instance of `Some`, `false` otherwise.
11
+ *
12
+ * @example
13
+ * import { some, none, isSome } from 'fp-ts/Option'
14
+ *
15
+ * assert.strictEqual(isSome(some(1)), true)
16
+ * assert.strictEqual(isSome(none), false)
17
+ *
18
+ * @category guards
19
+ * @since 2.0.0
20
+ */
21
+ var isSome = function (fa) { return fa._tag === 'Some'; };
22
+ /**
23
+ * Returns `true` if the option is `None`, `false` otherwise.
24
+ *
25
+ * @example
26
+ * import { some, none, isNone } from 'fp-ts/Option'
27
+ *
28
+ * assert.strictEqual(isNone(some(1)), false)
29
+ * assert.strictEqual(isNone(none), true)
30
+ *
31
+ * @category guards
32
+ * @since 2.0.0
33
+ */
34
+ var isNone = function (fa) { return fa._tag === 'None'; };
35
+ // -------------------------------------------------------------------------------------
36
+ // constructors
37
+ // -------------------------------------------------------------------------------------
38
+ /**
39
+ * `None` doesn't have a constructor, instead you can use it directly as a value. Represents a missing value.
40
+ *
41
+ * @category constructors
42
+ * @since 2.0.0
43
+ */
44
+ var none = { _tag: 'None' };
45
+ /**
46
+ * Constructs a `Some`. Represents an optional value that exists.
47
+ *
48
+ * @category constructors
49
+ * @since 2.0.0
50
+ */
51
+ var some = function (a) { return ({ _tag: 'Some', value: a }); };
52
+ /**
53
+ * Constructs a new `Option` from a nullable type. If the value is `null` or `undefined`, returns `None`, otherwise
54
+ * returns the value wrapped in a `Some`.
55
+ *
56
+ * @example
57
+ * import { none, some, fromNullable } from 'fp-ts/Option'
58
+ *
59
+ * assert.deepStrictEqual(fromNullable(undefined), none)
60
+ * assert.deepStrictEqual(fromNullable(null), none)
61
+ * assert.deepStrictEqual(fromNullable(1), some(1))
62
+ *
63
+ * @category constructors
64
+ * @since 2.0.0
65
+ */
66
+ function fromNullable(a) {
67
+ return a == null ? none : some(a);
68
+ }
69
+ /**
70
+ * Extracts the value out of the structure, if it exists. Otherwise returns `undefined`.
71
+ *
72
+ * @example
73
+ * import { some, none, toUndefined } from 'fp-ts/Option'
74
+ * import { pipe } from 'fp-ts/function'
75
+ *
76
+ * assert.strictEqual(
77
+ * pipe(
78
+ * some(1),
79
+ * toUndefined
80
+ * ),
81
+ * 1
82
+ * )
83
+ * assert.strictEqual(
84
+ * pipe(
85
+ * none,
86
+ * toUndefined
87
+ * ),
88
+ * undefined
89
+ * )
90
+ *
91
+ * @category destructors
92
+ * @since 2.0.0
93
+ */
94
+ function toUndefined(ma) {
95
+ return isNone(ma) ? undefined : ma.value;
96
+ }
97
+
98
+ function injectHistory(Component) {
99
+ activeRouter.ActiveRouter.injectProps(Component, ['history', 'location']);
100
+ }
101
+
102
+ function appReady() {
103
+ postMessage({
104
+ type: 'appReady'
105
+ });
106
+ }
107
+ function postMessage(message, origin) {
108
+ if (origin === undefined)
109
+ origin = '*';
110
+ message.sender = 'flare';
111
+ window.parent.postMessage(message, origin);
112
+ }
113
+ function resize(height, width) {
114
+ postMessage({
115
+ type: 'contentResized',
116
+ height,
117
+ width
118
+ });
119
+ }
120
+ function navigation(url) {
121
+ postMessage({
122
+ type: 'pageNavigated',
123
+ url
124
+ });
125
+ }
126
+ function complete() {
127
+ postMessage({ type: 'complete' });
128
+ }
129
+ function submitSuccess() {
130
+ postMessage({
131
+ type: 'submitSuccess'
132
+ });
133
+ }
134
+ const iframe = { appReady, resize, navigation, complete, submitSuccess };
135
+
136
+ const appendToMap = (map, propName, value) => {
137
+ const items = map.get(propName);
138
+ if (!items) {
139
+ map.set(propName, [value]);
140
+ }
141
+ else if (!items.includes(value)) {
142
+ items.push(value);
143
+ }
144
+ };
145
+ const debounce = (fn, ms) => {
146
+ let timeoutId;
147
+ return (...args) => {
148
+ if (timeoutId) {
149
+ clearTimeout(timeoutId);
150
+ }
151
+ timeoutId = setTimeout(() => {
152
+ timeoutId = 0;
153
+ fn(...args);
154
+ }, ms);
155
+ };
156
+ };
157
+
158
+ /**
159
+ * Check if a possible element isConnected.
160
+ * The property might not be there, so we check for it.
161
+ *
162
+ * We want it to return true if isConnected is not a property,
163
+ * otherwise we would remove these elements and would not update.
164
+ *
165
+ * Better leak in Edge than to be useless.
166
+ */
167
+ const isConnected = (maybeElement) => !('isConnected' in maybeElement) || maybeElement.isConnected;
168
+ const cleanupElements = debounce((map) => {
169
+ for (let key of map.keys()) {
170
+ map.set(key, map.get(key).filter(isConnected));
171
+ }
172
+ }, 2000);
173
+ const stencilSubscription = ({ on }) => {
174
+ const elmsToUpdate = new Map();
175
+ if (typeof index.getRenderingRef === 'function') {
176
+ // If we are not in a stencil project, we do nothing.
177
+ // This function is not really exported by @stencil/core.
178
+ on('dispose', () => {
179
+ elmsToUpdate.clear();
180
+ });
181
+ on('get', (propName) => {
182
+ const elm = index.getRenderingRef();
183
+ if (elm) {
184
+ appendToMap(elmsToUpdate, propName, elm);
185
+ }
186
+ });
187
+ on('set', (propName) => {
188
+ const elements = elmsToUpdate.get(propName);
189
+ if (elements) {
190
+ elmsToUpdate.set(propName, elements.filter(index.forceUpdate));
191
+ }
192
+ cleanupElements(elmsToUpdate);
193
+ });
194
+ on('reset', () => {
195
+ elmsToUpdate.forEach((elms) => elms.forEach(index.forceUpdate));
196
+ cleanupElements(elmsToUpdate);
197
+ });
198
+ }
199
+ };
200
+
201
+ const createObservableMap = (defaultState, shouldUpdate = (a, b) => a !== b) => {
202
+ let states = new Map(Object.entries(defaultState !== null && defaultState !== void 0 ? defaultState : {}));
203
+ const handlers = {
204
+ dispose: [],
205
+ get: [],
206
+ set: [],
207
+ reset: [],
208
+ };
209
+ const reset = () => {
210
+ states = new Map(Object.entries(defaultState !== null && defaultState !== void 0 ? defaultState : {}));
211
+ handlers.reset.forEach((cb) => cb());
212
+ };
213
+ const dispose = () => {
214
+ // Call first dispose as resetting the state would
215
+ // cause less updates ;)
216
+ handlers.dispose.forEach((cb) => cb());
217
+ reset();
218
+ };
219
+ const get = (propName) => {
220
+ handlers.get.forEach((cb) => cb(propName));
221
+ return states.get(propName);
222
+ };
223
+ const set = (propName, value) => {
224
+ const oldValue = states.get(propName);
225
+ if (shouldUpdate(value, oldValue, propName)) {
226
+ states.set(propName, value);
227
+ handlers.set.forEach((cb) => cb(propName, value, oldValue));
228
+ }
229
+ };
230
+ const state = (typeof Proxy === 'undefined'
231
+ ? {}
232
+ : new Proxy(defaultState, {
233
+ get(_, propName) {
234
+ return get(propName);
235
+ },
236
+ ownKeys(_) {
237
+ return Array.from(states.keys());
238
+ },
239
+ getOwnPropertyDescriptor() {
240
+ return {
241
+ enumerable: true,
242
+ configurable: true,
243
+ };
244
+ },
245
+ has(_, propName) {
246
+ return states.has(propName);
247
+ },
248
+ set(_, propName, value) {
249
+ set(propName, value);
250
+ return true;
251
+ },
252
+ }));
253
+ const on = (eventName, callback) => {
254
+ handlers[eventName].push(callback);
255
+ return () => {
256
+ removeFromArray(handlers[eventName], callback);
257
+ };
258
+ };
259
+ const onChange = (propName, cb) => {
260
+ const unSet = on('set', (key, newValue) => {
261
+ if (key === propName) {
262
+ cb(newValue);
263
+ }
264
+ });
265
+ const unReset = on('reset', () => cb(defaultState[propName]));
266
+ return () => {
267
+ unSet();
268
+ unReset();
269
+ };
270
+ };
271
+ const use = (...subscriptions) => subscriptions.forEach((subscription) => {
272
+ if (subscription.set) {
273
+ on('set', subscription.set);
274
+ }
275
+ if (subscription.get) {
276
+ on('get', subscription.get);
277
+ }
278
+ if (subscription.reset) {
279
+ on('reset', subscription.reset);
280
+ }
281
+ });
282
+ return {
283
+ state,
284
+ get,
285
+ set,
286
+ on,
287
+ onChange,
288
+ use,
289
+ dispose,
290
+ reset,
291
+ };
292
+ };
293
+ const removeFromArray = (array, item) => {
294
+ const index = array.indexOf(item);
295
+ if (index >= 0) {
296
+ array[index] = array[array.length - 1];
297
+ array.length--;
298
+ }
299
+ };
300
+
301
+ const createStore = (defaultState, shouldUpdate) => {
302
+ const map = createObservableMap(defaultState, shouldUpdate);
303
+ stencilSubscription(map);
304
+ return map;
305
+ };
306
+
307
+ const initial = {
308
+ handleSubmitFn: async function () {
309
+ return;
310
+ },
311
+ fundName: '',
312
+ fundDetails: { type: 'null' },
313
+ promotedFundId: undefined
314
+ };
315
+ const { state } = createStore(initial);
316
+
317
+ (function (SuperSelectionAppRoutes) {
318
+ SuperSelectionAppRoutes["ExistingChoicePage"] = "/existing";
319
+ SuperSelectionAppRoutes["SuperCampaign"] = "/super-campaign";
320
+ SuperSelectionAppRoutes["ChoicePage"] = "/";
321
+ SuperSelectionAppRoutes["MyOwnFund"] = "/super-choice/my-own-fund/";
322
+ SuperSelectionAppRoutes["MyOwnFundEngagementStep"] = "/super-choice/my-own-fund-engagement/";
323
+ SuperSelectionAppRoutes["Prefill"] = "/super-choice/prefill/";
324
+ SuperSelectionAppRoutes["PrefillInvalidMyOwnFundPage"] = "/super-choice/sss-prefill-invalid-my-own-fund/";
325
+ SuperSelectionAppRoutes["PrefillMyOwnFundPage"] = "/super-choice/prefill-my-own-fund/";
326
+ SuperSelectionAppRoutes["PrefillSMSFPage"] = "/super-choice/prefill-smsf/";
327
+ SuperSelectionAppRoutes["PrefillInvalidSMSFPage"] = "/super-choice/prefill-invalid-smsf/";
328
+ SuperSelectionAppRoutes["SelfManagedFund"] = "/super-choice/smsf/";
329
+ SuperSelectionAppRoutes["DefaultFund"] = "/super-choice/default/";
330
+ SuperSelectionAppRoutes["FeaturedFunds"] = "/super-choice/featured-funds/";
331
+ SuperSelectionAppRoutes["StandardChoice"] = "/standard-choice/";
332
+ SuperSelectionAppRoutes["Success"] = "/success/";
333
+ })(exports.SuperSelectionAppRoutes || (exports.SuperSelectionAppRoutes = {}));
334
+ const superSelectionAppStencilRoutes = [
335
+ index.h("stencil-route", { url: exports.SuperSelectionAppRoutes.ExistingChoicePage, component: "sss-existing-choice-page" }),
336
+ index.h("stencil-route", { url: exports.SuperSelectionAppRoutes.SuperCampaign, component: "sss-super-campaign-host" }),
337
+ index.h("stencil-route", { exact: true, url: exports.SuperSelectionAppRoutes.ChoicePage, component: "sss-choice-router" }),
338
+ index.h("stencil-route", { url: exports.SuperSelectionAppRoutes.MyOwnFund, component: "sss-super-byof-host" }),
339
+ index.h("stencil-route", { url: exports.SuperSelectionAppRoutes.MyOwnFundEngagementStep, component: "sss-my-own-fund-engagement-step-host" }),
340
+ index.h("stencil-route", { url: exports.SuperSelectionAppRoutes.PrefillInvalidMyOwnFundPage, component: "sss-prefill-invalid-my-own-fund" }),
341
+ index.h("stencil-route", { url: exports.SuperSelectionAppRoutes.Prefill, component: "sss-prefill" }),
342
+ index.h("stencil-route", { url: exports.SuperSelectionAppRoutes.PrefillMyOwnFundPage, component: "sss-prefill-my-own-fund" }),
343
+ index.h("stencil-route", { url: exports.SuperSelectionAppRoutes.PrefillSMSFPage, component: "sss-prefill-smsf" }),
344
+ index.h("stencil-route", { url: exports.SuperSelectionAppRoutes.PrefillInvalidSMSFPage, component: "sss-prefill-invalid-smsf" }),
345
+ index.h("stencil-route", { url: exports.SuperSelectionAppRoutes.SelfManagedFund, component: "sss-super-smsf-host" }),
346
+ index.h("stencil-route", { url: exports.SuperSelectionAppRoutes.DefaultFund, component: "sss-default-fund" }),
347
+ index.h("stencil-route", { url: exports.SuperSelectionAppRoutes.FeaturedFunds, component: "sss-super-campaign-featured-funds" }),
348
+ index.h("stencil-route", { url: exports.SuperSelectionAppRoutes.StandardChoice, component: "sss-standard-choice-form" }),
349
+ index.h("stencil-route", { url: exports.SuperSelectionAppRoutes.Success, component: "sss-success" })
350
+ ];
351
+
352
+ function createCommonjsModule(fn, basedir, module) {
353
+ return module = {
354
+ path: basedir,
355
+ exports: {},
356
+ require: function (path, base) {
357
+ return commonjsRequire();
358
+ }
359
+ }, fn(module, module.exports), module.exports;
360
+ }
361
+
362
+ function commonjsRequire () {
363
+ throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
364
+ }
365
+
366
+ var _function = createCommonjsModule(function (module, exports) {
367
+ /**
368
+ * @since 2.0.0
369
+ */
370
+ Object.defineProperty(exports, "__esModule", { value: true });
371
+ exports.bindTo_ = exports.bind_ = exports.hole = exports.pipe = exports.untupled = exports.tupled = exports.absurd = exports.decrement = exports.increment = exports.tuple = exports.flow = exports.flip = exports.constVoid = exports.constUndefined = exports.constNull = exports.constFalse = exports.constTrue = exports.constant = exports.not = exports.unsafeCoerce = exports.identity = void 0;
372
+ /**
373
+ * @since 2.0.0
374
+ */
375
+ function identity(a) {
376
+ return a;
377
+ }
378
+ exports.identity = identity;
379
+ /**
380
+ * @since 2.0.0
381
+ */
382
+ exports.unsafeCoerce = identity;
383
+ /**
384
+ * @since 2.0.0
385
+ */
386
+ function not(predicate) {
387
+ return function (a) { return !predicate(a); };
388
+ }
389
+ exports.not = not;
390
+ /**
391
+ * @since 2.0.0
392
+ */
393
+ function constant(a) {
394
+ return function () { return a; };
395
+ }
396
+ exports.constant = constant;
397
+ /**
398
+ * A thunk that returns always `true`.
399
+ *
400
+ * @since 2.0.0
401
+ */
402
+ exports.constTrue =
403
+ /*#__PURE__*/
404
+ constant(true);
405
+ /**
406
+ * A thunk that returns always `false`.
407
+ *
408
+ * @since 2.0.0
409
+ */
410
+ exports.constFalse =
411
+ /*#__PURE__*/
412
+ constant(false);
413
+ /**
414
+ * A thunk that returns always `null`.
415
+ *
416
+ * @since 2.0.0
417
+ */
418
+ exports.constNull =
419
+ /*#__PURE__*/
420
+ constant(null);
421
+ /**
422
+ * A thunk that returns always `undefined`.
423
+ *
424
+ * @since 2.0.0
425
+ */
426
+ exports.constUndefined =
427
+ /*#__PURE__*/
428
+ constant(undefined);
429
+ /**
430
+ * A thunk that returns always `void`.
431
+ *
432
+ * @since 2.0.0
433
+ */
434
+ exports.constVoid = exports.constUndefined;
435
+ // TODO: remove in v3
436
+ /**
437
+ * Flips the order of the arguments of a function of two arguments.
438
+ *
439
+ * @since 2.0.0
440
+ */
441
+ function flip(f) {
442
+ return function (b, a) { return f(a, b); };
443
+ }
444
+ exports.flip = flip;
445
+ function flow(ab, bc, cd, de, ef, fg, gh, hi, ij) {
446
+ switch (arguments.length) {
447
+ case 1:
448
+ return ab;
449
+ case 2:
450
+ return function () {
451
+ return bc(ab.apply(this, arguments));
452
+ };
453
+ case 3:
454
+ return function () {
455
+ return cd(bc(ab.apply(this, arguments)));
456
+ };
457
+ case 4:
458
+ return function () {
459
+ return de(cd(bc(ab.apply(this, arguments))));
460
+ };
461
+ case 5:
462
+ return function () {
463
+ return ef(de(cd(bc(ab.apply(this, arguments)))));
464
+ };
465
+ case 6:
466
+ return function () {
467
+ return fg(ef(de(cd(bc(ab.apply(this, arguments))))));
468
+ };
469
+ case 7:
470
+ return function () {
471
+ return gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))));
472
+ };
473
+ case 8:
474
+ return function () {
475
+ return hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments))))))));
476
+ };
477
+ case 9:
478
+ return function () {
479
+ return ij(hi(gh(fg(ef(de(cd(bc(ab.apply(this, arguments)))))))));
480
+ };
481
+ }
482
+ return;
483
+ }
484
+ exports.flow = flow;
485
+ /**
486
+ * @since 2.0.0
487
+ */
488
+ function tuple() {
489
+ var t = [];
490
+ for (var _i = 0; _i < arguments.length; _i++) {
491
+ t[_i] = arguments[_i];
492
+ }
493
+ return t;
494
+ }
495
+ exports.tuple = tuple;
496
+ /**
497
+ * @since 2.0.0
498
+ */
499
+ function increment(n) {
500
+ return n + 1;
501
+ }
502
+ exports.increment = increment;
503
+ /**
504
+ * @since 2.0.0
505
+ */
506
+ function decrement(n) {
507
+ return n - 1;
508
+ }
509
+ exports.decrement = decrement;
510
+ /**
511
+ * @since 2.0.0
512
+ */
513
+ function absurd(_) {
514
+ throw new Error('Called `absurd` function which should be uncallable');
515
+ }
516
+ exports.absurd = absurd;
517
+ /**
518
+ * Creates a tupled version of this function: instead of `n` arguments, it accepts a single tuple argument.
519
+ *
520
+ * @example
521
+ * import { tupled } from 'fp-ts/function'
522
+ *
523
+ * const add = tupled((x: number, y: number): number => x + y)
524
+ *
525
+ * assert.strictEqual(add([1, 2]), 3)
526
+ *
527
+ * @since 2.4.0
528
+ */
529
+ function tupled(f) {
530
+ return function (a) { return f.apply(void 0, a); };
531
+ }
532
+ exports.tupled = tupled;
533
+ /**
534
+ * Inverse function of `tupled`
535
+ *
536
+ * @since 2.4.0
537
+ */
538
+ function untupled(f) {
539
+ return function () {
540
+ var a = [];
541
+ for (var _i = 0; _i < arguments.length; _i++) {
542
+ a[_i] = arguments[_i];
543
+ }
544
+ return f(a);
545
+ };
546
+ }
547
+ exports.untupled = untupled;
548
+ function pipe(a, ab, bc, cd, de, ef, fg, gh, hi, ij, jk, kl, lm, mn, no, op, pq, qr, rs, st) {
549
+ switch (arguments.length) {
550
+ case 1:
551
+ return a;
552
+ case 2:
553
+ return ab(a);
554
+ case 3:
555
+ return bc(ab(a));
556
+ case 4:
557
+ return cd(bc(ab(a)));
558
+ case 5:
559
+ return de(cd(bc(ab(a))));
560
+ case 6:
561
+ return ef(de(cd(bc(ab(a)))));
562
+ case 7:
563
+ return fg(ef(de(cd(bc(ab(a))))));
564
+ case 8:
565
+ return gh(fg(ef(de(cd(bc(ab(a)))))));
566
+ case 9:
567
+ return hi(gh(fg(ef(de(cd(bc(ab(a))))))));
568
+ case 10:
569
+ return ij(hi(gh(fg(ef(de(cd(bc(ab(a)))))))));
570
+ case 11:
571
+ return jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a))))))))));
572
+ case 12:
573
+ return kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a)))))))))));
574
+ case 13:
575
+ return lm(kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a))))))))))));
576
+ case 14:
577
+ return mn(lm(kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a)))))))))))));
578
+ case 15:
579
+ return no(mn(lm(kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a))))))))))))));
580
+ case 16:
581
+ return op(no(mn(lm(kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a)))))))))))))));
582
+ case 17:
583
+ return pq(op(no(mn(lm(kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a))))))))))))))));
584
+ case 18:
585
+ return qr(pq(op(no(mn(lm(kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a)))))))))))))))));
586
+ case 19:
587
+ return rs(qr(pq(op(no(mn(lm(kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a))))))))))))))))));
588
+ case 20:
589
+ return st(rs(qr(pq(op(no(mn(lm(kl(jk(ij(hi(gh(fg(ef(de(cd(bc(ab(a)))))))))))))))))));
590
+ }
591
+ return;
592
+ }
593
+ exports.pipe = pipe;
594
+ /**
595
+ * Type hole simulation
596
+ *
597
+ * @since 2.7.0
598
+ */
599
+ exports.hole = absurd;
600
+ /**
601
+ * @internal
602
+ */
603
+ var bind_ = function (a, name, b) {
604
+ var _a;
605
+ return Object.assign({}, a, (_a = {}, _a[name] = b, _a));
606
+ };
607
+ exports.bind_ = bind_;
608
+ /**
609
+ * @internal
610
+ */
611
+ var bindTo_ = function (name) { return function (b) {
612
+ var _a;
613
+ return (_a = {}, _a[name] = b, _a);
614
+ }; };
615
+ exports.bindTo_ = bindTo_;
616
+ });
617
+
618
+ var Option = createCommonjsModule(function (module, exports) {
619
+ Object.defineProperty(exports, "__esModule", { value: true });
620
+ exports.getApplySemigroup = exports.getOrd = exports.getEq = exports.getShow = exports.URI = exports.wilt = exports.wither = exports.sequence = exports.traverse = exports.partitionMap = exports.partition = exports.filterMap = exports.filter = exports.separate = exports.compact = exports.reduceRight = exports.foldMap = exports.reduce = exports.duplicate = exports.extend = exports.throwError = exports.zero = exports.alt = exports.altW = exports.flatten = exports.chainFirst = exports.chain = exports.of = exports.apSecond = exports.apFirst = exports.ap = exports.map = exports.chainNullableK = exports.mapNullable = exports.fromNullableK = exports.getOrElse = exports.getOrElseW = exports.toUndefined = exports.toNullable = exports.fold = exports.fromEither = exports.getRight = exports.getLeft = exports.tryCatch = exports.fromPredicate = exports.fromNullable = exports.some = exports.none = exports.isNone = exports.isSome = void 0;
621
+ exports.sequenceArray = exports.traverseArray = exports.traverseArrayWithIndex = exports.apS = exports.bind = exports.bindTo = exports.Do = exports.getRefinement = exports.exists = exports.elem = exports.option = exports.MonadThrow = exports.Witherable = exports.Traversable = exports.Filterable = exports.Compactable = exports.Extend = exports.Alternative = exports.Alt = exports.Foldable = exports.Monad = exports.Applicative = exports.Functor = exports.getMonoid = exports.getLastMonoid = exports.getFirstMonoid = exports.getApplyMonoid = void 0;
622
+
623
+ // -------------------------------------------------------------------------------------
624
+ // guards
625
+ // -------------------------------------------------------------------------------------
626
+ /**
627
+ * Returns `true` if the option is an instance of `Some`, `false` otherwise.
628
+ *
629
+ * @example
630
+ * import { some, none, isSome } from 'fp-ts/Option'
631
+ *
632
+ * assert.strictEqual(isSome(some(1)), true)
633
+ * assert.strictEqual(isSome(none), false)
634
+ *
635
+ * @category guards
636
+ * @since 2.0.0
637
+ */
638
+ var isSome = function (fa) { return fa._tag === 'Some'; };
639
+ exports.isSome = isSome;
640
+ /**
641
+ * Returns `true` if the option is `None`, `false` otherwise.
642
+ *
643
+ * @example
644
+ * import { some, none, isNone } from 'fp-ts/Option'
645
+ *
646
+ * assert.strictEqual(isNone(some(1)), false)
647
+ * assert.strictEqual(isNone(none), true)
648
+ *
649
+ * @category guards
650
+ * @since 2.0.0
651
+ */
652
+ var isNone = function (fa) { return fa._tag === 'None'; };
653
+ exports.isNone = isNone;
654
+ // -------------------------------------------------------------------------------------
655
+ // constructors
656
+ // -------------------------------------------------------------------------------------
657
+ /**
658
+ * `None` doesn't have a constructor, instead you can use it directly as a value. Represents a missing value.
659
+ *
660
+ * @category constructors
661
+ * @since 2.0.0
662
+ */
663
+ exports.none = { _tag: 'None' };
664
+ /**
665
+ * Constructs a `Some`. Represents an optional value that exists.
666
+ *
667
+ * @category constructors
668
+ * @since 2.0.0
669
+ */
670
+ var some = function (a) { return ({ _tag: 'Some', value: a }); };
671
+ exports.some = some;
672
+ /**
673
+ * Constructs a new `Option` from a nullable type. If the value is `null` or `undefined`, returns `None`, otherwise
674
+ * returns the value wrapped in a `Some`.
675
+ *
676
+ * @example
677
+ * import { none, some, fromNullable } from 'fp-ts/Option'
678
+ *
679
+ * assert.deepStrictEqual(fromNullable(undefined), none)
680
+ * assert.deepStrictEqual(fromNullable(null), none)
681
+ * assert.deepStrictEqual(fromNullable(1), some(1))
682
+ *
683
+ * @category constructors
684
+ * @since 2.0.0
685
+ */
686
+ function fromNullable(a) {
687
+ return a == null ? exports.none : exports.some(a);
688
+ }
689
+ exports.fromNullable = fromNullable;
690
+ function fromPredicate(predicate) {
691
+ return function (a) { return (predicate(a) ? exports.some(a) : exports.none); };
692
+ }
693
+ exports.fromPredicate = fromPredicate;
694
+ /**
695
+ * Transforms an exception into an `Option`. If `f` throws, returns `None`, otherwise returns the output wrapped in a
696
+ * `Some`.
697
+ *
698
+ * @example
699
+ * import { none, some, tryCatch } from 'fp-ts/Option'
700
+ *
701
+ * assert.deepStrictEqual(
702
+ * tryCatch(() => {
703
+ * throw new Error()
704
+ * }),
705
+ * none
706
+ * )
707
+ * assert.deepStrictEqual(tryCatch(() => 1), some(1))
708
+ *
709
+ * @category constructors
710
+ * @since 2.0.0
711
+ */
712
+ function tryCatch(f) {
713
+ try {
714
+ return exports.some(f());
715
+ }
716
+ catch (e) {
717
+ return exports.none;
718
+ }
719
+ }
720
+ exports.tryCatch = tryCatch;
721
+ /**
722
+ * Returns the `Left` value of an `Either` if possible.
723
+ *
724
+ * @example
725
+ * import { getLeft, none, some } from 'fp-ts/Option'
726
+ * import { right, left } from 'fp-ts/Either'
727
+ *
728
+ * assert.deepStrictEqual(getLeft(right(1)), none)
729
+ * assert.deepStrictEqual(getLeft(left('a')), some('a'))
730
+ *
731
+ * @category constructors
732
+ * @since 2.0.0
733
+ */
734
+ function getLeft(ma) {
735
+ return ma._tag === 'Right' ? exports.none : exports.some(ma.left);
736
+ }
737
+ exports.getLeft = getLeft;
738
+ /**
739
+ * Returns the `Right` value of an `Either` if possible.
740
+ *
741
+ * @example
742
+ * import { getRight, none, some } from 'fp-ts/Option'
743
+ * import { right, left } from 'fp-ts/Either'
744
+ *
745
+ * assert.deepStrictEqual(getRight(right(1)), some(1))
746
+ * assert.deepStrictEqual(getRight(left('a')), none)
747
+ *
748
+ * @category constructors
749
+ * @since 2.0.0
750
+ */
751
+ function getRight(ma) {
752
+ return ma._tag === 'Left' ? exports.none : exports.some(ma.right);
753
+ }
754
+ exports.getRight = getRight;
755
+ /**
756
+ * Transforms an `Either` to an `Option` discarding the error.
757
+ *
758
+ * Alias of [getRight](#getRight)
759
+ *
760
+ * Derivable from `MonadThrow`.
761
+ *
762
+ * @category constructors
763
+ * @since 2.0.0
764
+ */
765
+ exports.fromEither = getRight;
766
+ // -------------------------------------------------------------------------------------
767
+ // destructors
768
+ // -------------------------------------------------------------------------------------
769
+ /**
770
+ * Takes a (lazy) default value, a function, and an `Option` value, if the `Option` value is `None` the default value is
771
+ * returned, otherwise the function is applied to the value inside the `Some` and the result is returned.
772
+ *
773
+ * @example
774
+ * import { some, none, fold } from 'fp-ts/Option'
775
+ * import { pipe } from 'fp-ts/function'
776
+ *
777
+ * assert.strictEqual(
778
+ * pipe(
779
+ * some(1),
780
+ * fold(() => 'a none', a => `a some containing ${a}`)
781
+ * ),
782
+ * 'a some containing 1'
783
+ * )
784
+ *
785
+ * assert.strictEqual(
786
+ * pipe(
787
+ * none,
788
+ * fold(() => 'a none', a => `a some containing ${a}`)
789
+ * ),
790
+ * 'a none'
791
+ * )
792
+ *
793
+ * @category destructors
794
+ * @since 2.0.0
795
+ */
796
+ function fold(onNone, onSome) {
797
+ return function (ma) { return (exports.isNone(ma) ? onNone() : onSome(ma.value)); };
798
+ }
799
+ exports.fold = fold;
800
+ /**
801
+ * Extracts the value out of the structure, if it exists. Otherwise returns `null`.
802
+ *
803
+ * @example
804
+ * import { some, none, toNullable } from 'fp-ts/Option'
805
+ * import { pipe } from 'fp-ts/function'
806
+ *
807
+ * assert.strictEqual(
808
+ * pipe(
809
+ * some(1),
810
+ * toNullable
811
+ * ),
812
+ * 1
813
+ * )
814
+ * assert.strictEqual(
815
+ * pipe(
816
+ * none,
817
+ * toNullable
818
+ * ),
819
+ * null
820
+ * )
821
+ *
822
+ * @category destructors
823
+ * @since 2.0.0
824
+ */
825
+ function toNullable(ma) {
826
+ return exports.isNone(ma) ? null : ma.value;
827
+ }
828
+ exports.toNullable = toNullable;
829
+ /**
830
+ * Extracts the value out of the structure, if it exists. Otherwise returns `undefined`.
831
+ *
832
+ * @example
833
+ * import { some, none, toUndefined } from 'fp-ts/Option'
834
+ * import { pipe } from 'fp-ts/function'
835
+ *
836
+ * assert.strictEqual(
837
+ * pipe(
838
+ * some(1),
839
+ * toUndefined
840
+ * ),
841
+ * 1
842
+ * )
843
+ * assert.strictEqual(
844
+ * pipe(
845
+ * none,
846
+ * toUndefined
847
+ * ),
848
+ * undefined
849
+ * )
850
+ *
851
+ * @category destructors
852
+ * @since 2.0.0
853
+ */
854
+ function toUndefined(ma) {
855
+ return exports.isNone(ma) ? undefined : ma.value;
856
+ }
857
+ exports.toUndefined = toUndefined;
858
+ /**
859
+ * Less strict version of [`getOrElse`](#getOrElse).
860
+ *
861
+ * @category destructors
862
+ * @since 2.6.0
863
+ */
864
+ var getOrElseW = function (onNone) { return function (ma) { return (exports.isNone(ma) ? onNone() : ma.value); }; };
865
+ exports.getOrElseW = getOrElseW;
866
+ /**
867
+ * Extracts the value out of the structure, if it exists. Otherwise returns the given default value
868
+ *
869
+ * @example
870
+ * import { some, none, getOrElse } from 'fp-ts/Option'
871
+ * import { pipe } from 'fp-ts/function'
872
+ *
873
+ * assert.strictEqual(
874
+ * pipe(
875
+ * some(1),
876
+ * getOrElse(() => 0)
877
+ * ),
878
+ * 1
879
+ * )
880
+ * assert.strictEqual(
881
+ * pipe(
882
+ * none,
883
+ * getOrElse(() => 0)
884
+ * ),
885
+ * 0
886
+ * )
887
+ *
888
+ * @category destructors
889
+ * @since 2.0.0
890
+ */
891
+ exports.getOrElse = exports.getOrElseW;
892
+ // -------------------------------------------------------------------------------------
893
+ // combinators
894
+ // -------------------------------------------------------------------------------------
895
+ /**
896
+ * Returns a *smart constructor* from a function that returns a nullable value.
897
+ *
898
+ * @example
899
+ * import { fromNullableK, none, some } from 'fp-ts/Option'
900
+ *
901
+ * const f = (s: string): number | undefined => {
902
+ * const n = parseFloat(s)
903
+ * return isNaN(n) ? undefined : n
904
+ * }
905
+ *
906
+ * const g = fromNullableK(f)
907
+ *
908
+ * assert.deepStrictEqual(g('1'), some(1))
909
+ * assert.deepStrictEqual(g('a'), none)
910
+ *
911
+ * @category combinators
912
+ * @since 2.9.0
913
+ */
914
+ function fromNullableK(f) {
915
+ return function () {
916
+ var a = [];
917
+ for (var _i = 0; _i < arguments.length; _i++) {
918
+ a[_i] = arguments[_i];
919
+ }
920
+ return fromNullable(f.apply(void 0, a));
921
+ };
922
+ }
923
+ exports.fromNullableK = fromNullableK;
924
+ /**
925
+ * @category combinators
926
+ * @since 2.0.0
927
+ * @deprecated
928
+ */
929
+ exports.mapNullable = chainNullableK;
930
+ /**
931
+ * This is `chain` + `fromNullable`, useful when working with optional values.
932
+ *
933
+ * @example
934
+ * import { some, none, fromNullable, chainNullableK } from 'fp-ts/Option'
935
+ * import { pipe } from 'fp-ts/function'
936
+ *
937
+ * interface Employee {
938
+ * company?: {
939
+ * address?: {
940
+ * street?: {
941
+ * name?: string
942
+ * }
943
+ * }
944
+ * }
945
+ * }
946
+ *
947
+ * const employee1: Employee = { company: { address: { street: { name: 'high street' } } } }
948
+ *
949
+ * assert.deepStrictEqual(
950
+ * pipe(
951
+ * fromNullable(employee1.company),
952
+ * chainNullableK(company => company.address),
953
+ * chainNullableK(address => address.street),
954
+ * chainNullableK(street => street.name)
955
+ * ),
956
+ * some('high street')
957
+ * )
958
+ *
959
+ * const employee2: Employee = { company: { address: { street: {} } } }
960
+ *
961
+ * assert.deepStrictEqual(
962
+ * pipe(
963
+ * fromNullable(employee2.company),
964
+ * chainNullableK(company => company.address),
965
+ * chainNullableK(address => address.street),
966
+ * chainNullableK(street => street.name)
967
+ * ),
968
+ * none
969
+ * )
970
+ *
971
+ * @category combinators
972
+ * @since 2.9.0
973
+ */
974
+ function chainNullableK(f) {
975
+ return function (ma) { return (exports.isNone(ma) ? exports.none : fromNullable(f(ma.value))); };
976
+ }
977
+ exports.chainNullableK = chainNullableK;
978
+ // -------------------------------------------------------------------------------------
979
+ // non-pipeables
980
+ // -------------------------------------------------------------------------------------
981
+ var map_ = function (fa, f) { return _function.pipe(fa, exports.map(f)); };
982
+ var ap_ = function (fab, fa) { return _function.pipe(fab, exports.ap(fa)); };
983
+ var chain_ = function (ma, f) { return _function.pipe(ma, exports.chain(f)); };
984
+ var reduce_ = function (fa, b, f) { return _function.pipe(fa, exports.reduce(b, f)); };
985
+ var foldMap_ = function (M) {
986
+ var foldMapM = exports.foldMap(M);
987
+ return function (fa, f) { return _function.pipe(fa, foldMapM(f)); };
988
+ };
989
+ var reduceRight_ = function (fa, b, f) { return _function.pipe(fa, exports.reduceRight(b, f)); };
990
+ var traverse_ = function (F) {
991
+ var traverseF = exports.traverse(F);
992
+ return function (ta, f) { return _function.pipe(ta, traverseF(f)); };
993
+ };
994
+ /* istanbul ignore next */
995
+ var alt_ = function (fa, that) { return _function.pipe(fa, exports.alt(that)); };
996
+ var filter_ = function (fa, predicate) {
997
+ return _function.pipe(fa, exports.filter(predicate));
998
+ };
999
+ /* istanbul ignore next */
1000
+ var filterMap_ = function (fa, f) { return _function.pipe(fa, exports.filterMap(f)); };
1001
+ /* istanbul ignore next */
1002
+ var extend_ = function (wa, f) { return _function.pipe(wa, exports.extend(f)); };
1003
+ /* istanbul ignore next */
1004
+ var partition_ = function (fa, predicate) { return _function.pipe(fa, exports.partition(predicate)); };
1005
+ /* istanbul ignore next */
1006
+ var partitionMap_ = function (fa, f) { return _function.pipe(fa, exports.partitionMap(f)); };
1007
+ /* istanbul ignore next */
1008
+ var wither_ = function (F) {
1009
+ var witherF = exports.wither(F);
1010
+ return function (fa, f) { return _function.pipe(fa, witherF(f)); };
1011
+ };
1012
+ /* istanbul ignore next */
1013
+ var wilt_ = function (F) {
1014
+ var wiltF = exports.wilt(F);
1015
+ return function (fa, f) { return _function.pipe(fa, wiltF(f)); };
1016
+ };
1017
+ // -------------------------------------------------------------------------------------
1018
+ // pipeables
1019
+ // -------------------------------------------------------------------------------------
1020
+ /**
1021
+ * `map` can be used to turn functions `(a: A) => B` into functions `(fa: F<A>) => F<B>` whose argument and return types
1022
+ * use the type constructor `F` to represent some computational context.
1023
+ *
1024
+ * @category Functor
1025
+ * @since 2.0.0
1026
+ */
1027
+ var map = function (f) { return function (fa) {
1028
+ return exports.isNone(fa) ? exports.none : exports.some(f(fa.value));
1029
+ }; };
1030
+ exports.map = map;
1031
+ /**
1032
+ * Apply a function to an argument under a type constructor.
1033
+ *
1034
+ * @category Apply
1035
+ * @since 2.0.0
1036
+ */
1037
+ var ap = function (fa) { return function (fab) {
1038
+ return exports.isNone(fab) ? exports.none : exports.isNone(fa) ? exports.none : exports.some(fab.value(fa.value));
1039
+ }; };
1040
+ exports.ap = ap;
1041
+ /**
1042
+ * Combine two effectful actions, keeping only the result of the first.
1043
+ *
1044
+ * Derivable from `Apply`.
1045
+ *
1046
+ * @category combinators
1047
+ * @since 2.0.0
1048
+ */
1049
+ var apFirst = function (fb) {
1050
+ return _function.flow(exports.map(function (a) { return function () { return a; }; }), exports.ap(fb));
1051
+ };
1052
+ exports.apFirst = apFirst;
1053
+ /**
1054
+ * Combine two effectful actions, keeping only the result of the second.
1055
+ *
1056
+ * Derivable from `Apply`.
1057
+ *
1058
+ * @category combinators
1059
+ * @since 2.0.0
1060
+ */
1061
+ var apSecond = function (fb) {
1062
+ return _function.flow(exports.map(function () { return function (b) { return b; }; }), exports.ap(fb));
1063
+ };
1064
+ exports.apSecond = apSecond;
1065
+ /**
1066
+ * Wrap a value into the type constructor.
1067
+ *
1068
+ * @category Applicative
1069
+ * @since 2.7.0
1070
+ */
1071
+ exports.of = exports.some;
1072
+ /**
1073
+ * Composes computations in sequence, using the return value of one computation to determine the next computation.
1074
+ *
1075
+ * @category Monad
1076
+ * @since 2.0.0
1077
+ */
1078
+ var chain = function (f) { return function (ma) {
1079
+ return exports.isNone(ma) ? exports.none : f(ma.value);
1080
+ }; };
1081
+ exports.chain = chain;
1082
+ /**
1083
+ * Composes computations in sequence, using the return value of one computation to determine the next computation and
1084
+ * keeping only the result of the first.
1085
+ *
1086
+ * Derivable from `Monad`.
1087
+ *
1088
+ * @category combinators
1089
+ * @since 2.0.0
1090
+ */
1091
+ var chainFirst = function (f) {
1092
+ return exports.chain(function (a) {
1093
+ return _function.pipe(f(a), exports.map(function () { return a; }));
1094
+ });
1095
+ };
1096
+ exports.chainFirst = chainFirst;
1097
+ /**
1098
+ * Derivable from `Monad`.
1099
+ *
1100
+ * @category combinators
1101
+ * @since 2.0.0
1102
+ */
1103
+ exports.flatten =
1104
+ /*#__PURE__*/
1105
+ exports.chain(_function.identity);
1106
+ /**
1107
+ * Less strict version of [`alt`](#alt).
1108
+ *
1109
+ * @category Alt
1110
+ * @since 2.9.0
1111
+ */
1112
+ var altW = function (that) { return function (fa) {
1113
+ return exports.isNone(fa) ? that() : fa;
1114
+ }; };
1115
+ exports.altW = altW;
1116
+ /**
1117
+ * Identifies an associative operation on a type constructor. It is similar to `Semigroup`, except that it applies to
1118
+ * types of kind `* -> *`.
1119
+ *
1120
+ * In case of `Option` returns the left-most non-`None` value.
1121
+ *
1122
+ * @example
1123
+ * import * as O from 'fp-ts/Option'
1124
+ * import { pipe } from 'fp-ts/function'
1125
+ *
1126
+ * assert.deepStrictEqual(
1127
+ * pipe(
1128
+ * O.some('a'),
1129
+ * O.alt(() => O.some('b'))
1130
+ * ),
1131
+ * O.some('a')
1132
+ * )
1133
+ * assert.deepStrictEqual(
1134
+ * pipe(
1135
+ * O.none,
1136
+ * O.alt(() => O.some('b'))
1137
+ * ),
1138
+ * O.some('b')
1139
+ * )
1140
+ *
1141
+ * @category Alt
1142
+ * @since 2.0.0
1143
+ */
1144
+ exports.alt = exports.altW;
1145
+ /**
1146
+ * @category Alternative
1147
+ * @since 2.7.0
1148
+ */
1149
+ var zero = function () { return exports.none; };
1150
+ exports.zero = zero;
1151
+ /**
1152
+ * @category MonadThrow
1153
+ * @since 2.7.0
1154
+ */
1155
+ var throwError = function () { return exports.none; };
1156
+ exports.throwError = throwError;
1157
+ /**
1158
+ * @category Extend
1159
+ * @since 2.0.0
1160
+ */
1161
+ var extend = function (f) { return function (wa) {
1162
+ return exports.isNone(wa) ? exports.none : exports.some(f(wa));
1163
+ }; };
1164
+ exports.extend = extend;
1165
+ /**
1166
+ * Derivable from `Extend`.
1167
+ *
1168
+ * @category combinators
1169
+ * @since 2.0.0
1170
+ */
1171
+ exports.duplicate =
1172
+ /*#__PURE__*/
1173
+ exports.extend(_function.identity);
1174
+ /**
1175
+ * @category Foldable
1176
+ * @since 2.0.0
1177
+ */
1178
+ var reduce = function (b, f) { return function (fa) {
1179
+ return exports.isNone(fa) ? b : f(b, fa.value);
1180
+ }; };
1181
+ exports.reduce = reduce;
1182
+ /**
1183
+ * @category Foldable
1184
+ * @since 2.0.0
1185
+ */
1186
+ var foldMap = function (M) { return function (f) { return function (fa) {
1187
+ return exports.isNone(fa) ? M.empty : f(fa.value);
1188
+ }; }; };
1189
+ exports.foldMap = foldMap;
1190
+ /**
1191
+ * @category Foldable
1192
+ * @since 2.0.0
1193
+ */
1194
+ var reduceRight = function (b, f) { return function (fa) {
1195
+ return exports.isNone(fa) ? b : f(fa.value, b);
1196
+ }; };
1197
+ exports.reduceRight = reduceRight;
1198
+ /**
1199
+ * @category Compactable
1200
+ * @since 2.0.0
1201
+ */
1202
+ exports.compact = exports.flatten;
1203
+ var defaultSeparate = { left: exports.none, right: exports.none };
1204
+ /**
1205
+ * @category Compactable
1206
+ * @since 2.0.0
1207
+ */
1208
+ var separate = function (ma) {
1209
+ var o = _function.pipe(ma, exports.map(function (e) { return ({
1210
+ left: getLeft(e),
1211
+ right: getRight(e)
1212
+ }); }));
1213
+ return exports.isNone(o) ? defaultSeparate : o.value;
1214
+ };
1215
+ exports.separate = separate;
1216
+ /**
1217
+ * @category Filterable
1218
+ * @since 2.0.0
1219
+ */
1220
+ var filter = function (predicate) { return function (fa) { return (exports.isNone(fa) ? exports.none : predicate(fa.value) ? fa : exports.none); }; };
1221
+ exports.filter = filter;
1222
+ /**
1223
+ * @category Filterable
1224
+ * @since 2.0.0
1225
+ */
1226
+ var filterMap = function (f) { return function (fa) {
1227
+ return exports.isNone(fa) ? exports.none : f(fa.value);
1228
+ }; };
1229
+ exports.filterMap = filterMap;
1230
+ /**
1231
+ * @category Filterable
1232
+ * @since 2.0.0
1233
+ */
1234
+ var partition = function (predicate) { return function (fa) {
1235
+ return {
1236
+ left: filter_(fa, function (a) { return !predicate(a); }),
1237
+ right: filter_(fa, predicate)
1238
+ };
1239
+ }; };
1240
+ exports.partition = partition;
1241
+ /**
1242
+ * @category Filterable
1243
+ * @since 2.0.0
1244
+ */
1245
+ var partitionMap = function (f) { return _function.flow(exports.map(f), exports.separate); };
1246
+ exports.partitionMap = partitionMap;
1247
+ /**
1248
+ * @category Traversable
1249
+ * @since 2.6.3
1250
+ */
1251
+ var traverse = function (F) { return function (f) { return function (ta) { return (exports.isNone(ta) ? F.of(exports.none) : F.map(f(ta.value), exports.some)); }; }; };
1252
+ exports.traverse = traverse;
1253
+ /**
1254
+ * @category Traversable
1255
+ * @since 2.6.3
1256
+ */
1257
+ var sequence = function (F) { return function (ta) { return (exports.isNone(ta) ? F.of(exports.none) : F.map(ta.value, exports.some)); }; };
1258
+ exports.sequence = sequence;
1259
+ /**
1260
+ * @category Witherable
1261
+ * @since 2.6.5
1262
+ */
1263
+ var wither = function (F) { return function (f) { return function (fa) { return (exports.isNone(fa) ? F.of(exports.none) : f(fa.value)); }; }; };
1264
+ exports.wither = wither;
1265
+ /**
1266
+ * @category Witherable
1267
+ * @since 2.6.5
1268
+ */
1269
+ var wilt = function (F) { return function (f) { return function (fa) {
1270
+ return exports.isNone(fa)
1271
+ ? F.of({
1272
+ left: exports.none,
1273
+ right: exports.none
1274
+ })
1275
+ : F.map(f(fa.value), function (e) { return ({
1276
+ left: getLeft(e),
1277
+ right: getRight(e)
1278
+ }); });
1279
+ }; }; };
1280
+ exports.wilt = wilt;
1281
+ // -------------------------------------------------------------------------------------
1282
+ // instances
1283
+ // -------------------------------------------------------------------------------------
1284
+ /**
1285
+ * @category instances
1286
+ * @since 2.0.0
1287
+ */
1288
+ exports.URI = 'Option';
1289
+ /**
1290
+ * @category instances
1291
+ * @since 2.0.0
1292
+ */
1293
+ function getShow(S) {
1294
+ return {
1295
+ show: function (ma) { return (exports.isNone(ma) ? 'none' : "some(" + S.show(ma.value) + ")"); }
1296
+ };
1297
+ }
1298
+ exports.getShow = getShow;
1299
+ /**
1300
+ * @example
1301
+ * import { none, some, getEq } from 'fp-ts/Option'
1302
+ * import { eqNumber } from 'fp-ts/Eq'
1303
+ *
1304
+ * const E = getEq(eqNumber)
1305
+ * assert.strictEqual(E.equals(none, none), true)
1306
+ * assert.strictEqual(E.equals(none, some(1)), false)
1307
+ * assert.strictEqual(E.equals(some(1), none), false)
1308
+ * assert.strictEqual(E.equals(some(1), some(2)), false)
1309
+ * assert.strictEqual(E.equals(some(1), some(1)), true)
1310
+ *
1311
+ * @category instances
1312
+ * @since 2.0.0
1313
+ */
1314
+ function getEq(E) {
1315
+ return {
1316
+ equals: function (x, y) { return x === y || (exports.isNone(x) ? exports.isNone(y) : exports.isNone(y) ? false : E.equals(x.value, y.value)); }
1317
+ };
1318
+ }
1319
+ exports.getEq = getEq;
1320
+ /**
1321
+ * The `Ord` instance allows `Option` values to be compared with
1322
+ * `compare`, whenever there is an `Ord` instance for
1323
+ * the type the `Option` contains.
1324
+ *
1325
+ * `None` is considered to be less than any `Some` value.
1326
+ *
1327
+ *
1328
+ * @example
1329
+ * import { none, some, getOrd } from 'fp-ts/Option'
1330
+ * import { ordNumber } from 'fp-ts/Ord'
1331
+ *
1332
+ * const O = getOrd(ordNumber)
1333
+ * assert.strictEqual(O.compare(none, none), 0)
1334
+ * assert.strictEqual(O.compare(none, some(1)), -1)
1335
+ * assert.strictEqual(O.compare(some(1), none), 1)
1336
+ * assert.strictEqual(O.compare(some(1), some(2)), -1)
1337
+ * assert.strictEqual(O.compare(some(1), some(1)), 0)
1338
+ *
1339
+ * @category instances
1340
+ * @since 2.0.0
1341
+ */
1342
+ function getOrd(O) {
1343
+ return {
1344
+ equals: getEq(O).equals,
1345
+ compare: function (x, y) { return (x === y ? 0 : exports.isSome(x) ? (exports.isSome(y) ? O.compare(x.value, y.value) : 1) : -1); }
1346
+ };
1347
+ }
1348
+ exports.getOrd = getOrd;
1349
+ /**
1350
+ * `Apply` semigroup
1351
+ *
1352
+ * | x | y | concat(x, y) |
1353
+ * | ------- | ------- | ------------------ |
1354
+ * | none | none | none |
1355
+ * | some(a) | none | none |
1356
+ * | none | some(a) | none |
1357
+ * | some(a) | some(b) | some(concat(a, b)) |
1358
+ *
1359
+ * @example
1360
+ * import { getApplySemigroup, some, none } from 'fp-ts/Option'
1361
+ * import { semigroupSum } from 'fp-ts/Semigroup'
1362
+ *
1363
+ * const S = getApplySemigroup(semigroupSum)
1364
+ * assert.deepStrictEqual(S.concat(none, none), none)
1365
+ * assert.deepStrictEqual(S.concat(some(1), none), none)
1366
+ * assert.deepStrictEqual(S.concat(none, some(1)), none)
1367
+ * assert.deepStrictEqual(S.concat(some(1), some(2)), some(3))
1368
+ *
1369
+ * @category instances
1370
+ * @since 2.0.0
1371
+ */
1372
+ function getApplySemigroup(S) {
1373
+ return {
1374
+ concat: function (x, y) { return (exports.isSome(x) && exports.isSome(y) ? exports.some(S.concat(x.value, y.value)) : exports.none); }
1375
+ };
1376
+ }
1377
+ exports.getApplySemigroup = getApplySemigroup;
1378
+ /**
1379
+ * @category instances
1380
+ * @since 2.0.0
1381
+ */
1382
+ function getApplyMonoid(M) {
1383
+ return {
1384
+ concat: getApplySemigroup(M).concat,
1385
+ empty: exports.some(M.empty)
1386
+ };
1387
+ }
1388
+ exports.getApplyMonoid = getApplyMonoid;
1389
+ /**
1390
+ * Monoid returning the left-most non-`None` value
1391
+ *
1392
+ * | x | y | concat(x, y) |
1393
+ * | ------- | ------- | ------------ |
1394
+ * | none | none | none |
1395
+ * | some(a) | none | some(a) |
1396
+ * | none | some(a) | some(a) |
1397
+ * | some(a) | some(b) | some(a) |
1398
+ *
1399
+ * @example
1400
+ * import { getFirstMonoid, some, none } from 'fp-ts/Option'
1401
+ *
1402
+ * const M = getFirstMonoid<number>()
1403
+ * assert.deepStrictEqual(M.concat(none, none), none)
1404
+ * assert.deepStrictEqual(M.concat(some(1), none), some(1))
1405
+ * assert.deepStrictEqual(M.concat(none, some(1)), some(1))
1406
+ * assert.deepStrictEqual(M.concat(some(1), some(2)), some(1))
1407
+ *
1408
+ * @category instances
1409
+ * @since 2.0.0
1410
+ */
1411
+ function getFirstMonoid() {
1412
+ return {
1413
+ concat: function (x, y) { return (exports.isNone(x) ? y : x); },
1414
+ empty: exports.none
1415
+ };
1416
+ }
1417
+ exports.getFirstMonoid = getFirstMonoid;
1418
+ /**
1419
+ * Monoid returning the right-most non-`None` value
1420
+ *
1421
+ * | x | y | concat(x, y) |
1422
+ * | ------- | ------- | ------------ |
1423
+ * | none | none | none |
1424
+ * | some(a) | none | some(a) |
1425
+ * | none | some(a) | some(a) |
1426
+ * | some(a) | some(b) | some(b) |
1427
+ *
1428
+ * @example
1429
+ * import { getLastMonoid, some, none } from 'fp-ts/Option'
1430
+ *
1431
+ * const M = getLastMonoid<number>()
1432
+ * assert.deepStrictEqual(M.concat(none, none), none)
1433
+ * assert.deepStrictEqual(M.concat(some(1), none), some(1))
1434
+ * assert.deepStrictEqual(M.concat(none, some(1)), some(1))
1435
+ * assert.deepStrictEqual(M.concat(some(1), some(2)), some(2))
1436
+ *
1437
+ * @category instances
1438
+ * @since 2.0.0
1439
+ */
1440
+ function getLastMonoid() {
1441
+ return {
1442
+ concat: function (x, y) { return (exports.isNone(y) ? x : y); },
1443
+ empty: exports.none
1444
+ };
1445
+ }
1446
+ exports.getLastMonoid = getLastMonoid;
1447
+ /**
1448
+ * Monoid returning the left-most non-`None` value. If both operands are `Some`s then the inner values are
1449
+ * concatenated using the provided `Semigroup`
1450
+ *
1451
+ * | x | y | concat(x, y) |
1452
+ * | ------- | ------- | ------------------ |
1453
+ * | none | none | none |
1454
+ * | some(a) | none | some(a) |
1455
+ * | none | some(a) | some(a) |
1456
+ * | some(a) | some(b) | some(concat(a, b)) |
1457
+ *
1458
+ * @example
1459
+ * import { getMonoid, some, none } from 'fp-ts/Option'
1460
+ * import { semigroupSum } from 'fp-ts/Semigroup'
1461
+ *
1462
+ * const M = getMonoid(semigroupSum)
1463
+ * assert.deepStrictEqual(M.concat(none, none), none)
1464
+ * assert.deepStrictEqual(M.concat(some(1), none), some(1))
1465
+ * assert.deepStrictEqual(M.concat(none, some(1)), some(1))
1466
+ * assert.deepStrictEqual(M.concat(some(1), some(2)), some(3))
1467
+ *
1468
+ * @category instances
1469
+ * @since 2.0.0
1470
+ */
1471
+ function getMonoid(S) {
1472
+ return {
1473
+ concat: function (x, y) { return (exports.isNone(x) ? y : exports.isNone(y) ? x : exports.some(S.concat(x.value, y.value))); },
1474
+ empty: exports.none
1475
+ };
1476
+ }
1477
+ exports.getMonoid = getMonoid;
1478
+ /**
1479
+ * @category instances
1480
+ * @since 2.7.0
1481
+ */
1482
+ exports.Functor = {
1483
+ URI: exports.URI,
1484
+ map: map_
1485
+ };
1486
+ /**
1487
+ * @category instances
1488
+ * @since 2.7.0
1489
+ */
1490
+ exports.Applicative = {
1491
+ URI: exports.URI,
1492
+ map: map_,
1493
+ ap: ap_,
1494
+ of: exports.of
1495
+ };
1496
+ /**
1497
+ * @category instances
1498
+ * @since 2.7.0
1499
+ */
1500
+ exports.Monad = {
1501
+ URI: exports.URI,
1502
+ map: map_,
1503
+ ap: ap_,
1504
+ of: exports.of,
1505
+ chain: chain_
1506
+ };
1507
+ /**
1508
+ * @category instances
1509
+ * @since 2.7.0
1510
+ */
1511
+ exports.Foldable = {
1512
+ URI: exports.URI,
1513
+ reduce: reduce_,
1514
+ foldMap: foldMap_,
1515
+ reduceRight: reduceRight_
1516
+ };
1517
+ /**
1518
+ * @category instances
1519
+ * @since 2.7.0
1520
+ */
1521
+ exports.Alt = {
1522
+ URI: exports.URI,
1523
+ map: map_,
1524
+ alt: alt_
1525
+ };
1526
+ /**
1527
+ * @category instances
1528
+ * @since 2.7.0
1529
+ */
1530
+ exports.Alternative = {
1531
+ URI: exports.URI,
1532
+ map: map_,
1533
+ ap: ap_,
1534
+ of: exports.of,
1535
+ alt: alt_,
1536
+ zero: exports.zero
1537
+ };
1538
+ /**
1539
+ * @category instances
1540
+ * @since 2.7.0
1541
+ */
1542
+ exports.Extend = {
1543
+ URI: exports.URI,
1544
+ map: map_,
1545
+ extend: extend_
1546
+ };
1547
+ /**
1548
+ * @category instances
1549
+ * @since 2.7.0
1550
+ */
1551
+ exports.Compactable = {
1552
+ URI: exports.URI,
1553
+ compact: exports.compact,
1554
+ separate: exports.separate
1555
+ };
1556
+ /**
1557
+ * @category instances
1558
+ * @since 2.7.0
1559
+ */
1560
+ exports.Filterable = {
1561
+ URI: exports.URI,
1562
+ map: map_,
1563
+ compact: exports.compact,
1564
+ separate: exports.separate,
1565
+ filter: filter_,
1566
+ filterMap: filterMap_,
1567
+ partition: partition_,
1568
+ partitionMap: partitionMap_
1569
+ };
1570
+ /**
1571
+ * @category instances
1572
+ * @since 2.7.0
1573
+ */
1574
+ exports.Traversable = {
1575
+ URI: exports.URI,
1576
+ map: map_,
1577
+ reduce: reduce_,
1578
+ foldMap: foldMap_,
1579
+ reduceRight: reduceRight_,
1580
+ traverse: traverse_,
1581
+ sequence: exports.sequence
1582
+ };
1583
+ /**
1584
+ * @category instances
1585
+ * @since 2.7.0
1586
+ */
1587
+ exports.Witherable = {
1588
+ URI: exports.URI,
1589
+ map: map_,
1590
+ reduce: reduce_,
1591
+ foldMap: foldMap_,
1592
+ reduceRight: reduceRight_,
1593
+ traverse: traverse_,
1594
+ sequence: exports.sequence,
1595
+ compact: exports.compact,
1596
+ separate: exports.separate,
1597
+ filter: filter_,
1598
+ filterMap: filterMap_,
1599
+ partition: partition_,
1600
+ partitionMap: partitionMap_,
1601
+ wither: wither_,
1602
+ wilt: wilt_
1603
+ };
1604
+ /**
1605
+ * @category instances
1606
+ * @since 2.7.0
1607
+ */
1608
+ exports.MonadThrow = {
1609
+ URI: exports.URI,
1610
+ map: map_,
1611
+ ap: ap_,
1612
+ of: exports.of,
1613
+ chain: chain_,
1614
+ throwError: exports.throwError
1615
+ };
1616
+ // TODO: remove in v3
1617
+ /**
1618
+ * @category instances
1619
+ * @since 2.0.0
1620
+ */
1621
+ exports.option = {
1622
+ URI: exports.URI,
1623
+ map: map_,
1624
+ of: exports.of,
1625
+ ap: ap_,
1626
+ chain: chain_,
1627
+ reduce: reduce_,
1628
+ foldMap: foldMap_,
1629
+ reduceRight: reduceRight_,
1630
+ traverse: traverse_,
1631
+ sequence: exports.sequence,
1632
+ zero: exports.zero,
1633
+ alt: alt_,
1634
+ extend: extend_,
1635
+ compact: exports.compact,
1636
+ separate: exports.separate,
1637
+ filter: filter_,
1638
+ filterMap: filterMap_,
1639
+ partition: partition_,
1640
+ partitionMap: partitionMap_,
1641
+ wither: wither_,
1642
+ wilt: wilt_,
1643
+ throwError: exports.throwError
1644
+ };
1645
+ // -------------------------------------------------------------------------------------
1646
+ // utils
1647
+ // -------------------------------------------------------------------------------------
1648
+ /**
1649
+ * Returns `true` if `ma` contains `a`
1650
+ *
1651
+ * @example
1652
+ * import { some, none, elem } from 'fp-ts/Option'
1653
+ * import { eqNumber } from 'fp-ts/Eq'
1654
+ *
1655
+ * assert.strictEqual(elem(eqNumber)(1, some(1)), true)
1656
+ * assert.strictEqual(elem(eqNumber)(2, some(1)), false)
1657
+ * assert.strictEqual(elem(eqNumber)(1, none), false)
1658
+ *
1659
+ * @since 2.0.0
1660
+ */
1661
+ function elem(E) {
1662
+ return function (a, ma) { return (exports.isNone(ma) ? false : E.equals(a, ma.value)); };
1663
+ }
1664
+ exports.elem = elem;
1665
+ /**
1666
+ * Returns `true` if the predicate is satisfied by the wrapped value
1667
+ *
1668
+ * @example
1669
+ * import { some, none, exists } from 'fp-ts/Option'
1670
+ * import { pipe } from 'fp-ts/function'
1671
+ *
1672
+ * assert.strictEqual(
1673
+ * pipe(
1674
+ * some(1),
1675
+ * exists(n => n > 0)
1676
+ * ),
1677
+ * true
1678
+ * )
1679
+ * assert.strictEqual(
1680
+ * pipe(
1681
+ * some(1),
1682
+ * exists(n => n > 1)
1683
+ * ),
1684
+ * false
1685
+ * )
1686
+ * assert.strictEqual(
1687
+ * pipe(
1688
+ * none,
1689
+ * exists(n => n > 0)
1690
+ * ),
1691
+ * false
1692
+ * )
1693
+ *
1694
+ * @since 2.0.0
1695
+ */
1696
+ function exists(predicate) {
1697
+ return function (ma) { return (exports.isNone(ma) ? false : predicate(ma.value)); };
1698
+ }
1699
+ exports.exists = exists;
1700
+ /**
1701
+ * Returns a `Refinement` (i.e. a custom type guard) from a `Option` returning function.
1702
+ * This function ensures that a custom type guard definition is type-safe.
1703
+ *
1704
+ * ```ts
1705
+ * import { some, none, getRefinement } from 'fp-ts/Option'
1706
+ *
1707
+ * type A = { type: 'A' }
1708
+ * type B = { type: 'B' }
1709
+ * type C = A | B
1710
+ *
1711
+ * const isA = (c: C): c is A => c.type === 'B' // <= typo but typescript doesn't complain
1712
+ * const isA = getRefinement<C, A>(c => (c.type === 'B' ? some(c) : none)) // static error: Type '"B"' is not assignable to type '"A"'
1713
+ * ```
1714
+ *
1715
+ * @since 2.0.0
1716
+ */
1717
+ function getRefinement(getOption) {
1718
+ return function (a) { return exports.isSome(getOption(a)); };
1719
+ }
1720
+ exports.getRefinement = getRefinement;
1721
+ // -------------------------------------------------------------------------------------
1722
+ // do notation
1723
+ // -------------------------------------------------------------------------------------
1724
+ /**
1725
+ * @since 2.9.0
1726
+ */
1727
+ exports.Do =
1728
+ /*#__PURE__*/
1729
+ exports.of({});
1730
+ /**
1731
+ * @since 2.8.0
1732
+ */
1733
+ var bindTo = function (name) { return exports.map(_function.bindTo_(name)); };
1734
+ exports.bindTo = bindTo;
1735
+ /**
1736
+ * @since 2.8.0
1737
+ */
1738
+ var bind = function (name, f) {
1739
+ return exports.chain(function (a) {
1740
+ return _function.pipe(f(a), exports.map(function (b) { return _function.bind_(a, name, b); }));
1741
+ });
1742
+ };
1743
+ exports.bind = bind;
1744
+ // -------------------------------------------------------------------------------------
1745
+ // pipeable sequence S
1746
+ // -------------------------------------------------------------------------------------
1747
+ /**
1748
+ * @since 2.8.0
1749
+ */
1750
+ var apS = function (name, fb) {
1751
+ return _function.flow(exports.map(function (a) { return function (b) { return _function.bind_(a, name, b); }; }), exports.ap(fb));
1752
+ };
1753
+ exports.apS = apS;
1754
+ // -------------------------------------------------------------------------------------
1755
+ // array utils
1756
+ // -------------------------------------------------------------------------------------
1757
+ /**
1758
+ *
1759
+ * @since 2.9.0
1760
+ */
1761
+ var traverseArrayWithIndex = function (f) { return function (arr) {
1762
+ // tslint:disable-next-line: readonly-array
1763
+ var result = [];
1764
+ for (var i = 0; i < arr.length; i++) {
1765
+ var b = f(i, arr[i]);
1766
+ if (exports.isNone(b)) {
1767
+ return exports.none;
1768
+ }
1769
+ result.push(b.value);
1770
+ }
1771
+ return exports.some(result);
1772
+ }; };
1773
+ exports.traverseArrayWithIndex = traverseArrayWithIndex;
1774
+ /**
1775
+ * Runs an action for every element in array and accumulates the results in option
1776
+ *
1777
+ * this function have the same behavior of `A.sequence(O.option)` but it's optimized and perform better
1778
+ *
1779
+ * @example
1780
+ *
1781
+ * import * as A from 'fp-ts/Array'
1782
+ * import { traverseArray, some, fromPredicate, none } from 'fp-ts/Option'
1783
+ * import { pipe } from 'fp-ts/function'
1784
+ *
1785
+ * const arr = A.range(0, 10)
1786
+ * assert.deepStrictEqual(pipe(arr, traverseArray(some)), some(arr))
1787
+ * assert.deepStrictEqual(pipe(arr, traverseArray(fromPredicate((x) => x > 5))), none)
1788
+ *
1789
+ * @since 2.9.0
1790
+ */
1791
+ var traverseArray = function (f) { return exports.traverseArrayWithIndex(function (_, a) { return f(a); }); };
1792
+ exports.traverseArray = traverseArray;
1793
+ /**
1794
+ * get an array of option and convert it to option of array
1795
+ *
1796
+ * this function have the same behavior of `A.sequence(O.option)` but it's optimized and perform better
1797
+ *
1798
+ * @example
1799
+ *
1800
+ * import * as A from 'fp-ts/Array'
1801
+ * import { sequenceArray, some, none, fromPredicate } from 'fp-ts/Option'
1802
+ * import { pipe } from 'fp-ts/function'
1803
+ *
1804
+ * const arr = A.range(0, 10)
1805
+ * assert.deepStrictEqual(pipe(arr, A.map(some), sequenceArray), some(arr))
1806
+ * assert.deepStrictEqual(pipe(arr, A.map(fromPredicate(x => x > 8)), sequenceArray), none)
1807
+ *
1808
+ * @since 2.9.0
1809
+ */
1810
+ exports.sequenceArray =
1811
+ /*#__PURE__*/
1812
+ exports.traverseArray(_function.identity);
1813
+ });
1814
+
1815
+ function e(e){this.message=e;}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var r="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(r){var t=String(r).replace(/=+$/,"");if(t.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,o,a=0,i=0,c="";o=t.charAt(i++);~o&&(n=a%4?64*n+o:o,a++%4)?c+=String.fromCharCode(255&n>>(-2*a&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);return c};function t(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw "Illegal base64url string!"}try{return function(e){return decodeURIComponent(r(e).replace(/(.)/g,(function(e,r){var t=r.charCodeAt(0).toString(16).toUpperCase();return t.length<2&&(t="0"+t),"%"+t})))}(t)}catch(e){return r(t)}}function n(e){this.message=e;}function o(e,r){if("string"!=typeof e)throw new n("Invalid token specified");var o=!0===(r=r||{}).header?0:1;try{return JSON.parse(t(e.split(".")[o]))}catch(e){throw new n("Invalid token specified: "+e.message)}}n.prototype=new Error,n.prototype.name="InvalidTokenError";
1816
+
1817
+ var __assign = (undefined && undefined.__assign) || function () {
1818
+ __assign = Object.assign || function(t) {
1819
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
1820
+ s = arguments[i];
1821
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1822
+ t[p] = s[p];
1823
+ }
1824
+ return t;
1825
+ };
1826
+ return __assign.apply(this, arguments);
1827
+ };
1828
+ var __spreadArrays = (undefined && undefined.__spreadArrays) || function () {
1829
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
1830
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
1831
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
1832
+ r[k] = a[j];
1833
+ return r;
1834
+ };
1835
+ var mix = function (one, two, mergeArrays) {
1836
+ if (mergeArrays === void 0) { mergeArrays = false; }
1837
+ if (!one || !two || typeof one !== "object" || typeof two !== "object")
1838
+ return one;
1839
+ var clone = __assign({}, one);
1840
+ for (var prop in two) {
1841
+ if (two.hasOwnProperty(prop)) {
1842
+ if (two[prop] instanceof Array && one[prop] instanceof Array) {
1843
+ clone[prop] = mergeArrays ? __spreadArrays(one[prop], two[prop]) : two[prop];
1844
+ }
1845
+ else if (typeof two[prop] === "object" && typeof one[prop] === "object") {
1846
+ clone[prop] = mix(one[prop], two[prop], mergeArrays);
1847
+ }
1848
+ else {
1849
+ clone[prop] = two[prop];
1850
+ }
1851
+ }
1852
+ }
1853
+ return clone;
1854
+ };
1855
+
1856
+ var __spreadArrays$1 = (undefined && undefined.__spreadArrays) || function () {
1857
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
1858
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
1859
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
1860
+ r[k] = a[j];
1861
+ return r;
1862
+ };
1863
+ var config = {
1864
+ // Default options
1865
+ defaults: {},
1866
+ // Error type
1867
+ errorType: null,
1868
+ // Polyfills
1869
+ polyfills: {
1870
+ fetch: null,
1871
+ FormData: null,
1872
+ URLSearchParams: null,
1873
+ performance: null,
1874
+ PerformanceObserver: null,
1875
+ AbortController: null
1876
+ },
1877
+ polyfill: function (p, _a) {
1878
+ var _b = _a === void 0 ? {} : _a, _c = _b.doThrow, doThrow = _c === void 0 ? true : _c, _d = _b.instance, instance = _d === void 0 ? false : _d;
1879
+ var args = [];
1880
+ for (var _i = 2; _i < arguments.length; _i++) {
1881
+ args[_i - 2] = arguments[_i];
1882
+ }
1883
+ var res = this.polyfills[p] ||
1884
+ (typeof self !== "undefined" ? self[p] : null) ||
1885
+ (typeof global !== "undefined" ? global[p] : null);
1886
+ if (doThrow && !res)
1887
+ throw new Error(p + " is not defined");
1888
+ return instance && res ? new (res.bind.apply(res, __spreadArrays$1([void 0], args)))() : res;
1889
+ }
1890
+ };
1891
+
1892
+ var onMatch = function (entries, name, callback, _performance) {
1893
+ if (!entries.getEntriesByName)
1894
+ return false;
1895
+ var matches = entries.getEntriesByName(name);
1896
+ if (matches && matches.length > 0) {
1897
+ callback(matches.reverse()[0]);
1898
+ if (_performance.clearMeasures)
1899
+ _performance.clearMeasures(name);
1900
+ perfs.callbacks.delete(name);
1901
+ if (perfs.callbacks.size < 1) {
1902
+ perfs.observer.disconnect();
1903
+ if (_performance.clearResourceTimings) {
1904
+ _performance.clearResourceTimings();
1905
+ }
1906
+ }
1907
+ return true;
1908
+ }
1909
+ return false;
1910
+ };
1911
+ var lazyObserver = function (_performance, _observer) {
1912
+ if (!perfs.observer && _performance && _observer) {
1913
+ perfs.observer = new _observer(function (entries) {
1914
+ perfs.callbacks.forEach(function (callback, name) {
1915
+ onMatch(entries, name, callback, _performance);
1916
+ });
1917
+ });
1918
+ if (_performance.clearResourceTimings)
1919
+ _performance.clearResourceTimings();
1920
+ }
1921
+ return perfs.observer;
1922
+ };
1923
+ var perfs = {
1924
+ callbacks: new Map(),
1925
+ observer: null,
1926
+ observe: function (name, callback) {
1927
+ if (!name || !callback)
1928
+ return;
1929
+ var _performance = config.polyfill("performance", { doThrow: false });
1930
+ var _observer = config.polyfill("PerformanceObserver", { doThrow: false });
1931
+ if (!lazyObserver(_performance, _observer))
1932
+ return;
1933
+ if (!onMatch(_performance, name, callback, _performance)) {
1934
+ if (perfs.callbacks.size < 1)
1935
+ perfs.observer.observe({ entryTypes: ["resource", "measure"] });
1936
+ perfs.callbacks.set(name, callback);
1937
+ }
1938
+ }
1939
+ };
1940
+
1941
+ var middlewareHelper = function (middlewares) { return function (fetchFunction) {
1942
+ return (middlewares.length === 0 ?
1943
+ fetchFunction :
1944
+ middlewares.length === 1 ?
1945
+ middlewares[0](fetchFunction) :
1946
+ middlewares.reduceRight(function (acc, curr, idx) {
1947
+ return (idx === middlewares.length - 2) ? curr(acc(fetchFunction)) : curr(acc);
1948
+ }));
1949
+ }; };
1950
+
1951
+ var WretchErrorWrapper = /** @class */ (function () {
1952
+ function WretchErrorWrapper(error) {
1953
+ this.error = error;
1954
+ }
1955
+ return WretchErrorWrapper;
1956
+ }());
1957
+ var resolver = function (wretcher) {
1958
+ var url = wretcher._url, _catchers = wretcher._catchers, resolvers = wretcher._resolvers, middlewares = wretcher._middlewares, opts = wretcher._options;
1959
+ var catchers = new Map(_catchers);
1960
+ var finalOptions = mix(config.defaults, opts);
1961
+ var fetchController = config.polyfill("AbortController", { doThrow: false, instance: true });
1962
+ if (!finalOptions["signal"] && fetchController) {
1963
+ finalOptions["signal"] = fetchController.signal;
1964
+ }
1965
+ // Request timeout
1966
+ var timeout = {
1967
+ ref: null,
1968
+ clear: function () {
1969
+ if (timeout.ref) {
1970
+ clearTimeout(timeout.ref);
1971
+ timeout.ref = null;
1972
+ }
1973
+ }
1974
+ };
1975
+ // The generated fetch request
1976
+ var fetchRequest = middlewareHelper(middlewares)(config.polyfill("fetch"))(url, finalOptions);
1977
+ // Throws on an http error
1978
+ var throwingPromise = fetchRequest
1979
+ .catch(function (error) {
1980
+ throw new WretchErrorWrapper(error);
1981
+ })
1982
+ .then(function (response) {
1983
+ timeout.clear();
1984
+ if (!response.ok) {
1985
+ return response[config.errorType || "text"]().then(function (msg) {
1986
+ // Enhances the error object
1987
+ var err = new Error(msg);
1988
+ err[config.errorType || "text"] = msg;
1989
+ err["status"] = response.status;
1990
+ err["response"] = response;
1991
+ throw err;
1992
+ });
1993
+ }
1994
+ return response;
1995
+ });
1996
+ // Wraps the Promise in order to dispatch the error to a matching catcher
1997
+ var catchersWrapper = function (promise) {
1998
+ return promise.catch(function (err) {
1999
+ timeout.clear();
2000
+ var error = err instanceof WretchErrorWrapper ? err.error : err;
2001
+ if (err instanceof WretchErrorWrapper && catchers.has("__fromFetch"))
2002
+ return catchers.get("__fromFetch")(error, wretcher);
2003
+ else if (catchers.has(error.status))
2004
+ return catchers.get(error.status)(error, wretcher);
2005
+ else if (catchers.has(error.name))
2006
+ return catchers.get(error.name)(error, wretcher);
2007
+ else
2008
+ throw error;
2009
+ });
2010
+ };
2011
+ var bodyParser = function (funName) { return function (cb) { return funName ?
2012
+ // If a callback is provided, then callback with the body result otherwise return the parsed body itself.
2013
+ catchersWrapper(throwingPromise.then(function (_) { return _ && _[funName](); }).then(function (_) { return cb ? cb(_) : _; })) :
2014
+ // No body parsing method - return the response
2015
+ catchersWrapper(throwingPromise.then(function (_) { return cb ? cb(_) : _; })); }; };
2016
+ var responseChain = {
2017
+ /**
2018
+ * Retrieves the raw result as a promise.
2019
+ */
2020
+ res: bodyParser(null),
2021
+ /**
2022
+ * Retrieves the result as a parsed JSON object.
2023
+ */
2024
+ json: bodyParser("json"),
2025
+ /**
2026
+ * Retrieves the result as a Blob object.
2027
+ */
2028
+ blob: bodyParser("blob"),
2029
+ /**
2030
+ * Retrieves the result as a FormData object.
2031
+ */
2032
+ formData: bodyParser("formData"),
2033
+ /**
2034
+ * Retrieves the result as an ArrayBuffer object.
2035
+ */
2036
+ arrayBuffer: bodyParser("arrayBuffer"),
2037
+ /**
2038
+ * Retrieves the result as a string.
2039
+ */
2040
+ text: bodyParser("text"),
2041
+ /**
2042
+ * Performs a callback on the API performance timings of the request.
2043
+ *
2044
+ * Warning: Still experimental on browsers and node.js
2045
+ */
2046
+ perfs: function (cb) {
2047
+ fetchRequest.then(function (res) { return perfs.observe(res.url, cb); });
2048
+ return responseChain;
2049
+ },
2050
+ /**
2051
+ * Aborts the request after a fixed time.
2052
+ *
2053
+ * @param time Time in milliseconds
2054
+ * @param controller A custom controller
2055
+ */
2056
+ setTimeout: function (time, controller) {
2057
+ if (controller === void 0) { controller = fetchController; }
2058
+ timeout.clear();
2059
+ timeout.ref = setTimeout(function () { return controller.abort(); }, time);
2060
+ return responseChain;
2061
+ },
2062
+ /**
2063
+ * Returns the automatically generated AbortController alongside the current wretch response as a pair.
2064
+ */
2065
+ controller: function () { return [fetchController, responseChain]; },
2066
+ /**
2067
+ * Catches an http response with a specific error code or name and performs a callback.
2068
+ */
2069
+ error: function (errorId, cb) {
2070
+ catchers.set(errorId, cb);
2071
+ return responseChain;
2072
+ },
2073
+ /**
2074
+ * Catches a bad request (http code 400) and performs a callback.
2075
+ */
2076
+ badRequest: function (cb) { return responseChain.error(400, cb); },
2077
+ /**
2078
+ * Catches an unauthorized request (http code 401) and performs a callback.
2079
+ */
2080
+ unauthorized: function (cb) { return responseChain.error(401, cb); },
2081
+ /**
2082
+ * Catches a forbidden request (http code 403) and performs a callback.
2083
+ */
2084
+ forbidden: function (cb) { return responseChain.error(403, cb); },
2085
+ /**
2086
+ * Catches a "not found" request (http code 404) and performs a callback.
2087
+ */
2088
+ notFound: function (cb) { return responseChain.error(404, cb); },
2089
+ /**
2090
+ * Catches a timeout (http code 408) and performs a callback.
2091
+ */
2092
+ timeout: function (cb) { return responseChain.error(408, cb); },
2093
+ /**
2094
+ * Catches an internal server error (http code 500) and performs a callback.
2095
+ */
2096
+ internalError: function (cb) { return responseChain.error(500, cb); },
2097
+ /**
2098
+ * Catches errors thrown when calling the fetch function and performs a callback.
2099
+ */
2100
+ fetchError: function (cb) { return responseChain.error("__fromFetch", cb); },
2101
+ /**
2102
+ * Catches an AbortError and performs a callback.
2103
+ */
2104
+ onAbort: function (cb) { return responseChain.error("AbortError", cb); }
2105
+ };
2106
+ return resolvers.reduce(function (chain, r) { return r(chain, wretcher); }, responseChain);
2107
+ };
2108
+
2109
+ var __assign$1 = (undefined && undefined.__assign) || function () {
2110
+ __assign$1 = Object.assign || function(t) {
2111
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
2112
+ s = arguments[i];
2113
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2114
+ t[p] = s[p];
2115
+ }
2116
+ return t;
2117
+ };
2118
+ return __assign$1.apply(this, arguments);
2119
+ };
2120
+ var __spreadArrays$2 = (undefined && undefined.__spreadArrays) || function () {
2121
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
2122
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
2123
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
2124
+ r[k] = a[j];
2125
+ return r;
2126
+ };
2127
+ var JSON_MIME = "application/json";
2128
+ var CONTENT_TYPE_HEADER = "Content-Type";
2129
+ /**
2130
+ * The Wretcher class used to perform easy fetch requests.
2131
+ *
2132
+ * Immutability : almost every method of this class return a fresh Wretcher object.
2133
+ */
2134
+ var Wretcher = /** @class */ (function () {
2135
+ function Wretcher(_url, _options, _catchers, _resolvers, _middlewares, _deferredChain) {
2136
+ if (_catchers === void 0) { _catchers = new Map(); }
2137
+ if (_resolvers === void 0) { _resolvers = []; }
2138
+ if (_middlewares === void 0) { _middlewares = []; }
2139
+ if (_deferredChain === void 0) { _deferredChain = []; }
2140
+ this._url = _url;
2141
+ this._options = _options;
2142
+ this._catchers = _catchers;
2143
+ this._resolvers = _resolvers;
2144
+ this._middlewares = _middlewares;
2145
+ this._deferredChain = _deferredChain;
2146
+ }
2147
+ Wretcher.factory = function (url, options) {
2148
+ if (url === void 0) { url = ""; }
2149
+ if (options === void 0) { options = {}; }
2150
+ return new Wretcher(url, options);
2151
+ };
2152
+ Wretcher.prototype.selfFactory = function (_a) {
2153
+ var _b = _a === void 0 ? {} : _a, _c = _b.url, url = _c === void 0 ? this._url : _c, _d = _b.options, options = _d === void 0 ? this._options : _d, _e = _b.catchers, catchers = _e === void 0 ? this._catchers : _e, _f = _b.resolvers, resolvers = _f === void 0 ? this._resolvers : _f, _g = _b.middlewares, middlewares = _g === void 0 ? this._middlewares : _g, _h = _b.deferredChain, deferredChain = _h === void 0 ? this._deferredChain : _h;
2154
+ return new Wretcher(url, __assign$1({}, options), new Map(catchers), __spreadArrays$2(resolvers), __spreadArrays$2(middlewares), __spreadArrays$2(deferredChain));
2155
+ };
2156
+ /**
2157
+ * Sets the default fetch options used for every subsequent fetch call.
2158
+ * @param options New default options
2159
+ * @param mixin If true, mixes in instead of replacing the existing options
2160
+ */
2161
+ Wretcher.prototype.defaults = function (options, mixin) {
2162
+ if (mixin === void 0) { mixin = false; }
2163
+ config.defaults = mixin ? mix(config.defaults, options) : options;
2164
+ return this;
2165
+ };
2166
+ /**
2167
+ * Sets the method (text, json ...) used to parse the data contained in the response body in case of an HTTP error.
2168
+ *
2169
+ * Persists for every subsequent requests.
2170
+ *
2171
+ * Default is "text".
2172
+ */
2173
+ Wretcher.prototype.errorType = function (method) {
2174
+ config.errorType = method;
2175
+ return this;
2176
+ };
2177
+ /**
2178
+ * Sets the non-global polyfills which will be used for every subsequent calls.
2179
+ *
2180
+ * Needed for libraries like [fetch-ponyfill](https://github.com/qubyte/fetch-ponyfill).
2181
+ *
2182
+ * @param polyfills An object containing the polyfills.
2183
+ */
2184
+ Wretcher.prototype.polyfills = function (polyfills) {
2185
+ config.polyfills = __assign$1(__assign$1({}, config.polyfills), polyfills);
2186
+ return this;
2187
+ };
2188
+ /**
2189
+ * Returns a new Wretcher object with the argument url appended and the same options.
2190
+ * @param url String url
2191
+ * @param replace Boolean If true, replaces the current url instead of appending
2192
+ */
2193
+ Wretcher.prototype.url = function (url, replace) {
2194
+ if (replace === void 0) { replace = false; }
2195
+ if (replace)
2196
+ return this.selfFactory({ url: url });
2197
+ var split = this._url.split("?");
2198
+ return this.selfFactory({
2199
+ url: split.length > 1 ?
2200
+ split[0] + url + "?" + split[1] :
2201
+ this._url + url
2202
+ });
2203
+ };
2204
+ /**
2205
+ * Returns a new Wretcher object with the same url and new options.
2206
+ * @param options New options
2207
+ * @param mixin If true, mixes in instead of replacing the existing options
2208
+ */
2209
+ Wretcher.prototype.options = function (options, mixin) {
2210
+ if (mixin === void 0) { mixin = true; }
2211
+ return this.selfFactory({ options: mixin ? mix(this._options, options) : options });
2212
+ };
2213
+ /**
2214
+ * Converts a javascript object to query parameters,
2215
+ * then appends this query string to the current url.
2216
+ *
2217
+ * If given a string, use the string as the query verbatim.
2218
+ *
2219
+ * ```
2220
+ * let w = wretch("http://example.com") // url is http://example.com
2221
+ *
2222
+ * // Chain query calls
2223
+ * w = w.query({ a: 1, b : 2 }) // url is now http://example.com?a=1&b=2
2224
+ * w = w.query("foo-bar-baz-woz") // url is now http://example.com?a=1&b=2&foo-bar-baz-woz
2225
+ *
2226
+ * // Pass true as the second argument to replace existing query parameters
2227
+ * w = w.query("c=3&d=4", true) // url is now http://example.com?c=3&d=4
2228
+ * ```
2229
+ *
2230
+ * @param qp An object which will be converted, or a string which will be used verbatim.
2231
+ */
2232
+ Wretcher.prototype.query = function (qp, replace) {
2233
+ if (replace === void 0) { replace = false; }
2234
+ return this.selfFactory({ url: appendQueryParams(this._url, qp, replace) });
2235
+ };
2236
+ /**
2237
+ * Set request headers.
2238
+ * @param headerValues An object containing header keys and values
2239
+ */
2240
+ Wretcher.prototype.headers = function (headerValues) {
2241
+ return this.selfFactory({ options: mix(this._options, { headers: headerValues || {} }) });
2242
+ };
2243
+ /**
2244
+ * Shortcut to set the "Accept" header.
2245
+ * @param headerValue Header value
2246
+ */
2247
+ Wretcher.prototype.accept = function (headerValue) {
2248
+ return this.headers({ Accept: headerValue });
2249
+ };
2250
+ /**
2251
+ * Shortcut to set the "Content-Type" header.
2252
+ * @param headerValue Header value
2253
+ */
2254
+ Wretcher.prototype.content = function (headerValue) {
2255
+ var _a;
2256
+ return this.headers((_a = {}, _a[CONTENT_TYPE_HEADER] = headerValue, _a));
2257
+ };
2258
+ /**
2259
+ * Shortcut to set the "Authorization" header.
2260
+ * @param headerValue Header value
2261
+ */
2262
+ Wretcher.prototype.auth = function (headerValue) {
2263
+ return this.headers({ Authorization: headerValue });
2264
+ };
2265
+ /**
2266
+ * Adds a default catcher which will be called on every subsequent request error when the error code matches.
2267
+ * @param errorId Error code or name
2268
+ * @param catcher: The catcher method
2269
+ */
2270
+ Wretcher.prototype.catcher = function (errorId, catcher) {
2271
+ var newMap = new Map(this._catchers);
2272
+ newMap.set(errorId, catcher);
2273
+ return this.selfFactory({ catchers: newMap });
2274
+ };
2275
+ /**
2276
+ * Associates a custom signal with the request.
2277
+ * @param controller : An AbortController
2278
+ */
2279
+ Wretcher.prototype.signal = function (controller) {
2280
+ return this.selfFactory({ options: __assign$1(__assign$1({}, this._options), { signal: controller.signal }) });
2281
+ };
2282
+ /**
2283
+ * Program a resolver to perform response chain tasks automatically.
2284
+ * @param doResolve : Resolver callback
2285
+ */
2286
+ Wretcher.prototype.resolve = function (doResolve, clear) {
2287
+ if (clear === void 0) { clear = false; }
2288
+ return this.selfFactory({ resolvers: clear ? [doResolve] : __spreadArrays$2(this._resolvers, [doResolve]) });
2289
+ };
2290
+ /**
2291
+ * Defer wretcher methods that will be chained and called just before the request is performed.
2292
+ */
2293
+ Wretcher.prototype.defer = function (callback, clear) {
2294
+ if (clear === void 0) { clear = false; }
2295
+ return this.selfFactory({
2296
+ deferredChain: clear ? [callback] : __spreadArrays$2(this._deferredChain, [callback])
2297
+ });
2298
+ };
2299
+ /**
2300
+ * Add middlewares to intercept a request before being sent.
2301
+ */
2302
+ Wretcher.prototype.middlewares = function (middlewares, clear) {
2303
+ if (clear === void 0) { clear = false; }
2304
+ return this.selfFactory({
2305
+ middlewares: clear ? middlewares : __spreadArrays$2(this._middlewares, middlewares)
2306
+ });
2307
+ };
2308
+ Wretcher.prototype.method = function (method, options, body) {
2309
+ if (options === void 0) { options = {}; }
2310
+ if (body === void 0) { body = null; }
2311
+ var headers = this._options.headers;
2312
+ var baseWretcher = !body ? this :
2313
+ typeof body === "object" && (!headers ||
2314
+ Object.entries(headers).every(function (_a) {
2315
+ var k = _a[0], v = _a[1];
2316
+ return k.toLowerCase() !== CONTENT_TYPE_HEADER.toLowerCase() ||
2317
+ v.startsWith(JSON_MIME);
2318
+ })) ? this.json(body) :
2319
+ this.body(body);
2320
+ baseWretcher = baseWretcher.options(__assign$1(__assign$1({}, options), { method: method }));
2321
+ var deferredWretcher = baseWretcher._deferredChain.reduce(function (acc, curr) { return curr(acc, acc._url, acc._options); }, baseWretcher);
2322
+ return resolver(deferredWretcher);
2323
+ };
2324
+ /**
2325
+ * Performs a get request.
2326
+ */
2327
+ Wretcher.prototype.get = function (options) {
2328
+ return this.method("GET", options);
2329
+ };
2330
+ /**
2331
+ * Performs a delete request.
2332
+ */
2333
+ Wretcher.prototype.delete = function (options) {
2334
+ return this.method("DELETE", options);
2335
+ };
2336
+ /**
2337
+ * Performs a put request.
2338
+ */
2339
+ Wretcher.prototype.put = function (body, options) {
2340
+ return this.method("PUT", options, body);
2341
+ };
2342
+ /**
2343
+ * Performs a post request.
2344
+ */
2345
+ Wretcher.prototype.post = function (body, options) {
2346
+ return this.method("POST", options, body);
2347
+ };
2348
+ /**
2349
+ * Performs a patch request.
2350
+ */
2351
+ Wretcher.prototype.patch = function (body, options) {
2352
+ return this.method("PATCH", options, body);
2353
+ };
2354
+ /**
2355
+ * Performs a head request.
2356
+ */
2357
+ Wretcher.prototype.head = function (options) {
2358
+ return this.method("HEAD", options);
2359
+ };
2360
+ /**
2361
+ * Performs an options request
2362
+ */
2363
+ Wretcher.prototype.opts = function (options) {
2364
+ return this.method("OPTIONS", options);
2365
+ };
2366
+ /**
2367
+ * Replay a request.
2368
+ */
2369
+ Wretcher.prototype.replay = function (options) {
2370
+ return this.method(this._options.method, options);
2371
+ };
2372
+ /**
2373
+ * Sets the request body with any content.
2374
+ * @param contents The body contents
2375
+ */
2376
+ Wretcher.prototype.body = function (contents) {
2377
+ return this.selfFactory({ options: __assign$1(__assign$1({}, this._options), { body: contents }) });
2378
+ };
2379
+ /**
2380
+ * Sets the content type header, stringifies an object and sets the request body.
2381
+ * @param jsObject An object which will be serialized into a JSON
2382
+ */
2383
+ Wretcher.prototype.json = function (jsObject) {
2384
+ var _a;
2385
+ var preservedContentType = (_a = Object.entries(this._options.headers || {}).find(function (_a) {
2386
+ var k = _a[0], v = _a[1];
2387
+ return k.toLowerCase() === CONTENT_TYPE_HEADER.toLowerCase() && v.startsWith(JSON_MIME);
2388
+ })) === null || _a === void 0 ? void 0 : _a[1];
2389
+ return this.content(preservedContentType || JSON_MIME).body(JSON.stringify(jsObject));
2390
+ };
2391
+ /**
2392
+ * Converts the javascript object to a FormData and sets the request body.
2393
+ * @param formObject An object which will be converted to a FormData
2394
+ * @param recursive If `true`, will recurse through all nested objects
2395
+ * Can be set as an array of string to exclude specific keys.
2396
+ * See https://github.com/elbywan/wretch/issues/68 for more details.
2397
+ */
2398
+ Wretcher.prototype.formData = function (formObject, recursive) {
2399
+ if (recursive === void 0) { recursive = false; }
2400
+ return this.body(convertFormData(formObject, recursive));
2401
+ };
2402
+ /**
2403
+ * Converts the input to an url encoded string and sets the content-type header and body.
2404
+ * If the input argument is already a string, skips the conversion part.
2405
+ *
2406
+ * @param input An object to convert into an url encoded string or an already encoded string
2407
+ */
2408
+ Wretcher.prototype.formUrl = function (input) {
2409
+ return this
2410
+ .body(typeof input === "string" ? input : convertFormUrl(input))
2411
+ .content("application/x-www-form-urlencoded");
2412
+ };
2413
+ return Wretcher;
2414
+ }());
2415
+ // Internal helpers
2416
+ var appendQueryParams = function (url, qp, replace) {
2417
+ var queryString;
2418
+ if (typeof qp === "string") {
2419
+ queryString = qp;
2420
+ }
2421
+ else {
2422
+ var usp = config.polyfill("URLSearchParams", { instance: true });
2423
+ for (var key in qp) {
2424
+ if (qp[key] instanceof Array) {
2425
+ for (var _i = 0, _a = qp[key]; _i < _a.length; _i++) {
2426
+ var val = _a[_i];
2427
+ usp.append(key, val);
2428
+ }
2429
+ }
2430
+ else {
2431
+ usp.append(key, qp[key]);
2432
+ }
2433
+ }
2434
+ queryString = usp.toString();
2435
+ }
2436
+ var split = url.split("?");
2437
+ if (replace || split.length < 2)
2438
+ return split[0] + "?" + queryString;
2439
+ return url + "&" + queryString;
2440
+ };
2441
+ function convertFormData(formObject, recursive, formData, ancestors) {
2442
+ if (recursive === void 0) { recursive = false; }
2443
+ if (formData === void 0) { formData = config.polyfill("FormData", { instance: true }); }
2444
+ if (ancestors === void 0) { ancestors = []; }
2445
+ Object.entries(formObject).forEach(function (_a) {
2446
+ var key = _a[0], value = _a[1];
2447
+ var formKey = ancestors.reduce(function (acc, ancestor) { return (acc ? acc + "[" + ancestor + "]" : ancestor); }, null);
2448
+ formKey = formKey ? formKey + "[" + key + "]" : key;
2449
+ if (value instanceof Array) {
2450
+ for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
2451
+ var item = value_1[_i];
2452
+ formData.append(formKey + "[]", item);
2453
+ }
2454
+ }
2455
+ else if (recursive &&
2456
+ typeof value === "object" &&
2457
+ (!(recursive instanceof Array) ||
2458
+ !recursive.includes(key))) {
2459
+ if (value !== null) {
2460
+ convertFormData(value, recursive, formData, __spreadArrays$2(ancestors, [key]));
2461
+ }
2462
+ }
2463
+ else {
2464
+ formData.append(formKey, value);
2465
+ }
2466
+ });
2467
+ return formData;
2468
+ }
2469
+ function encodeQueryValue(key, value) {
2470
+ return encodeURIComponent(key) +
2471
+ "=" +
2472
+ encodeURIComponent(typeof value === "object" ?
2473
+ JSON.stringify(value) :
2474
+ "" + value);
2475
+ }
2476
+ function convertFormUrl(formObject) {
2477
+ return Object.keys(formObject)
2478
+ .map(function (key) {
2479
+ var value = formObject[key];
2480
+ if (value instanceof Array) {
2481
+ return value.map(function (v) { return encodeQueryValue(key, v); }).join("&");
2482
+ }
2483
+ return encodeQueryValue(key, value);
2484
+ })
2485
+ .join("&");
2486
+ }
2487
+
2488
+ var factory = Wretcher.factory;
2489
+ factory["default"] = Wretcher.factory;
2490
+
2491
+ function buildBackendApiClient() {
2492
+ const jwt = superSelectionAppService.jwt;
2493
+ const profileId = superSelectionAppService.profileId;
2494
+ const accountId = superSelectionAppService.accountIdOrDefault;
2495
+ const partnerId = superSelectionAppService.partnerIdOrDefault;
2496
+ return factory(superSelectionAppService.apiBaseUrl).headers({
2497
+ Authorization: `Bearer ${jwt}`,
2498
+ 'X-PROFILE-ID': profileId,
2499
+ 'X-PARTNER-ID': partnerId,
2500
+ 'X-ACCOUNT-ID': accountId
2501
+ });
2502
+ }
2503
+
2504
+ const slate = {
2505
+ fundId: 'slate',
2506
+ usi: '32367272075001'
2507
+ };
2508
+
2509
+ function hydratePromotedFundChoiceDtoKind(dto) {
2510
+ if ('slate' in dto) {
2511
+ dto.kind = 'slate';
2512
+ }
2513
+ else if ('australianRetirementTrust' in dto) {
2514
+ dto.kind = 'australianRetirementTrust';
2515
+ }
2516
+ else if ('aware' in dto) {
2517
+ dto.kind = 'aware';
2518
+ }
2519
+ else if ('active' in dto) {
2520
+ dto.kind = 'active';
2521
+ }
2522
+ else if ('australianEthical' in dto) {
2523
+ dto.kind = 'australianEthical';
2524
+ }
2525
+ else if ('virgin' in dto) {
2526
+ dto.kind = 'virgin';
2527
+ }
2528
+ else if ('spirit' in dto) {
2529
+ dto.kind = 'spirit';
2530
+ }
2531
+ else if ('firstSuper' in dto) {
2532
+ dto.kind = 'firstSuper';
2533
+ }
2534
+ else if ('mercerMyChoice' in dto) {
2535
+ dto.kind = 'mercerMyChoice';
2536
+ }
2537
+ else if ('generic' in dto) {
2538
+ dto.kind = 'generic';
2539
+ }
2540
+ }
2541
+ function getPromotedFundUsi(dto) {
2542
+ switch (dto.kind) {
2543
+ case 'slate':
2544
+ return slate.usi;
2545
+ case 'australianRetirementTrust':
2546
+ return dto.australianRetirementTrust.usi;
2547
+ case 'aware':
2548
+ return dto.aware.usi;
2549
+ case 'active':
2550
+ return dto.active.usi;
2551
+ case 'australianEthical':
2552
+ return dto.australianEthical.usi;
2553
+ case 'virgin':
2554
+ return dto.virgin.usi;
2555
+ case 'spirit':
2556
+ return dto.spirit.usi;
2557
+ case 'firstSuper':
2558
+ return dto.firstSuper.usi;
2559
+ case 'mercerMyChoice':
2560
+ return dto.mercerMyChoice.usi;
2561
+ case 'generic':
2562
+ return dto.generic.usi;
2563
+ default:
2564
+ return '';
2565
+ }
2566
+ }
2567
+ function getPromotedFundId(dto) {
2568
+ switch (dto.kind) {
2569
+ case 'slate':
2570
+ return slate.fundId;
2571
+ case 'australianRetirementTrust':
2572
+ return 'australian-retirement-trust';
2573
+ case 'aware':
2574
+ return 'aware';
2575
+ case 'active':
2576
+ return 'active';
2577
+ case 'australianEthical':
2578
+ return 'australian-ethical';
2579
+ case 'virgin':
2580
+ return 'virgin';
2581
+ case 'spirit':
2582
+ return 'spirit';
2583
+ case 'firstSuper':
2584
+ return 'first-super';
2585
+ case 'mercerMyChoice':
2586
+ return 'mercermychoice';
2587
+ case 'generic':
2588
+ return dto.generic.fundId;
2589
+ default:
2590
+ return '';
2591
+ }
2592
+ }
2593
+ function getSuperChoiceUsi(dto) {
2594
+ switch (dto.kind) {
2595
+ case 'Promoted':
2596
+ return some(getPromotedFundUsi(dto.promoted));
2597
+ case 'MyOwnFund':
2598
+ return some(dto.myOwnFund.usi);
2599
+ case 'SMSF':
2600
+ return none;
2601
+ case 'Default':
2602
+ return some(dto.default.usi);
2603
+ case 'PromotedDefault':
2604
+ return some(dto.promotedDefault.usi);
2605
+ case 'DefinedBenefits':
2606
+ return some(dto.definedBenefits.usi);
2607
+ case 'PromotedDefaultWithJoin':
2608
+ return some(dto.promotedDefaultWithJoin.usi);
2609
+ default:
2610
+ return none;
2611
+ }
2612
+ }
2613
+ function getPromotedFundMemberNumber(dto) {
2614
+ switch (dto.kind) {
2615
+ case 'slate':
2616
+ return dto.slate.memberNumber;
2617
+ case 'australianRetirementTrust':
2618
+ return dto.australianRetirementTrust.memberNumber;
2619
+ case 'aware':
2620
+ return dto.aware.memberNumber;
2621
+ case 'active':
2622
+ return dto.active.memberNumber;
2623
+ case 'australianEthical':
2624
+ return dto.australianEthical.memberNumber;
2625
+ case 'virgin':
2626
+ return dto.virgin.memberNumber;
2627
+ case 'spirit':
2628
+ return dto.spirit.memberNumber;
2629
+ case 'firstSuper':
2630
+ return dto.firstSuper.memberNumber;
2631
+ case 'mercerMyChoice':
2632
+ return dto.mercerMyChoice.memberNumber;
2633
+ case 'generic':
2634
+ return dto.generic.memberNumber;
2635
+ default:
2636
+ return '';
2637
+ }
2638
+ }
2639
+ function getSuperChoiceMemberNumber(dto) {
2640
+ switch (dto.kind) {
2641
+ case 'Promoted':
2642
+ return some(getPromotedFundMemberNumber(dto.promoted));
2643
+ case 'MyOwnFund':
2644
+ return some(dto.myOwnFund.memberNumber);
2645
+ case 'DefinedBenefits':
2646
+ return some(dto.definedBenefits.memberNumber);
2647
+ case 'PromotedDefaultWithJoin':
2648
+ return some(dto.promotedDefaultWithJoin.memberNumber);
2649
+ case 'SMSF':
2650
+ case 'Default':
2651
+ case 'PromotedDefault':
2652
+ return none;
2653
+ default:
2654
+ return none;
2655
+ }
2656
+ }
2657
+ function hydrateSuperChoiceDetailsDtoKind(dto) {
2658
+ if ('promoted' in dto) {
2659
+ dto.kind = 'Promoted';
2660
+ }
2661
+ else if ('myOwnFund' in dto) {
2662
+ dto.kind = 'MyOwnFund';
2663
+ }
2664
+ else if ('smsf' in dto) {
2665
+ dto.kind = 'SMSF';
2666
+ }
2667
+ else if ('default' in dto) {
2668
+ dto.kind = 'Default';
2669
+ }
2670
+ else if ('promotedDefault' in dto) {
2671
+ dto.kind = 'PromotedDefault';
2672
+ }
2673
+ else if ('definedBenefits' in dto) {
2674
+ dto.kind = 'DefinedBenefits';
2675
+ }
2676
+ else if ('promotedDefaultWithJoin' in dto) {
2677
+ dto.kind = 'PromotedDefaultWithJoin';
2678
+ }
2679
+ }
2680
+
2681
+ class SuperSelectionApi {
2682
+ async getAustralianFundsAsync(searchFilter, includeInactive = false) {
2683
+ return buildBackendApiClient()
2684
+ .url(`super-choice/australian-funds-v2?${this.toQueryString(includeInactive, searchFilter)}`)
2685
+ .get()
2686
+ .notFound(() => {
2687
+ throw new Error('Failed to fetch the list of australian super funds.');
2688
+ })
2689
+ .json();
2690
+ }
2691
+ async getAustralianFundAsync(usi, includeInactive) {
2692
+ const queryStr = includeInactive ? '?includeInactive=true' : '';
2693
+ return buildBackendApiClient()
2694
+ .url(`super-choice/australian-funds/${usi}${queryStr}`)
2695
+ .get()
2696
+ .notFound(() => {
2697
+ throw new Error('Failed to fetch australian super fund.');
2698
+ })
2699
+ .json();
2700
+ }
2701
+ async getAppStateAsync() {
2702
+ var _a;
2703
+ const response = await buildBackendApiClient()
2704
+ .url('client-app-state')
2705
+ .get()
2706
+ .notFound(() => {
2707
+ throw new Error('Failed to fetch application configuration.');
2708
+ })
2709
+ .json();
2710
+ if ((_a = response.superBuyer.superChoice) === null || _a === void 0 ? void 0 : _a.choiceDetails) {
2711
+ hydrateSuperChoiceDetailsDtoKind(response.superBuyer.superChoice.choiceDetails);
2712
+ switch (response.superBuyer.superChoice.choiceDetails.kind) {
2713
+ case 'Promoted':
2714
+ hydratePromotedFundChoiceDtoKind(response.superBuyer.superChoice.choiceDetails.promoted);
2715
+ break;
2716
+ }
2717
+ }
2718
+ return response;
2719
+ }
2720
+ async clickPromotedTileAsync(payload) {
2721
+ return buildBackendApiClient().url('click-promoted-tile').post(payload).res();
2722
+ }
2723
+ async viewSuperFundPanelAsync(payload) {
2724
+ return buildBackendApiClient().url('view-super-fund-panel').post(payload).res();
2725
+ }
2726
+ toSearchFilterQueryString(searchFilter) {
2727
+ return (`search=${searchFilter.searchString}` +
2728
+ (searchFilter.maxRecordCount > 0 ? '&maxRecordCount=' + searchFilter.maxRecordCount : ''));
2729
+ }
2730
+ toQueryString(includeInactive, searchFilter) {
2731
+ const search = this.toSearchFilterQueryString(searchFilter);
2732
+ const inactive = includeInactive ? 'includeInactive=true' : '';
2733
+ const isNotEmpty = (s) => s && s.length;
2734
+ return [search, inactive].filter(isNotEmpty).join('&');
2735
+ }
2736
+ }
2737
+ const superSelectionApi = new SuperSelectionApi();
2738
+
2739
+ (function (SuperCampaignComponentStatus) {
2740
+ SuperCampaignComponentStatus[SuperCampaignComponentStatus["NotLoaded"] = 1] = "NotLoaded";
2741
+ SuperCampaignComponentStatus[SuperCampaignComponentStatus["Loaded"] = 2] = "Loaded";
2742
+ SuperCampaignComponentStatus[SuperCampaignComponentStatus["NotWorking"] = 3] = "NotWorking";
2743
+ })(exports.SuperCampaignComponentStatus || (exports.SuperCampaignComponentStatus = {}));
2744
+ class SuperCampaignState {
2745
+ constructor() {
2746
+ this._promotedFundsShown = [];
2747
+ }
2748
+ get PromotedFundIds() {
2749
+ return this._promotedFundsShown.map((p) => p.fundId);
2750
+ }
2751
+ set promotedFundsShown(value) {
2752
+ this._promotedFundsShown = value;
2753
+ }
2754
+ get DefaultFundPosition() {
2755
+ const index = this._promotedFundsShown.findIndex((value) => value.fundType === 'promoted-default');
2756
+ if (index === -1)
2757
+ return undefined;
2758
+ return index + 1;
2759
+ }
2760
+ }
2761
+ const initialState = {
2762
+ apiBaseUrl: Option.none,
2763
+ appBaseUrl: Option.none,
2764
+ profileId: Option.none,
2765
+ jwt: Option.none,
2766
+ superBuyer: Option.none,
2767
+ superChoicePrefill: Option.none,
2768
+ promotedFunds: Option.none,
2769
+ accountConfiguration: Option.none,
2770
+ profileConfiguration: Option.none,
2771
+ hasSuccessPageBeenAcknowledged: false,
2772
+ hasSuperSelectionBeenSubmitted: false,
2773
+ isDefinedBenefitsEligible: Option.none,
2774
+ superCampaignEnabled: true,
2775
+ superCampaignState: undefined,
2776
+ superCampaignComponentStatus: exports.SuperCampaignComponentStatus.NotLoaded,
2777
+ hideFooterSection: false,
2778
+ bringYourOwnFundCustomStepEnabled: false,
2779
+ featuredFundsEnabled: false
2780
+ };
2781
+
2782
+ class SuperSelectionAppService {
2783
+ constructor() {
2784
+ const { state, onChange } = createStore(initialState);
2785
+ this._state = state;
2786
+ this._onChange = onChange;
2787
+ onChange('jwt', (jwt) => {
2788
+ this._state.profileId = _function.pipe(jwt, Option.chain((jwtValue) => Option.fromNullable(o(jwtValue).sub)));
2789
+ });
2790
+ }
2791
+ get state() {
2792
+ return this._state;
2793
+ }
2794
+ get onChange() {
2795
+ return this._onChange;
2796
+ }
2797
+ get superBuyer() {
2798
+ if (Option.isNone(this._state.superBuyer)) {
2799
+ throw Error('User information is not set');
2800
+ }
2801
+ return this._state.superBuyer.value;
2802
+ }
2803
+ get apiBaseUrl() {
2804
+ if (Option.isNone(this._state.apiBaseUrl)) {
2805
+ throw Error('API base URL is not set');
2806
+ }
2807
+ return this._state.apiBaseUrl.value;
2808
+ }
2809
+ get appBaseUrl() {
2810
+ if (Option.isNone(this._state.appBaseUrl)) {
2811
+ throw Error('App base URL is not set');
2812
+ }
2813
+ return this._state.appBaseUrl.value;
2814
+ }
2815
+ get promotedFunds() {
2816
+ if (this.state.superCampaignEnabled && this.superCampaignState !== undefined) {
2817
+ return this.superCampaignState.PromotedFundIds;
2818
+ }
2819
+ if (Option.isNone(this._state.promotedFunds)) {
2820
+ throw Error('Promoted Funds is not set');
2821
+ }
2822
+ return this._state.promotedFunds.value;
2823
+ }
2824
+ get promotedDefaultFundPosition() {
2825
+ if (this.state.superCampaignEnabled && this.superCampaignState !== undefined) {
2826
+ return Option.fromNullable(this.superCampaignState.DefaultFundPosition);
2827
+ }
2828
+ return Option.none;
2829
+ }
2830
+ get promotedFundsConfig() {
2831
+ return {
2832
+ shownFunds: this.promotedFunds,
2833
+ promotedDefaultFundPosition: Option.toUndefined(this.promotedDefaultFundPosition),
2834
+ promotedFundsConfigSource: this.isUsingSuperCampaign ? 'superCampaign' : 'superSelection'
2835
+ };
2836
+ }
2837
+ get profileId() {
2838
+ if (Option.isNone(this._state.profileId)) {
2839
+ throw Error('Failed to get Profile ID from JWT');
2840
+ }
2841
+ return this._state.profileId.value;
2842
+ }
2843
+ get defaultFundUsi() {
2844
+ const profileConfigDefaultFundUsi = _function.pipe(this._state.profileConfiguration, Option.map((config) => Option.fromNullable(config.defaultFundUsi)), Option.flatten);
2845
+ if (Option.isSome(profileConfigDefaultFundUsi)) {
2846
+ return profileConfigDefaultFundUsi;
2847
+ }
2848
+ return _function.pipe(this._state.accountConfiguration, Option.map((config) => Option.fromNullable(config.defaultFundUsi)), Option.flatten);
2849
+ }
2850
+ get accountIdOrDefault() {
2851
+ return _function.pipe(this._state.accountConfiguration, Option.map((config) => config.accountId), Option.getOrElse(() => ''));
2852
+ }
2853
+ get partnerIdOrDefault() {
2854
+ return _function.pipe(this._state.superBuyer, Option.map((superBuyer) => superBuyer.partnerId), Option.getOrElse(() => ''));
2855
+ }
2856
+ get jwt() {
2857
+ if (Option.isNone(this._state.jwt)) {
2858
+ throw Error('No authentication information was found');
2859
+ }
2860
+ return this._state.jwt.value;
2861
+ }
2862
+ completeSuperSelectionFlow() {
2863
+ this._state.hasSuccessPageBeenAcknowledged = true;
2864
+ }
2865
+ markSuperSelectionAsSubmitted() {
2866
+ this._state.hasSuperSelectionBeenSubmitted = true;
2867
+ }
2868
+ get isDefinedBenefitsEligible() {
2869
+ return this._state.isDefinedBenefitsEligible;
2870
+ }
2871
+ async loadAppStateAsync() {
2872
+ const appStateResponse = await superSelectionApi.getAppStateAsync();
2873
+ this._state.accountConfiguration = Option.fromNullable(appStateResponse.accountConfiguration);
2874
+ this._state.profileConfiguration = Option.fromNullable(appStateResponse.profileConfiguration);
2875
+ this._state.superBuyer = Option.fromNullable(appStateResponse.superBuyer);
2876
+ this._state.promotedFunds = Option.fromNullable(appStateResponse.promotedFunds);
2877
+ this._state.bringYourOwnFundCustomStepEnabled =
2878
+ appStateResponse.bringYourOwnFundCustomStepEnabled;
2879
+ this._state.featuredFundsEnabled = appStateResponse.featuredFundsEnabled;
2880
+ this._state.superChoicePrefill = Option.fromNullable(appStateResponse.prefill);
2881
+ this._state.isDefinedBenefitsEligible = Option.fromNullable(appStateResponse.isDefinedBenefitsEligible);
2882
+ if (Option.isSome(this._state.accountConfiguration)) {
2883
+ if (this._state.accountConfiguration.value.featureSet.type === 'basic') {
2884
+ this._state.superCampaignEnabled = false;
2885
+ }
2886
+ }
2887
+ }
2888
+ setSuperCampaignPromotedFundsShown(shownFunds) {
2889
+ if (this._state.superCampaignState !== undefined)
2890
+ this._state.superCampaignState.promotedFundsShown = shownFunds;
2891
+ else
2892
+ throw new Error('Cannot set shown funds for SuperCampaing state because it is undefined');
2893
+ }
2894
+ viewSuperFundPanelAsync(placementId, promotedFundIdListOverride) {
2895
+ return superSelectionApi.viewSuperFundPanelAsync(Object.assign(Object.assign({}, this.promotedFundsConfig), { shownFunds: promotedFundIdListOverride
2896
+ ? promotedFundIdListOverride
2897
+ : this.promotedFundsConfig.shownFunds, placementId }));
2898
+ }
2899
+ get superCampaignState() {
2900
+ return this._state.superCampaignState;
2901
+ }
2902
+ get superCampaignComponentStatus() {
2903
+ return this._state.superCampaignComponentStatus;
2904
+ }
2905
+ set superCampaignComponentStatus(value) {
2906
+ if (value === exports.SuperCampaignComponentStatus.Loaded) {
2907
+ this._state.superCampaignComponentStatus = exports.SuperCampaignComponentStatus.Loaded;
2908
+ this._state.superCampaignState = new SuperCampaignState();
2909
+ }
2910
+ else {
2911
+ this._state.superCampaignComponentStatus = value;
2912
+ this._state.superCampaignState = undefined;
2913
+ }
2914
+ }
2915
+ get isUsingSuperCampaign() {
2916
+ return this.state.superCampaignEnabled && this.superCampaignState !== undefined;
2917
+ }
2918
+ get isBringYourOwnFundCustomStepEnabled() {
2919
+ return this.state.bringYourOwnFundCustomStepEnabled;
2920
+ }
2921
+ get isFeaturedFundsEnabled() {
2922
+ return this.state.featuredFundsEnabled;
2923
+ }
2924
+ get superCampaignCanNotBeActivated() {
2925
+ return (!this.state.superCampaignEnabled ||
2926
+ this.superCampaignComponentStatus === exports.SuperCampaignComponentStatus.NotWorking);
2927
+ }
2928
+ get hideFooterSection() {
2929
+ return this._state.hideFooterSection;
2930
+ }
2931
+ set hideFooterSection(value) {
2932
+ this._state.hideFooterSection = value;
2933
+ }
2934
+ get backendUrl() {
2935
+ return Option.map(this.getBaseUrl)(this.state.apiBaseUrl);
2936
+ }
2937
+ getBaseUrl(url) {
2938
+ const parsedUrl = new URL(url);
2939
+ return `${parsedUrl.protocol}//${parsedUrl.hostname}${parsedUrl.port.length > 0 ? `:${parsedUrl.port}` : ''}`;
2940
+ }
2941
+ }
2942
+ const superSelectionAppService = new SuperSelectionAppService();
2943
+
2944
+ class NavigationService {
2945
+ navigateInternally(history, route) {
2946
+ const path = `${this.appBaseUrl}${this.toRouteWithLeadingSlash(route)}`;
2947
+ iframe.navigation(path);
2948
+ history.push(path);
2949
+ }
2950
+ navigateInternallyToStandardChoice(options) {
2951
+ state.handleSubmitFn = options.handleSubmitFn;
2952
+ state.fundName = options.fundName;
2953
+ state.fundDetails = options.fundDetails;
2954
+ state.promotedFundId = options.promotedFundId;
2955
+ this.navigateInternally(options.history, exports.SuperSelectionAppRoutes.StandardChoice);
2956
+ }
2957
+ toExternalUrl(url) {
2958
+ const externalUrl = new URL(url);
2959
+ externalUrl.searchParams.append('_extnav', 'true');
2960
+ return externalUrl.href;
2961
+ }
2962
+ get appBaseUrl() {
2963
+ const baseUrl = superSelectionAppService.appBaseUrl;
2964
+ return baseUrl.replace(/\/$/, '');
2965
+ }
2966
+ toRouteWithLeadingSlash(route) {
2967
+ return route.length > 0 && route[0] === '/' ? route : `/${route}`;
2968
+ }
2969
+ }
2970
+ const navigationService = new NavigationService();
2971
+
2972
+ class CustomFundChoiceApi {
2973
+ async submitDefaultFundChoiceAsync(dto) {
2974
+ return buildBackendApiClient()
2975
+ .url('super-choice/default')
2976
+ .post(dto)
2977
+ .badRequest(() => {
2978
+ throw new Error('Failed to process default fund join request');
2979
+ })
2980
+ .text();
2981
+ }
2982
+ async submitCustomFundChoiceAsync(dto) {
2983
+ return buildBackendApiClient()
2984
+ .url('super-choice/custom-fund')
2985
+ .post(dto)
2986
+ .badRequest(() => {
2987
+ throw new Error('Failed to process custom fund join request');
2988
+ })
2989
+ .text();
2990
+ }
2991
+ async submitSelfManagedFundChoiceAsync(dto) {
2992
+ return buildBackendApiClient()
2993
+ .url('super-choice/smsf')
2994
+ .post(dto)
2995
+ .badRequest(() => {
2996
+ throw new Error('Failed to process SMSF choice request');
2997
+ })
2998
+ .text();
2999
+ }
3000
+ async submitDefinedBenefitsChoiceAsync(dto) {
3001
+ return buildBackendApiClient()
3002
+ .url('super-choice/defined-benefits')
3003
+ .post(dto)
3004
+ .badRequest(() => {
3005
+ throw new Error('Failed to process Defined Benefits choice request');
3006
+ })
3007
+ .text();
3008
+ }
3009
+ async validateAbnForSMSF(abn) {
3010
+ const response = await buildBackendApiClient()
3011
+ .url(`super-choice/smsf/${abn}/validate`)
3012
+ .get()
3013
+ .badRequest(() => {
3014
+ throw new Error('Failed to verify that if the provided abn is used for regulated fund');
3015
+ })
3016
+ .json();
3017
+ return response.result;
3018
+ }
3019
+ }
3020
+ const customFundChoiceApi = new CustomFundChoiceApi();
3021
+
3022
+ exports.Option = Option;
3023
+ exports.buildBackendApiClient = buildBackendApiClient;
3024
+ exports.createStore = createStore;
3025
+ exports.customFundChoiceApi = customFundChoiceApi;
3026
+ exports.factory = factory;
3027
+ exports.fromNullable = fromNullable;
3028
+ exports.getPromotedFundId = getPromotedFundId;
3029
+ exports.getSuperChoiceMemberNumber = getSuperChoiceMemberNumber;
3030
+ exports.getSuperChoiceUsi = getSuperChoiceUsi;
3031
+ exports.iframe = iframe;
3032
+ exports.injectHistory = injectHistory;
3033
+ exports.isNone = isNone;
3034
+ exports.isSome = isSome;
3035
+ exports.navigationService = navigationService;
3036
+ exports.none = none;
3037
+ exports.slate = slate;
3038
+ exports.some = some;
3039
+ exports.state = state;
3040
+ exports.superSelectionApi = superSelectionApi;
3041
+ exports.superSelectionAppService = superSelectionAppService;
3042
+ exports.superSelectionAppStencilRoutes = superSelectionAppStencilRoutes;
3043
+ exports.toUndefined = toUndefined;