@equinor/roma-framework 1.1.0 → 2.0.1

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.
@@ -1,16 +1,30 @@
1
+ var __typeError = (msg) => {
2
+ throw TypeError(msg);
3
+ };
4
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
5
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
6
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
7
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
8
+ var _config, _connections, _builderCallbacks, _endpoints, _manifests;
1
9
  import { jsx, jsxs, Fragment } from "react/jsx-runtime";
2
10
  import { useFramework, FrameworkProvider } from "@equinor/fusion-framework-react";
3
11
  import { configureModules } from "@equinor/fusion-framework-app";
4
12
  import * as React from "react";
5
- import { useState, useEffect, lazy, useRef, createContext, useContext, useMemo, useDebugValue, useLayoutEffect } from "react";
13
+ import { useState, useEffect, lazy, useRef, createContext, useContext, useMemo } from "react";
6
14
  import { ModuleProvider } from "@equinor/fusion-framework-react-module";
7
15
  import styled, { StyleSheetManager, keyframes } from "styled-components";
8
16
  import { EdsProvider, StarProgress, Typography, Card, Button, TopBar, SideSheet, Menu, Tooltip, Icon } from "@equinor/eds-core-react";
9
- import { O as Observable, i as isFunction, E as EmptyError, o as operate, c as createOperatorSubscriber, a as innerFrom, I as IntlProvider, b as invariant, j as joinPaths, g as getPathContributingMatches, w as warning, r as resolveTo, s as stripBasename, d as createPath, B as BehaviorSubject, S as Subject, m as map } from "./router-CrMzSazo.mjs";
17
+ import { E as EmptyError, o as operate, c as createOperatorSubscriber, i as innerFrom, a as identity, b as isFunction, I as IntlProvider, d as invariant, j as joinPaths, g as getPathContributingMatches, w as warning, r as resolveTo, s as stripBasename, e as createPath, B as BehaviorSubject, f as firstValueFrom, h as of, k as from } from "./router-CD1QGwNJ.mjs";
10
18
  import { QueryClient, QueryClientProvider, useQueryClient, useQuery, useMutation } from "@tanstack/react-query";
11
19
  import { useCurrentApp, useApps as useApps$1 } from "@equinor/fusion-framework-react/app";
12
20
  import { App } from "@equinor/fusion-framework-module-app/app";
13
- import { comment_more, notifications, accessible, account_circle, help_outline } from "@equinor/eds-icons";
21
+ import { comment_more, accessible, account_circle, help_outline } from "@equinor/eds-icons";
22
+ import { enableAppModule } from "@equinor/fusion-framework-module-app";
23
+ import { enableContext } from "@equinor/fusion-framework-module-context";
24
+ import { ConsoleLogger } from "@equinor/fusion-framework-module-msal/client";
25
+ import { enableNavigation } from "@equinor/fusion-framework-module-navigation";
26
+ import { ModuleConfigBuilder } from "@equinor/fusion-framework-module";
27
+ import { enableServiceDiscovery } from "@equinor/fusion-framework-module-service-discovery";
14
28
  import { tokens } from "@equinor/eds-tokens";
15
29
  import { useHttpClient } from "@equinor/fusion-framework-react-module-http";
16
30
  const createExtraScopePlugin = (scope) => {
@@ -38,9 +52,6 @@ const StyleProvider = ({ scope, children }) => {
38
52
  }
39
53
  return /* @__PURE__ */ jsx(StyleSheetManager, { stylisPlugins, children: /* @__PURE__ */ jsx("div", { id: scope, children }) });
40
54
  };
41
- function isObservable(obj) {
42
- return !!obj && (obj instanceof Observable || isFunction(obj.lift) && isFunction(obj.subscribe));
43
- }
44
55
  function lastValueFrom(source, config) {
45
56
  return new Promise(function(resolve, reject) {
46
57
  var _hasValue = false;
@@ -61,6 +72,14 @@ function lastValueFrom(source, config) {
61
72
  });
62
73
  });
63
74
  }
75
+ function map(project, thisArg) {
76
+ return operate(function(source, subscriber) {
77
+ var index = 0;
78
+ source.subscribe(createOperatorSubscriber(subscriber, function(value) {
79
+ subscriber.next(project.call(thisArg, value, index++));
80
+ }));
81
+ });
82
+ }
64
83
  function filter(predicate, thisArg) {
65
84
  return operate(function(source, subscriber) {
66
85
  var index = 0;
@@ -69,6 +88,28 @@ function filter(predicate, thisArg) {
69
88
  }));
70
89
  });
71
90
  }
91
+ function catchError(selector) {
92
+ return operate(function(source, subscriber) {
93
+ var innerSub = null;
94
+ var syncUnsub = false;
95
+ var handledResult;
96
+ innerSub = source.subscribe(createOperatorSubscriber(subscriber, void 0, void 0, function(err) {
97
+ handledResult = innerFrom(selector(err, catchError(selector)(source)));
98
+ if (innerSub) {
99
+ innerSub.unsubscribe();
100
+ innerSub = null;
101
+ handledResult.subscribe(subscriber);
102
+ } else {
103
+ syncUnsub = true;
104
+ }
105
+ }));
106
+ if (syncUnsub) {
107
+ innerSub.unsubscribe();
108
+ innerSub = null;
109
+ handledResult.subscribe(subscriber);
110
+ }
111
+ });
112
+ }
72
113
  function switchMap(project, resultSelector) {
73
114
  return operate(function(source, subscriber) {
74
115
  var innerSubscriber = null;
@@ -93,6 +134,35 @@ function switchMap(project, resultSelector) {
93
134
  }));
94
135
  });
95
136
  }
137
+ function tap(observerOrNext, error, complete) {
138
+ var tapObserver = isFunction(observerOrNext) || error || complete ? { next: observerOrNext, error, complete } : observerOrNext;
139
+ return tapObserver ? operate(function(source, subscriber) {
140
+ var _a;
141
+ (_a = tapObserver.subscribe) === null || _a === void 0 ? void 0 : _a.call(tapObserver);
142
+ var isUnsub = true;
143
+ source.subscribe(createOperatorSubscriber(subscriber, function(value) {
144
+ var _a2;
145
+ (_a2 = tapObserver.next) === null || _a2 === void 0 ? void 0 : _a2.call(tapObserver, value);
146
+ subscriber.next(value);
147
+ }, function() {
148
+ var _a2;
149
+ isUnsub = false;
150
+ (_a2 = tapObserver.complete) === null || _a2 === void 0 ? void 0 : _a2.call(tapObserver);
151
+ subscriber.complete();
152
+ }, function(err) {
153
+ var _a2;
154
+ isUnsub = false;
155
+ (_a2 = tapObserver.error) === null || _a2 === void 0 ? void 0 : _a2.call(tapObserver, err);
156
+ subscriber.error(err);
157
+ }, function() {
158
+ var _a2, _b;
159
+ if (isUnsub) {
160
+ (_a2 = tapObserver.unsubscribe) === null || _a2 === void 0 ? void 0 : _a2.call(tapObserver);
161
+ }
162
+ (_b = tapObserver.finalize) === null || _b === void 0 ? void 0 : _b.call(tapObserver);
163
+ }));
164
+ }) : identity;
165
+ }
96
166
  const EdsEventProvider = ({ event, children }) => {
97
167
  const [density, setDensity] = useState(
98
168
  localStorage.getItem("roma__density") ?? "comfortable"
@@ -106,11 +176,14 @@ const EdsEventProvider = ({ event, children }) => {
106
176
  }, [event]);
107
177
  return /* @__PURE__ */ jsx(EdsProvider, { density, children });
108
178
  };
109
- const makeComponent = (Component, args, configure) => lazy(async () => {
110
- const init = configureModules(configure);
179
+ function getDefaultExportFromCjs(x) {
180
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
181
+ }
182
+ const makeComponent = (Component, args, configure2) => lazy(async () => {
183
+ const init = configureModules(configure2);
111
184
  const modules = await init(args);
112
185
  const manifest = args.env.manifest;
113
- const appKey = manifest.key;
186
+ const appKey = manifest.appKey;
114
187
  const { fusion } = args;
115
188
  modules.event.dispatchEvent("onReactAppLoaded", {
116
189
  detail: { modules, fusion },
@@ -122,7 +195,7 @@ const makeComponent = (Component, args, configure) => lazy(async () => {
122
195
  };
123
196
  });
124
197
  const withStyleIsolation = (children, args) => lazy(async () => {
125
- const appKey = args.env.manifest.key;
198
+ const appKey = args.env.manifest.appKey;
126
199
  return {
127
200
  default: () => /* @__PURE__ */ jsx(StyleProvider, { scope: `roma-${appKey}`, children })
128
201
  };
@@ -180,7 +253,7 @@ const RomaErrorViewer = ({
180
253
  };
181
254
  function getAppModule(app, framework) {
182
255
  const initializeData = {
183
- appKey: app.key,
256
+ appKey: app.appKey,
184
257
  manifest: app,
185
258
  config: {
186
259
  environment: "development",
@@ -233,7 +306,7 @@ function AppLoader({
233
306
  }
234
307
  });
235
308
  if (kind === "app") {
236
- setCurrentApp(app.key);
309
+ setCurrentApp(app.appKey);
237
310
  }
238
311
  });
239
312
  return appModule;
@@ -372,7 +445,7 @@ function useLocation() {
372
445
  return React.useContext(LocationContext).location;
373
446
  }
374
447
  const navigateEffectWarning = "You should call navigate() in a React.useEffect(), not when your component is first rendered.";
375
- function useIsomorphicLayoutEffect$1(cb) {
448
+ function useIsomorphicLayoutEffect(cb) {
376
449
  let isStatic = React.useContext(NavigationContext).static;
377
450
  if (!isStatic) {
378
451
  React.useLayoutEffect(cb);
@@ -404,7 +477,7 @@ function useNavigateUnstable() {
404
477
  } = useLocation();
405
478
  let routePathnamesJson = JSON.stringify(getPathContributingMatches(matches).map((match) => match.pathnameBase));
406
479
  let activeRef = React.useRef(false);
407
- useIsomorphicLayoutEffect$1(() => {
480
+ useIsomorphicLayoutEffect(() => {
408
481
  activeRef.current = true;
409
482
  });
410
483
  let navigate = React.useCallback(function(to, options) {
@@ -492,7 +565,7 @@ function useNavigateStable() {
492
565
  } = useDataRouterContext$1(DataRouterHook$1.UseNavigateStable);
493
566
  let id = useCurrentRouteId(DataRouterStateHook$1.UseNavigateStable);
494
567
  let activeRef = React.useRef(false);
495
- useIsomorphicLayoutEffect$1(() => {
568
+ useIsomorphicLayoutEffect(() => {
496
569
  activeRef.current = true;
497
570
  });
498
571
  let navigate = React.useCallback(function(to, options) {
@@ -551,17 +624,17 @@ function _objectWithoutPropertiesLoose(source, excluded) {
551
624
  }
552
625
  const defaultMethod = "get";
553
626
  const defaultEncType = "application/x-www-form-urlencoded";
554
- function isHtmlElement(object) {
555
- return object != null && typeof object.tagName === "string";
627
+ function isHtmlElement(object2) {
628
+ return object2 != null && typeof object2.tagName === "string";
556
629
  }
557
- function isButtonElement(object) {
558
- return isHtmlElement(object) && object.tagName.toLowerCase() === "button";
630
+ function isButtonElement(object2) {
631
+ return isHtmlElement(object2) && object2.tagName.toLowerCase() === "button";
559
632
  }
560
- function isFormElement(object) {
561
- return isHtmlElement(object) && object.tagName.toLowerCase() === "form";
633
+ function isFormElement(object2) {
634
+ return isHtmlElement(object2) && object2.tagName.toLowerCase() === "form";
562
635
  }
563
- function isInputElement(object) {
564
- return isHtmlElement(object) && object.tagName.toLowerCase() === "input";
636
+ function isInputElement(object2) {
637
+ return isHtmlElement(object2) && object2.tagName.toLowerCase() === "input";
565
638
  }
566
639
  function isModifiedEvent(event) {
567
640
  return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
@@ -964,7 +1037,8 @@ function AppLoadError({
964
1037
  ] });
965
1038
  }
966
1039
  const AppProvider = ({ children }) => {
967
- const { apps, isLoading, error } = useApps$1({ includeHidden: true });
1040
+ const { apps: _apps, isLoading, error } = useApps$1();
1041
+ const apps = _apps;
968
1042
  return /* @__PURE__ */ jsx(
969
1043
  AppContext.Provider,
970
1044
  {
@@ -977,9 +1051,7 @@ const AppProvider = ({ children }) => {
977
1051
  }
978
1052
  );
979
1053
  };
980
- const useApps = ({
981
- includeHidden
982
- } = {}) => {
1054
+ const useApps = ({ includeHidden } = {}) => {
983
1055
  const { apps: allApps, isLoading, error } = useContext(AppContext);
984
1056
  return useMemo(() => {
985
1057
  if (!allApps) return { isLoading, apps: [], error };
@@ -994,7 +1066,7 @@ const AppViewer = () => {
994
1066
  const { appKey } = useParams();
995
1067
  const { apps } = useApps({ includeHidden: true });
996
1068
  const app = useMemo(() => {
997
- return apps == null ? void 0 : apps.find((app2) => app2.key === appKey);
1069
+ return apps == null ? void 0 : apps.find((app2) => app2.appKey === appKey);
998
1070
  }, [appKey, apps]);
999
1071
  if (!apps) {
1000
1072
  return /* @__PURE__ */ jsx(EquinorLoader, { text: "Loading apps..." });
@@ -1074,7 +1146,7 @@ const SideSheets = ({
1074
1146
  children: apps && apps.length > 0 ? /* @__PURE__ */ jsx(
1075
1147
  AppLoader,
1076
1148
  {
1077
- app: apps.find((app) => app.key === "activity-feed") ?? null
1149
+ app: apps.find((app) => app.appKey === "activity-feed") ?? null
1078
1150
  }
1079
1151
  ) : null
1080
1152
  }
@@ -1083,177 +1155,6 @@ const SideSheets = ({
1083
1155
  "sheet-activity"
1084
1156
  );
1085
1157
  };
1086
- const useSseModule = () => {
1087
- return useFramework().modules.sse;
1088
- };
1089
- function useObservableInternal(useCustomEffect, init, inputs) {
1090
- if (!inputs) {
1091
- return useState(init)[0];
1092
- }
1093
- const [inputs$] = useState(() => new BehaviorSubject(inputs));
1094
- const [source$] = useState(() => init(inputs$));
1095
- const firstEffectRef = useRef(true);
1096
- useCustomEffect(() => {
1097
- if (firstEffectRef.current) {
1098
- firstEffectRef.current = false;
1099
- return;
1100
- }
1101
- inputs$.next(inputs);
1102
- }, inputs);
1103
- return source$;
1104
- }
1105
- function useObservable(init, inputs) {
1106
- return useObservableInternal(useEffect, init, inputs);
1107
- }
1108
- var getEmptySubject = () => new Subject();
1109
- var useIsomorphicLayoutEffect = /* @__PURE__ */ (() => (
1110
- /* istanbul ignore next */
1111
- typeof window === "undefined" ? useEffect : useLayoutEffect
1112
- ))();
1113
- var toObserver = (args) => {
1114
- var _a;
1115
- return ((_a = args[1]) == null ? void 0 : _a.next) ? args[1] : {
1116
- next: args[1],
1117
- error: args[2],
1118
- complete: args[3]
1119
- };
1120
- };
1121
- function useSubscriptionInternal(useCustomEffect, args) {
1122
- const argsRef = useRef(args);
1123
- const observerRef = useRef();
1124
- const subscriptionRef = useRef();
1125
- useIsomorphicLayoutEffect(() => {
1126
- argsRef.current = args;
1127
- observerRef.current = toObserver(args);
1128
- });
1129
- useCustomEffect(() => {
1130
- const input$ = argsRef.current[0];
1131
- if (!observerRef.current) {
1132
- observerRef.current = toObserver(argsRef.current);
1133
- }
1134
- const subscription = input$.subscribe({
1135
- next: (value) => {
1136
- var _a, _b;
1137
- if (input$ === argsRef.current[0]) {
1138
- (_b = (_a = observerRef.current).next) == null ? void 0 : _b.call(_a, value);
1139
- }
1140
- },
1141
- error: (error) => {
1142
- if (input$ === argsRef.current[0]) {
1143
- observerRef.current.error ? observerRef.current.error(error) : console.error(error);
1144
- }
1145
- },
1146
- complete: () => {
1147
- var _a, _b;
1148
- if (input$ === argsRef.current[0]) {
1149
- (_b = (_a = observerRef.current).complete) == null ? void 0 : _b.call(_a);
1150
- }
1151
- }
1152
- });
1153
- subscriptionRef.current = subscription;
1154
- return () => {
1155
- subscription.unsubscribe();
1156
- };
1157
- }, [args[0]]);
1158
- return subscriptionRef;
1159
- }
1160
- function useSubscription(input$, observerOrNext$, error, complete) {
1161
- return useSubscriptionInternal(useEffect, [
1162
- input$,
1163
- observerOrNext$,
1164
- error,
1165
- complete
1166
- ]);
1167
- }
1168
- function useObservableStateInternal(useSubscription2, state$OrInit, initialState) {
1169
- if (isObservable(state$OrInit)) {
1170
- const state$ = state$OrInit;
1171
- const [state, setState] = useState(() => {
1172
- if (state$ instanceof BehaviorSubject || state$.value !== void 0) {
1173
- return state$.value;
1174
- }
1175
- if (typeof initialState === "function") {
1176
- return initialState();
1177
- }
1178
- return initialState;
1179
- });
1180
- useSubscription2(state$, setState);
1181
- useDebugValue(state);
1182
- return state;
1183
- } else {
1184
- const init = state$OrInit;
1185
- const [state, setState] = useState(initialState);
1186
- const [input$] = useState(getEmptySubject);
1187
- const [state$] = useState(() => init(input$, state));
1188
- const callback = useRef((state2) => input$.next(state2)).current;
1189
- useSubscription2(state$, setState);
1190
- useDebugValue(state);
1191
- return [state, callback];
1192
- }
1193
- }
1194
- function useObservableState(state$OrInit, initialState) {
1195
- return useObservableStateInternal(
1196
- useSubscription,
1197
- state$OrInit,
1198
- initialState
1199
- );
1200
- }
1201
- const mapEvents = (opts = {
1202
- limit: 10
1203
- }) => map((allEvents) => {
1204
- const value = allEvents.filter((v, i, arr) => {
1205
- return arr.slice(0, i).every((x) => x.id !== v.id);
1206
- });
1207
- if (!opts.filter) {
1208
- return value;
1209
- } else {
1210
- return value.filter((v) => {
1211
- const filters = opts.filter;
1212
- return Object.keys(filters.attributes).every((key) => {
1213
- const currentValue = v[key];
1214
- const filterValue = filters.attributes[key];
1215
- if (filterValue === null || filterValue === void 0) return true;
1216
- if (key === "payload") {
1217
- let valueStr;
1218
- try {
1219
- valueStr = JSON.stringify(currentValue);
1220
- } catch {
1221
- }
1222
- if (valueStr === void 0) return true;
1223
- const re = new RegExp(filters.attributes[key], "ig");
1224
- return re.test(valueStr ?? "");
1225
- } else if (Array.isArray(filters.attributes[key])) {
1226
- if (filters.attributes[key].length === 0) return true;
1227
- return filters.attributes[key].includes(
1228
- currentValue
1229
- );
1230
- } else {
1231
- return filters.attributes[key] == currentValue;
1232
- }
1233
- });
1234
- });
1235
- }
1236
- });
1237
- const useSse = (name, opts) => {
1238
- const limit = ((opts == null ? void 0 : opts.limit) ?? 10) > 100 ? 100 : opts == null ? void 0 : opts.limit;
1239
- const module = useSseModule();
1240
- const connection = module.connect(name);
1241
- const stream$ = connection.messageList$.pipe();
1242
- const safeStream$ = useObservable(
1243
- (options) => options.pipe(
1244
- switchMap((opt) => {
1245
- return stream$.pipe(mapEvents(opt[0]));
1246
- })
1247
- ),
1248
- [opts]
1249
- );
1250
- const messages = useObservableState(safeStream$, []);
1251
- return {
1252
- messages: messages.slice(0, limit),
1253
- setReadState: connection.setReadState,
1254
- setAllRead: connection.setAllRead
1255
- };
1256
- };
1257
1158
  const HeaderMenu = ({ menuState }) => {
1258
1159
  const { currentApp } = useCurrentApp();
1259
1160
  const { apps: applications } = useApps({ includeHidden: true });
@@ -1272,13 +1173,15 @@ const HeaderMenu = ({ menuState }) => {
1272
1173
  return ((_a = user == null ? void 0 : user.idTokenClaims) == null ? void 0 : _a.roles) ?? ["No access role"];
1273
1174
  }, [user]);
1274
1175
  const getFeedbackAreaFromTags = (currentApp2, applications2) => {
1275
- const manifest = applications2.find((app) => app.key === (currentApp2 == null ? void 0 : currentApp2.appKey));
1276
- const tags = (manifest == null ? void 0 : manifest.tags) ?? [];
1176
+ const manifest = applications2.find(
1177
+ (app) => app.appKey === (currentApp2 == null ? void 0 : currentApp2.appKey)
1178
+ );
1179
+ const tags = (manifest == null ? void 0 : manifest.keywords) ?? [];
1277
1180
  if (tags.includes("trading")) return "10543";
1278
1181
  if (tags.includes("liquids-operations")) return "10511";
1279
1182
  return "10540";
1280
1183
  };
1281
- const opts = useMemo(
1184
+ useMemo(
1282
1185
  () => ({
1283
1186
  limit: 10,
1284
1187
  filter: {
@@ -1296,7 +1199,10 @@ const HeaderMenu = ({ menuState }) => {
1296
1199
  const e = new CustomEvent("onDensityChanged", { detail: newDensity });
1297
1200
  event.dispatchEvent("onDensityChanged", e);
1298
1201
  };
1299
- const { messages } = useSse("activity", opts);
1202
+ const quickLinks = applications.find((app) => app.appKey === "quick-links");
1203
+ const notificationCenter = applications.find(
1204
+ (app) => app.appKey === "notifications"
1205
+ );
1300
1206
  return /* @__PURE__ */ jsxs(Fragment, { children: [
1301
1207
  /* @__PURE__ */ jsx(Tooltip, { title: "Submit and view your previous feedback", children: /* @__PURE__ */ jsxs(
1302
1208
  Button,
@@ -1311,127 +1217,2784 @@ const HeaderMenu = ({ menuState }) => {
1311
1217
  ]
1312
1218
  }
1313
1219
  ) }),
1314
- /* @__PURE__ */ jsx(Tooltip, { title: "View notifications and notification settings", children: /* @__PURE__ */ jsxs(
1220
+ /* @__PURE__ */ jsx(Tooltip, { title: "Switch between compact and comfortable view", children: /* @__PURE__ */ jsx(
1315
1221
  Button,
1316
1222
  {
1317
- variant: "ghost",
1318
- onClick: () => menuState.setActivityLogOpen(true),
1223
+ onClick: () => menuState.setA11yOpen(true),
1224
+ ref: a11yRef,
1225
+ variant: "ghost_icon",
1226
+ children: /* @__PURE__ */ jsx(Icon, { data: accessible })
1227
+ }
1228
+ ) }),
1229
+ /* @__PURE__ */ jsx(
1230
+ StyledMenu,
1231
+ {
1232
+ onClose: () => menuState.setA11yOpen(false),
1233
+ anchorEl: a11yRef.current,
1234
+ open: menuState.a11yOpen,
1235
+ children: /* @__PURE__ */ jsxs(Menu.Section, { title: "Density", children: [
1236
+ /* @__PURE__ */ jsx(
1237
+ Menu.Item,
1238
+ {
1239
+ active: density === "comfortable",
1240
+ onClick: () => toggleDensity("comfortable"),
1241
+ children: "Comfortable"
1242
+ }
1243
+ ),
1244
+ /* @__PURE__ */ jsx(
1245
+ Menu.Item,
1246
+ {
1247
+ active: density === "compact",
1248
+ onClick: () => toggleDensity("compact"),
1249
+ children: "Compact"
1250
+ }
1251
+ )
1252
+ ] })
1253
+ }
1254
+ ),
1255
+ notificationCenter && /* @__PURE__ */ jsx(AppLoader, { app: notificationCenter, kind: "widget" }),
1256
+ quickLinks && /* @__PURE__ */ jsx(AppLoader, { app: quickLinks, kind: "widget" }),
1257
+ /* @__PURE__ */ jsx(Tooltip, { title: "View user settings", children: /* @__PURE__ */ jsx(
1258
+ Button,
1259
+ {
1260
+ onClick: () => menuState.setUserMenuOpen(true),
1261
+ ref: userRef,
1262
+ variant: "ghost_icon",
1263
+ children: /* @__PURE__ */ jsx(Icon, { data: account_circle })
1264
+ }
1265
+ ) }),
1266
+ /* @__PURE__ */ jsxs(
1267
+ StyledMenu,
1268
+ {
1269
+ onClose: () => menuState.setUserMenuOpen(false),
1270
+ anchorEl: userRef.current,
1271
+ open: menuState.userMenuOpen,
1319
1272
  children: [
1320
- /* @__PURE__ */ jsx(Icon, { data: notifications }),
1321
- /* @__PURE__ */ jsx(Typography, { variant: "chip__badge", group: "ui", children: (messages == null ? void 0 : messages.filter((m) => !m.read).length) ?? 0 })
1273
+ /* @__PURE__ */ jsxs(Menu.Section, { title: "Profile", children: [
1274
+ /* @__PURE__ */ jsx(Menu.Item, { children: user.name }),
1275
+ /* @__PURE__ */ jsx(
1276
+ Menu.Item,
1277
+ {
1278
+ onClick: () => auth.defaultClient.logoutRedirect({
1279
+ postLogoutRedirectUri: window.location.origin
1280
+ }),
1281
+ children: "Sign out"
1282
+ }
1283
+ )
1284
+ ] }),
1285
+ /* @__PURE__ */ jsx(Menu.Section, { title: "Roles", children: roles.map((r) => /* @__PURE__ */ jsx(Menu.Item, { children: r }, r)) })
1322
1286
  ]
1323
1287
  }
1324
- ) }),
1325
- /* @__PURE__ */ jsx(Tooltip, { title: "Switch between compact and comfortable view", children: /* @__PURE__ */ jsx(
1326
- Button,
1327
- {
1328
- onClick: () => menuState.setA11yOpen(true),
1329
- ref: a11yRef,
1330
- variant: "ghost_icon",
1331
- children: /* @__PURE__ */ jsx(Icon, { data: accessible })
1288
+ ),
1289
+ /* @__PURE__ */ jsx(Tooltip, { title: "Release notes", children: /* @__PURE__ */ jsx(
1290
+ Button,
1291
+ {
1292
+ variant: "ghost_icon",
1293
+ as: "a",
1294
+ href: `https://statoilsrm.sharepoint.com/sites/Roma/Lists/Releases/AllItems.aspx`,
1295
+ target: "_blank",
1296
+ children: /* @__PURE__ */ jsx(Icon, { data: help_outline })
1297
+ }
1298
+ ) })
1299
+ ] });
1300
+ };
1301
+ const Header = () => {
1302
+ const [a11yOpen, setA11yOpen] = useState(false);
1303
+ const [userMenuOpen, setUserMenuOpen] = useState(false);
1304
+ const [activityLogOpen, setActivityLogOpen] = useState(false);
1305
+ const { apps: allApps } = useApps({ includeHidden: true });
1306
+ const headerMenuState = {
1307
+ a11yOpen,
1308
+ setA11yOpen,
1309
+ userMenuOpen,
1310
+ setUserMenuOpen,
1311
+ activityLogOpen,
1312
+ setActivityLogOpen
1313
+ };
1314
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1315
+ /* @__PURE__ */ jsxs(TopBarFadeIn, { id: "cli-top-bar", children: [
1316
+ /* @__PURE__ */ jsx(TopBar.Header, { children: /* @__PURE__ */ jsxs(Styled.Title, { children: [
1317
+ /* @__PURE__ */ jsx(Icon, { color: "#eb0037", data: logoIcon, viewBox: "0 0 42 48" }),
1318
+ /* @__PURE__ */ jsx("span", { children: "Roma" })
1319
+ ] }) }),
1320
+ /* @__PURE__ */ jsx(TopBar.CustomContent, {}),
1321
+ /* @__PURE__ */ jsx(TopBar.Actions, { children: /* @__PURE__ */ jsx(HeaderMenu, { menuState: headerMenuState }) })
1322
+ ] }),
1323
+ /* @__PURE__ */ jsx(SideSheets, { apps: allApps, menuState: headerMenuState })
1324
+ ] });
1325
+ };
1326
+ async function getBytes(stream, onChunk) {
1327
+ const reader = stream.getReader();
1328
+ let result;
1329
+ while (!(result = await reader.read()).done) {
1330
+ onChunk(result.value);
1331
+ }
1332
+ }
1333
+ function getLines(onLine) {
1334
+ let buffer;
1335
+ let position;
1336
+ let fieldLength;
1337
+ let discardTrailingNewline = false;
1338
+ return function onChunk(arr) {
1339
+ if (buffer === void 0) {
1340
+ buffer = arr;
1341
+ position = 0;
1342
+ fieldLength = -1;
1343
+ } else {
1344
+ buffer = concat(buffer, arr);
1345
+ }
1346
+ const bufLength = buffer.length;
1347
+ let lineStart = 0;
1348
+ while (position < bufLength) {
1349
+ if (discardTrailingNewline) {
1350
+ if (buffer[position] === 10) {
1351
+ lineStart = ++position;
1352
+ }
1353
+ discardTrailingNewline = false;
1354
+ }
1355
+ let lineEnd = -1;
1356
+ for (; position < bufLength && lineEnd === -1; ++position) {
1357
+ switch (buffer[position]) {
1358
+ case 58:
1359
+ if (fieldLength === -1) {
1360
+ fieldLength = position - lineStart;
1361
+ }
1362
+ break;
1363
+ case 13:
1364
+ discardTrailingNewline = true;
1365
+ case 10:
1366
+ lineEnd = position;
1367
+ break;
1368
+ }
1369
+ }
1370
+ if (lineEnd === -1) {
1371
+ break;
1372
+ }
1373
+ onLine(buffer.subarray(lineStart, lineEnd), fieldLength);
1374
+ lineStart = position;
1375
+ fieldLength = -1;
1376
+ }
1377
+ if (lineStart === bufLength) {
1378
+ buffer = void 0;
1379
+ } else if (lineStart !== 0) {
1380
+ buffer = buffer.subarray(lineStart);
1381
+ position -= lineStart;
1382
+ }
1383
+ };
1384
+ }
1385
+ function getMessages(onId, onRetry, onMessage) {
1386
+ let message = newMessage();
1387
+ const decoder = new TextDecoder();
1388
+ return function onLine(line, fieldLength) {
1389
+ if (line.length === 0) {
1390
+ onMessage === null || onMessage === void 0 ? void 0 : onMessage(message);
1391
+ message = newMessage();
1392
+ } else if (fieldLength > 0) {
1393
+ const field = decoder.decode(line.subarray(0, fieldLength));
1394
+ const valueOffset = fieldLength + (line[fieldLength + 1] === 32 ? 2 : 1);
1395
+ const value = decoder.decode(line.subarray(valueOffset));
1396
+ switch (field) {
1397
+ case "data":
1398
+ message.data = message.data ? message.data + "\n" + value : value;
1399
+ break;
1400
+ case "event":
1401
+ message.event = value;
1402
+ break;
1403
+ case "id":
1404
+ onId(message.id = value);
1405
+ break;
1406
+ case "retry":
1407
+ const retry = parseInt(value, 10);
1408
+ if (!isNaN(retry)) {
1409
+ onRetry(message.retry = retry);
1410
+ }
1411
+ break;
1412
+ }
1413
+ }
1414
+ };
1415
+ }
1416
+ function concat(a, b) {
1417
+ const res = new Uint8Array(a.length + b.length);
1418
+ res.set(a);
1419
+ res.set(b, a.length);
1420
+ return res;
1421
+ }
1422
+ function newMessage() {
1423
+ return {
1424
+ data: "",
1425
+ event: "",
1426
+ id: "",
1427
+ retry: void 0
1428
+ };
1429
+ }
1430
+ var __rest = function(s, e) {
1431
+ var t = {};
1432
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
1433
+ t[p] = s[p];
1434
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
1435
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
1436
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
1437
+ t[p[i]] = s[p[i]];
1438
+ }
1439
+ return t;
1440
+ };
1441
+ const EventStreamContentType = "text/event-stream";
1442
+ const DefaultRetryInterval = 1e3;
1443
+ const LastEventId = "last-event-id";
1444
+ function fetchEventSource(input, _a) {
1445
+ var { signal: inputSignal, headers: inputHeaders, onopen: inputOnOpen, onmessage, onclose, onerror, openWhenHidden, fetch: inputFetch } = _a, rest = __rest(_a, ["signal", "headers", "onopen", "onmessage", "onclose", "onerror", "openWhenHidden", "fetch"]);
1446
+ return new Promise((resolve, reject) => {
1447
+ const headers = Object.assign({}, inputHeaders);
1448
+ if (!headers.accept) {
1449
+ headers.accept = EventStreamContentType;
1450
+ }
1451
+ let curRequestController;
1452
+ function onVisibilityChange() {
1453
+ curRequestController.abort();
1454
+ if (!document.hidden) {
1455
+ create();
1456
+ }
1457
+ }
1458
+ if (!openWhenHidden) {
1459
+ document.addEventListener("visibilitychange", onVisibilityChange);
1460
+ }
1461
+ let retryInterval = DefaultRetryInterval;
1462
+ let retryTimer = 0;
1463
+ function dispose() {
1464
+ document.removeEventListener("visibilitychange", onVisibilityChange);
1465
+ window.clearTimeout(retryTimer);
1466
+ curRequestController.abort();
1467
+ }
1468
+ inputSignal === null || inputSignal === void 0 ? void 0 : inputSignal.addEventListener("abort", () => {
1469
+ dispose();
1470
+ resolve();
1471
+ });
1472
+ const fetch2 = inputFetch !== null && inputFetch !== void 0 ? inputFetch : window.fetch;
1473
+ const onopen = inputOnOpen !== null && inputOnOpen !== void 0 ? inputOnOpen : defaultOnOpen;
1474
+ async function create() {
1475
+ var _a2;
1476
+ curRequestController = new AbortController();
1477
+ try {
1478
+ const response = await fetch2(input, Object.assign(Object.assign({}, rest), { headers, signal: curRequestController.signal }));
1479
+ await onopen(response);
1480
+ await getBytes(response.body, getLines(getMessages((id) => {
1481
+ if (id) {
1482
+ headers[LastEventId] = id;
1483
+ } else {
1484
+ delete headers[LastEventId];
1485
+ }
1486
+ }, (retry) => {
1487
+ retryInterval = retry;
1488
+ }, onmessage)));
1489
+ onclose === null || onclose === void 0 ? void 0 : onclose();
1490
+ dispose();
1491
+ resolve();
1492
+ } catch (err) {
1493
+ if (!curRequestController.signal.aborted) {
1494
+ try {
1495
+ const interval = (_a2 = onerror === null || onerror === void 0 ? void 0 : onerror(err)) !== null && _a2 !== void 0 ? _a2 : retryInterval;
1496
+ window.clearTimeout(retryTimer);
1497
+ retryTimer = window.setTimeout(create, interval);
1498
+ } catch (innerErr) {
1499
+ dispose();
1500
+ reject(innerErr);
1501
+ }
1502
+ }
1503
+ }
1504
+ }
1505
+ create();
1506
+ });
1507
+ }
1508
+ function defaultOnOpen(response) {
1509
+ const contentType = response.headers.get("content-type");
1510
+ if (!(contentType === null || contentType === void 0 ? void 0 : contentType.startsWith(EventStreamContentType))) {
1511
+ throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`);
1512
+ }
1513
+ }
1514
+ function promisifyRequest(request) {
1515
+ return new Promise((resolve, reject) => {
1516
+ request.oncomplete = request.onsuccess = () => resolve(request.result);
1517
+ request.onabort = request.onerror = () => reject(request.error);
1518
+ });
1519
+ }
1520
+ function createStore(dbName, storeName) {
1521
+ const request = indexedDB.open(dbName);
1522
+ request.onupgradeneeded = () => request.result.createObjectStore(storeName);
1523
+ const dbp = promisifyRequest(request);
1524
+ return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));
1525
+ }
1526
+ let defaultGetStoreFunc;
1527
+ function defaultGetStore() {
1528
+ if (!defaultGetStoreFunc) {
1529
+ defaultGetStoreFunc = createStore("keyval-store", "keyval");
1530
+ }
1531
+ return defaultGetStoreFunc;
1532
+ }
1533
+ function get(key, customStore = defaultGetStore()) {
1534
+ return customStore("readonly", (store) => promisifyRequest(store.get(key)));
1535
+ }
1536
+ function set(key, value, customStore = defaultGetStore()) {
1537
+ return customStore("readwrite", (store) => {
1538
+ store.put(value, key);
1539
+ return promisifyRequest(store.transaction);
1540
+ });
1541
+ }
1542
+ function del(key, customStore = defaultGetStore()) {
1543
+ return customStore("readwrite", (store) => {
1544
+ store.delete(key);
1545
+ return promisifyRequest(store.transaction);
1546
+ });
1547
+ }
1548
+ const setupEventSource = async (config, subject, abort, consecutiveErrors = 0) => {
1549
+ let messages = [];
1550
+ let token = await config.options.accessTokenFactory();
1551
+ if (consecutiveErrors > 5) return;
1552
+ fetchEventSource(config.url, {
1553
+ headers: {
1554
+ Authorization: `Bearer ${token}`
1555
+ },
1556
+ openWhenHidden: true,
1557
+ signal: abort.signal,
1558
+ onmessage: async (eventSourceMessage) => {
1559
+ const data = eventSourceMessage.data;
1560
+ consecutiveErrors = 0;
1561
+ try {
1562
+ const parsed = JSON.parse(data);
1563
+ if (parsed.subject === "keep-alive") return;
1564
+ const eventReadState = await get("eventReadState") ?? {};
1565
+ messages = [
1566
+ {
1567
+ ...parsed,
1568
+ // @ts-expect-error nothing to see here
1569
+ eventSourceId: eventSourceMessage.id,
1570
+ read: eventReadState[parsed.id] ?? false
1571
+ },
1572
+ ...messages
1573
+ ];
1574
+ subject.next(messages);
1575
+ } catch (ex) {
1576
+ console.error("Failed to parse message: ", ex);
1577
+ }
1578
+ },
1579
+ onerror: (err) => {
1580
+ console.log("Closing event source due to error", err);
1581
+ throw err;
1582
+ }
1583
+ }).then(() => {
1584
+ config.options.accessTokenFactory().then((t) => token = t);
1585
+ if (config.options.reconnect) {
1586
+ setTimeout(
1587
+ () => setupEventSource(config, subject, abort, consecutiveErrors + 1),
1588
+ 5e3
1589
+ );
1590
+ }
1591
+ }).catch(() => {
1592
+ config.options.accessTokenFactory().then((t) => token = t);
1593
+ if (config.options.reconnect) {
1594
+ setTimeout(
1595
+ () => setupEventSource(config, subject, abort, consecutiveErrors + 1),
1596
+ 5e3
1597
+ );
1598
+ }
1599
+ });
1600
+ return {
1601
+ abort,
1602
+ subject
1603
+ };
1604
+ };
1605
+ class Connection {
1606
+ constructor() {
1607
+ this.abort = new AbortController();
1608
+ this.messageList = new BehaviorSubject([]);
1609
+ this.setReadState = async (eventId, read) => {
1610
+ const currentValues = await firstValueFrom(this.messageList);
1611
+ const newValues = [...currentValues];
1612
+ const currentEventIndex = newValues.findIndex((e) => e.id === eventId);
1613
+ if (currentEventIndex >= 0) {
1614
+ newValues[currentEventIndex] = {
1615
+ ...newValues[currentEventIndex],
1616
+ read
1617
+ };
1618
+ } else {
1619
+ newValues.push({
1620
+ ...newValues[currentEventIndex],
1621
+ read
1622
+ });
1623
+ }
1624
+ const eventReadState = await get("eventReadState") ?? {};
1625
+ const currentState = newValues.reduce(
1626
+ (a, b) => ({
1627
+ ...a,
1628
+ [b.id]: b.read
1629
+ }),
1630
+ {}
1631
+ );
1632
+ await set("eventReadState", {
1633
+ ...eventReadState,
1634
+ ...currentState
1635
+ });
1636
+ this.messageList.next(newValues);
1637
+ };
1638
+ this.setAllRead = async () => {
1639
+ const currentValues = await firstValueFrom(this.messageList);
1640
+ const newValues = [...currentValues].map((v) => ({ ...v, read: true }));
1641
+ const eventReadState = await get("eventReadState") ?? {};
1642
+ const currentState = newValues.reduce(
1643
+ (a, b) => ({
1644
+ ...a,
1645
+ [b.id]: b.read
1646
+ }),
1647
+ {}
1648
+ );
1649
+ await set("eventReadState", {
1650
+ ...eventReadState,
1651
+ ...currentState
1652
+ });
1653
+ this.messageList.next(newValues);
1654
+ };
1655
+ }
1656
+ get messageList$() {
1657
+ return this.messageList.asObservable();
1658
+ }
1659
+ }
1660
+ class SseModuleProvider {
1661
+ constructor(config) {
1662
+ __privateAdd(this, _config);
1663
+ __privateAdd(this, _connections, {});
1664
+ __privateSet(this, _config, config);
1665
+ }
1666
+ connect(name) {
1667
+ if (!(name in __privateGet(this, _connections))) {
1668
+ __privateGet(this, _connections)[name] = new Connection();
1669
+ const options = __privateGet(this, _config).endpoints[name];
1670
+ this.createConnection(name, options);
1671
+ }
1672
+ return __privateGet(this, _connections)[name];
1673
+ }
1674
+ createConnection(name, options) {
1675
+ const config = __privateGet(this, _connections)[name];
1676
+ setupEventSource(options, config.messageList, config.abort).catch(
1677
+ (err) => console.error(`Failed to set up connection for ${name}:`, err)
1678
+ );
1679
+ }
1680
+ }
1681
+ _config = new WeakMap();
1682
+ _connections = new WeakMap();
1683
+ class SseModuleConfigBuilder extends ModuleConfigBuilder {
1684
+ addEndpoint(name, config) {
1685
+ this._config.addEndpoint(name, config);
1686
+ }
1687
+ }
1688
+ class SseConfigurator {
1689
+ constructor() {
1690
+ __privateAdd(this, _builderCallbacks, []);
1691
+ __privateAdd(this, _endpoints, {});
1692
+ }
1693
+ /**
1694
+ * register SSE endpoint configuration.
1695
+ */
1696
+ addEndpoint(name, config) {
1697
+ __privateGet(this, _endpoints)[name] = config;
1698
+ }
1699
+ /**
1700
+ * add callback for building config on when configurator is creating config.
1701
+ * {@link SseConfigurator.createConfig}
1702
+ */
1703
+ onCreateConfig(cb) {
1704
+ __privateGet(this, _builderCallbacks).push(cb);
1705
+ }
1706
+ /**
1707
+ * normally executed in `init` phase of module, which creates configuration to the module provider.
1708
+ * cycles threw all registered configuration builders.
1709
+ * await all registered hub configurations.
1710
+ */
1711
+ async createConfig(init) {
1712
+ for (const cb of __privateGet(this, _builderCallbacks)) {
1713
+ const builder = new SseModuleConfigBuilder(
1714
+ init,
1715
+ this
1716
+ );
1717
+ await Promise.resolve(cb(builder));
1718
+ }
1719
+ return { endpoints: __privateGet(this, _endpoints) };
1720
+ }
1721
+ }
1722
+ _builderCallbacks = new WeakMap();
1723
+ _endpoints = new WeakMap();
1724
+ const moduleKey = "sse";
1725
+ const module = {
1726
+ name: moduleKey,
1727
+ configure: () => new SseConfigurator(),
1728
+ initialize: async (init) => {
1729
+ const config = await init.config.createConfig(init);
1730
+ return new SseModuleProvider(config);
1731
+ }
1732
+ };
1733
+ const configureFromFramework = async (args, builder) => {
1734
+ const authProvider = await builder.requireInstance("auth");
1735
+ const events = await builder.requireInstance("event");
1736
+ const serviceDiscovery = await builder.requireInstance("serviceDiscovery");
1737
+ events.dispatchEvent(
1738
+ "onSseActivated",
1739
+ new CustomEvent("onSseActivated", { detail: { name: args.name } })
1740
+ );
1741
+ const service = await serviceDiscovery.resolveService(args.name);
1742
+ builder.addEndpoint(args.name, {
1743
+ url: service.uri,
1744
+ options: {
1745
+ accessTokenFactory: async () => {
1746
+ const token = await authProvider.acquireAccessToken({
1747
+ scopes: service.defaultScopes
1748
+ });
1749
+ if (!token) {
1750
+ throw Error("failed to acquire access token");
1751
+ }
1752
+ return token;
1753
+ },
1754
+ reconnect: true
1755
+ }
1756
+ });
1757
+ };
1758
+ function enableSse(configurator, name, optionsOrCallback) {
1759
+ {
1760
+ configurator.addConfig({
1761
+ module,
1762
+ configure: (sseConfigurator) => {
1763
+ sseConfigurator.onCreateConfig(
1764
+ (builder) => configureFromFramework({ name }, builder)
1765
+ );
1766
+ }
1767
+ });
1768
+ }
1769
+ }
1770
+ function Cache(maxSize) {
1771
+ this._maxSize = maxSize;
1772
+ this.clear();
1773
+ }
1774
+ Cache.prototype.clear = function() {
1775
+ this._size = 0;
1776
+ this._values = /* @__PURE__ */ Object.create(null);
1777
+ };
1778
+ Cache.prototype.get = function(key) {
1779
+ return this._values[key];
1780
+ };
1781
+ Cache.prototype.set = function(key, value) {
1782
+ this._size >= this._maxSize && this.clear();
1783
+ if (!(key in this._values)) this._size++;
1784
+ return this._values[key] = value;
1785
+ };
1786
+ var SPLIT_REGEX = /[^.^\]^[]+|(?=\[\]|\.\.)/g, DIGIT_REGEX = /^\d+$/, LEAD_DIGIT_REGEX = /^\d/, SPEC_CHAR_REGEX = /[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g, CLEAN_QUOTES_REGEX = /^\s*(['"]?)(.*?)(\1)\s*$/, MAX_CACHE_SIZE = 512;
1787
+ var pathCache = new Cache(MAX_CACHE_SIZE), setCache = new Cache(MAX_CACHE_SIZE), getCache = new Cache(MAX_CACHE_SIZE);
1788
+ var propertyExpr = {
1789
+ Cache,
1790
+ split,
1791
+ normalizePath,
1792
+ setter: function(path) {
1793
+ var parts = normalizePath(path);
1794
+ return setCache.get(path) || setCache.set(path, function setter(obj, value) {
1795
+ var index = 0;
1796
+ var len = parts.length;
1797
+ var data = obj;
1798
+ while (index < len - 1) {
1799
+ var part = parts[index];
1800
+ if (part === "__proto__" || part === "constructor" || part === "prototype") {
1801
+ return obj;
1802
+ }
1803
+ data = data[parts[index++]];
1804
+ }
1805
+ data[parts[index]] = value;
1806
+ });
1807
+ },
1808
+ getter: function(path, safe) {
1809
+ var parts = normalizePath(path);
1810
+ return getCache.get(path) || getCache.set(path, function getter(data) {
1811
+ var index = 0, len = parts.length;
1812
+ while (index < len) {
1813
+ if (data != null || !safe) data = data[parts[index++]];
1814
+ else return;
1815
+ }
1816
+ return data;
1817
+ });
1818
+ },
1819
+ join: function(segments) {
1820
+ return segments.reduce(function(path, part) {
1821
+ return path + (isQuoted(part) || DIGIT_REGEX.test(part) ? "[" + part + "]" : (path ? "." : "") + part);
1822
+ }, "");
1823
+ },
1824
+ forEach: function(path, cb, thisArg) {
1825
+ forEach(Array.isArray(path) ? path : split(path), cb, thisArg);
1826
+ }
1827
+ };
1828
+ function normalizePath(path) {
1829
+ return pathCache.get(path) || pathCache.set(
1830
+ path,
1831
+ split(path).map(function(part) {
1832
+ return part.replace(CLEAN_QUOTES_REGEX, "$2");
1833
+ })
1834
+ );
1835
+ }
1836
+ function split(path) {
1837
+ return path.match(SPLIT_REGEX) || [""];
1838
+ }
1839
+ function forEach(parts, iter, thisArg) {
1840
+ var len = parts.length, part, idx, isArray, isBracket;
1841
+ for (idx = 0; idx < len; idx++) {
1842
+ part = parts[idx];
1843
+ if (part) {
1844
+ if (shouldBeQuoted(part)) {
1845
+ part = '"' + part + '"';
1846
+ }
1847
+ isBracket = isQuoted(part);
1848
+ isArray = !isBracket && /^\d+$/.test(part);
1849
+ iter.call(thisArg, part, isBracket, isArray, idx, parts);
1850
+ }
1851
+ }
1852
+ }
1853
+ function isQuoted(str) {
1854
+ return typeof str === "string" && str && ["'", '"'].indexOf(str.charAt(0)) !== -1;
1855
+ }
1856
+ function hasLeadingNumber(part) {
1857
+ return part.match(LEAD_DIGIT_REGEX) && !part.match(DIGIT_REGEX);
1858
+ }
1859
+ function hasSpecialChars(part) {
1860
+ return SPEC_CHAR_REGEX.test(part);
1861
+ }
1862
+ function shouldBeQuoted(part) {
1863
+ return !isQuoted(part) && (hasLeadingNumber(part) || hasSpecialChars(part));
1864
+ }
1865
+ const reWords = /[A-Z\xc0-\xd6\xd8-\xde]?[a-z\xdf-\xf6\xf8-\xff]+(?:['’](?:d|ll|m|re|s|t|ve))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde]|$)|(?:[A-Z\xc0-\xd6\xd8-\xde]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:D|LL|M|RE|S|T|VE))?(?=[\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000]|[A-Z\xc0-\xd6\xd8-\xde](?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])|$)|[A-Z\xc0-\xd6\xd8-\xde]?(?:[a-z\xdf-\xf6\xf8-\xff]|[^\ud800-\udfff\xac\xb1\xd7\xf7\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\xbf\u2000-\u206f \t\x0b\f\xa0\ufeff\n\r\u2028\u2029\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\d+\u2700-\u27bfa-z\xdf-\xf6\xf8-\xffA-Z\xc0-\xd6\xd8-\xde])+(?:['’](?:d|ll|m|re|s|t|ve))?|[A-Z\xc0-\xd6\xd8-\xde]+(?:['’](?:D|LL|M|RE|S|T|VE))?|\d*(?:1ST|2ND|3RD|(?![123])\dTH)(?=\b|[a-z_])|\d*(?:1st|2nd|3rd|(?![123])\dth)(?=\b|[A-Z_])|\d+|(?:[\u2700-\u27bf]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?(?:\u200d(?:[^\ud800-\udfff]|(?:\ud83c[\udde6-\uddff]){2}|[\ud800-\udbff][\udc00-\udfff])[\ufe0e\ufe0f]?(?:[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]|\ud83c[\udffb-\udfff])?)*/g;
1866
+ const words = (str) => str.match(reWords) || [];
1867
+ const upperFirst = (str) => str[0].toUpperCase() + str.slice(1);
1868
+ const join = (str, d) => words(str).join(d).toLowerCase();
1869
+ const camelCase = (str) => words(str).reduce(
1870
+ (acc, next) => `${acc}${!acc ? next.toLowerCase() : next[0].toUpperCase() + next.slice(1).toLowerCase()}`,
1871
+ ""
1872
+ );
1873
+ const pascalCase = (str) => upperFirst(camelCase(str));
1874
+ const snakeCase = (str) => join(str, "_");
1875
+ const kebabCase = (str) => join(str, "-");
1876
+ const sentenceCase = (str) => upperFirst(join(str, " "));
1877
+ const titleCase = (str) => words(str).map(upperFirst).join(" ");
1878
+ var tinyCase = {
1879
+ words,
1880
+ upperFirst,
1881
+ camelCase,
1882
+ pascalCase,
1883
+ snakeCase,
1884
+ kebabCase,
1885
+ sentenceCase,
1886
+ titleCase
1887
+ };
1888
+ var toposort$2 = { exports: {} };
1889
+ toposort$2.exports = function(edges) {
1890
+ return toposort(uniqueNodes(edges), edges);
1891
+ };
1892
+ toposort$2.exports.array = toposort;
1893
+ function toposort(nodes, edges) {
1894
+ var cursor = nodes.length, sorted = new Array(cursor), visited = {}, i = cursor, outgoingEdges = makeOutgoingEdges(edges), nodesHash = makeNodesHash(nodes);
1895
+ edges.forEach(function(edge) {
1896
+ if (!nodesHash.has(edge[0]) || !nodesHash.has(edge[1])) {
1897
+ throw new Error("Unknown node. There is an unknown node in the supplied edges.");
1898
+ }
1899
+ });
1900
+ while (i--) {
1901
+ if (!visited[i]) visit(nodes[i], i, /* @__PURE__ */ new Set());
1902
+ }
1903
+ return sorted;
1904
+ function visit(node, i2, predecessors) {
1905
+ if (predecessors.has(node)) {
1906
+ var nodeRep;
1907
+ try {
1908
+ nodeRep = ", node was:" + JSON.stringify(node);
1909
+ } catch (e) {
1910
+ nodeRep = "";
1911
+ }
1912
+ throw new Error("Cyclic dependency" + nodeRep);
1913
+ }
1914
+ if (!nodesHash.has(node)) {
1915
+ throw new Error("Found unknown node. Make sure to provided all involved nodes. Unknown node: " + JSON.stringify(node));
1916
+ }
1917
+ if (visited[i2]) return;
1918
+ visited[i2] = true;
1919
+ var outgoing = outgoingEdges.get(node) || /* @__PURE__ */ new Set();
1920
+ outgoing = Array.from(outgoing);
1921
+ if (i2 = outgoing.length) {
1922
+ predecessors.add(node);
1923
+ do {
1924
+ var child = outgoing[--i2];
1925
+ visit(child, nodesHash.get(child), predecessors);
1926
+ } while (i2);
1927
+ predecessors.delete(node);
1928
+ }
1929
+ sorted[--cursor] = node;
1930
+ }
1931
+ }
1932
+ function uniqueNodes(arr) {
1933
+ var res = /* @__PURE__ */ new Set();
1934
+ for (var i = 0, len = arr.length; i < len; i++) {
1935
+ var edge = arr[i];
1936
+ res.add(edge[0]);
1937
+ res.add(edge[1]);
1938
+ }
1939
+ return Array.from(res);
1940
+ }
1941
+ function makeOutgoingEdges(arr) {
1942
+ var edges = /* @__PURE__ */ new Map();
1943
+ for (var i = 0, len = arr.length; i < len; i++) {
1944
+ var edge = arr[i];
1945
+ if (!edges.has(edge[0])) edges.set(edge[0], /* @__PURE__ */ new Set());
1946
+ if (!edges.has(edge[1])) edges.set(edge[1], /* @__PURE__ */ new Set());
1947
+ edges.get(edge[0]).add(edge[1]);
1948
+ }
1949
+ return edges;
1950
+ }
1951
+ function makeNodesHash(arr) {
1952
+ var res = /* @__PURE__ */ new Map();
1953
+ for (var i = 0, len = arr.length; i < len; i++) {
1954
+ res.set(arr[i], i);
1955
+ }
1956
+ return res;
1957
+ }
1958
+ var toposortExports = toposort$2.exports;
1959
+ const toposort$1 = /* @__PURE__ */ getDefaultExportFromCjs(toposortExports);
1960
+ const toString = Object.prototype.toString;
1961
+ const errorToString = Error.prototype.toString;
1962
+ const regExpToString = RegExp.prototype.toString;
1963
+ const symbolToString = typeof Symbol !== "undefined" ? Symbol.prototype.toString : () => "";
1964
+ const SYMBOL_REGEXP = /^Symbol\((.*)\)(.*)$/;
1965
+ function printNumber(val) {
1966
+ if (val != +val) return "NaN";
1967
+ const isNegativeZero = val === 0 && 1 / val < 0;
1968
+ return isNegativeZero ? "-0" : "" + val;
1969
+ }
1970
+ function printSimpleValue(val, quoteStrings = false) {
1971
+ if (val == null || val === true || val === false) return "" + val;
1972
+ const typeOf = typeof val;
1973
+ if (typeOf === "number") return printNumber(val);
1974
+ if (typeOf === "string") return quoteStrings ? `"${val}"` : val;
1975
+ if (typeOf === "function") return "[Function " + (val.name || "anonymous") + "]";
1976
+ if (typeOf === "symbol") return symbolToString.call(val).replace(SYMBOL_REGEXP, "Symbol($1)");
1977
+ const tag = toString.call(val).slice(8, -1);
1978
+ if (tag === "Date") return isNaN(val.getTime()) ? "" + val : val.toISOString(val);
1979
+ if (tag === "Error" || val instanceof Error) return "[" + errorToString.call(val) + "]";
1980
+ if (tag === "RegExp") return regExpToString.call(val);
1981
+ return null;
1982
+ }
1983
+ function printValue(value, quoteStrings) {
1984
+ let result = printSimpleValue(value, quoteStrings);
1985
+ if (result !== null) return result;
1986
+ return JSON.stringify(value, function(key, value2) {
1987
+ let result2 = printSimpleValue(this[key], quoteStrings);
1988
+ if (result2 !== null) return result2;
1989
+ return value2;
1990
+ }, 2);
1991
+ }
1992
+ function toArray(value) {
1993
+ return value == null ? [] : [].concat(value);
1994
+ }
1995
+ let _Symbol$toStringTag;
1996
+ let strReg = /\$\{\s*(\w+)\s*\}/g;
1997
+ _Symbol$toStringTag = Symbol.toStringTag;
1998
+ class ValidationError extends Error {
1999
+ static formatError(message, params) {
2000
+ const path = params.label || params.path || "this";
2001
+ if (path !== params.path) params = Object.assign({}, params, {
2002
+ path
2003
+ });
2004
+ if (typeof message === "string") return message.replace(strReg, (_, key) => printValue(params[key]));
2005
+ if (typeof message === "function") return message(params);
2006
+ return message;
2007
+ }
2008
+ static isError(err) {
2009
+ return err && err.name === "ValidationError";
2010
+ }
2011
+ constructor(errorOrErrors, value, field, type, disableStack) {
2012
+ super();
2013
+ this.value = void 0;
2014
+ this.path = void 0;
2015
+ this.type = void 0;
2016
+ this.errors = void 0;
2017
+ this.params = void 0;
2018
+ this.inner = void 0;
2019
+ this[_Symbol$toStringTag] = "Error";
2020
+ this.name = "ValidationError";
2021
+ this.value = value;
2022
+ this.path = field;
2023
+ this.type = type;
2024
+ this.errors = [];
2025
+ this.inner = [];
2026
+ toArray(errorOrErrors).forEach((err) => {
2027
+ if (ValidationError.isError(err)) {
2028
+ this.errors.push(...err.errors);
2029
+ const innerErrors = err.inner.length ? err.inner : [err];
2030
+ this.inner.push(...innerErrors);
2031
+ } else {
2032
+ this.errors.push(err);
2033
+ }
2034
+ });
2035
+ this.message = this.errors.length > 1 ? `${this.errors.length} errors occurred` : this.errors[0];
2036
+ if (!disableStack && Error.captureStackTrace) Error.captureStackTrace(this, ValidationError);
2037
+ }
2038
+ }
2039
+ let mixed = {
2040
+ default: "${path} is invalid",
2041
+ required: "${path} is a required field",
2042
+ defined: "${path} must be defined",
2043
+ notNull: "${path} cannot be null",
2044
+ oneOf: "${path} must be one of the following values: ${values}",
2045
+ notOneOf: "${path} must not be one of the following values: ${values}",
2046
+ notType: ({
2047
+ path,
2048
+ type,
2049
+ value,
2050
+ originalValue
2051
+ }) => {
2052
+ const castMsg = originalValue != null && originalValue !== value ? ` (cast from the value \`${printValue(originalValue, true)}\`).` : ".";
2053
+ return type !== "mixed" ? `${path} must be a \`${type}\` type, but the final value was: \`${printValue(value, true)}\`` + castMsg : `${path} must match the configured type. The validated value was: \`${printValue(value, true)}\`` + castMsg;
2054
+ }
2055
+ };
2056
+ let string = {
2057
+ length: "${path} must be exactly ${length} characters",
2058
+ min: "${path} must be at least ${min} characters",
2059
+ max: "${path} must be at most ${max} characters",
2060
+ matches: '${path} must match the following: "${regex}"',
2061
+ email: "${path} must be a valid email",
2062
+ url: "${path} must be a valid URL",
2063
+ uuid: "${path} must be a valid UUID",
2064
+ trim: "${path} must be a trimmed string",
2065
+ lowercase: "${path} must be a lowercase string",
2066
+ uppercase: "${path} must be a upper case string"
2067
+ };
2068
+ let number = {
2069
+ min: "${path} must be greater than or equal to ${min}",
2070
+ max: "${path} must be less than or equal to ${max}",
2071
+ lessThan: "${path} must be less than ${less}",
2072
+ moreThan: "${path} must be greater than ${more}",
2073
+ positive: "${path} must be a positive number",
2074
+ negative: "${path} must be a negative number",
2075
+ integer: "${path} must be an integer"
2076
+ };
2077
+ let date = {
2078
+ min: "${path} field must be later than ${min}",
2079
+ max: "${path} field must be at earlier than ${max}"
2080
+ };
2081
+ let boolean = {
2082
+ isValue: "${path} field must be ${value}"
2083
+ };
2084
+ let object = {
2085
+ noUnknown: "${path} field has unspecified keys: ${unknown}"
2086
+ };
2087
+ let array = {
2088
+ min: "${path} field must have at least ${min} items",
2089
+ max: "${path} field must have less than or equal to ${max} items",
2090
+ length: "${path} must have ${length} items"
2091
+ };
2092
+ let tuple = {
2093
+ notType: (params) => {
2094
+ const {
2095
+ path,
2096
+ value,
2097
+ spec
2098
+ } = params;
2099
+ const typeLen = spec.types.length;
2100
+ if (Array.isArray(value)) {
2101
+ if (value.length < typeLen) return `${path} tuple value has too few items, expected a length of ${typeLen} but got ${value.length} for value: \`${printValue(value, true)}\``;
2102
+ if (value.length > typeLen) return `${path} tuple value has too many items, expected a length of ${typeLen} but got ${value.length} for value: \`${printValue(value, true)}\``;
2103
+ }
2104
+ return ValidationError.formatError(mixed.notType, params);
2105
+ }
2106
+ };
2107
+ Object.assign(/* @__PURE__ */ Object.create(null), {
2108
+ mixed,
2109
+ string,
2110
+ number,
2111
+ date,
2112
+ object,
2113
+ array,
2114
+ boolean,
2115
+ tuple
2116
+ });
2117
+ const isSchema = (obj) => obj && obj.__isYupSchema__;
2118
+ class Condition {
2119
+ static fromOptions(refs, config) {
2120
+ if (!config.then && !config.otherwise) throw new TypeError("either `then:` or `otherwise:` is required for `when()` conditions");
2121
+ let {
2122
+ is,
2123
+ then,
2124
+ otherwise
2125
+ } = config;
2126
+ let check = typeof is === "function" ? is : (...values) => values.every((value) => value === is);
2127
+ return new Condition(refs, (values, schema) => {
2128
+ var _branch;
2129
+ let branch = check(...values) ? then : otherwise;
2130
+ return (_branch = branch == null ? void 0 : branch(schema)) != null ? _branch : schema;
2131
+ });
2132
+ }
2133
+ constructor(refs, builder) {
2134
+ this.fn = void 0;
2135
+ this.refs = refs;
2136
+ this.refs = refs;
2137
+ this.fn = builder;
2138
+ }
2139
+ resolve(base, options) {
2140
+ let values = this.refs.map((ref) => (
2141
+ // TODO: ? operator here?
2142
+ ref.getValue(options == null ? void 0 : options.value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context)
2143
+ ));
2144
+ let schema = this.fn(values, base, options);
2145
+ if (schema === void 0 || // @ts-ignore this can be base
2146
+ schema === base) {
2147
+ return base;
2148
+ }
2149
+ if (!isSchema(schema)) throw new TypeError("conditions must return a schema object");
2150
+ return schema.resolve(options);
2151
+ }
2152
+ }
2153
+ const prefixes = {
2154
+ context: "$",
2155
+ value: "."
2156
+ };
2157
+ class Reference {
2158
+ constructor(key, options = {}) {
2159
+ this.key = void 0;
2160
+ this.isContext = void 0;
2161
+ this.isValue = void 0;
2162
+ this.isSibling = void 0;
2163
+ this.path = void 0;
2164
+ this.getter = void 0;
2165
+ this.map = void 0;
2166
+ if (typeof key !== "string") throw new TypeError("ref must be a string, got: " + key);
2167
+ this.key = key.trim();
2168
+ if (key === "") throw new TypeError("ref must be a non-empty string");
2169
+ this.isContext = this.key[0] === prefixes.context;
2170
+ this.isValue = this.key[0] === prefixes.value;
2171
+ this.isSibling = !this.isContext && !this.isValue;
2172
+ let prefix = this.isContext ? prefixes.context : this.isValue ? prefixes.value : "";
2173
+ this.path = this.key.slice(prefix.length);
2174
+ this.getter = this.path && propertyExpr.getter(this.path, true);
2175
+ this.map = options.map;
2176
+ }
2177
+ getValue(value, parent, context) {
2178
+ let result = this.isContext ? context : this.isValue ? value : parent;
2179
+ if (this.getter) result = this.getter(result || {});
2180
+ if (this.map) result = this.map(result);
2181
+ return result;
2182
+ }
2183
+ /**
2184
+ *
2185
+ * @param {*} value
2186
+ * @param {Object} options
2187
+ * @param {Object=} options.context
2188
+ * @param {Object=} options.parent
2189
+ */
2190
+ cast(value, options) {
2191
+ return this.getValue(value, options == null ? void 0 : options.parent, options == null ? void 0 : options.context);
2192
+ }
2193
+ resolve() {
2194
+ return this;
2195
+ }
2196
+ describe() {
2197
+ return {
2198
+ type: "ref",
2199
+ key: this.key
2200
+ };
2201
+ }
2202
+ toString() {
2203
+ return `Ref(${this.key})`;
2204
+ }
2205
+ static isRef(value) {
2206
+ return value && value.__isYupRef;
2207
+ }
2208
+ }
2209
+ Reference.prototype.__isYupRef = true;
2210
+ const isAbsent = (value) => value == null;
2211
+ function createValidation(config) {
2212
+ function validate({
2213
+ value,
2214
+ path = "",
2215
+ options,
2216
+ originalValue,
2217
+ schema
2218
+ }, panic, next) {
2219
+ const {
2220
+ name,
2221
+ test,
2222
+ params,
2223
+ message,
2224
+ skipAbsent
2225
+ } = config;
2226
+ let {
2227
+ parent,
2228
+ context,
2229
+ abortEarly = schema.spec.abortEarly,
2230
+ disableStackTrace = schema.spec.disableStackTrace
2231
+ } = options;
2232
+ function resolve(item) {
2233
+ return Reference.isRef(item) ? item.getValue(value, parent, context) : item;
2234
+ }
2235
+ function createError(overrides = {}) {
2236
+ var _overrides$disableSta;
2237
+ const nextParams = Object.assign({
2238
+ value,
2239
+ originalValue,
2240
+ label: schema.spec.label,
2241
+ path: overrides.path || path,
2242
+ spec: schema.spec
2243
+ }, params, overrides.params);
2244
+ for (const key of Object.keys(nextParams)) nextParams[key] = resolve(nextParams[key]);
2245
+ const error = new ValidationError(ValidationError.formatError(overrides.message || message, nextParams), value, nextParams.path, overrides.type || name, (_overrides$disableSta = overrides.disableStackTrace) != null ? _overrides$disableSta : disableStackTrace);
2246
+ error.params = nextParams;
2247
+ return error;
2248
+ }
2249
+ const invalid = abortEarly ? panic : next;
2250
+ let ctx = {
2251
+ path,
2252
+ parent,
2253
+ type: name,
2254
+ from: options.from,
2255
+ createError,
2256
+ resolve,
2257
+ options,
2258
+ originalValue,
2259
+ schema
2260
+ };
2261
+ const handleResult = (validOrError) => {
2262
+ if (ValidationError.isError(validOrError)) invalid(validOrError);
2263
+ else if (!validOrError) invalid(createError());
2264
+ else next(null);
2265
+ };
2266
+ const handleError2 = (err) => {
2267
+ if (ValidationError.isError(err)) invalid(err);
2268
+ else panic(err);
2269
+ };
2270
+ const shouldSkip = skipAbsent && isAbsent(value);
2271
+ if (shouldSkip) {
2272
+ return handleResult(true);
2273
+ }
2274
+ let result;
2275
+ try {
2276
+ var _result;
2277
+ result = test.call(ctx, value, ctx);
2278
+ if (typeof ((_result = result) == null ? void 0 : _result.then) === "function") {
2279
+ if (options.sync) {
2280
+ throw new Error(`Validation test of type: "${ctx.type}" returned a Promise during a synchronous validate. This test will finish after the validate call has returned`);
2281
+ }
2282
+ return Promise.resolve(result).then(handleResult, handleError2);
2283
+ }
2284
+ } catch (err) {
2285
+ handleError2(err);
2286
+ return;
2287
+ }
2288
+ handleResult(result);
2289
+ }
2290
+ validate.OPTIONS = config;
2291
+ return validate;
2292
+ }
2293
+ function getIn(schema, path, value, context = value) {
2294
+ let parent, lastPart, lastPartDebug;
2295
+ if (!path) return {
2296
+ parent,
2297
+ parentPath: path,
2298
+ schema
2299
+ };
2300
+ propertyExpr.forEach(path, (_part, isBracket, isArray) => {
2301
+ let part = isBracket ? _part.slice(1, _part.length - 1) : _part;
2302
+ schema = schema.resolve({
2303
+ context,
2304
+ parent,
2305
+ value
2306
+ });
2307
+ let isTuple = schema.type === "tuple";
2308
+ let idx = isArray ? parseInt(part, 10) : 0;
2309
+ if (schema.innerType || isTuple) {
2310
+ if (isTuple && !isArray) throw new Error(`Yup.reach cannot implicitly index into a tuple type. the path part "${lastPartDebug}" must contain an index to the tuple element, e.g. "${lastPartDebug}[0]"`);
2311
+ if (value && idx >= value.length) {
2312
+ throw new Error(`Yup.reach cannot resolve an array item at index: ${_part}, in the path: ${path}. because there is no value at that index. `);
2313
+ }
2314
+ parent = value;
2315
+ value = value && value[idx];
2316
+ schema = isTuple ? schema.spec.types[idx] : schema.innerType;
2317
+ }
2318
+ if (!isArray) {
2319
+ if (!schema.fields || !schema.fields[part]) throw new Error(`The schema does not contain the path: ${path}. (failed at: ${lastPartDebug} which is a type: "${schema.type}")`);
2320
+ parent = value;
2321
+ value = value && value[part];
2322
+ schema = schema.fields[part];
2323
+ }
2324
+ lastPart = part;
2325
+ lastPartDebug = isBracket ? "[" + _part + "]" : "." + _part;
2326
+ });
2327
+ return {
2328
+ schema,
2329
+ parent,
2330
+ parentPath: lastPart
2331
+ };
2332
+ }
2333
+ class ReferenceSet extends Set {
2334
+ describe() {
2335
+ const description = [];
2336
+ for (const item of this.values()) {
2337
+ description.push(Reference.isRef(item) ? item.describe() : item);
2338
+ }
2339
+ return description;
2340
+ }
2341
+ resolveAll(resolve) {
2342
+ let result = [];
2343
+ for (const item of this.values()) {
2344
+ result.push(resolve(item));
2345
+ }
2346
+ return result;
2347
+ }
2348
+ clone() {
2349
+ return new ReferenceSet(this.values());
2350
+ }
2351
+ merge(newItems, removeItems) {
2352
+ const next = this.clone();
2353
+ newItems.forEach((value) => next.add(value));
2354
+ removeItems.forEach((value) => next.delete(value));
2355
+ return next;
2356
+ }
2357
+ }
2358
+ function clone(src, seen = /* @__PURE__ */ new Map()) {
2359
+ if (isSchema(src) || !src || typeof src !== "object") return src;
2360
+ if (seen.has(src)) return seen.get(src);
2361
+ let copy;
2362
+ if (src instanceof Date) {
2363
+ copy = new Date(src.getTime());
2364
+ seen.set(src, copy);
2365
+ } else if (src instanceof RegExp) {
2366
+ copy = new RegExp(src);
2367
+ seen.set(src, copy);
2368
+ } else if (Array.isArray(src)) {
2369
+ copy = new Array(src.length);
2370
+ seen.set(src, copy);
2371
+ for (let i = 0; i < src.length; i++) copy[i] = clone(src[i], seen);
2372
+ } else if (src instanceof Map) {
2373
+ copy = /* @__PURE__ */ new Map();
2374
+ seen.set(src, copy);
2375
+ for (const [k, v] of src.entries()) copy.set(k, clone(v, seen));
2376
+ } else if (src instanceof Set) {
2377
+ copy = /* @__PURE__ */ new Set();
2378
+ seen.set(src, copy);
2379
+ for (const v of src) copy.add(clone(v, seen));
2380
+ } else if (src instanceof Object) {
2381
+ copy = {};
2382
+ seen.set(src, copy);
2383
+ for (const [k, v] of Object.entries(src)) copy[k] = clone(v, seen);
2384
+ } else {
2385
+ throw Error(`Unable to clone ${src}`);
2386
+ }
2387
+ return copy;
2388
+ }
2389
+ class Schema {
2390
+ constructor(options) {
2391
+ this.type = void 0;
2392
+ this.deps = [];
2393
+ this.tests = void 0;
2394
+ this.transforms = void 0;
2395
+ this.conditions = [];
2396
+ this._mutate = void 0;
2397
+ this.internalTests = {};
2398
+ this._whitelist = new ReferenceSet();
2399
+ this._blacklist = new ReferenceSet();
2400
+ this.exclusiveTests = /* @__PURE__ */ Object.create(null);
2401
+ this._typeCheck = void 0;
2402
+ this.spec = void 0;
2403
+ this.tests = [];
2404
+ this.transforms = [];
2405
+ this.withMutation(() => {
2406
+ this.typeError(mixed.notType);
2407
+ });
2408
+ this.type = options.type;
2409
+ this._typeCheck = options.check;
2410
+ this.spec = Object.assign({
2411
+ strip: false,
2412
+ strict: false,
2413
+ abortEarly: true,
2414
+ recursive: true,
2415
+ disableStackTrace: false,
2416
+ nullable: false,
2417
+ optional: true,
2418
+ coerce: true
2419
+ }, options == null ? void 0 : options.spec);
2420
+ this.withMutation((s) => {
2421
+ s.nonNullable();
2422
+ });
2423
+ }
2424
+ // TODO: remove
2425
+ get _type() {
2426
+ return this.type;
2427
+ }
2428
+ clone(spec) {
2429
+ if (this._mutate) {
2430
+ if (spec) Object.assign(this.spec, spec);
2431
+ return this;
2432
+ }
2433
+ const next = Object.create(Object.getPrototypeOf(this));
2434
+ next.type = this.type;
2435
+ next._typeCheck = this._typeCheck;
2436
+ next._whitelist = this._whitelist.clone();
2437
+ next._blacklist = this._blacklist.clone();
2438
+ next.internalTests = Object.assign({}, this.internalTests);
2439
+ next.exclusiveTests = Object.assign({}, this.exclusiveTests);
2440
+ next.deps = [...this.deps];
2441
+ next.conditions = [...this.conditions];
2442
+ next.tests = [...this.tests];
2443
+ next.transforms = [...this.transforms];
2444
+ next.spec = clone(Object.assign({}, this.spec, spec));
2445
+ return next;
2446
+ }
2447
+ label(label) {
2448
+ let next = this.clone();
2449
+ next.spec.label = label;
2450
+ return next;
2451
+ }
2452
+ meta(...args) {
2453
+ if (args.length === 0) return this.spec.meta;
2454
+ let next = this.clone();
2455
+ next.spec.meta = Object.assign(next.spec.meta || {}, args[0]);
2456
+ return next;
2457
+ }
2458
+ withMutation(fn) {
2459
+ let before = this._mutate;
2460
+ this._mutate = true;
2461
+ let result = fn(this);
2462
+ this._mutate = before;
2463
+ return result;
2464
+ }
2465
+ concat(schema) {
2466
+ if (!schema || schema === this) return this;
2467
+ if (schema.type !== this.type && this.type !== "mixed") throw new TypeError(`You cannot \`concat()\` schema's of different types: ${this.type} and ${schema.type}`);
2468
+ let base = this;
2469
+ let combined = schema.clone();
2470
+ const mergedSpec = Object.assign({}, base.spec, combined.spec);
2471
+ combined.spec = mergedSpec;
2472
+ combined.internalTests = Object.assign({}, base.internalTests, combined.internalTests);
2473
+ combined._whitelist = base._whitelist.merge(schema._whitelist, schema._blacklist);
2474
+ combined._blacklist = base._blacklist.merge(schema._blacklist, schema._whitelist);
2475
+ combined.tests = base.tests;
2476
+ combined.exclusiveTests = base.exclusiveTests;
2477
+ combined.withMutation((next) => {
2478
+ schema.tests.forEach((fn) => {
2479
+ next.test(fn.OPTIONS);
2480
+ });
2481
+ });
2482
+ combined.transforms = [...base.transforms, ...combined.transforms];
2483
+ return combined;
2484
+ }
2485
+ isType(v) {
2486
+ if (v == null) {
2487
+ if (this.spec.nullable && v === null) return true;
2488
+ if (this.spec.optional && v === void 0) return true;
2489
+ return false;
2490
+ }
2491
+ return this._typeCheck(v);
2492
+ }
2493
+ resolve(options) {
2494
+ let schema = this;
2495
+ if (schema.conditions.length) {
2496
+ let conditions = schema.conditions;
2497
+ schema = schema.clone();
2498
+ schema.conditions = [];
2499
+ schema = conditions.reduce((prevSchema, condition) => condition.resolve(prevSchema, options), schema);
2500
+ schema = schema.resolve(options);
2501
+ }
2502
+ return schema;
2503
+ }
2504
+ resolveOptions(options) {
2505
+ var _options$strict, _options$abortEarly, _options$recursive, _options$disableStack;
2506
+ return Object.assign({}, options, {
2507
+ from: options.from || [],
2508
+ strict: (_options$strict = options.strict) != null ? _options$strict : this.spec.strict,
2509
+ abortEarly: (_options$abortEarly = options.abortEarly) != null ? _options$abortEarly : this.spec.abortEarly,
2510
+ recursive: (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive,
2511
+ disableStackTrace: (_options$disableStack = options.disableStackTrace) != null ? _options$disableStack : this.spec.disableStackTrace
2512
+ });
2513
+ }
2514
+ /**
2515
+ * Run the configured transform pipeline over an input value.
2516
+ */
2517
+ cast(value, options = {}) {
2518
+ let resolvedSchema = this.resolve(Object.assign({
2519
+ value
2520
+ }, options));
2521
+ let allowOptionality = options.assert === "ignore-optionality";
2522
+ let result = resolvedSchema._cast(value, options);
2523
+ if (options.assert !== false && !resolvedSchema.isType(result)) {
2524
+ if (allowOptionality && isAbsent(result)) {
2525
+ return result;
2526
+ }
2527
+ let formattedValue = printValue(value);
2528
+ let formattedResult = printValue(result);
2529
+ throw new TypeError(`The value of ${options.path || "field"} could not be cast to a value that satisfies the schema type: "${resolvedSchema.type}".
2530
+
2531
+ attempted value: ${formattedValue}
2532
+ ` + (formattedResult !== formattedValue ? `result of cast: ${formattedResult}` : ""));
2533
+ }
2534
+ return result;
2535
+ }
2536
+ _cast(rawValue, options) {
2537
+ let value = rawValue === void 0 ? rawValue : this.transforms.reduce((prevValue, fn) => fn.call(this, prevValue, rawValue, this), rawValue);
2538
+ if (value === void 0) {
2539
+ value = this.getDefault(options);
2540
+ }
2541
+ return value;
2542
+ }
2543
+ _validate(_value, options = {}, panic, next) {
2544
+ let {
2545
+ path,
2546
+ originalValue = _value,
2547
+ strict = this.spec.strict
2548
+ } = options;
2549
+ let value = _value;
2550
+ if (!strict) {
2551
+ value = this._cast(value, Object.assign({
2552
+ assert: false
2553
+ }, options));
2554
+ }
2555
+ let initialTests = [];
2556
+ for (let test of Object.values(this.internalTests)) {
2557
+ if (test) initialTests.push(test);
2558
+ }
2559
+ this.runTests({
2560
+ path,
2561
+ value,
2562
+ originalValue,
2563
+ options,
2564
+ tests: initialTests
2565
+ }, panic, (initialErrors) => {
2566
+ if (initialErrors.length) {
2567
+ return next(initialErrors, value);
2568
+ }
2569
+ this.runTests({
2570
+ path,
2571
+ value,
2572
+ originalValue,
2573
+ options,
2574
+ tests: this.tests
2575
+ }, panic, next);
2576
+ });
2577
+ }
2578
+ /**
2579
+ * Executes a set of validations, either schema, produced Tests or a nested
2580
+ * schema validate result.
2581
+ */
2582
+ runTests(runOptions, panic, next) {
2583
+ let fired = false;
2584
+ let {
2585
+ tests,
2586
+ value,
2587
+ originalValue,
2588
+ path,
2589
+ options
2590
+ } = runOptions;
2591
+ let panicOnce = (arg) => {
2592
+ if (fired) return;
2593
+ fired = true;
2594
+ panic(arg, value);
2595
+ };
2596
+ let nextOnce = (arg) => {
2597
+ if (fired) return;
2598
+ fired = true;
2599
+ next(arg, value);
2600
+ };
2601
+ let count = tests.length;
2602
+ let nestedErrors = [];
2603
+ if (!count) return nextOnce([]);
2604
+ let args = {
2605
+ value,
2606
+ originalValue,
2607
+ path,
2608
+ options,
2609
+ schema: this
2610
+ };
2611
+ for (let i = 0; i < tests.length; i++) {
2612
+ const test = tests[i];
2613
+ test(args, panicOnce, function finishTestRun(err) {
2614
+ if (err) {
2615
+ Array.isArray(err) ? nestedErrors.push(...err) : nestedErrors.push(err);
2616
+ }
2617
+ if (--count <= 0) {
2618
+ nextOnce(nestedErrors);
2619
+ }
2620
+ });
2621
+ }
2622
+ }
2623
+ asNestedTest({
2624
+ key,
2625
+ index,
2626
+ parent,
2627
+ parentPath,
2628
+ originalParent,
2629
+ options
2630
+ }) {
2631
+ const k = key != null ? key : index;
2632
+ if (k == null) {
2633
+ throw TypeError("Must include `key` or `index` for nested validations");
2634
+ }
2635
+ const isIndex = typeof k === "number";
2636
+ let value = parent[k];
2637
+ const testOptions = Object.assign({}, options, {
2638
+ // Nested validations fields are always strict:
2639
+ // 1. parent isn't strict so the casting will also have cast inner values
2640
+ // 2. parent is strict in which case the nested values weren't cast either
2641
+ strict: true,
2642
+ parent,
2643
+ value,
2644
+ originalValue: originalParent[k],
2645
+ // FIXME: tests depend on `index` being passed around deeply,
2646
+ // we should not let the options.key/index bleed through
2647
+ key: void 0,
2648
+ // index: undefined,
2649
+ [isIndex ? "index" : "key"]: k,
2650
+ path: isIndex || k.includes(".") ? `${parentPath || ""}[${value ? k : `"${k}"`}]` : (parentPath ? `${parentPath}.` : "") + key
2651
+ });
2652
+ return (_, panic, next) => this.resolve(testOptions)._validate(value, testOptions, panic, next);
2653
+ }
2654
+ validate(value, options) {
2655
+ var _options$disableStack2;
2656
+ let schema = this.resolve(Object.assign({}, options, {
2657
+ value
2658
+ }));
2659
+ let disableStackTrace = (_options$disableStack2 = options == null ? void 0 : options.disableStackTrace) != null ? _options$disableStack2 : schema.spec.disableStackTrace;
2660
+ return new Promise((resolve, reject) => schema._validate(value, options, (error, parsed) => {
2661
+ if (ValidationError.isError(error)) error.value = parsed;
2662
+ reject(error);
2663
+ }, (errors, validated) => {
2664
+ if (errors.length) reject(new ValidationError(errors, validated, void 0, void 0, disableStackTrace));
2665
+ else resolve(validated);
2666
+ }));
2667
+ }
2668
+ validateSync(value, options) {
2669
+ var _options$disableStack3;
2670
+ let schema = this.resolve(Object.assign({}, options, {
2671
+ value
2672
+ }));
2673
+ let result;
2674
+ let disableStackTrace = (_options$disableStack3 = options == null ? void 0 : options.disableStackTrace) != null ? _options$disableStack3 : schema.spec.disableStackTrace;
2675
+ schema._validate(value, Object.assign({}, options, {
2676
+ sync: true
2677
+ }), (error, parsed) => {
2678
+ if (ValidationError.isError(error)) error.value = parsed;
2679
+ throw error;
2680
+ }, (errors, validated) => {
2681
+ if (errors.length) throw new ValidationError(errors, value, void 0, void 0, disableStackTrace);
2682
+ result = validated;
2683
+ });
2684
+ return result;
2685
+ }
2686
+ isValid(value, options) {
2687
+ return this.validate(value, options).then(() => true, (err) => {
2688
+ if (ValidationError.isError(err)) return false;
2689
+ throw err;
2690
+ });
2691
+ }
2692
+ isValidSync(value, options) {
2693
+ try {
2694
+ this.validateSync(value, options);
2695
+ return true;
2696
+ } catch (err) {
2697
+ if (ValidationError.isError(err)) return false;
2698
+ throw err;
2699
+ }
2700
+ }
2701
+ _getDefault(options) {
2702
+ let defaultValue = this.spec.default;
2703
+ if (defaultValue == null) {
2704
+ return defaultValue;
2705
+ }
2706
+ return typeof defaultValue === "function" ? defaultValue.call(this, options) : clone(defaultValue);
2707
+ }
2708
+ getDefault(options) {
2709
+ let schema = this.resolve(options || {});
2710
+ return schema._getDefault(options);
2711
+ }
2712
+ default(def) {
2713
+ if (arguments.length === 0) {
2714
+ return this._getDefault();
2715
+ }
2716
+ let next = this.clone({
2717
+ default: def
2718
+ });
2719
+ return next;
2720
+ }
2721
+ strict(isStrict = true) {
2722
+ return this.clone({
2723
+ strict: isStrict
2724
+ });
2725
+ }
2726
+ nullability(nullable, message) {
2727
+ const next = this.clone({
2728
+ nullable
2729
+ });
2730
+ next.internalTests.nullable = createValidation({
2731
+ message,
2732
+ name: "nullable",
2733
+ test(value) {
2734
+ return value === null ? this.schema.spec.nullable : true;
2735
+ }
2736
+ });
2737
+ return next;
2738
+ }
2739
+ optionality(optional, message) {
2740
+ const next = this.clone({
2741
+ optional
2742
+ });
2743
+ next.internalTests.optionality = createValidation({
2744
+ message,
2745
+ name: "optionality",
2746
+ test(value) {
2747
+ return value === void 0 ? this.schema.spec.optional : true;
2748
+ }
2749
+ });
2750
+ return next;
2751
+ }
2752
+ optional() {
2753
+ return this.optionality(true);
2754
+ }
2755
+ defined(message = mixed.defined) {
2756
+ return this.optionality(false, message);
2757
+ }
2758
+ nullable() {
2759
+ return this.nullability(true);
2760
+ }
2761
+ nonNullable(message = mixed.notNull) {
2762
+ return this.nullability(false, message);
2763
+ }
2764
+ required(message = mixed.required) {
2765
+ return this.clone().withMutation((next) => next.nonNullable(message).defined(message));
2766
+ }
2767
+ notRequired() {
2768
+ return this.clone().withMutation((next) => next.nullable().optional());
2769
+ }
2770
+ transform(fn) {
2771
+ let next = this.clone();
2772
+ next.transforms.push(fn);
2773
+ return next;
2774
+ }
2775
+ /**
2776
+ * Adds a test function to the schema's queue of tests.
2777
+ * tests can be exclusive or non-exclusive.
2778
+ *
2779
+ * - exclusive tests, will replace any existing tests of the same name.
2780
+ * - non-exclusive: can be stacked
2781
+ *
2782
+ * If a non-exclusive test is added to a schema with an exclusive test of the same name
2783
+ * the exclusive test is removed and further tests of the same name will be stacked.
2784
+ *
2785
+ * If an exclusive test is added to a schema with non-exclusive tests of the same name
2786
+ * the previous tests are removed and further tests of the same name will replace each other.
2787
+ */
2788
+ test(...args) {
2789
+ let opts;
2790
+ if (args.length === 1) {
2791
+ if (typeof args[0] === "function") {
2792
+ opts = {
2793
+ test: args[0]
2794
+ };
2795
+ } else {
2796
+ opts = args[0];
2797
+ }
2798
+ } else if (args.length === 2) {
2799
+ opts = {
2800
+ name: args[0],
2801
+ test: args[1]
2802
+ };
2803
+ } else {
2804
+ opts = {
2805
+ name: args[0],
2806
+ message: args[1],
2807
+ test: args[2]
2808
+ };
2809
+ }
2810
+ if (opts.message === void 0) opts.message = mixed.default;
2811
+ if (typeof opts.test !== "function") throw new TypeError("`test` is a required parameters");
2812
+ let next = this.clone();
2813
+ let validate = createValidation(opts);
2814
+ let isExclusive = opts.exclusive || opts.name && next.exclusiveTests[opts.name] === true;
2815
+ if (opts.exclusive) {
2816
+ if (!opts.name) throw new TypeError("Exclusive tests must provide a unique `name` identifying the test");
2817
+ }
2818
+ if (opts.name) next.exclusiveTests[opts.name] = !!opts.exclusive;
2819
+ next.tests = next.tests.filter((fn) => {
2820
+ if (fn.OPTIONS.name === opts.name) {
2821
+ if (isExclusive) return false;
2822
+ if (fn.OPTIONS.test === validate.OPTIONS.test) return false;
2823
+ }
2824
+ return true;
2825
+ });
2826
+ next.tests.push(validate);
2827
+ return next;
2828
+ }
2829
+ when(keys, options) {
2830
+ if (!Array.isArray(keys) && typeof keys !== "string") {
2831
+ options = keys;
2832
+ keys = ".";
2833
+ }
2834
+ let next = this.clone();
2835
+ let deps = toArray(keys).map((key) => new Reference(key));
2836
+ deps.forEach((dep) => {
2837
+ if (dep.isSibling) next.deps.push(dep.key);
2838
+ });
2839
+ next.conditions.push(typeof options === "function" ? new Condition(deps, options) : Condition.fromOptions(deps, options));
2840
+ return next;
2841
+ }
2842
+ typeError(message) {
2843
+ let next = this.clone();
2844
+ next.internalTests.typeError = createValidation({
2845
+ message,
2846
+ name: "typeError",
2847
+ skipAbsent: true,
2848
+ test(value) {
2849
+ if (!this.schema._typeCheck(value)) return this.createError({
2850
+ params: {
2851
+ type: this.schema.type
2852
+ }
2853
+ });
2854
+ return true;
2855
+ }
2856
+ });
2857
+ return next;
2858
+ }
2859
+ oneOf(enums, message = mixed.oneOf) {
2860
+ let next = this.clone();
2861
+ enums.forEach((val) => {
2862
+ next._whitelist.add(val);
2863
+ next._blacklist.delete(val);
2864
+ });
2865
+ next.internalTests.whiteList = createValidation({
2866
+ message,
2867
+ name: "oneOf",
2868
+ skipAbsent: true,
2869
+ test(value) {
2870
+ let valids = this.schema._whitelist;
2871
+ let resolved = valids.resolveAll(this.resolve);
2872
+ return resolved.includes(value) ? true : this.createError({
2873
+ params: {
2874
+ values: Array.from(valids).join(", "),
2875
+ resolved
2876
+ }
2877
+ });
2878
+ }
2879
+ });
2880
+ return next;
2881
+ }
2882
+ notOneOf(enums, message = mixed.notOneOf) {
2883
+ let next = this.clone();
2884
+ enums.forEach((val) => {
2885
+ next._blacklist.add(val);
2886
+ next._whitelist.delete(val);
2887
+ });
2888
+ next.internalTests.blacklist = createValidation({
2889
+ message,
2890
+ name: "notOneOf",
2891
+ test(value) {
2892
+ let invalids = this.schema._blacklist;
2893
+ let resolved = invalids.resolveAll(this.resolve);
2894
+ if (resolved.includes(value)) return this.createError({
2895
+ params: {
2896
+ values: Array.from(invalids).join(", "),
2897
+ resolved
2898
+ }
2899
+ });
2900
+ return true;
2901
+ }
2902
+ });
2903
+ return next;
2904
+ }
2905
+ strip(strip = true) {
2906
+ let next = this.clone();
2907
+ next.spec.strip = strip;
2908
+ return next;
2909
+ }
2910
+ /**
2911
+ * Return a serialized description of the schema including validations, flags, types etc.
2912
+ *
2913
+ * @param options Provide any needed context for resolving runtime schema alterations (lazy, when conditions, etc).
2914
+ */
2915
+ describe(options) {
2916
+ const next = (options ? this.resolve(options) : this).clone();
2917
+ const {
2918
+ label,
2919
+ meta,
2920
+ optional,
2921
+ nullable
2922
+ } = next.spec;
2923
+ const description = {
2924
+ meta,
2925
+ label,
2926
+ optional,
2927
+ nullable,
2928
+ default: next.getDefault(options),
2929
+ type: next.type,
2930
+ oneOf: next._whitelist.describe(),
2931
+ notOneOf: next._blacklist.describe(),
2932
+ tests: next.tests.map((fn) => ({
2933
+ name: fn.OPTIONS.name,
2934
+ params: fn.OPTIONS.params
2935
+ })).filter((n, idx, list) => list.findIndex((c) => c.name === n.name) === idx)
2936
+ };
2937
+ return description;
2938
+ }
2939
+ }
2940
+ Schema.prototype.__isYupSchema__ = true;
2941
+ for (const method of ["validate", "validateSync"]) Schema.prototype[`${method}At`] = function(path, value, options = {}) {
2942
+ const {
2943
+ parent,
2944
+ parentPath,
2945
+ schema
2946
+ } = getIn(this, path, value, options.context);
2947
+ return schema[method](parent && parent[parentPath], Object.assign({}, options, {
2948
+ parent,
2949
+ path
2950
+ }));
2951
+ };
2952
+ for (const alias of ["equals", "is"]) Schema.prototype[alias] = Schema.prototype.oneOf;
2953
+ for (const alias of ["not", "nope"]) Schema.prototype[alias] = Schema.prototype.notOneOf;
2954
+ function create$7() {
2955
+ return new BooleanSchema();
2956
+ }
2957
+ class BooleanSchema extends Schema {
2958
+ constructor() {
2959
+ super({
2960
+ type: "boolean",
2961
+ check(v) {
2962
+ if (v instanceof Boolean) v = v.valueOf();
2963
+ return typeof v === "boolean";
2964
+ }
2965
+ });
2966
+ this.withMutation(() => {
2967
+ this.transform((value, _raw, ctx) => {
2968
+ if (ctx.spec.coerce && !ctx.isType(value)) {
2969
+ if (/^(true|1)$/i.test(String(value))) return true;
2970
+ if (/^(false|0)$/i.test(String(value))) return false;
2971
+ }
2972
+ return value;
2973
+ });
2974
+ });
2975
+ }
2976
+ isTrue(message = boolean.isValue) {
2977
+ return this.test({
2978
+ message,
2979
+ name: "is-value",
2980
+ exclusive: true,
2981
+ params: {
2982
+ value: "true"
2983
+ },
2984
+ test(value) {
2985
+ return isAbsent(value) || value === true;
2986
+ }
2987
+ });
2988
+ }
2989
+ isFalse(message = boolean.isValue) {
2990
+ return this.test({
2991
+ message,
2992
+ name: "is-value",
2993
+ exclusive: true,
2994
+ params: {
2995
+ value: "false"
2996
+ },
2997
+ test(value) {
2998
+ return isAbsent(value) || value === false;
2999
+ }
3000
+ });
3001
+ }
3002
+ default(def) {
3003
+ return super.default(def);
3004
+ }
3005
+ defined(msg) {
3006
+ return super.defined(msg);
3007
+ }
3008
+ optional() {
3009
+ return super.optional();
3010
+ }
3011
+ required(msg) {
3012
+ return super.required(msg);
3013
+ }
3014
+ notRequired() {
3015
+ return super.notRequired();
3016
+ }
3017
+ nullable() {
3018
+ return super.nullable();
3019
+ }
3020
+ nonNullable(msg) {
3021
+ return super.nonNullable(msg);
3022
+ }
3023
+ strip(v) {
3024
+ return super.strip(v);
3025
+ }
3026
+ }
3027
+ create$7.prototype = BooleanSchema.prototype;
3028
+ let rEmail = (
3029
+ // eslint-disable-next-line
3030
+ /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/
3031
+ );
3032
+ let rUrl = (
3033
+ // eslint-disable-next-line
3034
+ /^((https?|ftp):)?\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i
3035
+ );
3036
+ let rUUID = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
3037
+ let isTrimmed = (value) => isAbsent(value) || value === value.trim();
3038
+ let objStringTag = {}.toString();
3039
+ function create$6() {
3040
+ return new StringSchema();
3041
+ }
3042
+ class StringSchema extends Schema {
3043
+ constructor() {
3044
+ super({
3045
+ type: "string",
3046
+ check(value) {
3047
+ if (value instanceof String) value = value.valueOf();
3048
+ return typeof value === "string";
3049
+ }
3050
+ });
3051
+ this.withMutation(() => {
3052
+ this.transform((value, _raw, ctx) => {
3053
+ if (!ctx.spec.coerce || ctx.isType(value)) return value;
3054
+ if (Array.isArray(value)) return value;
3055
+ const strValue = value != null && value.toString ? value.toString() : value;
3056
+ if (strValue === objStringTag) return value;
3057
+ return strValue;
3058
+ });
3059
+ });
3060
+ }
3061
+ required(message) {
3062
+ return super.required(message).withMutation((schema) => schema.test({
3063
+ message: message || mixed.required,
3064
+ name: "required",
3065
+ skipAbsent: true,
3066
+ test: (value) => !!value.length
3067
+ }));
3068
+ }
3069
+ notRequired() {
3070
+ return super.notRequired().withMutation((schema) => {
3071
+ schema.tests = schema.tests.filter((t) => t.OPTIONS.name !== "required");
3072
+ return schema;
3073
+ });
3074
+ }
3075
+ length(length, message = string.length) {
3076
+ return this.test({
3077
+ message,
3078
+ name: "length",
3079
+ exclusive: true,
3080
+ params: {
3081
+ length
3082
+ },
3083
+ skipAbsent: true,
3084
+ test(value) {
3085
+ return value.length === this.resolve(length);
3086
+ }
3087
+ });
3088
+ }
3089
+ min(min, message = string.min) {
3090
+ return this.test({
3091
+ message,
3092
+ name: "min",
3093
+ exclusive: true,
3094
+ params: {
3095
+ min
3096
+ },
3097
+ skipAbsent: true,
3098
+ test(value) {
3099
+ return value.length >= this.resolve(min);
3100
+ }
3101
+ });
3102
+ }
3103
+ max(max, message = string.max) {
3104
+ return this.test({
3105
+ name: "max",
3106
+ exclusive: true,
3107
+ message,
3108
+ params: {
3109
+ max
3110
+ },
3111
+ skipAbsent: true,
3112
+ test(value) {
3113
+ return value.length <= this.resolve(max);
3114
+ }
3115
+ });
3116
+ }
3117
+ matches(regex, options) {
3118
+ let excludeEmptyString = false;
3119
+ let message;
3120
+ let name;
3121
+ if (options) {
3122
+ if (typeof options === "object") {
3123
+ ({
3124
+ excludeEmptyString = false,
3125
+ message,
3126
+ name
3127
+ } = options);
3128
+ } else {
3129
+ message = options;
3130
+ }
3131
+ }
3132
+ return this.test({
3133
+ name: name || "matches",
3134
+ message: message || string.matches,
3135
+ params: {
3136
+ regex
3137
+ },
3138
+ skipAbsent: true,
3139
+ test: (value) => value === "" && excludeEmptyString || value.search(regex) !== -1
3140
+ });
3141
+ }
3142
+ email(message = string.email) {
3143
+ return this.matches(rEmail, {
3144
+ name: "email",
3145
+ message,
3146
+ excludeEmptyString: true
3147
+ });
3148
+ }
3149
+ url(message = string.url) {
3150
+ return this.matches(rUrl, {
3151
+ name: "url",
3152
+ message,
3153
+ excludeEmptyString: true
3154
+ });
3155
+ }
3156
+ uuid(message = string.uuid) {
3157
+ return this.matches(rUUID, {
3158
+ name: "uuid",
3159
+ message,
3160
+ excludeEmptyString: false
3161
+ });
3162
+ }
3163
+ //-- transforms --
3164
+ ensure() {
3165
+ return this.default("").transform((val) => val === null ? "" : val);
3166
+ }
3167
+ trim(message = string.trim) {
3168
+ return this.transform((val) => val != null ? val.trim() : val).test({
3169
+ message,
3170
+ name: "trim",
3171
+ test: isTrimmed
3172
+ });
3173
+ }
3174
+ lowercase(message = string.lowercase) {
3175
+ return this.transform((value) => !isAbsent(value) ? value.toLowerCase() : value).test({
3176
+ message,
3177
+ name: "string_case",
3178
+ exclusive: true,
3179
+ skipAbsent: true,
3180
+ test: (value) => isAbsent(value) || value === value.toLowerCase()
3181
+ });
3182
+ }
3183
+ uppercase(message = string.uppercase) {
3184
+ return this.transform((value) => !isAbsent(value) ? value.toUpperCase() : value).test({
3185
+ message,
3186
+ name: "string_case",
3187
+ exclusive: true,
3188
+ skipAbsent: true,
3189
+ test: (value) => isAbsent(value) || value === value.toUpperCase()
3190
+ });
3191
+ }
3192
+ }
3193
+ create$6.prototype = StringSchema.prototype;
3194
+ const isoReg = /^(\d{4}|[+-]\d{6})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:[ T]?(\d{2}):?(\d{2})(?::?(\d{2})(?:[,.](\d{1,}))?)?(?:(Z)|([+-])(\d{2})(?::?(\d{2}))?)?)?$/;
3195
+ function toNumber(str, defaultValue = 0) {
3196
+ return Number(str) || defaultValue;
3197
+ }
3198
+ function parseIsoDate(date2) {
3199
+ const regexResult = isoReg.exec(date2);
3200
+ if (!regexResult) return Date.parse ? Date.parse(date2) : Number.NaN;
3201
+ const struct = {
3202
+ year: toNumber(regexResult[1]),
3203
+ month: toNumber(regexResult[2], 1) - 1,
3204
+ day: toNumber(regexResult[3], 1),
3205
+ hour: toNumber(regexResult[4]),
3206
+ minute: toNumber(regexResult[5]),
3207
+ second: toNumber(regexResult[6]),
3208
+ millisecond: regexResult[7] ? (
3209
+ // allow arbitrary sub-second precision beyond milliseconds
3210
+ toNumber(regexResult[7].substring(0, 3))
3211
+ ) : 0,
3212
+ z: regexResult[8] || void 0,
3213
+ plusMinus: regexResult[9] || void 0,
3214
+ hourOffset: toNumber(regexResult[10]),
3215
+ minuteOffset: toNumber(regexResult[11])
3216
+ };
3217
+ if (struct.z === void 0 && struct.plusMinus === void 0) {
3218
+ return new Date(struct.year, struct.month, struct.day, struct.hour, struct.minute, struct.second, struct.millisecond).valueOf();
3219
+ }
3220
+ let totalMinutesOffset = 0;
3221
+ if (struct.z !== "Z" && struct.plusMinus !== void 0) {
3222
+ totalMinutesOffset = struct.hourOffset * 60 + struct.minuteOffset;
3223
+ if (struct.plusMinus === "+") totalMinutesOffset = 0 - totalMinutesOffset;
3224
+ }
3225
+ return Date.UTC(struct.year, struct.month, struct.day, struct.hour, struct.minute + totalMinutesOffset, struct.second, struct.millisecond);
3226
+ }
3227
+ let invalidDate = /* @__PURE__ */ new Date("");
3228
+ let isDate = (obj) => Object.prototype.toString.call(obj) === "[object Date]";
3229
+ class DateSchema extends Schema {
3230
+ constructor() {
3231
+ super({
3232
+ type: "date",
3233
+ check(v) {
3234
+ return isDate(v) && !isNaN(v.getTime());
3235
+ }
3236
+ });
3237
+ this.withMutation(() => {
3238
+ this.transform((value, _raw, ctx) => {
3239
+ if (!ctx.spec.coerce || ctx.isType(value) || value === null) return value;
3240
+ value = parseIsoDate(value);
3241
+ return !isNaN(value) ? new Date(value) : DateSchema.INVALID_DATE;
3242
+ });
3243
+ });
3244
+ }
3245
+ prepareParam(ref, name) {
3246
+ let param;
3247
+ if (!Reference.isRef(ref)) {
3248
+ let cast = this.cast(ref);
3249
+ if (!this._typeCheck(cast)) throw new TypeError(`\`${name}\` must be a Date or a value that can be \`cast()\` to a Date`);
3250
+ param = cast;
3251
+ } else {
3252
+ param = ref;
3253
+ }
3254
+ return param;
3255
+ }
3256
+ min(min, message = date.min) {
3257
+ let limit = this.prepareParam(min, "min");
3258
+ return this.test({
3259
+ message,
3260
+ name: "min",
3261
+ exclusive: true,
3262
+ params: {
3263
+ min
3264
+ },
3265
+ skipAbsent: true,
3266
+ test(value) {
3267
+ return value >= this.resolve(limit);
3268
+ }
3269
+ });
3270
+ }
3271
+ max(max, message = date.max) {
3272
+ let limit = this.prepareParam(max, "max");
3273
+ return this.test({
3274
+ message,
3275
+ name: "max",
3276
+ exclusive: true,
3277
+ params: {
3278
+ max
3279
+ },
3280
+ skipAbsent: true,
3281
+ test(value) {
3282
+ return value <= this.resolve(limit);
3283
+ }
3284
+ });
3285
+ }
3286
+ }
3287
+ DateSchema.INVALID_DATE = invalidDate;
3288
+ DateSchema.prototype;
3289
+ function sortFields(fields, excludedEdges = []) {
3290
+ let edges = [];
3291
+ let nodes = /* @__PURE__ */ new Set();
3292
+ let excludes = new Set(excludedEdges.map(([a, b]) => `${a}-${b}`));
3293
+ function addNode(depPath, key) {
3294
+ let node = propertyExpr.split(depPath)[0];
3295
+ nodes.add(node);
3296
+ if (!excludes.has(`${key}-${node}`)) edges.push([key, node]);
3297
+ }
3298
+ for (const key of Object.keys(fields)) {
3299
+ let value = fields[key];
3300
+ nodes.add(key);
3301
+ if (Reference.isRef(value) && value.isSibling) addNode(value.path, key);
3302
+ else if (isSchema(value) && "deps" in value) value.deps.forEach((path) => addNode(path, key));
3303
+ }
3304
+ return toposort$1.array(Array.from(nodes), edges).reverse();
3305
+ }
3306
+ function findIndex(arr, err) {
3307
+ let idx = Infinity;
3308
+ arr.some((key, ii) => {
3309
+ var _err$path;
3310
+ if ((_err$path = err.path) != null && _err$path.includes(key)) {
3311
+ idx = ii;
3312
+ return true;
3313
+ }
3314
+ });
3315
+ return idx;
3316
+ }
3317
+ function sortByKeyOrder(keys) {
3318
+ return (a, b) => {
3319
+ return findIndex(keys, a) - findIndex(keys, b);
3320
+ };
3321
+ }
3322
+ const parseJson = (value, _, ctx) => {
3323
+ if (typeof value !== "string") {
3324
+ return value;
3325
+ }
3326
+ let parsed = value;
3327
+ try {
3328
+ parsed = JSON.parse(value);
3329
+ } catch (err) {
3330
+ }
3331
+ return ctx.isType(parsed) ? parsed : value;
3332
+ };
3333
+ function deepPartial(schema) {
3334
+ if ("fields" in schema) {
3335
+ const partial = {};
3336
+ for (const [key, fieldSchema2] of Object.entries(schema.fields)) {
3337
+ partial[key] = deepPartial(fieldSchema2);
3338
+ }
3339
+ return schema.setFields(partial);
3340
+ }
3341
+ if (schema.type === "array") {
3342
+ const nextArray = schema.optional();
3343
+ if (nextArray.innerType) nextArray.innerType = deepPartial(nextArray.innerType);
3344
+ return nextArray;
3345
+ }
3346
+ if (schema.type === "tuple") {
3347
+ return schema.optional().clone({
3348
+ types: schema.spec.types.map(deepPartial)
3349
+ });
3350
+ }
3351
+ if ("optional" in schema) {
3352
+ return schema.optional();
3353
+ }
3354
+ return schema;
3355
+ }
3356
+ const deepHas = (obj, p) => {
3357
+ const path = [...propertyExpr.normalizePath(p)];
3358
+ if (path.length === 1) return path[0] in obj;
3359
+ let last = path.pop();
3360
+ let parent = propertyExpr.getter(propertyExpr.join(path), true)(obj);
3361
+ return !!(parent && last in parent);
3362
+ };
3363
+ let isObject = (obj) => Object.prototype.toString.call(obj) === "[object Object]";
3364
+ function unknown(ctx, value) {
3365
+ let known = Object.keys(ctx.fields);
3366
+ return Object.keys(value).filter((key) => known.indexOf(key) === -1);
3367
+ }
3368
+ const defaultSort = sortByKeyOrder([]);
3369
+ function create$3(spec) {
3370
+ return new ObjectSchema(spec);
3371
+ }
3372
+ class ObjectSchema extends Schema {
3373
+ constructor(spec) {
3374
+ super({
3375
+ type: "object",
3376
+ check(value) {
3377
+ return isObject(value) || typeof value === "function";
3378
+ }
3379
+ });
3380
+ this.fields = /* @__PURE__ */ Object.create(null);
3381
+ this._sortErrors = defaultSort;
3382
+ this._nodes = [];
3383
+ this._excludedEdges = [];
3384
+ this.withMutation(() => {
3385
+ if (spec) {
3386
+ this.shape(spec);
3387
+ }
3388
+ });
3389
+ }
3390
+ _cast(_value, options = {}) {
3391
+ var _options$stripUnknown;
3392
+ let value = super._cast(_value, options);
3393
+ if (value === void 0) return this.getDefault(options);
3394
+ if (!this._typeCheck(value)) return value;
3395
+ let fields = this.fields;
3396
+ let strip = (_options$stripUnknown = options.stripUnknown) != null ? _options$stripUnknown : this.spec.noUnknown;
3397
+ let props = [].concat(this._nodes, Object.keys(value).filter((v) => !this._nodes.includes(v)));
3398
+ let intermediateValue = {};
3399
+ let innerOptions = Object.assign({}, options, {
3400
+ parent: intermediateValue,
3401
+ __validating: options.__validating || false
3402
+ });
3403
+ let isChanged = false;
3404
+ for (const prop of props) {
3405
+ let field = fields[prop];
3406
+ let exists = prop in value;
3407
+ if (field) {
3408
+ let fieldValue;
3409
+ let inputValue = value[prop];
3410
+ innerOptions.path = (options.path ? `${options.path}.` : "") + prop;
3411
+ field = field.resolve({
3412
+ value: inputValue,
3413
+ context: options.context,
3414
+ parent: intermediateValue
3415
+ });
3416
+ let fieldSpec = field instanceof Schema ? field.spec : void 0;
3417
+ let strict = fieldSpec == null ? void 0 : fieldSpec.strict;
3418
+ if (fieldSpec != null && fieldSpec.strip) {
3419
+ isChanged = isChanged || prop in value;
3420
+ continue;
3421
+ }
3422
+ fieldValue = !options.__validating || !strict ? (
3423
+ // TODO: use _cast, this is double resolving
3424
+ field.cast(value[prop], innerOptions)
3425
+ ) : value[prop];
3426
+ if (fieldValue !== void 0) {
3427
+ intermediateValue[prop] = fieldValue;
3428
+ }
3429
+ } else if (exists && !strip) {
3430
+ intermediateValue[prop] = value[prop];
3431
+ }
3432
+ if (exists !== prop in intermediateValue || intermediateValue[prop] !== value[prop]) {
3433
+ isChanged = true;
3434
+ }
3435
+ }
3436
+ return isChanged ? intermediateValue : value;
3437
+ }
3438
+ _validate(_value, options = {}, panic, next) {
3439
+ let {
3440
+ from: from2 = [],
3441
+ originalValue = _value,
3442
+ recursive = this.spec.recursive
3443
+ } = options;
3444
+ options.from = [{
3445
+ schema: this,
3446
+ value: originalValue
3447
+ }, ...from2];
3448
+ options.__validating = true;
3449
+ options.originalValue = originalValue;
3450
+ super._validate(_value, options, panic, (objectErrors, value) => {
3451
+ if (!recursive || !isObject(value)) {
3452
+ next(objectErrors, value);
3453
+ return;
3454
+ }
3455
+ originalValue = originalValue || value;
3456
+ let tests = [];
3457
+ for (let key of this._nodes) {
3458
+ let field = this.fields[key];
3459
+ if (!field || Reference.isRef(field)) {
3460
+ continue;
3461
+ }
3462
+ tests.push(field.asNestedTest({
3463
+ options,
3464
+ key,
3465
+ parent: value,
3466
+ parentPath: options.path,
3467
+ originalParent: originalValue
3468
+ }));
3469
+ }
3470
+ this.runTests({
3471
+ tests,
3472
+ value,
3473
+ originalValue,
3474
+ options
3475
+ }, panic, (fieldErrors) => {
3476
+ next(fieldErrors.sort(this._sortErrors).concat(objectErrors), value);
3477
+ });
3478
+ });
3479
+ }
3480
+ clone(spec) {
3481
+ const next = super.clone(spec);
3482
+ next.fields = Object.assign({}, this.fields);
3483
+ next._nodes = this._nodes;
3484
+ next._excludedEdges = this._excludedEdges;
3485
+ next._sortErrors = this._sortErrors;
3486
+ return next;
3487
+ }
3488
+ concat(schema) {
3489
+ let next = super.concat(schema);
3490
+ let nextFields = next.fields;
3491
+ for (let [field, schemaOrRef] of Object.entries(this.fields)) {
3492
+ const target = nextFields[field];
3493
+ nextFields[field] = target === void 0 ? schemaOrRef : target;
3494
+ }
3495
+ return next.withMutation((s) => (
3496
+ // XXX: excludes here is wrong
3497
+ s.setFields(nextFields, [...this._excludedEdges, ...schema._excludedEdges])
3498
+ ));
3499
+ }
3500
+ _getDefault(options) {
3501
+ if ("default" in this.spec) {
3502
+ return super._getDefault(options);
3503
+ }
3504
+ if (!this._nodes.length) {
3505
+ return void 0;
3506
+ }
3507
+ let dft = {};
3508
+ this._nodes.forEach((key) => {
3509
+ var _innerOptions;
3510
+ const field = this.fields[key];
3511
+ let innerOptions = options;
3512
+ if ((_innerOptions = innerOptions) != null && _innerOptions.value) {
3513
+ innerOptions = Object.assign({}, innerOptions, {
3514
+ parent: innerOptions.value,
3515
+ value: innerOptions.value[key]
3516
+ });
3517
+ }
3518
+ dft[key] = field && "getDefault" in field ? field.getDefault(innerOptions) : void 0;
3519
+ });
3520
+ return dft;
3521
+ }
3522
+ setFields(shape, excludedEdges) {
3523
+ let next = this.clone();
3524
+ next.fields = shape;
3525
+ next._nodes = sortFields(shape, excludedEdges);
3526
+ next._sortErrors = sortByKeyOrder(Object.keys(shape));
3527
+ if (excludedEdges) next._excludedEdges = excludedEdges;
3528
+ return next;
3529
+ }
3530
+ shape(additions, excludes = []) {
3531
+ return this.clone().withMutation((next) => {
3532
+ let edges = next._excludedEdges;
3533
+ if (excludes.length) {
3534
+ if (!Array.isArray(excludes[0])) excludes = [excludes];
3535
+ edges = [...next._excludedEdges, ...excludes];
3536
+ }
3537
+ return next.setFields(Object.assign(next.fields, additions), edges);
3538
+ });
3539
+ }
3540
+ partial() {
3541
+ const partial = {};
3542
+ for (const [key, schema] of Object.entries(this.fields)) {
3543
+ partial[key] = "optional" in schema && schema.optional instanceof Function ? schema.optional() : schema;
3544
+ }
3545
+ return this.setFields(partial);
3546
+ }
3547
+ deepPartial() {
3548
+ const next = deepPartial(this);
3549
+ return next;
3550
+ }
3551
+ pick(keys) {
3552
+ const picked = {};
3553
+ for (const key of keys) {
3554
+ if (this.fields[key]) picked[key] = this.fields[key];
3555
+ }
3556
+ return this.setFields(picked, this._excludedEdges.filter(([a, b]) => keys.includes(a) && keys.includes(b)));
3557
+ }
3558
+ omit(keys) {
3559
+ const remaining = [];
3560
+ for (const key of Object.keys(this.fields)) {
3561
+ if (keys.includes(key)) continue;
3562
+ remaining.push(key);
3563
+ }
3564
+ return this.pick(remaining);
3565
+ }
3566
+ from(from2, to, alias) {
3567
+ let fromGetter = propertyExpr.getter(from2, true);
3568
+ return this.transform((obj) => {
3569
+ if (!obj) return obj;
3570
+ let newObj = obj;
3571
+ if (deepHas(obj, from2)) {
3572
+ newObj = Object.assign({}, obj);
3573
+ if (!alias) delete newObj[from2];
3574
+ newObj[to] = fromGetter(obj);
3575
+ }
3576
+ return newObj;
3577
+ });
3578
+ }
3579
+ /** Parse an input JSON string to an object */
3580
+ json() {
3581
+ return this.transform(parseJson);
3582
+ }
3583
+ noUnknown(noAllow = true, message = object.noUnknown) {
3584
+ if (typeof noAllow !== "boolean") {
3585
+ message = noAllow;
3586
+ noAllow = true;
3587
+ }
3588
+ let next = this.test({
3589
+ name: "noUnknown",
3590
+ exclusive: true,
3591
+ message,
3592
+ test(value) {
3593
+ if (value == null) return true;
3594
+ const unknownKeys = unknown(this.schema, value);
3595
+ return !noAllow || unknownKeys.length === 0 || this.createError({
3596
+ params: {
3597
+ unknown: unknownKeys.join(", ")
3598
+ }
3599
+ });
3600
+ }
3601
+ });
3602
+ next.spec.noUnknown = noAllow;
3603
+ return next;
3604
+ }
3605
+ unknown(allow = true, message = object.noUnknown) {
3606
+ return this.noUnknown(!allow, message);
3607
+ }
3608
+ transformKeys(fn) {
3609
+ return this.transform((obj) => {
3610
+ if (!obj) return obj;
3611
+ const result = {};
3612
+ for (const key of Object.keys(obj)) result[fn(key)] = obj[key];
3613
+ return result;
3614
+ });
3615
+ }
3616
+ camelCase() {
3617
+ return this.transformKeys(tinyCase.camelCase);
3618
+ }
3619
+ snakeCase() {
3620
+ return this.transformKeys(tinyCase.snakeCase);
3621
+ }
3622
+ constantCase() {
3623
+ return this.transformKeys((key) => tinyCase.snakeCase(key).toUpperCase());
3624
+ }
3625
+ describe(options) {
3626
+ const next = (options ? this.resolve(options) : this).clone();
3627
+ const base = super.describe(options);
3628
+ base.fields = {};
3629
+ for (const [key, value] of Object.entries(next.fields)) {
3630
+ var _innerOptions2;
3631
+ let innerOptions = options;
3632
+ if ((_innerOptions2 = innerOptions) != null && _innerOptions2.value) {
3633
+ innerOptions = Object.assign({}, innerOptions, {
3634
+ parent: innerOptions.value,
3635
+ value: innerOptions.value[key]
3636
+ });
3637
+ }
3638
+ base.fields[key] = value.describe(innerOptions);
3639
+ }
3640
+ return base;
3641
+ }
3642
+ }
3643
+ create$3.prototype = ObjectSchema.prototype;
3644
+ function create$2(type) {
3645
+ return new ArraySchema(type);
3646
+ }
3647
+ class ArraySchema extends Schema {
3648
+ constructor(type) {
3649
+ super({
3650
+ type: "array",
3651
+ spec: {
3652
+ types: type
3653
+ },
3654
+ check(v) {
3655
+ return Array.isArray(v);
3656
+ }
3657
+ });
3658
+ this.innerType = void 0;
3659
+ this.innerType = type;
3660
+ }
3661
+ _cast(_value, _opts) {
3662
+ const value = super._cast(_value, _opts);
3663
+ if (!this._typeCheck(value) || !this.innerType) {
3664
+ return value;
3665
+ }
3666
+ let isChanged = false;
3667
+ const castArray = value.map((v, idx) => {
3668
+ const castElement = this.innerType.cast(v, Object.assign({}, _opts, {
3669
+ path: `${_opts.path || ""}[${idx}]`
3670
+ }));
3671
+ if (castElement !== v) {
3672
+ isChanged = true;
3673
+ }
3674
+ return castElement;
3675
+ });
3676
+ return isChanged ? castArray : value;
3677
+ }
3678
+ _validate(_value, options = {}, panic, next) {
3679
+ var _options$recursive;
3680
+ let innerType = this.innerType;
3681
+ let recursive = (_options$recursive = options.recursive) != null ? _options$recursive : this.spec.recursive;
3682
+ options.originalValue != null ? options.originalValue : _value;
3683
+ super._validate(_value, options, panic, (arrayErrors, value) => {
3684
+ var _options$originalValu2;
3685
+ if (!recursive || !innerType || !this._typeCheck(value)) {
3686
+ next(arrayErrors, value);
3687
+ return;
1332
3688
  }
1333
- ) }),
1334
- /* @__PURE__ */ jsx(
1335
- StyledMenu,
1336
- {
1337
- onClose: () => menuState.setA11yOpen(false),
1338
- anchorEl: a11yRef.current,
1339
- open: menuState.a11yOpen,
1340
- children: /* @__PURE__ */ jsxs(Menu.Section, { title: "Density", children: [
1341
- /* @__PURE__ */ jsx(
1342
- Menu.Item,
1343
- {
1344
- active: density === "comfortable",
1345
- onClick: () => toggleDensity("comfortable"),
1346
- children: "Comfortable"
1347
- }
1348
- ),
1349
- /* @__PURE__ */ jsx(
1350
- Menu.Item,
1351
- {
1352
- active: density === "compact",
1353
- onClick: () => toggleDensity("compact"),
1354
- children: "Compact"
1355
- }
1356
- )
1357
- ] })
3689
+ let tests = new Array(value.length);
3690
+ for (let index = 0; index < value.length; index++) {
3691
+ var _options$originalValu;
3692
+ tests[index] = innerType.asNestedTest({
3693
+ options,
3694
+ index,
3695
+ parent: value,
3696
+ parentPath: options.path,
3697
+ originalParent: (_options$originalValu = options.originalValue) != null ? _options$originalValu : _value
3698
+ });
1358
3699
  }
1359
- ),
1360
- /* @__PURE__ */ jsx(
1361
- AppLoader,
1362
- {
1363
- app: applications.find((app) => app.key === "quick-links") ?? null,
1364
- kind: "widget"
3700
+ this.runTests({
3701
+ value,
3702
+ tests,
3703
+ originalValue: (_options$originalValu2 = options.originalValue) != null ? _options$originalValu2 : _value,
3704
+ options
3705
+ }, panic, (innerTypeErrors) => next(innerTypeErrors.concat(arrayErrors), value));
3706
+ });
3707
+ }
3708
+ clone(spec) {
3709
+ const next = super.clone(spec);
3710
+ next.innerType = this.innerType;
3711
+ return next;
3712
+ }
3713
+ /** Parse an input JSON string to an object */
3714
+ json() {
3715
+ return this.transform(parseJson);
3716
+ }
3717
+ concat(schema) {
3718
+ let next = super.concat(schema);
3719
+ next.innerType = this.innerType;
3720
+ if (schema.innerType)
3721
+ next.innerType = next.innerType ? (
3722
+ // @ts-expect-error Lazy doesn't have concat and will break
3723
+ next.innerType.concat(schema.innerType)
3724
+ ) : schema.innerType;
3725
+ return next;
3726
+ }
3727
+ of(schema) {
3728
+ let next = this.clone();
3729
+ if (!isSchema(schema)) throw new TypeError("`array.of()` sub-schema must be a valid yup schema not: " + printValue(schema));
3730
+ next.innerType = schema;
3731
+ next.spec = Object.assign({}, next.spec, {
3732
+ types: schema
3733
+ });
3734
+ return next;
3735
+ }
3736
+ length(length, message = array.length) {
3737
+ return this.test({
3738
+ message,
3739
+ name: "length",
3740
+ exclusive: true,
3741
+ params: {
3742
+ length
3743
+ },
3744
+ skipAbsent: true,
3745
+ test(value) {
3746
+ return value.length === this.resolve(length);
1365
3747
  }
1366
- ),
1367
- /* @__PURE__ */ jsx(Tooltip, { title: "View user settings", children: /* @__PURE__ */ jsx(
1368
- Button,
1369
- {
1370
- onClick: () => menuState.setUserMenuOpen(true),
1371
- ref: userRef,
1372
- variant: "ghost_icon",
1373
- children: /* @__PURE__ */ jsx(Icon, { data: account_circle })
3748
+ });
3749
+ }
3750
+ min(min, message) {
3751
+ message = message || array.min;
3752
+ return this.test({
3753
+ message,
3754
+ name: "min",
3755
+ exclusive: true,
3756
+ params: {
3757
+ min
3758
+ },
3759
+ skipAbsent: true,
3760
+ // FIXME(ts): Array<typeof T>
3761
+ test(value) {
3762
+ return value.length >= this.resolve(min);
1374
3763
  }
1375
- ) }),
1376
- /* @__PURE__ */ jsxs(
1377
- StyledMenu,
1378
- {
1379
- onClose: () => menuState.setUserMenuOpen(false),
1380
- anchorEl: userRef.current,
1381
- open: menuState.userMenuOpen,
1382
- children: [
1383
- /* @__PURE__ */ jsxs(Menu.Section, { title: "Profile", children: [
1384
- /* @__PURE__ */ jsx(Menu.Item, { children: user.name }),
1385
- /* @__PURE__ */ jsx(
1386
- Menu.Item,
1387
- {
1388
- onClick: () => auth.defaultClient.logoutRedirect({
1389
- postLogoutRedirectUri: window.location.origin
1390
- }),
1391
- children: "Sign out"
1392
- }
1393
- )
1394
- ] }),
1395
- /* @__PURE__ */ jsx(Menu.Section, { title: "Roles", children: roles.map((r) => /* @__PURE__ */ jsx(Menu.Item, { children: r }, r)) })
1396
- ]
3764
+ });
3765
+ }
3766
+ max(max, message) {
3767
+ message = message || array.max;
3768
+ return this.test({
3769
+ message,
3770
+ name: "max",
3771
+ exclusive: true,
3772
+ params: {
3773
+ max
3774
+ },
3775
+ skipAbsent: true,
3776
+ test(value) {
3777
+ return value.length <= this.resolve(max);
1397
3778
  }
1398
- ),
1399
- /* @__PURE__ */ jsx(Tooltip, { title: "Release notes", children: /* @__PURE__ */ jsx(
1400
- Button,
1401
- {
1402
- variant: "ghost_icon",
1403
- as: "a",
1404
- href: `https://statoilsrm.sharepoint.com/sites/Roma/Lists/Releases/AllItems.aspx`,
1405
- target: "_blank",
1406
- children: /* @__PURE__ */ jsx(Icon, { data: help_outline })
3779
+ });
3780
+ }
3781
+ ensure() {
3782
+ return this.default(() => []).transform((val, original) => {
3783
+ if (this._typeCheck(val)) return val;
3784
+ return original == null ? [] : [].concat(original);
3785
+ });
3786
+ }
3787
+ compact(rejector) {
3788
+ let reject = !rejector ? (v) => !!v : (v, i, a) => !rejector(v, i, a);
3789
+ return this.transform((values) => values != null ? values.filter(reject) : values);
3790
+ }
3791
+ describe(options) {
3792
+ const next = (options ? this.resolve(options) : this).clone();
3793
+ const base = super.describe(options);
3794
+ if (next.innerType) {
3795
+ var _innerOptions;
3796
+ let innerOptions = options;
3797
+ if ((_innerOptions = innerOptions) != null && _innerOptions.value) {
3798
+ innerOptions = Object.assign({}, innerOptions, {
3799
+ parent: innerOptions.value,
3800
+ value: innerOptions.value[0]
3801
+ });
1407
3802
  }
1408
- ) })
1409
- ] });
1410
- };
1411
- const Header = () => {
1412
- const [a11yOpen, setA11yOpen] = useState(false);
1413
- const [userMenuOpen, setUserMenuOpen] = useState(false);
1414
- const [activityLogOpen, setActivityLogOpen] = useState(false);
1415
- const { apps: allApps } = useApps({ includeHidden: true });
1416
- const headerMenuState = {
1417
- a11yOpen,
1418
- setA11yOpen,
1419
- userMenuOpen,
1420
- setUserMenuOpen,
1421
- activityLogOpen,
1422
- setActivityLogOpen
1423
- };
1424
- return /* @__PURE__ */ jsxs(Fragment, { children: [
1425
- /* @__PURE__ */ jsxs(TopBarFadeIn, { id: "cli-top-bar", children: [
1426
- /* @__PURE__ */ jsx(TopBar.Header, { children: /* @__PURE__ */ jsxs(Styled.Title, { children: [
1427
- /* @__PURE__ */ jsx(Icon, { color: "#eb0037", data: logoIcon, viewBox: "0 0 42 48" }),
1428
- /* @__PURE__ */ jsx("span", { children: "Roma" })
1429
- ] }) }),
1430
- /* @__PURE__ */ jsx(TopBar.CustomContent, {}),
1431
- /* @__PURE__ */ jsx(TopBar.Actions, { children: /* @__PURE__ */ jsx(HeaderMenu, { menuState: headerMenuState }) })
1432
- ] }),
1433
- /* @__PURE__ */ jsx(SideSheets, { apps: allApps, menuState: headerMenuState })
1434
- ] });
3803
+ base.innerType = next.innerType.describe(innerOptions);
3804
+ }
3805
+ return base;
3806
+ }
3807
+ }
3808
+ create$2.prototype = ArraySchema.prototype;
3809
+ const fieldSchema = create$3().shape({
3810
+ fieldName: create$6().required().ensure(),
3811
+ fieldLabel: create$6().required().ensure(),
3812
+ fieldEnabled: create$7().default(true)
3813
+ });
3814
+ const cargoSettingsSchema = create$3().shape({
3815
+ fields: create$3().shape({
3816
+ contractual: create$3().shape({
3817
+ product: fieldSchema,
3818
+ quality: fieldSchema,
3819
+ contrquantity: fieldSchema,
3820
+ buyer: fieldSchema,
3821
+ seller: fieldSchema,
3822
+ incoterm: fieldSchema
3823
+ }),
3824
+ operational: create$3().shape({
3825
+ status: fieldSchema,
3826
+ loadingrange: fieldSchema,
3827
+ dischargerange: fieldSchema,
3828
+ loadport: fieldSchema,
3829
+ dischargeport: fieldSchema,
3830
+ qty: fieldSchema,
3831
+ remarks: fieldSchema
3832
+ }),
3833
+ vessel: create$3().shape({
3834
+ vesselname: fieldSchema,
3835
+ eta: fieldSchema
3836
+ })
3837
+ }),
3838
+ settings: create$3().shape({
3839
+ autowatch: create$3().shape({
3840
+ opsResponsible: create$7()
3841
+ })
3842
+ })
3843
+ });
3844
+ const settingSchema = create$3({
3845
+ cargo: cargoSettingsSchema
3846
+ }).default({
3847
+ cargo: cargoSettingsSchema.getDefault()
3848
+ });
3849
+ const watchListSchema = create$3().shape({
3850
+ watched: create$2().of(create$6()).required().default([]),
3851
+ unwatched: create$2().of(create$6()).required().default([])
3852
+ });
3853
+ const rootSchema = create$3({
3854
+ notificationSettings: settingSchema,
3855
+ watchListSettings: create$3({
3856
+ cargo: watchListSchema
3857
+ })
3858
+ });
3859
+ class CustomAppClient {
3860
+ constructor(client) {
3861
+ __privateAdd(this, _manifests, []);
3862
+ this.client = client;
3863
+ }
3864
+ // eslint-disable-next-line no-empty-pattern
3865
+ getAppConfig({}) {
3866
+ return of({});
3867
+ }
3868
+ getAppManifest({ appKey }) {
3869
+ const manifest = __privateGet(this, _manifests).find(
3870
+ (manifest2) => manifest2.appKey === appKey
3871
+ );
3872
+ if (!manifest)
3873
+ throw new Error(
3874
+ `AppNotFoundError: Manifest for appKey "${appKey}" not found`
3875
+ );
3876
+ return of(manifest);
3877
+ }
3878
+ getAppManifests() {
3879
+ return this.client.fetch$(`/api/apps`).pipe(
3880
+ switchMap(
3881
+ (r) => from(r.json())
3882
+ ),
3883
+ map(
3884
+ (v) => v.map((vv) => {
3885
+ let pathname;
3886
+ if (vv.entry.startsWith("/")) {
3887
+ pathname = vv.entry;
3888
+ } else {
3889
+ const url = new URL(vv.entry);
3890
+ pathname = `${url.pathname}${url.search}`;
3891
+ }
3892
+ return {
3893
+ ...vv,
3894
+ entry: pathname,
3895
+ keywords: vv.keywords ?? vv.tags,
3896
+ appKey: vv.appKey ?? vv.key,
3897
+ name: vv.displayName ?? vv.name,
3898
+ visualization: {
3899
+ icon: vv.icon,
3900
+ sortOrder: vv.order
3901
+ },
3902
+ build: {
3903
+ entryPoint: pathname,
3904
+ assetPath: "/",
3905
+ version: `${vv.version.major}.${vv.version.minor}.${vv.version.patch}`
3906
+ }
3907
+ };
3908
+ })
3909
+ ),
3910
+ tap((v) => __privateSet(this, _manifests, v)),
3911
+ catchError((err) => {
3912
+ console.error("Error fetching app manifests", err);
3913
+ return of([]);
3914
+ })
3915
+ );
3916
+ }
3917
+ getAppSettings() {
3918
+ console.log("getAppSettings");
3919
+ return of({});
3920
+ }
3921
+ updateAppSettings() {
3922
+ console.log("updateAppSettings");
3923
+ return of({});
3924
+ }
3925
+ }
3926
+ _manifests = new WeakMap();
3927
+ class ServiceDiscoveryClient {
3928
+ constructor() {
3929
+ this.cacheTime = 0;
3930
+ }
3931
+ async resolveService(key, allow_cache) {
3932
+ return this.resolveServices(allow_cache).then(
3933
+ (services) => services.find((s) => s.key === key)
3934
+ );
3935
+ }
3936
+ async resolveServices(allow_cache) {
3937
+ const wait = 60 * 1e3 * 30;
3938
+ if (this.cache && this.cacheTime > Date.now() - wait) {
3939
+ return this.cache;
3940
+ }
3941
+ this.cacheTime = Date.now();
3942
+ return fetch(`/_discovery/environments/current`).then((r) => r.json()).then((r) => {
3943
+ const services = r.services.map((s) => ({
3944
+ ...s,
3945
+ scopes: s.defaultScopes
3946
+ }));
3947
+ this.cache = services;
3948
+ return services;
3949
+ });
3950
+ }
3951
+ }
3952
+ const configure = async (config) => {
3953
+ var _a;
3954
+ const request = await fetch("/_discovery/environments/current");
3955
+ const environment = await request.json();
3956
+ const services = environment.services;
3957
+ if (!services) {
3958
+ throw new Error(`ServiceDiscoveryMissingError: No services found`);
3959
+ }
3960
+ const portalService = (_a = environment.services) == null ? void 0 : _a.find((v) => v.key === "portal");
3961
+ if (!portalService || !environment.frontendClientId) {
3962
+ const error = [];
3963
+ if (!portalService) error.push(`Missing service: "portal"`);
3964
+ if (!environment.frontendClientId) error.push(`Missing frontend clientId`);
3965
+ throw new Error(`Missing environment information:
3966
+ ${error.join("\n")}`);
3967
+ }
3968
+ config.logger.level = 2;
3969
+ config.configureMsal(
3970
+ {
3971
+ tenantId: "3aa4a235-b6e2-48d5-9195-7fcf05b459b0",
3972
+ clientId: environment.frontendClientId,
3973
+ redirectUri: "/authentication/login-callback"
3974
+ },
3975
+ { requiresAuth: true }
3976
+ );
3977
+ enableServiceDiscovery(config, async (builder) => {
3978
+ builder.setServiceDiscoveryClient(new ServiceDiscoveryClient());
3979
+ });
3980
+ enableContext(config);
3981
+ enableAppModule(config, (builder) => {
3982
+ builder.setAssetUri(`/`);
3983
+ builder.setClient(async (client) => {
3984
+ const http = await client.requireInstance("http");
3985
+ const httpClient = http.createClient(portalService);
3986
+ return new CustomAppClient(httpClient);
3987
+ });
3988
+ });
3989
+ enableNavigation(config);
3990
+ enableSse(config, "activity");
3991
+ config.onConfigured(() => {
3992
+ console.info("Fusion config done");
3993
+ });
3994
+ config.onInitialized(async (fusion) => {
3995
+ fusion.auth.defaultClient.setLogger(new ConsoleLogger(config.logger.level));
3996
+ window.sessionStorage.clear();
3997
+ });
1435
3998
  };
1436
3999
  const ErrorTypography = ({
1437
4000
  variant,
@@ -2500,40 +5063,6 @@ const useFindUsersByShortname = (shortnames, fields = ["displayName", "mail", "g
2500
5063
  const emails = (shortnames ?? []).map((name) => `${name}@equinor.com`);
2501
5064
  return useFindUsersByMail(emails, fields);
2502
5065
  };
2503
- function promisifyRequest(request) {
2504
- return new Promise((resolve, reject) => {
2505
- request.oncomplete = request.onsuccess = () => resolve(request.result);
2506
- request.onabort = request.onerror = () => reject(request.error);
2507
- });
2508
- }
2509
- function createStore(dbName, storeName) {
2510
- const request = indexedDB.open(dbName);
2511
- request.onupgradeneeded = () => request.result.createObjectStore(storeName);
2512
- const dbp = promisifyRequest(request);
2513
- return (txMode, callback) => dbp.then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));
2514
- }
2515
- let defaultGetStoreFunc;
2516
- function defaultGetStore() {
2517
- if (!defaultGetStoreFunc) {
2518
- defaultGetStoreFunc = createStore("keyval-store", "keyval");
2519
- }
2520
- return defaultGetStoreFunc;
2521
- }
2522
- function get(key, customStore = defaultGetStore()) {
2523
- return customStore("readonly", (store) => promisifyRequest(store.get(key)));
2524
- }
2525
- function set(key, value, customStore = defaultGetStore()) {
2526
- return customStore("readwrite", (store) => {
2527
- store.put(value, key);
2528
- return promisifyRequest(store.transaction);
2529
- });
2530
- }
2531
- function del(key, customStore = defaultGetStore()) {
2532
- return customStore("readwrite", (store) => {
2533
- store.delete(key);
2534
- return promisifyRequest(store.transaction);
2535
- });
2536
- }
2537
5066
  const checkRomaApi = (queryKey) => {
2538
5067
  const first = (queryKey ?? []).at(0);
2539
5068
  if (typeof first === "string") {
@@ -2684,6 +5213,194 @@ async function handleError(req) {
2684
5213
  }
2685
5214
  }
2686
5215
  }
5216
+ const useWatchDefaults = {
5217
+ notificationSettings: {
5218
+ cargo: {
5219
+ fields: {
5220
+ contractual: {
5221
+ product: {
5222
+ fieldName: "product",
5223
+ fieldLabel: "Product",
5224
+ fieldEnabled: true
5225
+ },
5226
+ quality: {
5227
+ fieldName: "quality",
5228
+ fieldLabel: "Quality",
5229
+ fieldEnabled: true
5230
+ },
5231
+ contrquantity: {
5232
+ fieldName: "contrquantity",
5233
+ fieldLabel: "Contr. Quantity",
5234
+ fieldEnabled: true
5235
+ },
5236
+ buyer: {
5237
+ fieldName: "buyer",
5238
+ fieldLabel: "Buyer",
5239
+ fieldEnabled: true
5240
+ },
5241
+ seller: {
5242
+ fieldName: "seller",
5243
+ fieldLabel: "Seller",
5244
+ fieldEnabled: true
5245
+ },
5246
+ incoterm: {
5247
+ fieldName: "incoterm",
5248
+ fieldLabel: "Incoterm",
5249
+ fieldEnabled: true
5250
+ }
5251
+ },
5252
+ operational: {
5253
+ status: {
5254
+ fieldName: "status",
5255
+ fieldLabel: "Status",
5256
+ fieldEnabled: true
5257
+ },
5258
+ loadingrange: {
5259
+ fieldName: "loadingrange",
5260
+ fieldLabel: "Loading Range",
5261
+ fieldEnabled: true
5262
+ },
5263
+ dischargerange: {
5264
+ fieldName: "dischargerange",
5265
+ fieldLabel: "Discharge Range",
5266
+ fieldEnabled: true
5267
+ },
5268
+ loadport: {
5269
+ fieldName: "loadport",
5270
+ fieldLabel: "Load port",
5271
+ fieldEnabled: true
5272
+ },
5273
+ dischargeport: {
5274
+ fieldName: "dischargeport",
5275
+ fieldLabel: "Discharge port",
5276
+ fieldEnabled: true
5277
+ },
5278
+ qty: {
5279
+ fieldName: "qty",
5280
+ fieldLabel: "Qty (any unit)",
5281
+ fieldEnabled: true
5282
+ },
5283
+ remarks: {
5284
+ fieldName: "remarks",
5285
+ fieldLabel: "Remarks",
5286
+ fieldEnabled: true
5287
+ }
5288
+ },
5289
+ vessel: {
5290
+ vesselname: {
5291
+ fieldName: "vesselname",
5292
+ fieldLabel: "Vessel name",
5293
+ fieldEnabled: true
5294
+ },
5295
+ eta: {
5296
+ fieldName: "eta",
5297
+ fieldLabel: "ETA",
5298
+ fieldEnabled: true
5299
+ }
5300
+ }
5301
+ },
5302
+ settings: {
5303
+ autowatch: {
5304
+ opsResponsible: false
5305
+ }
5306
+ }
5307
+ }
5308
+ },
5309
+ watchListSettings: {
5310
+ cargo: {
5311
+ watched: [],
5312
+ unwatched: []
5313
+ }
5314
+ }
5315
+ };
5316
+ const useManageWatchList = (system) => {
5317
+ const { data: setting } = useGetSettingsByAppShortName("notifications", {
5318
+ query: {
5319
+ meta: {
5320
+ persist: true
5321
+ },
5322
+ staleTime: 6e4 * 15,
5323
+ // Skip re-fetching if data is less than 15 minutes old
5324
+ select: (data) => {
5325
+ const setting2 = (data ?? []).filter(
5326
+ (f) => f.setting === "app-notifications"
5327
+ );
5328
+ return setting2 && setting2.length > 0 ? setting2[0] : rootSchema.cast(useWatchDefaults, { assert: false });
5329
+ }
5330
+ }
5331
+ });
5332
+ const framework = useFramework();
5333
+ const user = framework.modules.auth.defaultAccount;
5334
+ const userId = (user == null ? void 0 : user.username.split("@")[0].toLowerCase()) ?? "MISSINGUSER";
5335
+ const queryClient = useQueryClient();
5336
+ const updateMutator = useUpdateByUserIdAndId();
5337
+ const createMutator = useCreateSettingByUserId();
5338
+ const saveSetting = (setting2) => {
5339
+ if (!setting2.id) {
5340
+ createMutator.mutate(
5341
+ {
5342
+ userId,
5343
+ data: setting2
5344
+ },
5345
+ {
5346
+ onSuccess: () => {
5347
+ return queryClient.resetQueries({
5348
+ queryKey: getGetSettingsByAppShortNameQueryKey("notifications")
5349
+ });
5350
+ }
5351
+ }
5352
+ );
5353
+ } else {
5354
+ updateMutator.mutate(
5355
+ {
5356
+ userId,
5357
+ id: setting2.id,
5358
+ data: setting2
5359
+ },
5360
+ {
5361
+ onSuccess: () => {
5362
+ return queryClient.resetQueries({
5363
+ queryKey: getGetSettingsByAppShortNameQueryKey("notifications")
5364
+ });
5365
+ }
5366
+ }
5367
+ );
5368
+ }
5369
+ };
5370
+ return {
5371
+ watch(id) {
5372
+ if (!setting) {
5373
+ return;
5374
+ }
5375
+ setting.value.watchListSettings[system].unwatched = setting.value.watchListSettings[system].unwatched.filter(
5376
+ (i) => i !== id
5377
+ );
5378
+ setting.value.watchListSettings[system].watched = Array.from(
5379
+ /* @__PURE__ */ new Set([...setting.value.watchListSettings[system].watched, id])
5380
+ );
5381
+ saveSetting(setting);
5382
+ },
5383
+ unwatch(id) {
5384
+ if (!setting) {
5385
+ return;
5386
+ }
5387
+ setting.value.watchListSettings[system].watched = setting.value.watchListSettings[system].watched.filter((i) => i !== id);
5388
+ setting.value.watchListSettings[system].unwatched = Array.from(
5389
+ /* @__PURE__ */ new Set([...setting.value.watchListSettings[system].unwatched, id])
5390
+ );
5391
+ saveSetting(setting);
5392
+ },
5393
+ watched() {
5394
+ if (!setting) return [];
5395
+ return setting.value.watchListSettings[system].watched;
5396
+ },
5397
+ unwatched() {
5398
+ if (!setting) return [];
5399
+ return setting.value.watchListSettings[system].unwatched;
5400
+ },
5401
+ isSaving: createMutator.isPending || updateMutator.isPending
5402
+ };
5403
+ };
2687
5404
  export {
2688
5405
  AppContext,
2689
5406
  AppLoadError,
@@ -2698,7 +5415,9 @@ export {
2698
5415
  HttpErrorViewer,
2699
5416
  RomaErrorViewer,
2700
5417
  StyleProvider,
5418
+ configure,
2701
5419
  createIDBPersister,
5420
+ findUsersByMail,
2702
5421
  getGetAllAppsQueryKey,
2703
5422
  getGetAllCategoriesQueryKey,
2704
5423
  getGetAllRomaConfigurationByTypeQueryKey,
@@ -2812,6 +5531,7 @@ export {
2812
5531
  useListFeedbacksByCurrentUser,
2813
5532
  useListFeedbacksByCurrentUserHook,
2814
5533
  useListFeedbacksByCurrentUserQueryOptions,
5534
+ useManageWatchList,
2815
5535
  useStreamEvents,
2816
5536
  useStreamEventsHook,
2817
5537
  useStreamEventsQueryOptions,