@fctc/edu-logic-lib 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/provider.js CHANGED
@@ -1,48 +1,22 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
+
3
+ var _chunkU4CC2BBBjs = require('./chunk-U4CC2BBB.js');
4
+ require('./chunk-GGOFXFSX.js');
5
+ require('./chunk-S7YF2I23.js');
6
+ require('./chunk-W4W2L2NA.js');
7
+ require('./chunk-UY6GNZNB.js');
8
+ require('./chunk-IXDDYGKE.js');
9
+
29
10
 
30
- // src/provider.ts
31
- var provider_exports = {};
32
- __export(provider_exports, {
33
- MainProvider: () => MainProvider,
34
- ReactQueryProvider: () => ReactQueryProvider,
35
- VersionGate: () => VersionGate
36
- });
37
- module.exports = __toCommonJS(provider_exports);
11
+ var _chunkRZBHZYXGjs = require('./chunk-RZBHZYXG.js');
38
12
 
39
13
  // src/provider/react-query-provider.tsx
40
- var import_react = require("react");
41
- var import_react_query = require("@tanstack/react-query");
42
- var import_jsx_runtime = require("react/jsx-runtime");
14
+ var _react = require('react');
15
+ var _reactquery = require('@tanstack/react-query');
16
+ var _jsxruntime = require('react/jsx-runtime');
43
17
  var ReactQueryProvider = ({ children }) => {
44
- const [queryClient] = (0, import_react.useState)(
45
- () => new import_react_query.QueryClient({
18
+ const [queryClient] = _react.useState.call(void 0,
19
+ () => new (0, _reactquery.QueryClient)({
46
20
  defaultOptions: {
47
21
  queries: {
48
22
  refetchOnWindowFocus: false,
@@ -53,3240 +27,42 @@ var ReactQueryProvider = ({ children }) => {
53
27
  }
54
28
  })
55
29
  );
56
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_query.QueryClientProvider, { client: queryClient, children });
30
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _reactquery.QueryClientProvider, { client: queryClient, children });
57
31
  };
58
32
 
59
33
  // src/provider/redux-provider.tsx
60
- var import_react_redux2 = require("react-redux");
61
-
62
- // src/store/index.ts
63
- var import_react_redux = require("react-redux");
64
-
65
- // src/store/reducers/env-slice/index.ts
66
- var import_toolkit = require("@reduxjs/toolkit");
67
- var initialState = {
68
- baseUrl: "",
69
- requests: null,
70
- companies: [],
71
- user: {},
72
- envFile: null,
73
- defaultCompany: {
74
- id: null,
75
- logo: "",
76
- secondary_color: "",
77
- primary_color: ""
78
- },
79
- context: {
80
- uid: null,
81
- allowed_company_ids: [],
82
- lang: "vi_VN",
83
- tz: "Asia/Saigon"
84
- }
85
- };
86
- var envSlice = (0, import_toolkit.createSlice)({
87
- name: "env",
88
- initialState,
89
- reducers: {
90
- setEnv: (state, action) => {
91
- Object.assign(state, action.payload);
92
- },
93
- setUid: (state, action) => {
94
- state.context.uid = action.payload;
95
- },
96
- setAllowCompanies: (state, action) => {
97
- state.context.allowed_company_ids = action.payload;
98
- },
99
- setCompanies: (state, action) => {
100
- state.companies = action.payload;
101
- },
102
- setDefaultCompany: (state, action) => {
103
- state.defaultCompany = action.payload;
104
- },
105
- setLang: (state, action) => {
106
- state.context.lang = action.payload;
107
- },
108
- setUser: (state, action) => {
109
- state.user = action.payload;
110
- },
111
- setEnvFile: (state, action) => {
112
- state.envFile = action.payload;
113
- }
114
- }
115
- });
116
- var {
117
- setEnv,
118
- setUid,
119
- setLang,
120
- setAllowCompanies,
121
- setCompanies,
122
- setDefaultCompany,
123
- setUser,
124
- setEnvFile
125
- } = envSlice.actions;
126
- var env_slice_default = envSlice.reducer;
127
-
128
- // src/store/reducers/excel-slice/index.ts
129
- var import_toolkit2 = require("@reduxjs/toolkit");
130
- var initialState2 = {
131
- dataParse: null,
132
- idFile: null,
133
- isFileLoaded: false,
134
- loadingImport: false,
135
- selectedFile: null,
136
- errorData: null
137
- };
138
- var excelSlice = (0, import_toolkit2.createSlice)({
139
- name: "excel",
140
- initialState: initialState2,
141
- reducers: {
142
- setDataParse: (state, action) => {
143
- state.dataParse = action.payload;
144
- },
145
- setIdFile: (state, action) => {
146
- state.idFile = action.payload;
147
- },
148
- setIsFileLoaded: (state, action) => {
149
- state.isFileLoaded = action.payload;
150
- },
151
- setLoadingImport: (state, action) => {
152
- state.loadingImport = action.payload;
153
- },
154
- setSelectedFile: (state, action) => {
155
- state.selectedFile = action.payload;
156
- },
157
- setErrorData: (state, action) => {
158
- state.errorData = action.payload;
159
- }
160
- }
161
- });
162
- var {
163
- setDataParse,
164
- setIdFile,
165
- setIsFileLoaded,
166
- setLoadingImport,
167
- setSelectedFile,
168
- setErrorData
169
- } = excelSlice.actions;
170
- var excel_slice_default = excelSlice.reducer;
171
-
172
- // src/store/reducers/form-slice/index.ts
173
- var import_toolkit3 = require("@reduxjs/toolkit");
174
- var initialState3 = {
175
- viewDataStore: {},
176
- isShowingModalDetail: false,
177
- isShowModalTranslate: false,
178
- formSubmitComponent: {},
179
- fieldTranslation: null,
180
- listSubject: {},
181
- dataUser: {}
182
- };
183
- var formSlice = (0, import_toolkit3.createSlice)({
184
- name: "form",
185
- initialState: initialState3,
186
- reducers: {
187
- setViewDataStore: (state, action) => {
188
- state.viewDataStore = action.payload;
189
- },
190
- setIsShowingModalDetail: (state, action) => {
191
- state.isShowingModalDetail = action.payload;
192
- },
193
- setIsShowModalTranslate: (state, action) => {
194
- state.isShowModalTranslate = action.payload;
195
- },
196
- setFormSubmitComponent: (state, action) => {
197
- state.formSubmitComponent[action.payload.key] = action.payload.component;
198
- },
199
- setFieldTranslate: (state, action) => {
200
- state.fieldTranslation = action.payload;
201
- },
202
- setListSubject: (state, action) => {
203
- state.listSubject = action.payload;
204
- },
205
- setDataUser: (state, action) => {
206
- state.dataUser = action.payload;
207
- }
208
- }
209
- });
210
- var {
211
- setViewDataStore,
212
- setIsShowingModalDetail,
213
- setIsShowModalTranslate,
214
- setFormSubmitComponent,
215
- setFieldTranslate,
216
- setListSubject,
217
- setDataUser
218
- } = formSlice.actions;
219
- var form_slice_default = formSlice.reducer;
220
-
221
- // src/store/reducers/list-slice/index.ts
222
- var import_toolkit4 = require("@reduxjs/toolkit");
223
- var initialState4 = {
224
- pageLimit: 10,
225
- fields: {},
226
- order: "",
227
- selectedRowKeys: [],
228
- indexRowTableModal: -2,
229
- footerGroupTable: {},
230
- page: 0,
231
- domainTable: []
232
- };
233
- var listSlice = (0, import_toolkit4.createSlice)({
234
- name: "list",
235
- initialState: initialState4,
236
- reducers: {
237
- setPageLimit: (state, action) => {
238
- state.pageLimit = action.payload;
239
- },
240
- setFields: (state, action) => {
241
- state.fields = action.payload;
242
- },
243
- setOrder: (state, action) => {
244
- state.order = action.payload;
245
- },
246
- setSelectedRowKeys: (state, action) => {
247
- state.selectedRowKeys = action.payload;
248
- },
249
- setIndexRowTableModal: (state, action) => {
250
- state.indexRowTableModal = action.payload;
251
- },
252
- setPage: (state, action) => {
253
- state.page = action.payload;
254
- },
255
- setDomainTable: (state, action) => {
256
- state.domainTable = action.payload;
257
- }
258
- }
259
- });
260
- var {
261
- setPageLimit,
262
- setFields,
263
- setOrder,
264
- setSelectedRowKeys,
265
- setIndexRowTableModal,
266
- setPage,
267
- setDomainTable
268
- } = listSlice.actions;
269
- var list_slice_default = listSlice.reducer;
270
-
271
- // src/store/reducers/navbar-slice/index.ts
272
- var import_toolkit5 = require("@reduxjs/toolkit");
273
- var initialState5 = {
274
- menuList: []
275
- };
276
- var navbarSlice = (0, import_toolkit5.createSlice)({
277
- name: "navbar",
278
- initialState: initialState5,
279
- reducers: {
280
- setMenuList: (state, action) => {
281
- state.menuList = action.payload;
282
- }
283
- }
284
- });
285
- var { setMenuList } = navbarSlice.actions;
286
- var navbar_slice_default = navbarSlice.reducer;
287
-
288
- // src/store/reducers/profile-slice/index.ts
289
- var import_toolkit6 = require("@reduxjs/toolkit");
290
- var initialState6 = {
291
- profile: {}
292
- };
293
- var profileSlice = (0, import_toolkit6.createSlice)({
294
- name: "profile",
295
- initialState: initialState6,
296
- reducers: {
297
- setProfile: (state, action) => {
298
- state.profile = action.payload;
299
- }
300
- }
301
- });
302
- var { setProfile } = profileSlice.actions;
303
- var profile_slice_default = profileSlice.reducer;
304
-
305
- // src/store/reducers/search-slice/index.ts
306
- var import_toolkit7 = require("@reduxjs/toolkit");
307
- var initialState7 = {
308
- groupByDomain: null,
309
- tableHead: [],
310
- searchString: "",
311
- hoveredIndexSearchList: null,
312
- selectedTags: [],
313
- firstDomain: null,
314
- searchMap: {},
315
- typeFieldsSearch: "",
316
- modelSearch: "",
317
- filterBy: [],
318
- groupBy: []
319
- };
320
- var searchSlice = (0, import_toolkit7.createSlice)({
321
- name: "search",
322
- initialState: initialState7,
323
- reducers: {
324
- setGroupByDomain: (state, action) => {
325
- state.groupByDomain = action.payload;
326
- },
327
- setTableHead: (state, action) => {
328
- state.tableHead = action.payload;
329
- },
330
- setSearchString: (state, action) => {
331
- state.searchString = action.payload;
332
- },
333
- setHoveredIndexSearchList: (state, action) => {
334
- state.hoveredIndexSearchList = action.payload;
335
- },
336
- setSelectedTags: (state, action) => {
337
- state.selectedTags = action.payload;
338
- },
339
- setFirstDomain: (state, action) => {
340
- state.firstDomain = action.payload;
341
- },
342
- setTypeFieldsSearch: (state, action) => {
343
- state.typeFieldsSearch = action.payload;
344
- },
345
- setModelSearch: (state, action) => {
346
- state.modelSearch = action.payload;
347
- },
348
- setFilterBy: (state, action) => {
349
- state.filterBy = action.payload;
350
- },
351
- setGroupBy: (state, action) => {
352
- state.groupBy = action.payload;
353
- },
354
- setSearchMap: (state, action) => {
355
- state.searchMap = action.payload;
356
- },
357
- updateSearchMap: (state, action) => {
358
- if (!state.searchMap[action.payload.key]) {
359
- state.searchMap[action.payload.key] = [];
360
- }
361
- state.searchMap[action.payload.key].push(action.payload.value);
362
- },
363
- removeKeyFromSearchMap: (state, action) => {
364
- const { key, item } = action.payload;
365
- const values = state.searchMap[key];
366
- if (!values) return;
367
- if (item) {
368
- const filtered = values.filter((value) => value.name !== item.name);
369
- if (filtered.length > 0) {
370
- state.searchMap[key] = filtered;
371
- } else {
372
- delete state.searchMap[key];
373
- }
374
- } else {
375
- delete state.searchMap[key];
376
- }
377
- },
378
- clearSearchMap: (state) => {
379
- state.searchMap = {};
380
- }
381
- }
382
- });
383
- var {
384
- setGroupByDomain,
385
- setSelectedTags,
386
- setSearchString,
387
- setHoveredIndexSearchList,
388
- setFirstDomain,
389
- setTableHead,
390
- setFilterBy,
391
- setTypeFieldsSearch,
392
- setModelSearch,
393
- setSearchMap,
394
- updateSearchMap,
395
- removeKeyFromSearchMap,
396
- setGroupBy,
397
- clearSearchMap
398
- } = searchSlice.actions;
399
- var search_slice_default = searchSlice.reducer;
34
+ var _reactredux = require('react-redux');
400
35
 
401
- // src/store/store.ts
402
- var import_toolkit8 = require("@reduxjs/toolkit");
403
-
404
- // node_modules/redux/dist/redux.mjs
405
- function formatProdErrorMessage(code) {
406
- return `Minified Redux error #${code}; visit https://redux.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
407
- }
408
- var randomString = () => Math.random().toString(36).substring(7).split("").join(".");
409
- var ActionTypes = {
410
- INIT: `@@redux/INIT${/* @__PURE__ */ randomString()}`,
411
- REPLACE: `@@redux/REPLACE${/* @__PURE__ */ randomString()}`,
412
- PROBE_UNKNOWN_ACTION: () => `@@redux/PROBE_UNKNOWN_ACTION${randomString()}`
413
- };
414
- var actionTypes_default = ActionTypes;
415
- function isPlainObject(obj) {
416
- if (typeof obj !== "object" || obj === null)
417
- return false;
418
- let proto = obj;
419
- while (Object.getPrototypeOf(proto) !== null) {
420
- proto = Object.getPrototypeOf(proto);
421
- }
422
- return Object.getPrototypeOf(obj) === proto || Object.getPrototypeOf(obj) === null;
423
- }
424
- function miniKindOf(val) {
425
- if (val === void 0)
426
- return "undefined";
427
- if (val === null)
428
- return "null";
429
- const type = typeof val;
430
- switch (type) {
431
- case "boolean":
432
- case "string":
433
- case "number":
434
- case "symbol":
435
- case "function": {
436
- return type;
437
- }
438
- }
439
- if (Array.isArray(val))
440
- return "array";
441
- if (isDate(val))
442
- return "date";
443
- if (isError(val))
444
- return "error";
445
- const constructorName = ctorName(val);
446
- switch (constructorName) {
447
- case "Symbol":
448
- case "Promise":
449
- case "WeakMap":
450
- case "WeakSet":
451
- case "Map":
452
- case "Set":
453
- return constructorName;
454
- }
455
- return Object.prototype.toString.call(val).slice(8, -1).toLowerCase().replace(/\s/g, "");
456
- }
457
- function ctorName(val) {
458
- return typeof val.constructor === "function" ? val.constructor.name : null;
459
- }
460
- function isError(val) {
461
- return val instanceof Error || typeof val.message === "string" && val.constructor && typeof val.constructor.stackTraceLimit === "number";
462
- }
463
- function isDate(val) {
464
- if (val instanceof Date)
465
- return true;
466
- return typeof val.toDateString === "function" && typeof val.getDate === "function" && typeof val.setDate === "function";
467
- }
468
- function kindOf(val) {
469
- let typeOfVal = typeof val;
470
- if (process.env.NODE_ENV !== "production") {
471
- typeOfVal = miniKindOf(val);
472
- }
473
- return typeOfVal;
474
- }
475
- function warning(message) {
476
- if (typeof console !== "undefined" && typeof console.error === "function") {
477
- console.error(message);
478
- }
479
- try {
480
- throw new Error(message);
481
- } catch (e) {
482
- }
483
- }
484
- function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
485
- const reducerKeys = Object.keys(reducers);
486
- const argumentName = action && action.type === actionTypes_default.INIT ? "preloadedState argument passed to createStore" : "previous state received by the reducer";
487
- if (reducerKeys.length === 0) {
488
- return "Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";
489
- }
490
- if (!isPlainObject(inputState)) {
491
- return `The ${argumentName} has unexpected type of "${kindOf(inputState)}". Expected argument to be an object with the following keys: "${reducerKeys.join('", "')}"`;
492
- }
493
- const unexpectedKeys = Object.keys(inputState).filter((key) => !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]);
494
- unexpectedKeys.forEach((key) => {
495
- unexpectedKeyCache[key] = true;
496
- });
497
- if (action && action.type === actionTypes_default.REPLACE)
498
- return;
499
- if (unexpectedKeys.length > 0) {
500
- return `Unexpected ${unexpectedKeys.length > 1 ? "keys" : "key"} "${unexpectedKeys.join('", "')}" found in ${argumentName}. Expected to find one of the known reducer keys instead: "${reducerKeys.join('", "')}". Unexpected keys will be ignored.`;
501
- }
502
- }
503
- function assertReducerShape(reducers) {
504
- Object.keys(reducers).forEach((key) => {
505
- const reducer = reducers[key];
506
- const initialState8 = reducer(void 0, {
507
- type: actionTypes_default.INIT
508
- });
509
- if (typeof initialState8 === "undefined") {
510
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(12) : `The slice reducer for key "${key}" returned undefined during initialization. If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.`);
511
- }
512
- if (typeof reducer(void 0, {
513
- type: actionTypes_default.PROBE_UNKNOWN_ACTION()
514
- }) === "undefined") {
515
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(13) : `The slice reducer for key "${key}" returned undefined when probed with a random type. Don't try to handle '${actionTypes_default.INIT}' or other actions in "redux/*" namespace. They are considered private. Instead, you must return the current state for any unknown actions, unless it is undefined, in which case you must return the initial state, regardless of the action type. The initial state may not be undefined, but can be null.`);
516
- }
517
- });
518
- }
519
- function combineReducers(reducers) {
520
- const reducerKeys = Object.keys(reducers);
521
- const finalReducers = {};
522
- for (let i = 0; i < reducerKeys.length; i++) {
523
- const key = reducerKeys[i];
524
- if (process.env.NODE_ENV !== "production") {
525
- if (typeof reducers[key] === "undefined") {
526
- warning(`No reducer provided for key "${key}"`);
527
- }
528
- }
529
- if (typeof reducers[key] === "function") {
530
- finalReducers[key] = reducers[key];
531
- }
532
- }
533
- const finalReducerKeys = Object.keys(finalReducers);
534
- let unexpectedKeyCache;
535
- if (process.env.NODE_ENV !== "production") {
536
- unexpectedKeyCache = {};
537
- }
538
- let shapeAssertionError;
539
- try {
540
- assertReducerShape(finalReducers);
541
- } catch (e) {
542
- shapeAssertionError = e;
543
- }
544
- return function combination(state = {}, action) {
545
- if (shapeAssertionError) {
546
- throw shapeAssertionError;
547
- }
548
- if (process.env.NODE_ENV !== "production") {
549
- const warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);
550
- if (warningMessage) {
551
- warning(warningMessage);
552
- }
553
- }
554
- let hasChanged = false;
555
- const nextState = {};
556
- for (let i = 0; i < finalReducerKeys.length; i++) {
557
- const key = finalReducerKeys[i];
558
- const reducer = finalReducers[key];
559
- const previousStateForKey = state[key];
560
- const nextStateForKey = reducer(previousStateForKey, action);
561
- if (typeof nextStateForKey === "undefined") {
562
- const actionType = action && action.type;
563
- throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(14) : `When called with an action of type ${actionType ? `"${String(actionType)}"` : "(unknown type)"}, the slice reducer for key "${key}" returned undefined. To ignore an action, you must explicitly return the previous state. If you want this reducer to hold no value, you can return null instead of undefined.`);
564
- }
565
- nextState[key] = nextStateForKey;
566
- hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
567
- }
568
- hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
569
- return hasChanged ? nextState : state;
570
- };
571
- }
572
-
573
- // src/store/store.ts
574
- var rootReducer = combineReducers({
575
- env: env_slice_default,
576
- navbar: navbar_slice_default,
577
- list: list_slice_default,
578
- search: search_slice_default,
579
- form: form_slice_default,
580
- excel: excel_slice_default,
581
- profile: profile_slice_default
582
- });
583
- var envStore = (0, import_toolkit8.configureStore)({
584
- reducer: rootReducer,
585
- middleware: (getDefaultMiddleware) => getDefaultMiddleware({
586
- serializableCheck: false
587
- })
588
- });
589
-
590
- // src/provider/redux-provider.tsx
591
- var import_jsx_runtime2 = require("react/jsx-runtime");
592
36
  var ReduxProvider = ({ children }) => {
593
- return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react_redux2.Provider, { store: envStore, children });
37
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _reactredux.Provider, { store: _chunkRZBHZYXGjs.envStore, children });
594
38
  };
595
39
 
596
40
  // src/provider/main-provider.tsx
597
- var import_jsx_runtime3 = require("react/jsx-runtime");
41
+
598
42
  var MainProvider = ({ children }) => {
599
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ReduxProvider, { children: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(ReactQueryProvider, { children }) });
43
+ return /* @__PURE__ */ _jsxruntime.jsx.call(void 0, ReduxProvider, { children: /* @__PURE__ */ _jsxruntime.jsx.call(void 0, ReactQueryProvider, { children }) });
600
44
  };
601
45
 
602
46
  // src/provider/version-gate-provider.tsx
603
- var import_react2 = require("react");
604
- var import_react_query2 = require("@tanstack/react-query");
605
-
606
- // src/config/axios-client.ts
607
- var import_axios = __toESM(require("axios"));
608
- var MAINT_KEY = "MAINTENANCE_ACTIVE";
609
- var MAINT_AT = "MAINTENANCE_AT";
610
- var MAINT_LAST_PATH = "MAINTENANCE_LAST_PATH";
611
- var hasRedirectedToMaintenance = false;
612
- function setMaintenanceFlags() {
613
- if (typeof window === "undefined") return;
614
- const { pathname, search } = window.location;
615
- const lastPath = pathname + (search || "");
616
- if (pathname !== "/maintenance" && !window.localStorage.getItem(MAINT_LAST_PATH)) {
617
- window.localStorage.setItem(MAINT_LAST_PATH, lastPath);
618
- }
619
- window.localStorage.setItem(MAINT_KEY, "true");
620
- window.localStorage.setItem(MAINT_AT, String(Date.now()));
621
- }
622
- async function clearMaintenanceAndExit(getToken, opts) {
623
- if (typeof window === "undefined") return;
624
- const forceLogin = opts?.forceLogin === true;
625
- const clearTokenOnForce = opts?.clearTokenOnForce !== false;
626
- window.localStorage.removeItem(MAINT_KEY);
627
- window.localStorage.removeItem(MAINT_AT);
628
- const lastPath = window.localStorage.getItem(MAINT_LAST_PATH);
629
- window.localStorage.removeItem(MAINT_LAST_PATH);
630
- try {
631
- if (forceLogin) {
632
- if (clearTokenOnForce) {
633
- try {
634
- await opts?.clearToken?.();
635
- } catch {
636
- }
637
- }
638
- window.location.replace("/login");
639
- return;
640
- }
641
- const token = await getToken();
642
- if (token) {
643
- const target = lastPath && lastPath !== "/maintenance" ? lastPath : "/";
644
- window.location.replace(target);
645
- } else {
646
- window.location.replace("/login");
647
- }
648
- } catch {
649
- window.location.replace("/login");
650
- }
651
- }
652
- var axiosClient = {
653
- init(config) {
654
- const localStorage2 = config.localStorageUtils;
655
- const sessionStorage = config.sessionStorageUtils;
656
- const db = config.db;
657
- let isRefreshing = false;
658
- let failedQueue = [];
659
- const processQueue = (error, token = null) => {
660
- failedQueue?.forEach((prom) => {
661
- if (error) {
662
- prom.reject(error);
663
- } else {
664
- prom.resolve(token);
665
- }
666
- });
667
- failedQueue = [];
668
- };
669
- const instance = import_axios.default.create({
670
- adapter: import_axios.default.defaults.adapter,
671
- baseURL: config.baseUrl,
672
- timeout: 5e4,
673
- paramsSerializer: (params) => new URLSearchParams(params).toString()
674
- });
675
- if (typeof window !== "undefined") {
676
- const isMaint = window.localStorage.getItem(MAINT_KEY) === "true";
677
- const onMaintenancePage = window.location.pathname === "/maintenance";
678
- if (isMaint && !onMaintenancePage) {
679
- hasRedirectedToMaintenance = true;
680
- window.location.replace("/maintenance");
681
- }
682
- if (isMaint && onMaintenancePage) {
683
- const healthUrl = config.healthUrl || `${(config.baseUrl || "").replace(/\/+$/, "")}/health`;
684
- (async () => {
685
- try {
686
- await import_axios.default.get(healthUrl, { timeout: 8e3 });
687
- await clearMaintenanceAndExit(() => localStorage2.getAccessToken(), {
688
- forceLogin: true,
689
- clearTokenOnForce: true,
690
- clearToken: () => localStorage2.clearToken()
691
- });
692
- } catch {
693
- }
694
- })();
695
- }
696
- }
697
- instance.interceptors.request.use(
698
- async (configReq) => {
699
- const token = await localStorage2.getAccessToken();
700
- if (token) {
701
- configReq.headers["Authorization"] = "Bearer " + token;
702
- }
703
- return configReq;
704
- },
705
- (error) => Promise.reject(error)
706
- );
707
- instance.interceptors.response.use(
708
- (response) => {
709
- if (typeof window !== "undefined") {
710
- const isMaint = window.localStorage.getItem(MAINT_KEY) === "true";
711
- const onMaintenancePage = window.location.pathname === "/maintenance";
712
- if (isMaint && onMaintenancePage) {
713
- ;
714
- (async () => {
715
- await clearMaintenanceAndExit(
716
- () => localStorage2.getAccessToken(),
717
- {
718
- forceLogin: true,
719
- clearTokenOnForce: true,
720
- clearToken: () => localStorage2.clearToken()
721
- }
722
- );
723
- })();
724
- } else if (isMaint) {
725
- window.localStorage.removeItem(MAINT_KEY);
726
- window.localStorage.removeItem(MAINT_AT);
727
- window.localStorage.removeItem(MAINT_LAST_PATH);
728
- }
729
- }
730
- return handleResponse(response);
731
- },
732
- async (error) => {
733
- const status = error?.response?.status;
734
- if (status === 503) {
735
- if (typeof window !== "undefined") {
736
- setMaintenanceFlags();
737
- if (!hasRedirectedToMaintenance && window.location.pathname !== "/maintenance") {
738
- hasRedirectedToMaintenance = true;
739
- window.location.replace("/maintenance");
740
- }
741
- }
742
- return Promise.reject({
743
- code: 503,
744
- message: "SERVICE_UNAVAILABLE",
745
- original: error?.response?.data
746
- });
747
- }
748
- const handleError = async (err) => {
749
- if (!err.response) {
750
- return err;
751
- }
752
- const { data } = err.response;
753
- if (data && data.code === 400 && ["invalid_grant"].includes(data.data?.error)) {
754
- await clearAuthToken();
755
- }
756
- return data;
757
- };
758
- const originalRequest = error.config;
759
- if ((error.response?.status === 403 || error.response?.status === 401 || error.response?.status === 404) && ["TOKEN_EXPIRED", "AUTHEN_FAIL", 401].includes(
760
- error.response.data.code
761
- )) {
762
- if (isRefreshing) {
763
- return new Promise(function(resolve, reject) {
764
- failedQueue.push({ resolve, reject });
765
- }).then((token) => {
766
- originalRequest.headers["Authorization"] = "Bearer " + token;
767
- return instance.request(originalRequest);
768
- }).catch(async (err) => {
769
- if ((err.response?.status === 400 || err.response?.status === 401) && ["invalid_grant"].includes(err.response.data.error)) {
770
- await clearAuthToken();
771
- }
772
- });
773
- }
774
- const browserSession = await sessionStorage.getBrowserSession();
775
- const refreshToken = await localStorage2.getRefreshToken();
776
- const accessTokenExp = await localStorage2.getAccessToken();
777
- isRefreshing = true;
778
- if (!refreshToken && (!browserSession || browserSession == "unActive")) {
779
- await clearAuthToken();
780
- } else {
781
- const payload = Object.fromEntries(
782
- Object.entries({
783
- refresh_token: refreshToken,
784
- grant_type: "refresh_token",
785
- client_id: config.config.clientId,
786
- client_secret: config.config.clientSecret
787
- }).filter(([_, value]) => !!value)
788
- );
789
- return new Promise(function(resolve) {
790
- import_axios.default.post(
791
- `${config.baseUrl}${"/authentication/oauth2/token" /* AUTH_TOKEN_PATH */}`,
792
- payload,
793
- {
794
- headers: {
795
- "Content-Type": "multipart/form-data",
796
- Authorization: `Bearer ${accessTokenExp}`
797
- }
798
- }
799
- ).then(async (res) => {
800
- const data = res.data;
801
- await localStorage2.setToken(data.access_token);
802
- await localStorage2.setRefreshToken(data.refresh_token);
803
- import_axios.default.defaults.headers.common["Authorization"] = "Bearer " + data.access_token;
804
- originalRequest.headers["Authorization"] = "Bearer " + data.access_token;
805
- processQueue(null, data.access_token);
806
- resolve(instance.request(originalRequest));
807
- }).catch(async (err) => {
808
- if (err && (err?.error_code === "AUTHEN_FAIL" || err?.error_code === "TOKEN_EXPIRED" || err?.error_code === "TOKEN_INCORRECT" || err?.code === "ERR_BAD_REQUEST")) {
809
- await clearAuthToken();
810
- }
811
- if (err && err.response) {
812
- const { error_code } = err.response?.data || {};
813
- if (error_code === "AUTHEN_FAIL") {
814
- await clearAuthToken();
815
- }
816
- }
817
- processQueue(err, null);
818
- }).finally(() => {
819
- isRefreshing = false;
820
- });
821
- });
822
- }
823
- }
824
- return Promise.reject(await handleError(error));
825
- }
826
- );
827
- const handleResponse = (res) => {
828
- if (res && res.data) {
829
- return res.data;
830
- }
831
- return res;
832
- };
833
- const clearAuthToken = async () => {
834
- await localStorage2.clearToken();
835
- if (typeof window !== "undefined") {
836
- window.location.href = `/login`;
837
- }
838
- };
839
- function formatUrl(url, db2) {
840
- return url + (db2 ? "?db=" + db2 : "");
841
- }
842
- const responseBody = (response) => response;
843
- const requests = {
844
- get: (url, headers) => instance.get(formatUrl(url, db), headers).then(responseBody),
845
- post: (url, body, headers) => instance.post(formatUrl(url, db), body, { headers }).then(responseBody),
846
- post_excel: (url, body, headers) => instance.post(formatUrl(url, db), body, {
847
- responseType: "arraybuffer",
848
- headers: {
849
- "Content-Type": typeof window !== "undefined" ? "application/json" : "application/javascript",
850
- Accept: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
851
- }
852
- }).then(responseBody),
853
- put: (url, body, headers) => instance.put(formatUrl(url, db), body, headers).then(responseBody),
854
- patch: (url, body) => instance.patch(formatUrl(url, db), body).then(responseBody),
855
- delete: (url, body) => instance.delete(formatUrl(url, db), body).then(responseBody)
856
- };
857
- return requests;
858
- }
859
- };
860
47
 
861
- // src/environment/EnvStore.ts
862
- var EnvStore = class {
863
- envStore;
864
- baseUrl;
865
- requests;
866
- context;
867
- defaultCompany;
868
- config;
869
- companies;
870
- user;
871
- db;
872
- localStorageUtils;
873
- sessionStorageUtils;
874
- constructor(envStore2, localStorageUtils, sessionStorageUtils) {
875
- this.envStore = envStore2;
876
- this.localStorageUtils = localStorageUtils;
877
- this.sessionStorageUtils = sessionStorageUtils;
878
- this.setup();
879
- }
880
- setup() {
881
- const env2 = this.envStore.getState().env;
882
- this.baseUrl = env2?.baseUrl;
883
- this.requests = env2?.requests;
884
- this.context = env2?.context;
885
- this.defaultCompany = env2?.defaultCompany;
886
- this.config = env2?.config;
887
- this.companies = env2?.companies || [];
888
- this.user = env2?.user;
889
- this.db = env2?.db;
890
- }
891
- setupEnv(envConfig) {
892
- const dispatch = this.envStore.dispatch;
893
- const env2 = {
894
- ...envConfig,
895
- localStorageUtils: this.localStorageUtils,
896
- sessionStorageUtils: this.sessionStorageUtils
897
- };
898
- const requests = axiosClient.init(env2);
899
- dispatch(setEnv({ ...env2, requests }));
900
- this.setup();
901
- }
902
- setUid(uid) {
903
- const dispatch = this.envStore.dispatch;
904
- dispatch(setUid(uid));
905
- this.setup();
906
- }
907
- setLang(lang) {
908
- const dispatch = this.envStore.dispatch;
909
- dispatch(setLang(lang));
910
- this.setup();
911
- }
912
- setAllowCompanies(allowCompanies) {
913
- const dispatch = this.envStore.dispatch;
914
- dispatch(setAllowCompanies(allowCompanies));
915
- this.setup();
916
- }
917
- setCompanies(companies) {
918
- const dispatch = this.envStore.dispatch;
919
- dispatch(setCompanies(companies));
920
- this.setup();
921
- }
922
- setDefaultCompany(company) {
923
- const dispatch = this.envStore.dispatch;
924
- dispatch(setDefaultCompany(company));
925
- this.setup();
926
- }
927
- setUserInfo(userInfo) {
928
- const dispatch = this.envStore.dispatch;
929
- dispatch(setUser(userInfo));
930
- this.setup();
931
- }
932
- };
933
- var env = null;
934
- function getEnv() {
935
- if (!env) env = new EnvStore(envStore);
936
- return env;
937
- }
938
48
 
939
- // src/utils/domain/py_tokenizer.ts
940
- var TokenizerError = class extends Error {
941
- };
942
- var directMap = {
943
- "\\": "\\",
944
- '"': '"',
945
- "'": "'",
946
- a: "\x07",
947
- b: "\b",
948
- f: "\f",
949
- n: "\n",
950
- r: "\r",
951
- t: " ",
952
- v: "\v"
953
- };
954
- function decodeStringLiteral(str, unicode) {
955
- const out = [];
956
- let code;
957
- for (let i = 0; i < str.length; ++i) {
958
- if (str[i] !== "\\") {
959
- out.push(str[i]);
960
- continue;
961
- }
962
- const escape = str[i + 1];
963
- if (escape in directMap) {
964
- out.push(directMap[escape]);
965
- ++i;
966
- continue;
967
- }
968
- switch (escape) {
969
- case "\n":
970
- ++i;
971
- continue;
972
- case "N":
973
- if (!unicode) {
974
- break;
975
- }
976
- throw new TokenizerError("SyntaxError: \\N{} escape not implemented");
977
- case "u":
978
- if (!unicode) {
979
- break;
980
- }
981
- const uni = str.slice(i + 2, i + 6);
982
- if (!/[0-9a-f]{4}/i.test(uni)) {
983
- throw new TokenizerError(
984
- [
985
- "SyntaxError: (unicode error) 'unicodeescape' codec",
986
- " can't decode bytes in position ",
987
- i,
988
- "-",
989
- i + 4,
990
- ": truncated \\uXXXX escape"
991
- ].join("")
992
- );
993
- }
994
- code = parseInt(uni, 16);
995
- out.push(String.fromCharCode(code));
996
- i += 5;
997
- continue;
998
- case "U":
999
- if (!unicode) {
1000
- break;
1001
- }
1002
- throw new TokenizerError("SyntaxError: \\U escape not implemented");
1003
- case "x":
1004
- const hex = str.slice(i + 2, i + 4);
1005
- if (!/[0-9a-f]{2}/i.test(hex)) {
1006
- if (!unicode) {
1007
- throw new TokenizerError("ValueError: invalid \\x escape");
1008
- }
1009
- throw new TokenizerError(
1010
- [
1011
- "SyntaxError: (unicode error) 'unicodeescape'",
1012
- " codec can't decode bytes in position ",
1013
- i,
1014
- "-",
1015
- i + 2,
1016
- ": truncated \\xXX escape"
1017
- ].join("")
1018
- );
1019
- }
1020
- code = parseInt(hex, 16);
1021
- out.push(String.fromCharCode(code));
1022
- i += 3;
1023
- continue;
1024
- default:
1025
- if (!/[0-8]/.test(escape)) {
1026
- break;
1027
- }
1028
- const r = /[0-8]{1,3}/g;
1029
- r.lastIndex = i + 1;
1030
- const m = r.exec(str);
1031
- if (!m) break;
1032
- const oct = m[0];
1033
- code = parseInt(oct, 8);
1034
- out.push(String.fromCharCode(code));
1035
- i += oct.length;
1036
- continue;
1037
- }
1038
- out.push("\\");
1039
- }
1040
- return out.join("");
1041
- }
1042
- var constants = /* @__PURE__ */ new Set(["None", "False", "True"]);
1043
- var comparators = [
1044
- "in",
1045
- "not",
1046
- "not in",
1047
- "is",
1048
- "is not",
1049
- "<",
1050
- "<=",
1051
- ">",
1052
- ">=",
1053
- "<>",
1054
- "!=",
1055
- "=="
1056
- ];
1057
- var binaryOperators = [
1058
- "or",
1059
- "and",
1060
- "|",
1061
- "^",
1062
- "&",
1063
- "<<",
1064
- ">>",
1065
- "+",
1066
- "-",
1067
- "*",
1068
- "/",
1069
- "//",
1070
- "%",
1071
- "~",
1072
- "**",
1073
- "."
1074
- ];
1075
- var unaryOperators = ["-"];
1076
- var symbols = /* @__PURE__ */ new Set([
1077
- ...["(", ")", "[", "]", "{", "}", ":", ","],
1078
- ...["if", "else", "lambda", "="],
1079
- ...comparators,
1080
- ...binaryOperators,
1081
- ...unaryOperators
1082
- ]);
1083
- function group(...args) {
1084
- return "(" + args.join("|") + ")";
1085
- }
1086
- var Name = "[a-zA-Z_]\\w*";
1087
- var Whitespace = "[ \\f\\t]*";
1088
- var DecNumber = "\\d+(L|l)?";
1089
- var IntNumber = DecNumber;
1090
- var Exponent = "[eE][+-]?\\d+";
1091
- var PointFloat = group(`\\d+\\.\\d*(${Exponent})?`, `\\.\\d+(${Exponent})?`);
1092
- var FloatNumber = group(PointFloat, `\\d+${Exponent}`);
1093
- var Number2 = group(FloatNumber, IntNumber);
1094
- var Operator = group(
1095
- "\\*\\*=?",
1096
- ">>=?",
1097
- "<<=?",
1098
- "<>",
1099
- "!=",
1100
- "//=?",
1101
- "[+\\-*/%&|^=<>]=?",
1102
- "~"
1103
- );
1104
- var Bracket = "[\\[\\]\\(\\)\\{\\}]";
1105
- var Special = "[:;.,`@]";
1106
- var Funny = group(Operator, Bracket, Special);
1107
- var ContStr = group(
1108
- "([uU])?'([^\\n'\\\\]*(?:\\\\.[^\\n'\\\\]*)*)'",
1109
- '([uU])?"([^\\n"\\\\]*(?:\\\\.[^\\n"\\\\]*)*)"'
1110
- );
1111
- var PseudoToken = Whitespace + group(Number2, Funny, ContStr, Name);
1112
- var NumberPattern = new RegExp("^" + Number2 + "$");
1113
- var StringPattern = new RegExp("^" + ContStr + "$");
1114
- var NamePattern = new RegExp("^" + Name + "$");
1115
- var strip = new RegExp("^" + Whitespace);
1116
- function tokenize(str) {
1117
- const tokens = [];
1118
- const max = str.length;
1119
- let start = 0;
1120
- let end = 0;
1121
- const pseudoprog = new RegExp(PseudoToken, "g");
1122
- while (pseudoprog.lastIndex < max) {
1123
- const pseudomatch = pseudoprog.exec(str);
1124
- if (!pseudomatch) {
1125
- if (/^\s+$/.test(str.slice(end))) {
1126
- break;
1127
- }
1128
- throw new TokenizerError(
1129
- "Failed to tokenize <<" + str + ">> at index " + (end || 0) + "; parsed so far: " + tokens
1130
- );
1131
- }
1132
- if (pseudomatch.index > end) {
1133
- if (str.slice(end, pseudomatch.index).trim()) {
1134
- throw new TokenizerError("Invalid expression");
1135
- }
1136
- }
1137
- start = pseudomatch.index;
1138
- end = pseudoprog.lastIndex;
1139
- let token = str.slice(start, end).replace(strip, "");
1140
- if (NumberPattern.test(token)) {
1141
- tokens.push({
1142
- type: 0,
1143
- value: parseFloat(token)
1144
- });
1145
- } else if (StringPattern.test(token)) {
1146
- const m = StringPattern.exec(token);
1147
- if (!m) throw new TokenizerError("Invalid string match");
1148
- tokens.push({
1149
- type: 1,
1150
- value: decodeStringLiteral(
1151
- m[3] !== void 0 ? m[3] : m[5],
1152
- !!(m[2] || m[4])
1153
- )
1154
- });
1155
- } else if (symbols.has(token)) {
1156
- if (token === "in" && tokens.length > 0 && tokens[tokens.length - 1].value === "not") {
1157
- token = "not in";
1158
- tokens.pop();
1159
- } else if (token === "not" && tokens.length > 0 && tokens[tokens.length - 1].value === "is") {
1160
- token = "is not";
1161
- tokens.pop();
1162
- }
1163
- tokens.push({
1164
- type: 2,
1165
- value: token
1166
- });
1167
- } else if (constants.has(token)) {
1168
- tokens.push({
1169
- type: 4,
1170
- value: token
1171
- });
1172
- } else if (NamePattern.test(token)) {
1173
- tokens.push({
1174
- type: 3,
1175
- value: token
1176
- });
1177
- } else {
1178
- throw new TokenizerError("Invalid expression");
1179
- }
1180
- }
1181
- return tokens;
1182
- }
1183
49
 
1184
- // src/utils/domain/py_parser.ts
1185
- var ParserError = class extends Error {
1186
- };
1187
- var chainedOperators = new Set(comparators);
1188
- var infixOperators = /* @__PURE__ */ new Set([...binaryOperators, ...comparators]);
1189
- function bp(symbol) {
1190
- switch (symbol) {
1191
- case "=":
1192
- return 10;
1193
- case "if":
1194
- return 20;
1195
- case "in":
1196
- case "not in":
1197
- case "is":
1198
- case "is not":
1199
- case "<":
1200
- case "<=":
1201
- case ">":
1202
- case ">=":
1203
- case "<>":
1204
- case "==":
1205
- case "!=":
1206
- return 60;
1207
- case "or":
1208
- return 30;
1209
- case "and":
1210
- return 40;
1211
- case "not":
1212
- return 50;
1213
- case "|":
1214
- return 70;
1215
- case "^":
1216
- return 80;
1217
- case "&":
1218
- return 90;
1219
- case "<<":
1220
- case ">>":
1221
- return 100;
1222
- case "+":
1223
- case "-":
1224
- return 110;
1225
- case "*":
1226
- case "/":
1227
- case "//":
1228
- case "%":
1229
- return 120;
1230
- case "**":
1231
- return 140;
1232
- case ".":
1233
- case "(":
1234
- case "[":
1235
- return 150;
1236
- default:
1237
- return 0;
1238
- }
1239
- }
1240
- function bindingPower(token) {
1241
- return token.type === 2 ? bp(token.value) : 0;
1242
- }
1243
- function isSymbol(token, value) {
1244
- return token.type === 2 && token.value === value;
1245
- }
1246
- function parsePrefix(current, tokens) {
1247
- switch (current.type) {
1248
- case 0:
1249
- return { type: 0, value: current.value };
1250
- case 1:
1251
- return { type: 1, value: current.value };
1252
- case 4:
1253
- if (current.value === "None") {
1254
- return {
1255
- type: 3
1256
- /* None */
1257
- };
1258
- } else {
1259
- return { type: 2, value: current.value === "True" };
1260
- }
1261
- case 3:
1262
- return { type: 5, value: current.value };
1263
- case 2:
1264
- switch (current.value) {
1265
- case "-":
1266
- case "+":
1267
- case "~":
1268
- return {
1269
- type: 6,
1270
- op: current.value,
1271
- right: _parse(tokens, 130)
1272
- };
1273
- case "not":
1274
- return {
1275
- type: 6,
1276
- op: current.value,
1277
- right: _parse(tokens, 50)
1278
- };
1279
- case "(":
1280
- const content = [];
1281
- let isTuple = false;
1282
- while (tokens[0] && !isSymbol(tokens[0], ")")) {
1283
- content.push(_parse(tokens, 0));
1284
- if (tokens[0]) {
1285
- if (tokens[0] && isSymbol(tokens[0], ",")) {
1286
- isTuple = true;
1287
- tokens.shift();
1288
- } else if (!isSymbol(tokens[0], ")")) {
1289
- throw new ParserError("parsing error");
1290
- }
1291
- } else {
1292
- throw new ParserError("parsing error");
1293
- }
1294
- }
1295
- if (!tokens[0] || !isSymbol(tokens[0], ")")) {
1296
- throw new ParserError("parsing error");
1297
- }
1298
- tokens.shift();
1299
- isTuple = isTuple || content.length === 0;
1300
- return isTuple ? { type: 10, value: content } : content[0];
1301
- case "[":
1302
- const value = [];
1303
- while (tokens[0] && !isSymbol(tokens[0], "]")) {
1304
- value.push(_parse(tokens, 0));
1305
- if (tokens[0]) {
1306
- if (isSymbol(tokens[0], ",")) {
1307
- tokens.shift();
1308
- } else if (!isSymbol(tokens[0], "]")) {
1309
- throw new ParserError("parsing error");
1310
- }
1311
- }
1312
- }
1313
- if (!tokens[0] || !isSymbol(tokens[0], "]")) {
1314
- throw new ParserError("parsing error");
1315
- }
1316
- tokens.shift();
1317
- return { type: 4, value };
1318
- case "{":
1319
- const dict = {};
1320
- while (tokens[0] && !isSymbol(tokens[0], "}")) {
1321
- const key = _parse(tokens, 0);
1322
- if (key.type !== 1 && key.type !== 0 || !tokens[0] || !isSymbol(tokens[0], ":")) {
1323
- throw new ParserError("parsing error");
1324
- }
1325
- tokens.shift();
1326
- const val = _parse(tokens, 0);
1327
- dict[key.value] = val;
1328
- if (isSymbol(tokens[0], ",")) {
1329
- tokens.shift();
1330
- }
1331
- }
1332
- if (!tokens.shift()) {
1333
- throw new ParserError("parsing error");
1334
- }
1335
- return { type: 11, value: dict };
1336
- default:
1337
- throw new ParserError("Token cannot be parsed");
1338
- }
1339
- default:
1340
- throw new ParserError("Token cannot be parsed");
1341
- }
1342
- }
1343
- function parseInfix(left, current, tokens) {
1344
- switch (current.type) {
1345
- case 2:
1346
- if (infixOperators.has(current.value)) {
1347
- let right = _parse(tokens, bindingPower(current));
1348
- if (current.value === "and" || current.value === "or") {
1349
- return {
1350
- type: 14,
1351
- op: current.value,
1352
- left,
1353
- right
1354
- };
1355
- } else if (current.value === ".") {
1356
- if (right.type === 5) {
1357
- return {
1358
- type: 15,
1359
- obj: left,
1360
- key: right.value
1361
- };
1362
- } else {
1363
- throw new ParserError("invalid obj lookup");
1364
- }
1365
- }
1366
- let op = {
1367
- type: 7,
1368
- op: current.value,
1369
- left,
1370
- right
1371
- };
1372
- while (chainedOperators.has(current.value) && tokens[0] && tokens[0].type === 2 && chainedOperators.has(tokens[0].value)) {
1373
- const nextToken = tokens.shift();
1374
- op = {
1375
- type: 14,
1376
- op: "and",
1377
- left: op,
1378
- right: {
1379
- type: 7,
1380
- op: nextToken.value,
1381
- left: right,
1382
- right: _parse(tokens, bindingPower(nextToken))
1383
- }
1384
- };
1385
- right = op.right;
1386
- }
1387
- return op;
1388
- }
1389
- switch (current.value) {
1390
- case "(":
1391
- const args = [];
1392
- const kwargs = {};
1393
- while (tokens[0] && !isSymbol(tokens[0], ")")) {
1394
- const arg = _parse(tokens, 0);
1395
- if (arg.type === 9) {
1396
- kwargs[arg.name.value] = arg.value;
1397
- } else {
1398
- args.push(arg);
1399
- }
1400
- if (tokens[0] && isSymbol(tokens[0], ",")) {
1401
- tokens.shift();
1402
- }
1403
- }
1404
- if (!tokens[0] || !isSymbol(tokens[0], ")")) {
1405
- throw new ParserError("parsing error");
1406
- }
1407
- tokens.shift();
1408
- return { type: 8, fn: left, args, kwargs };
1409
- case "=":
1410
- if (left.type === 5) {
1411
- return {
1412
- type: 9,
1413
- name: left,
1414
- value: _parse(tokens, 10)
1415
- };
1416
- }
1417
- break;
1418
- case "[":
1419
- const key = _parse(tokens);
1420
- if (!tokens[0] || !isSymbol(tokens[0], "]")) {
1421
- throw new ParserError("parsing error");
1422
- }
1423
- tokens.shift();
1424
- return {
1425
- type: 12,
1426
- target: left,
1427
- key
1428
- };
1429
- case "if":
1430
- const condition = _parse(tokens);
1431
- if (!tokens[0] || !isSymbol(tokens[0], "else")) {
1432
- throw new ParserError("parsing error");
1433
- }
1434
- tokens.shift();
1435
- const ifFalse = _parse(tokens);
1436
- return {
1437
- type: 13,
1438
- condition,
1439
- ifTrue: left,
1440
- ifFalse
1441
- };
1442
- default:
1443
- break;
1444
- }
1445
- }
1446
- throw new ParserError("Token cannot be parsed");
1447
- }
1448
- function _parse(tokens, bp2 = 0) {
1449
- const token = tokens.shift();
1450
- if (!token) {
1451
- throw new ParserError("Unexpected end of input");
1452
- }
1453
- let expr = parsePrefix(token, tokens);
1454
- while (tokens[0] && bindingPower(tokens[0]) > bp2) {
1455
- expr = parseInfix(expr, tokens.shift(), tokens);
1456
- }
1457
- return expr;
1458
- }
1459
- function parse(tokens) {
1460
- if (tokens.length) {
1461
- return _parse(tokens, 0);
1462
- }
1463
- throw new ParserError("Missing token");
1464
- }
1465
- function parseArgs(args, spec) {
1466
- const last = args[args.length - 1];
1467
- const unnamedArgs = typeof last === "object" ? args.slice(0, -1) : args;
1468
- const kwargs = typeof last === "object" ? last : {};
1469
- for (const [index, val] of unnamedArgs.entries()) {
1470
- kwargs[spec[index]] = val;
1471
- }
1472
- return kwargs;
1473
- }
1474
-
1475
- // src/utils/domain/py_date.ts
1476
- var AssertionError = class extends Error {
1477
- };
1478
- var ValueError = class extends Error {
1479
- };
1480
- var NotSupportedError = class extends Error {
1481
- };
1482
- function fmt2(n) {
1483
- return String(n).padStart(2, "0");
1484
- }
1485
- function fmt4(n) {
1486
- return String(n).padStart(4, "0");
1487
- }
1488
- function divmod(a, b, fn) {
1489
- let mod = a % b;
1490
- if (mod > 0 && b < 0 || mod < 0 && b > 0) {
1491
- mod += b;
1492
- }
1493
- return fn(Math.floor(a / b), mod);
1494
- }
1495
- function assert(bool, message = "AssertionError") {
1496
- if (!bool) {
1497
- throw new AssertionError(message);
1498
- }
1499
- }
1500
- var DAYS_IN_MONTH = [
1501
- null,
1502
- 31,
1503
- 28,
1504
- 31,
1505
- 30,
1506
- 31,
1507
- 30,
1508
- 31,
1509
- 31,
1510
- 30,
1511
- 31,
1512
- 30,
1513
- 31
1514
- ];
1515
- var DAYS_BEFORE_MONTH = [null];
1516
- for (let dbm = 0, i = 1; i < DAYS_IN_MONTH.length; ++i) {
1517
- DAYS_BEFORE_MONTH.push(dbm);
1518
- dbm += DAYS_IN_MONTH[i];
1519
- }
1520
- function daysInMonth(year, month) {
1521
- if (month === 2 && isLeap(year)) {
1522
- return 29;
1523
- }
1524
- return DAYS_IN_MONTH[month];
1525
- }
1526
- function isLeap(year) {
1527
- return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
1528
- }
1529
- function daysBeforeYear(year) {
1530
- const y = year - 1;
1531
- return y * 365 + Math.floor(y / 4) - Math.floor(y / 100) + Math.floor(y / 400);
1532
- }
1533
- function daysBeforeMonth(year, month) {
1534
- const postLeapFeb = month > 2 && isLeap(year);
1535
- return DAYS_BEFORE_MONTH[month] + (postLeapFeb ? 1 : 0);
1536
- }
1537
- function ymd2ord(year, month, day) {
1538
- const dim = daysInMonth(year, month);
1539
- if (!(1 <= day && day <= dim)) {
1540
- throw new ValueError(`day must be in 1..${dim}`);
1541
- }
1542
- return daysBeforeYear(year) + daysBeforeMonth(year, month) + day;
1543
- }
1544
- var DI400Y = daysBeforeYear(401);
1545
- var DI100Y = daysBeforeYear(101);
1546
- var DI4Y = daysBeforeYear(5);
1547
- function ord2ymd(n) {
1548
- --n;
1549
- let n400 = 0, n100 = 0, n4 = 0, n1 = 0, n0 = 0;
1550
- divmod(n, DI400Y, (_n400, n2) => {
1551
- n400 = _n400;
1552
- divmod(n2, DI100Y, (_n100, n3) => {
1553
- n100 = _n100;
1554
- divmod(n3, DI4Y, (_n4, n5) => {
1555
- n4 = _n4;
1556
- divmod(n5, 365, (_n1, n6) => {
1557
- n1 = _n1;
1558
- n0 = n6;
1559
- });
1560
- });
1561
- });
1562
- });
1563
- n = n0;
1564
- const year = n400 * 400 + 1 + n100 * 100 + n4 * 4 + n1;
1565
- if (n1 === 4 || n100 === 100) {
1566
- assert(n0 === 0);
1567
- return {
1568
- year: year - 1,
1569
- month: 12,
1570
- day: 31
1571
- };
1572
- }
1573
- const leapyear = n1 === 3 && (n4 !== 24 || n100 === 3);
1574
- assert(leapyear === isLeap(year));
1575
- let month = n + 50 >> 5;
1576
- let preceding = DAYS_BEFORE_MONTH[month] + (month > 2 && leapyear ? 1 : 0);
1577
- if (preceding > n) {
1578
- --month;
1579
- preceding -= DAYS_IN_MONTH[month] + (month === 2 && leapyear ? 1 : 0);
1580
- }
1581
- n -= preceding;
1582
- return {
1583
- year,
1584
- month,
1585
- day: n + 1
1586
- };
1587
- }
1588
- function tmxxx(year, month, day, hour, minute, second, microsecond) {
1589
- hour = hour || 0;
1590
- minute = minute || 0;
1591
- second = second || 0;
1592
- microsecond = microsecond || 0;
1593
- if (microsecond < 0 || microsecond > 999999) {
1594
- divmod(microsecond, 1e6, (carry, ms) => {
1595
- microsecond = ms;
1596
- second += carry;
1597
- });
1598
- }
1599
- if (second < 0 || second > 59) {
1600
- divmod(second, 60, (carry, s) => {
1601
- second = s;
1602
- minute += carry;
1603
- });
1604
- }
1605
- if (minute < 0 || minute > 59) {
1606
- divmod(minute, 60, (carry, m) => {
1607
- minute = m;
1608
- hour += carry;
1609
- });
1610
- }
1611
- if (hour < 0 || hour > 23) {
1612
- divmod(hour, 24, (carry, h) => {
1613
- hour = h;
1614
- day += carry;
1615
- });
1616
- }
1617
- if (month < 1 || month > 12) {
1618
- divmod(month - 1, 12, (carry, m) => {
1619
- month = m + 1;
1620
- year += carry;
1621
- });
1622
- }
1623
- const dim = daysInMonth(year, month);
1624
- if (day < 1 || day > dim) {
1625
- if (day === 0) {
1626
- --month;
1627
- if (month > 0) {
1628
- day = daysInMonth(year, month);
1629
- } else {
1630
- --year;
1631
- month = 12;
1632
- day = 31;
1633
- }
1634
- } else if (day === dim + 1) {
1635
- ++month;
1636
- day = 1;
1637
- if (month > 12) {
1638
- month = 1;
1639
- ++year;
1640
- }
1641
- } else {
1642
- const r = ord2ymd(ymd2ord(year, month, 1) + (day - 1));
1643
- year = r.year;
1644
- month = r.month;
1645
- day = r.day;
1646
- }
1647
- }
1648
- return {
1649
- year,
1650
- month,
1651
- day,
1652
- hour,
1653
- minute,
1654
- second,
1655
- microsecond
1656
- };
1657
- }
1658
- var PyDate = class _PyDate {
1659
- constructor(year, month, day) {
1660
- this.year = year;
1661
- this.month = month;
1662
- this.day = day;
1663
- }
1664
- static today() {
1665
- return this.convertDate(/* @__PURE__ */ new Date());
1666
- }
1667
- static convertDate(date) {
1668
- const year = date.getFullYear();
1669
- const month = date.getMonth() + 1;
1670
- const day = date.getDate();
1671
- return new _PyDate(year, month, day);
1672
- }
1673
- static create(...args) {
1674
- const { year, month, day } = parseArgs(args, ["year", "month", "day"]);
1675
- return new _PyDate(year, month, day);
1676
- }
1677
- add(timedelta) {
1678
- const s = tmxxx(this.year, this.month, this.day + timedelta.days, 0, 0, 0);
1679
- return new _PyDate(s.year, s.month, s.day);
1680
- }
1681
- isEqual(other) {
1682
- if (!(other instanceof _PyDate)) {
1683
- return false;
1684
- }
1685
- return this.year === other.year && this.month === other.month && this.day === other.day;
1686
- }
1687
- strftime(format) {
1688
- return format.replace(/%([A-Za-z])/g, (m, c) => {
1689
- switch (c) {
1690
- case "Y":
1691
- return fmt4(this.year);
1692
- case "m":
1693
- return fmt2(this.month);
1694
- case "d":
1695
- return fmt2(this.day);
1696
- default:
1697
- throw new ValueError(`No known conversion for ${m}`);
1698
- }
1699
- });
1700
- }
1701
- substract(other) {
1702
- if (other instanceof PyTimeDelta) {
1703
- return this.add(other.negate());
1704
- }
1705
- if (other instanceof _PyDate) {
1706
- return PyTimeDelta.create(this.toordinal() - other.toordinal());
1707
- }
1708
- throw new NotSupportedError();
1709
- }
1710
- toJSON() {
1711
- return this.strftime("%Y-%m-%d");
1712
- }
1713
- toordinal() {
1714
- return ymd2ord(this.year, this.month, this.day);
1715
- }
1716
- };
1717
- var PyDateTime = class _PyDateTime {
1718
- constructor(year, month, day, hour, minute, second, microsecond) {
1719
- this.year = year;
1720
- this.month = month;
1721
- this.day = day;
1722
- this.hour = hour;
1723
- this.minute = minute;
1724
- this.second = second;
1725
- this.microsecond = microsecond;
1726
- }
1727
- static now() {
1728
- return this.convertDate(/* @__PURE__ */ new Date());
1729
- }
1730
- static convertDate(date) {
1731
- const year = date.getFullYear();
1732
- const month = date.getMonth() + 1;
1733
- const day = date.getDate();
1734
- const hour = date.getHours();
1735
- const minute = date.getMinutes();
1736
- const second = date.getSeconds();
1737
- return new _PyDateTime(year, month, day, hour, minute, second, 0);
1738
- }
1739
- static create(...args) {
1740
- const namedArgs = parseArgs(args, [
1741
- "year",
1742
- "month",
1743
- "day",
1744
- "hour",
1745
- "minute",
1746
- "second",
1747
- "microsecond"
1748
- ]);
1749
- const year = namedArgs.year;
1750
- const month = namedArgs.month;
1751
- const day = namedArgs.day;
1752
- const hour = namedArgs.hour || 0;
1753
- const minute = namedArgs.minute || 0;
1754
- const second = namedArgs.second || 0;
1755
- const ms = namedArgs.microsecond / 1e3 || 0;
1756
- return new _PyDateTime(year, month, day, hour, minute, second, ms);
1757
- }
1758
- static combine(...args) {
1759
- const { date, time } = parseArgs(args, ["date", "time"]);
1760
- return _PyDateTime.create(
1761
- date.year,
1762
- date.month,
1763
- date.day,
1764
- time.hour,
1765
- time.minute,
1766
- time.second
1767
- );
1768
- }
1769
- add(timedelta) {
1770
- const s = tmxxx(
1771
- this.year,
1772
- this.month,
1773
- this.day + timedelta.days,
1774
- this.hour,
1775
- this.minute,
1776
- this.second + timedelta.seconds,
1777
- this.microsecond + timedelta.microseconds
1778
- );
1779
- return new _PyDateTime(
1780
- s.year,
1781
- s.month,
1782
- s.day,
1783
- s.hour,
1784
- s.minute,
1785
- s.second,
1786
- s.microsecond
1787
- );
1788
- }
1789
- isEqual(other) {
1790
- if (!(other instanceof _PyDateTime)) {
1791
- return false;
1792
- }
1793
- return this.year === other.year && this.month === other.month && this.day === other.day && this.hour === other.hour && this.minute === other.minute && this.second === other.second && this.microsecond === other.microsecond;
1794
- }
1795
- strftime(format) {
1796
- return format.replace(/%([A-Za-z])/g, (m, c) => {
1797
- switch (c) {
1798
- case "Y":
1799
- return fmt4(this.year);
1800
- case "m":
1801
- return fmt2(this.month);
1802
- case "d":
1803
- return fmt2(this.day);
1804
- case "H":
1805
- return fmt2(this.hour);
1806
- case "M":
1807
- return fmt2(this.minute);
1808
- case "S":
1809
- return fmt2(this.second);
1810
- default:
1811
- throw new ValueError(`No known conversion for ${m}`);
1812
- }
1813
- });
1814
- }
1815
- substract(timedelta) {
1816
- return this.add(timedelta.negate());
1817
- }
1818
- toJSON() {
1819
- return this.strftime("%Y-%m-%d %H:%M:%S");
1820
- }
1821
- to_utc() {
1822
- const d = new Date(
1823
- this.year,
1824
- this.month - 1,
1825
- this.day,
1826
- this.hour,
1827
- this.minute,
1828
- this.second
1829
- );
1830
- const timedelta = PyTimeDelta.create({ minutes: d.getTimezoneOffset() });
1831
- return this.add(timedelta);
1832
- }
1833
- };
1834
- var PyTime = class _PyTime extends PyDate {
1835
- constructor(hour, minute, second) {
1836
- const now = /* @__PURE__ */ new Date();
1837
- const year = now.getFullYear();
1838
- const month = now.getMonth() + 1;
1839
- const day = now.getDate();
1840
- super(year, month, day);
1841
- this.hour = hour;
1842
- this.minute = minute;
1843
- this.second = second;
1844
- this.hour = hour;
1845
- this.minute = minute;
1846
- this.second = second;
1847
- }
1848
- static create(...args) {
1849
- const namedArgs = parseArgs(args, ["hour", "minute", "second"]);
1850
- const hour = namedArgs.hour || 0;
1851
- const minute = namedArgs.minute || 0;
1852
- const second = namedArgs.second || 0;
1853
- return new _PyTime(hour, minute, second);
1854
- }
1855
- strftime(format) {
1856
- return format.replace(/%([A-Za-z])/g, (m, c) => {
1857
- switch (c) {
1858
- case "Y":
1859
- return fmt4(this.year);
1860
- case "m":
1861
- return fmt2(this.month);
1862
- case "d":
1863
- return fmt2(this.day);
1864
- case "H":
1865
- return fmt2(this.hour);
1866
- case "M":
1867
- return fmt2(this.minute);
1868
- case "S":
1869
- return fmt2(this.second);
1870
- default:
1871
- throw new ValueError(`No known conversion for ${m}`);
1872
- }
1873
- });
1874
- }
1875
- toJSON() {
1876
- return this.strftime("%H:%M:%S");
1877
- }
1878
- };
1879
- var DAYS_IN_YEAR = [
1880
- 31,
1881
- 59,
1882
- 90,
1883
- 120,
1884
- 151,
1885
- 181,
1886
- 212,
1887
- 243,
1888
- 273,
1889
- 304,
1890
- 334,
1891
- 366
1892
- ];
1893
- var TIME_PERIODS = ["hour", "minute", "second"];
1894
- var PERIODS = ["year", "month", "day", ...TIME_PERIODS];
1895
- var RELATIVE_KEYS = "years months weeks days hours minutes seconds microseconds leapdays".split(
1896
- " "
1897
- );
1898
- var ABSOLUTE_KEYS = "year month day hour minute second microsecond weekday nlyearday yearday".split(
1899
- " "
1900
- );
1901
- var argsSpec = ["dt1", "dt2"];
1902
- var PyRelativeDelta = class _PyRelativeDelta {
1903
- static create(...args) {
1904
- const params = parseArgs(args, argsSpec);
1905
- if ("dt1" in params) {
1906
- throw new Error("relativedelta(dt1, dt2) is not supported for now");
1907
- }
1908
- for (const period of PERIODS) {
1909
- if (period in params) {
1910
- const val = params[period];
1911
- assert(val >= 0, `${period} ${val} is out of range`);
1912
- }
1913
- }
1914
- for (const key of RELATIVE_KEYS) {
1915
- params[key] = params[key] || 0;
1916
- }
1917
- for (const key of ABSOLUTE_KEYS) {
1918
- params[key] = key in params ? params[key] : null;
1919
- }
1920
- params.days += 7 * params.weeks;
1921
- let yearDay = 0;
1922
- if (params.nlyearday) {
1923
- yearDay = params.nlyearday;
1924
- } else if (params.yearday) {
1925
- yearDay = params.yearday;
1926
- if (yearDay > 59) {
1927
- params.leapDays = -1;
1928
- }
1929
- }
1930
- if (yearDay) {
1931
- for (let monthIndex = 0; monthIndex < DAYS_IN_YEAR.length; monthIndex++) {
1932
- if (yearDay <= DAYS_IN_YEAR[monthIndex]) {
1933
- params.month = monthIndex + 1;
1934
- if (monthIndex === 0) {
1935
- params.day = yearDay;
1936
- } else {
1937
- params.day = yearDay - DAYS_IN_YEAR[monthIndex - 1];
1938
- }
1939
- break;
1940
- }
1941
- }
1942
- }
1943
- return new _PyRelativeDelta(params);
1944
- }
1945
- static add(date, delta) {
1946
- if (!(date instanceof PyDate || date instanceof PyDateTime)) {
1947
- throw new NotSupportedError();
1948
- }
1949
- const s = tmxxx(
1950
- (delta.year || date.year) + delta.years,
1951
- (delta.month || date.month) + delta.months,
1952
- delta.day || date.day,
1953
- delta.hour || (date instanceof PyDateTime ? date.hour : 0),
1954
- delta.minute || (date instanceof PyDateTime ? date.minute : 0),
1955
- delta.second || (date instanceof PyDateTime ? date.second : 0),
1956
- delta.microseconds || (date instanceof PyDateTime ? date.microsecond : 0)
1957
- );
1958
- const newDateTime = new PyDateTime(
1959
- s.year,
1960
- s.month,
1961
- s.day,
1962
- s.hour,
1963
- s.minute,
1964
- s.second,
1965
- s.microsecond
1966
- );
1967
- let leapDays = 0;
1968
- if (delta.leapDays && newDateTime.month > 2 && isLeap(newDateTime.year)) {
1969
- leapDays = delta.leapDays;
1970
- }
1971
- const temp = newDateTime.add(
1972
- PyTimeDelta.create({
1973
- days: delta.days + leapDays,
1974
- hours: delta.hours,
1975
- minutes: delta.minutes,
1976
- seconds: delta.seconds,
1977
- microseconds: delta.microseconds
1978
- })
1979
- );
1980
- const hasTime = Boolean(
1981
- temp.hour || temp.minute || temp.second || temp.microsecond
1982
- );
1983
- const returnDate = !hasTime && date instanceof PyDate ? new PyDate(temp.year, temp.month, temp.day) : temp;
1984
- if (delta.weekday !== null) {
1985
- const wantedDow = delta.weekday + 1;
1986
- const _date = new Date(
1987
- returnDate.year,
1988
- returnDate.month - 1,
1989
- returnDate.day
1990
- );
1991
- const days = (7 - _date.getDay() + wantedDow) % 7;
1992
- return returnDate.add(new PyTimeDelta(days, 0, 0));
1993
- }
1994
- return returnDate;
1995
- }
1996
- static substract(date, delta) {
1997
- return _PyRelativeDelta.add(date, delta.negate());
1998
- }
1999
- constructor(params = {}, sign = 1) {
2000
- this.years = sign * params.years;
2001
- this.months = sign * params.months;
2002
- this.days = sign * params.days;
2003
- this.hours = sign * params.hours;
2004
- this.minutes = sign * params.minutes;
2005
- this.seconds = sign * params.seconds;
2006
- this.microseconds = sign * params.microseconds;
2007
- this.leapDays = params.leapDays;
2008
- this.year = params.year;
2009
- this.month = params.month;
2010
- this.day = params.day;
2011
- this.hour = params.hour;
2012
- this.minute = params.minute;
2013
- this.second = params.second;
2014
- this.microsecond = params.microsecond;
2015
- this.weekday = params.weekday;
2016
- }
2017
- years;
2018
- months;
2019
- days;
2020
- hours;
2021
- minutes;
2022
- seconds;
2023
- microseconds;
2024
- leapDays;
2025
- year;
2026
- month;
2027
- day;
2028
- hour;
2029
- minute;
2030
- second;
2031
- microsecond;
2032
- weekday;
2033
- negate() {
2034
- return new _PyRelativeDelta(this, -1);
2035
- }
2036
- isEqual() {
2037
- throw new NotSupportedError();
2038
- }
2039
- };
2040
- var TIME_DELTA_KEYS = "weeks days hours minutes seconds milliseconds microseconds".split(" ");
2041
- function modf(x) {
2042
- const mod = x % 1;
2043
- return [mod < 0 ? mod + 1 : mod, Math.floor(x)];
2044
- }
2045
- var PyTimeDelta = class _PyTimeDelta {
2046
- constructor(days, seconds, microseconds) {
2047
- this.days = days;
2048
- this.seconds = seconds;
2049
- this.microseconds = microseconds;
2050
- }
2051
- static create(...args) {
2052
- const namedArgs = parseArgs(args, ["days", "seconds", "microseconds"]);
2053
- for (const key of TIME_DELTA_KEYS) {
2054
- namedArgs[key] = namedArgs[key] || 0;
2055
- }
2056
- let d = 0;
2057
- let s = 0;
2058
- let us = 0;
2059
- const days = namedArgs.days + namedArgs.weeks * 7;
2060
- let seconds = namedArgs.seconds + 60 * namedArgs.minutes + 3600 * namedArgs.hours;
2061
- let microseconds = namedArgs.microseconds + 1e3 * namedArgs.milliseconds;
2062
- const [dFrac, dInt] = modf(days);
2063
- d = dInt;
2064
- let daysecondsfrac = 0;
2065
- if (dFrac) {
2066
- const [dsFrac, dsInt] = modf(dFrac * 24 * 3600);
2067
- s = dsInt;
2068
- daysecondsfrac = dsFrac;
2069
- }
2070
- const [sFrac, sInt] = modf(seconds);
2071
- seconds = sInt;
2072
- const secondsfrac = sFrac + daysecondsfrac;
2073
- divmod(seconds, 24 * 3600, (days2, seconds2) => {
2074
- d += days2;
2075
- s += seconds2;
2076
- });
2077
- microseconds += secondsfrac * 1e6;
2078
- divmod(microseconds, 1e6, (seconds2, microseconds2) => {
2079
- divmod(seconds2, 24 * 3600, (days2, seconds3) => {
2080
- d += days2;
2081
- s += seconds3;
2082
- us += Math.round(microseconds2);
2083
- });
2084
- });
2085
- return new _PyTimeDelta(d, s, us);
2086
- }
2087
- add(other) {
2088
- return _PyTimeDelta.create({
2089
- days: this.days + other.days,
2090
- seconds: this.seconds + other.seconds,
2091
- microseconds: this.microseconds + other.microseconds
2092
- });
2093
- }
2094
- divide(n) {
2095
- const us = (this.days * 24 * 3600 + this.seconds) * 1e6 + this.microseconds;
2096
- return _PyTimeDelta.create({ microseconds: Math.floor(us / n) });
2097
- }
2098
- isEqual(other) {
2099
- if (!(other instanceof _PyTimeDelta)) {
2100
- return false;
2101
- }
2102
- return this.days === other.days && this.seconds === other.seconds && this.microseconds === other.microseconds;
2103
- }
2104
- isTrue() {
2105
- return this.days !== 0 || this.seconds !== 0 || this.microseconds !== 0;
2106
- }
2107
- multiply(n) {
2108
- return _PyTimeDelta.create({
2109
- days: n * this.days,
2110
- seconds: n * this.seconds,
2111
- microseconds: n * this.microseconds
2112
- });
2113
- }
2114
- negate() {
2115
- return _PyTimeDelta.create({
2116
- days: -this.days,
2117
- seconds: -this.seconds,
2118
- microseconds: -this.microseconds
2119
- });
2120
- }
2121
- substract(other) {
2122
- return _PyTimeDelta.create({
2123
- days: this.days - other.days,
2124
- seconds: this.seconds - other.seconds,
2125
- microseconds: this.microseconds - other.microseconds
2126
- });
2127
- }
2128
- total_seconds() {
2129
- return this.days * 86400 + this.seconds + this.microseconds / 1e6;
2130
- }
2131
- };
2132
-
2133
- // src/utils/domain/py_builtin.ts
2134
- var EvaluationError = class extends Error {
2135
- constructor(message) {
2136
- super(message);
2137
- this.name = "EvaluationError";
2138
- }
2139
- };
2140
- function execOnIterable(iterable, func) {
2141
- if (iterable === null) {
2142
- throw new EvaluationError("value not iterable");
2143
- }
2144
- if (typeof iterable === "object" && !Array.isArray(iterable) && !(iterable instanceof Set)) {
2145
- iterable = Object.keys(iterable);
2146
- }
2147
- if (typeof iterable?.[Symbol.iterator] !== "function") {
2148
- throw new EvaluationError("value not iterable");
2149
- }
2150
- return func(iterable);
2151
- }
2152
- var BUILTINS = {
2153
- /**
2154
- * @param {any} value
2155
- * @returns {boolean}
2156
- */
2157
- bool(value) {
2158
- switch (typeof value) {
2159
- case "number":
2160
- return value !== 0;
2161
- case "string":
2162
- return value !== "";
2163
- case "boolean":
2164
- return value;
2165
- case "object":
2166
- if (value === null || value === void 0) {
2167
- return false;
2168
- }
2169
- if ("isTrue" in value && typeof value.isTrue === "function") {
2170
- return value.isTrue();
2171
- }
2172
- if (value instanceof Array) {
2173
- return !!value.length;
2174
- }
2175
- if (value instanceof Set) {
2176
- return !!value.size;
2177
- }
2178
- return Object.keys(value).length !== 0;
2179
- default:
2180
- return true;
2181
- }
2182
- },
2183
- set(iterable) {
2184
- if (arguments.length > 2) {
2185
- throw new EvaluationError(
2186
- `set expected at most 1 argument, got (${arguments.length - 1})`
2187
- );
2188
- }
2189
- return execOnIterable(
2190
- iterable,
2191
- (iterable2) => new Set(iterable2)
2192
- );
2193
- },
2194
- time: {
2195
- strftime(format) {
2196
- return PyDateTime.now().strftime(format);
2197
- }
2198
- },
2199
- context_today() {
2200
- return PyDate.today();
2201
- },
2202
- get current_date() {
2203
- return this.today;
2204
- },
2205
- get today() {
2206
- return PyDate.today().strftime("%Y-%m-%d");
2207
- },
2208
- get now() {
2209
- return PyDateTime.now().strftime("%Y-%m-%d %H:%M:%S");
2210
- },
2211
- datetime: {
2212
- time: PyTime,
2213
- timedelta: PyTimeDelta,
2214
- datetime: PyDateTime,
2215
- date: PyDate
2216
- },
2217
- relativedelta: PyRelativeDelta,
2218
- true: true,
2219
- false: false
2220
- };
2221
-
2222
- // src/utils/domain/py_utils.ts
2223
- function toPyValue(value) {
2224
- switch (typeof value) {
2225
- case "string":
2226
- return { type: 1, value };
2227
- case "number":
2228
- return { type: 0, value };
2229
- case "boolean":
2230
- return { type: 2, value };
2231
- case "object":
2232
- if (Array.isArray(value)) {
2233
- return { type: 4, value: value.map(toPyValue) };
2234
- } else if (value === null) {
2235
- return {
2236
- type: 3
2237
- /* None */
2238
- };
2239
- } else if (value instanceof Date) {
2240
- return {
2241
- type: 1,
2242
- value: String(PyDateTime.convertDate(value))
2243
- };
2244
- } else if (value instanceof PyDate || value instanceof PyDateTime) {
2245
- return { type: 1, value };
2246
- } else {
2247
- const content = {};
2248
- for (const key in value) {
2249
- content[key] = toPyValue(value[key]);
2250
- }
2251
- return { type: 11, value: content };
2252
- }
2253
- default:
2254
- throw new Error("Invalid type");
2255
- }
2256
- }
2257
- function formatAST(ast, lbp = 0) {
2258
- switch (ast.type) {
2259
- case 3:
2260
- return "None";
2261
- case 1:
2262
- return JSON.stringify(ast.value);
2263
- case 0:
2264
- return String(ast.value);
2265
- case 2:
2266
- return ast.value ? "True" : "False";
2267
- case 4:
2268
- return `[${ast.value.map(formatAST).join(", ")}]`;
2269
- case 6:
2270
- if (ast.op === "not") {
2271
- return `not ${formatAST(ast.right, 50)}`;
2272
- }
2273
- return `${ast.op}${formatAST(ast.right, 130)}`;
2274
- case 7:
2275
- const abp = bp(ast.op);
2276
- const binaryStr = `${formatAST(ast.left, abp)} ${ast.op} ${formatAST(ast.right, abp)}`;
2277
- return abp < lbp ? `(${binaryStr})` : binaryStr;
2278
- case 11:
2279
- const pairs = [];
2280
- for (const k in ast.value) {
2281
- pairs.push(`"${k}": ${formatAST(ast.value[k])}`);
2282
- }
2283
- return `{${pairs.join(", ")}}`;
2284
- case 10:
2285
- return `(${ast.value.map(formatAST).join(", ")})`;
2286
- case 5:
2287
- return ast.value;
2288
- case 12:
2289
- return `${formatAST(ast.target)}[${formatAST(ast.key)}]`;
2290
- case 13:
2291
- const { ifTrue, condition, ifFalse } = ast;
2292
- return `${formatAST(ifTrue)} if ${formatAST(condition)} else ${formatAST(ifFalse)}`;
2293
- case 14:
2294
- const boolAbp = bp(ast.op);
2295
- const boolStr = `${formatAST(ast.left, boolAbp)} ${ast.op} ${formatAST(ast.right, boolAbp)}`;
2296
- return boolAbp < lbp ? `(${boolStr})` : boolStr;
2297
- case 15:
2298
- return `${formatAST(ast.obj, 150)}.${ast.key}`;
2299
- case 8:
2300
- const args = ast.args.map(formatAST);
2301
- const kwargs = [];
2302
- for (const kwarg in ast.kwargs) {
2303
- kwargs.push(`${kwarg} = ${formatAST(ast.kwargs[kwarg])}`);
2304
- }
2305
- const argStr = args.concat(kwargs).join(", ");
2306
- return `${formatAST(ast.fn)}(${argStr})`;
2307
- default:
2308
- throw new Error("invalid expression: " + JSON.stringify(ast));
2309
- }
2310
- }
2311
- var PY_DICT = /* @__PURE__ */ Object.create(null);
2312
- function toPyDict(obj) {
2313
- return new Proxy(obj, {
2314
- getPrototypeOf() {
2315
- return PY_DICT;
2316
- }
2317
- });
2318
- }
2319
-
2320
- // src/utils/domain/py_interpreter.ts
2321
- var isTrue = BUILTINS.bool;
2322
- function applyUnaryOp(ast, context) {
2323
- const value = evaluate(ast.right, context);
2324
- switch (ast.op) {
2325
- case "-":
2326
- if (value instanceof Object && "negate" in value) {
2327
- return value.negate();
2328
- }
2329
- return -value;
2330
- case "+":
2331
- return value;
2332
- case "not":
2333
- return !isTrue(value);
2334
- default:
2335
- throw new EvaluationError(`Unknown unary operator: ${ast.op}`);
2336
- }
2337
- }
2338
- function pytypeIndex(val) {
2339
- switch (typeof val) {
2340
- case "object":
2341
- return val === null ? 1 : Array.isArray(val) ? 5 : 3;
2342
- case "number":
2343
- return 2;
2344
- case "string":
2345
- return 4;
2346
- default:
2347
- throw new EvaluationError(`Unknown type: ${typeof val}`);
2348
- }
2349
- }
2350
- function isLess(left, right) {
2351
- if (typeof left === "number" && typeof right === "number") {
2352
- return left < right;
2353
- }
2354
- if (typeof left === "boolean") {
2355
- left = left ? 1 : 0;
2356
- }
2357
- if (typeof right === "boolean") {
2358
- right = right ? 1 : 0;
2359
- }
2360
- const leftIndex = pytypeIndex(left);
2361
- const rightIndex = pytypeIndex(right);
2362
- if (leftIndex === rightIndex) {
2363
- return left < right;
2364
- }
2365
- return leftIndex < rightIndex;
2366
- }
2367
- function isEqual(left, right) {
2368
- if (typeof left !== typeof right) {
2369
- if (typeof left === "boolean" && typeof right === "number") {
2370
- return right === (left ? 1 : 0);
2371
- }
2372
- if (typeof left === "number" && typeof right === "boolean") {
2373
- return left === (right ? 1 : 0);
2374
- }
2375
- return false;
2376
- }
2377
- if (left instanceof Object && "isEqual" in left) {
2378
- return left.isEqual(right);
2379
- }
2380
- return left === right;
2381
- }
2382
- function isIn(left, right) {
2383
- if (Array.isArray(right)) {
2384
- return right.includes(left);
2385
- }
2386
- if (typeof right === "string" && typeof left === "string") {
2387
- return right.includes(left);
2388
- }
2389
- if (typeof right === "object") {
2390
- return left in right;
2391
- }
2392
- return false;
2393
- }
2394
- function applyBinaryOp(ast, context) {
2395
- const left = evaluate(ast.left, context);
2396
- const right = evaluate(ast.right, context);
2397
- switch (ast.op) {
2398
- case "+": {
2399
- const relativeDeltaOnLeft = left instanceof PyRelativeDelta;
2400
- const relativeDeltaOnRight = right instanceof PyRelativeDelta;
2401
- if (relativeDeltaOnLeft || relativeDeltaOnRight) {
2402
- const date = relativeDeltaOnLeft ? right : left;
2403
- const delta = relativeDeltaOnLeft ? left : right;
2404
- return PyRelativeDelta.add(date, delta);
2405
- }
2406
- const timeDeltaOnLeft = left instanceof PyTimeDelta;
2407
- const timeDeltaOnRight = right instanceof PyTimeDelta;
2408
- if (timeDeltaOnLeft && timeDeltaOnRight) {
2409
- return left.add(right);
2410
- }
2411
- if (timeDeltaOnLeft) {
2412
- if (right instanceof PyDate || right instanceof PyDateTime) {
2413
- return right.add(left);
2414
- } else {
2415
- throw new NotSupportedError();
2416
- }
2417
- }
2418
- if (timeDeltaOnRight) {
2419
- if (left instanceof PyDate || left instanceof PyDateTime) {
2420
- return left.add(right);
2421
- } else {
2422
- throw new NotSupportedError();
2423
- }
2424
- }
2425
- if (left instanceof Array && right instanceof Array) {
2426
- return [...left, ...right];
2427
- }
2428
- return left + right;
2429
- }
2430
- case "-": {
2431
- const isRightDelta = right instanceof PyRelativeDelta;
2432
- if (isRightDelta) {
2433
- return PyRelativeDelta.substract(left, right);
2434
- }
2435
- const timeDeltaOnRight = right instanceof PyTimeDelta;
2436
- if (timeDeltaOnRight) {
2437
- if (left instanceof PyTimeDelta) {
2438
- return left.substract(right);
2439
- } else if (left instanceof PyDate || left instanceof PyDateTime) {
2440
- return left.substract(right);
2441
- } else {
2442
- throw new NotSupportedError();
2443
- }
2444
- }
2445
- if (left instanceof PyDate) {
2446
- return left.substract(right);
2447
- }
2448
- return left - right;
2449
- }
2450
- case "*": {
2451
- const timeDeltaOnLeft = left instanceof PyTimeDelta;
2452
- const timeDeltaOnRight = right instanceof PyTimeDelta;
2453
- if (timeDeltaOnLeft || timeDeltaOnRight) {
2454
- const number = timeDeltaOnLeft ? right : left;
2455
- const delta = timeDeltaOnLeft ? left : right;
2456
- return delta.multiply(number);
2457
- }
2458
- return left * right;
2459
- }
2460
- case "/":
2461
- return left / right;
2462
- case "%":
2463
- return left % right;
2464
- case "//":
2465
- if (left instanceof PyTimeDelta) {
2466
- return left.divide(right);
2467
- }
2468
- return Math.floor(left / right);
2469
- case "**":
2470
- return left ** right;
2471
- case "==":
2472
- return isEqual(left, right);
2473
- case "<>":
2474
- case "!=":
2475
- return !isEqual(left, right);
2476
- case "<":
2477
- return isLess(left, right);
2478
- case ">":
2479
- return isLess(right, left);
2480
- case ">=":
2481
- return isEqual(left, right) || isLess(right, left);
2482
- case "<=":
2483
- return isEqual(left, right) || isLess(left, right);
2484
- case "in":
2485
- return isIn(left, right);
2486
- case "not in":
2487
- return !isIn(left, right);
2488
- default:
2489
- throw new EvaluationError(`Unknown binary operator: ${ast.op}`);
2490
- }
2491
- }
2492
- var DICT = {
2493
- get(...args) {
2494
- const { key, defValue } = parseArgs(args, ["key", "defValue"]);
2495
- const self = this;
2496
- if (key in self) {
2497
- return self[key];
2498
- } else if (defValue !== void 0) {
2499
- return defValue;
2500
- }
2501
- return null;
2502
- }
2503
- };
2504
- var STRING = {
2505
- lower() {
2506
- return this.toLowerCase();
2507
- },
2508
- upper() {
2509
- return this.toUpperCase();
2510
- }
2511
- };
2512
- function applyFunc(key, func, set, ...args) {
2513
- if (args.length === 1) {
2514
- return new Set(set);
2515
- }
2516
- if (args.length > 2) {
2517
- throw new EvaluationError(
2518
- `${key}: py_js supports at most 1 argument, got (${args.length - 1})`
2519
- );
2520
- }
2521
- return execOnIterable(args[0], func);
2522
- }
2523
- var SET = {
2524
- intersection(...args) {
2525
- return applyFunc(
2526
- "intersection",
2527
- (iterable) => {
2528
- const intersection = /* @__PURE__ */ new Set();
2529
- for (const i of iterable) {
2530
- if (this.has(i)) {
2531
- intersection.add(i);
2532
- }
2533
- }
2534
- return intersection;
2535
- },
2536
- this,
2537
- ...args
2538
- );
2539
- },
2540
- difference(...args) {
2541
- return applyFunc(
2542
- "difference",
2543
- (iterable) => {
2544
- iterable = new Set(iterable);
2545
- const difference = /* @__PURE__ */ new Set();
2546
- for (const e of this) {
2547
- if (!iterable.has(e)) {
2548
- difference.add(e);
2549
- }
2550
- }
2551
- return difference;
2552
- },
2553
- this,
2554
- ...args
2555
- );
2556
- },
2557
- union(...args) {
2558
- return applyFunc(
2559
- "union",
2560
- (iterable) => {
2561
- return /* @__PURE__ */ new Set([...this, ...iterable]);
2562
- },
2563
- this,
2564
- ...args
2565
- );
2566
- }
2567
- };
2568
- function methods(_class) {
2569
- return Object.getOwnPropertyNames(_class.prototype).map(
2570
- (prop) => _class.prototype[prop]
2571
- );
2572
- }
2573
- var allowedFns = /* @__PURE__ */ new Set([
2574
- BUILTINS.time.strftime,
2575
- BUILTINS.set,
2576
- BUILTINS.bool,
2577
- BUILTINS.context_today,
2578
- BUILTINS.datetime.datetime.now,
2579
- BUILTINS.datetime.datetime.combine,
2580
- BUILTINS.datetime.date.today,
2581
- ...methods(BUILTINS.relativedelta),
2582
- ...Object.values(BUILTINS.datetime).flatMap((obj) => methods(obj)),
2583
- ...Object.values(SET),
2584
- ...Object.values(DICT),
2585
- ...Object.values(STRING)
2586
- ]);
2587
- var unboundFn = /* @__PURE__ */ Symbol("unbound function");
2588
- function evaluate(ast, context = {}) {
2589
- const dicts = /* @__PURE__ */ new Set();
2590
- let pyContext;
2591
- const evalContext = Object.create(context);
2592
- if (!evalContext?.context) {
2593
- Object.defineProperty(evalContext, "context", {
2594
- get() {
2595
- if (!pyContext) {
2596
- pyContext = toPyDict(context);
2597
- }
2598
- return pyContext;
2599
- }
2600
- });
2601
- }
2602
- function _innerEvaluate(ast2) {
2603
- switch (ast2?.type) {
2604
- case 0:
2605
- // Number
2606
- case 1:
2607
- return ast2.value;
2608
- case 5:
2609
- if (ast2.value in evalContext) {
2610
- if (typeof evalContext[ast2.value] === "object" && evalContext[ast2.value]?.id && ast2?.value !== "parent") {
2611
- return evalContext[ast2.value]?.id;
2612
- }
2613
- return evalContext[ast2.value] ?? false;
2614
- } else if (ast2.value in BUILTINS) {
2615
- return BUILTINS[ast2.value];
2616
- } else {
2617
- return false;
2618
- }
2619
- case 3:
2620
- return null;
2621
- case 2:
2622
- return ast2.value;
2623
- case 6:
2624
- return applyUnaryOp(ast2, evalContext);
2625
- case 7:
2626
- return applyBinaryOp(ast2, evalContext);
2627
- case 14:
2628
- const left = _evaluate(ast2.left);
2629
- if (ast2.op === "and") {
2630
- return isTrue(left) ? _evaluate(ast2.right) : left;
2631
- } else {
2632
- return isTrue(left) ? left : _evaluate(ast2.right);
2633
- }
2634
- case 4:
2635
- // List
2636
- case 10:
2637
- return ast2.value.map(_evaluate);
2638
- case 11:
2639
- const dict = {};
2640
- for (const key2 in ast2.value) {
2641
- dict[key2] = _evaluate(ast2.value[key2]);
2642
- }
2643
- dicts.add(dict);
2644
- return dict;
2645
- case 8:
2646
- const fnValue = _evaluate(ast2.fn);
2647
- const args = ast2.args.map(_evaluate);
2648
- const kwargs = {};
2649
- for (const kwarg in ast2.kwargs) {
2650
- kwargs[kwarg] = _evaluate(ast2?.kwargs[kwarg]);
2651
- }
2652
- if (fnValue === PyDate || fnValue === PyDateTime || fnValue === PyTime || fnValue === PyRelativeDelta || fnValue === PyTimeDelta) {
2653
- return fnValue.create(...args, kwargs);
2654
- }
2655
- return fnValue(...args, kwargs);
2656
- case 12:
2657
- const dictVal = _evaluate(ast2.target);
2658
- const key = _evaluate(ast2.key);
2659
- return dictVal[key];
2660
- case 13:
2661
- if (isTrue(_evaluate(ast2.condition))) {
2662
- return _evaluate(ast2.ifTrue);
2663
- } else {
2664
- return _evaluate(ast2.ifFalse);
2665
- }
2666
- case 15:
2667
- let leftVal = _evaluate(ast2.obj);
2668
- let result;
2669
- if (dicts.has(leftVal) || Object.isPrototypeOf.call(PY_DICT, leftVal)) {
2670
- result = DICT[ast2.key];
2671
- } else if (typeof leftVal === "string") {
2672
- result = STRING[ast2.key];
2673
- } else if (leftVal instanceof Set) {
2674
- result = SET[ast2.key];
2675
- } else if (ast2.key === "get" && typeof leftVal === "object") {
2676
- result = DICT[ast2.key];
2677
- leftVal = toPyDict(leftVal);
2678
- } else if (typeof leftVal === "number") {
2679
- result = leftVal;
2680
- } else if (Array.isArray(leftVal[ast2.key])) {
2681
- result = leftVal[ast2.key]?.map(
2682
- (value) => value?.id ?? value
2683
- );
2684
- } else {
2685
- result = leftVal[ast2.key]?.id ?? leftVal[ast2.key] ?? false;
2686
- }
2687
- if (typeof result === "function") {
2688
- const bound = result.bind(leftVal);
2689
- bound[unboundFn] = result;
2690
- return bound;
2691
- }
2692
- return result;
2693
- default:
2694
- throw new EvaluationError(`AST of type ${ast2.type} cannot be evaluated`);
2695
- }
2696
- }
2697
- function _evaluate(ast2) {
2698
- const val = _innerEvaluate(ast2);
2699
- if (typeof val === "function" && !allowedFns.has(val) && !allowedFns.has(val[unboundFn])) {
2700
- throw new Error("Invalid Function Call");
2701
- }
2702
- return val;
2703
- }
2704
- return _evaluate(ast);
2705
- }
2706
-
2707
- // src/utils/domain/py.ts
2708
- function parseExpr(expr) {
2709
- const tokens = tokenize(expr);
2710
- return parse(tokens);
2711
- }
2712
-
2713
- // src/utils/domain/objects.ts
2714
- function shallowEqual(obj1, obj2, comparisonFn = (a, b) => a === b) {
2715
- if (!obj1 || !obj2 || typeof obj1 !== "object" || typeof obj2 !== "object") {
2716
- return obj1 === obj2;
2717
- }
2718
- const obj1Keys = Object.keys(obj1);
2719
- return obj1Keys.length === Object.keys(obj2).length && obj1Keys.every((key) => comparisonFn(obj1[key], obj2[key]));
2720
- }
2721
-
2722
- // src/utils/domain/arrays.ts
2723
- var shallowEqual2 = shallowEqual;
2724
-
2725
- // src/utils/domain/strings.ts
2726
- function escapeRegExp(str) {
2727
- return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2728
- }
2729
-
2730
- // src/utils/domain/domain.ts
2731
- var InvalidDomainError = class extends Error {
2732
- };
2733
- var Domain = class _Domain {
2734
- ast = { type: -1, value: null };
2735
- static TRUE;
2736
- static FALSE;
2737
- static combine(domains, operator) {
2738
- if (domains.length === 0) {
2739
- return new _Domain([]);
2740
- }
2741
- const domain1 = domains[0] instanceof _Domain ? domains[0] : new _Domain(domains[0]);
2742
- if (domains.length === 1) {
2743
- return domain1;
2744
- }
2745
- const domain2 = _Domain.combine(domains.slice(1), operator);
2746
- const result = new _Domain([]);
2747
- const astValues1 = domain1.ast.value;
2748
- const astValues2 = domain2.ast.value;
2749
- const op = operator === "AND" ? "&" : "|";
2750
- const combinedAST = {
2751
- type: 4,
2752
- value: astValues1.concat(astValues2)
2753
- };
2754
- result.ast = normalizeDomainAST(combinedAST, op);
2755
- return result;
2756
- }
2757
- static and(domains) {
2758
- return _Domain.combine(domains, "AND");
2759
- }
2760
- static or(domains) {
2761
- return _Domain.combine(domains, "OR");
2762
- }
2763
- static not(domain) {
2764
- const result = new _Domain(domain);
2765
- result.ast.value.unshift({ type: 1, value: "!" });
2766
- return result;
2767
- }
2768
- static removeDomainLeaves(domain, keysToRemove) {
2769
- function processLeaf(elements, idx, operatorCtx, newDomain2) {
2770
- const leaf = elements[idx];
2771
- if (leaf.type === 10) {
2772
- if (keysToRemove.includes(leaf.value[0].value)) {
2773
- if (operatorCtx === "&") {
2774
- newDomain2.ast.value.push(..._Domain.TRUE.ast.value);
2775
- } else if (operatorCtx === "|") {
2776
- newDomain2.ast.value.push(..._Domain.FALSE.ast.value);
2777
- }
2778
- } else {
2779
- newDomain2.ast.value.push(leaf);
2780
- }
2781
- return 1;
2782
- } else if (leaf.type === 1) {
2783
- if (leaf.value === "|" && elements[idx + 1].type === 10 && elements[idx + 2].type === 10 && keysToRemove.includes(elements[idx + 1].value[0].value) && keysToRemove.includes(elements[idx + 2].value[0].value)) {
2784
- newDomain2.ast.value.push(..._Domain.TRUE.ast.value);
2785
- return 3;
2786
- }
2787
- newDomain2.ast.value.push(leaf);
2788
- if (leaf.value === "!") {
2789
- return 1 + processLeaf(elements, idx + 1, "&", newDomain2);
2790
- }
2791
- const firstLeafSkip = processLeaf(
2792
- elements,
2793
- idx + 1,
2794
- leaf.value,
2795
- newDomain2
2796
- );
2797
- const secondLeafSkip = processLeaf(
2798
- elements,
2799
- idx + 1 + firstLeafSkip,
2800
- leaf.value,
2801
- newDomain2
2802
- );
2803
- return 1 + firstLeafSkip + secondLeafSkip;
2804
- }
2805
- return 0;
2806
- }
2807
- const d = new _Domain(domain);
2808
- if (d.ast.value.length === 0) {
2809
- return d;
2810
- }
2811
- const newDomain = new _Domain([]);
2812
- processLeaf(d.ast.value, 0, "&", newDomain);
2813
- return newDomain;
2814
- }
2815
- constructor(descr = []) {
2816
- if (descr instanceof _Domain) {
2817
- return new _Domain(descr.toString());
2818
- } else {
2819
- let rawAST;
2820
- try {
2821
- rawAST = typeof descr === "string" ? parseExpr(descr) : toAST(descr);
2822
- } catch (error) {
2823
- throw new InvalidDomainError(
2824
- `Invalid domain representation: ${descr}`,
2825
- {
2826
- cause: error
2827
- }
2828
- );
2829
- }
2830
- this.ast = normalizeDomainAST(rawAST);
2831
- }
2832
- }
2833
- contains(record) {
2834
- const expr = evaluate(this.ast, record);
2835
- return matchDomain(record, expr);
2836
- }
2837
- toString() {
2838
- return formatAST(this.ast);
2839
- }
2840
- toList(context) {
2841
- return evaluate(this.ast, context);
2842
- }
2843
- toJson() {
2844
- try {
2845
- const evaluatedAsList = this.toList({});
2846
- const evaluatedDomain = new _Domain(evaluatedAsList);
2847
- if (evaluatedDomain.toString() === this.toString()) {
2848
- return evaluatedAsList;
2849
- }
2850
- return this.toString();
2851
- } catch {
2852
- return this.toString();
2853
- }
2854
- }
2855
- };
2856
- var TRUE_LEAF = [1, "=", 1];
2857
- var FALSE_LEAF = [0, "=", 1];
2858
- var TRUE_DOMAIN = new Domain([TRUE_LEAF]);
2859
- var FALSE_DOMAIN = new Domain([FALSE_LEAF]);
2860
- Domain.TRUE = TRUE_DOMAIN;
2861
- Domain.FALSE = FALSE_DOMAIN;
2862
- function toAST(domain) {
2863
- const elems = domain.map((elem) => {
2864
- switch (elem) {
2865
- case "!":
2866
- case "&":
2867
- case "|":
2868
- return { type: 1, value: elem };
2869
- default:
2870
- return {
2871
- type: 10,
2872
- value: elem.map(toPyValue)
2873
- };
2874
- }
2875
- });
2876
- return { type: 4, value: elems };
2877
- }
2878
- function normalizeDomainAST(domain, op = "&") {
2879
- if (domain.type !== 4) {
2880
- if (domain.type === 10) {
2881
- const value = domain.value;
2882
- if (value.findIndex((e) => e.type === 10) === -1 || !value.every((e) => e.type === 10 || e.type === 1)) {
2883
- throw new InvalidDomainError("Invalid domain AST");
2884
- }
2885
- } else {
2886
- throw new InvalidDomainError("Invalid domain AST");
2887
- }
2888
- }
2889
- if (domain.value.length === 0) {
2890
- return domain;
2891
- }
2892
- let expected = 1;
2893
- for (const child of domain.value) {
2894
- switch (child.type) {
2895
- case 1:
2896
- if (child.value === "&" || child.value === "|") {
2897
- expected++;
2898
- } else if (child.value !== "!") {
2899
- throw new InvalidDomainError("Invalid domain AST");
2900
- }
2901
- break;
2902
- case 4:
2903
- /* list */
2904
- case 10:
2905
- if (child.value.length === 3) {
2906
- expected--;
2907
- break;
2908
- }
2909
- throw new InvalidDomainError("Invalid domain AST");
2910
- default:
2911
- throw new InvalidDomainError("Invalid domain AST");
2912
- }
2913
- }
2914
- const values = domain.value.slice();
2915
- while (expected < 0) {
2916
- expected++;
2917
- values.unshift({ type: 1, value: op });
2918
- }
2919
- if (expected > 0) {
2920
- throw new InvalidDomainError(
2921
- `invalid domain ${formatAST(domain)} (missing ${expected} segment(s))`
2922
- );
2923
- }
2924
- return { type: 4, value: values };
2925
- }
2926
- function matchCondition(record, condition) {
2927
- if (typeof condition === "boolean") {
2928
- return condition;
2929
- }
2930
- const [field, operator, value] = condition;
2931
- if (typeof field === "string") {
2932
- const names = field.split(".");
2933
- if (names.length >= 2) {
2934
- return matchCondition(record[names[0]], [
2935
- names.slice(1).join("."),
2936
- operator,
2937
- value
2938
- ]);
2939
- }
2940
- }
2941
- let likeRegexp, ilikeRegexp;
2942
- if (["like", "not like", "ilike", "not ilike"].includes(operator)) {
2943
- likeRegexp = new RegExp(
2944
- `(.*)${escapeRegExp(value).replaceAll("%", "(.*)")}(.*)`,
2945
- "g"
2946
- );
2947
- ilikeRegexp = new RegExp(
2948
- `(.*)${escapeRegExp(value).replaceAll("%", "(.*)")}(.*)`,
2949
- "gi"
2950
- );
2951
- }
2952
- const fieldValue = typeof field === "number" ? field : record[field];
2953
- switch (operator) {
2954
- case "=?":
2955
- if ([false, null].includes(value)) {
2956
- return true;
2957
- }
2958
- // eslint-disable-next-line no-fallthrough
2959
- case "=":
2960
- case "==":
2961
- if (Array.isArray(fieldValue) && Array.isArray(value)) {
2962
- return shallowEqual2(fieldValue, value);
2963
- }
2964
- return fieldValue === value;
2965
- case "!=":
2966
- case "<>":
2967
- return !matchCondition(record, [field, "==", value]);
2968
- case "<":
2969
- return fieldValue < value;
2970
- case "<=":
2971
- return fieldValue <= value;
2972
- case ">":
2973
- return fieldValue > value;
2974
- case ">=":
2975
- return fieldValue >= value;
2976
- case "in": {
2977
- const val = Array.isArray(value) ? value : [value];
2978
- const fieldVal = Array.isArray(fieldValue) ? fieldValue : [fieldValue];
2979
- return fieldVal.some((fv) => val.includes(fv));
2980
- }
2981
- case "not in": {
2982
- const val = Array.isArray(value) ? value : [value];
2983
- const fieldVal = Array.isArray(fieldValue) ? fieldValue : [fieldValue];
2984
- return !fieldVal.some((fv) => val.includes(fv));
2985
- }
2986
- case "like":
2987
- if (fieldValue === false) {
2988
- return false;
2989
- }
2990
- return Boolean(fieldValue.match(likeRegexp));
2991
- case "not like":
2992
- if (fieldValue === false) {
2993
- return false;
2994
- }
2995
- return Boolean(!fieldValue.match(likeRegexp));
2996
- case "=like":
2997
- if (fieldValue === false) {
2998
- return false;
2999
- }
3000
- return new RegExp(escapeRegExp(value).replace(/%/g, ".*")).test(
3001
- fieldValue
3002
- );
3003
- case "ilike":
3004
- if (fieldValue === false) {
3005
- return false;
3006
- }
3007
- return Boolean(fieldValue.match(ilikeRegexp));
3008
- case "not ilike":
3009
- if (fieldValue === false) {
3010
- return false;
3011
- }
3012
- return Boolean(!fieldValue.match(ilikeRegexp));
3013
- case "=ilike":
3014
- if (fieldValue === false) {
3015
- return false;
3016
- }
3017
- return new RegExp(escapeRegExp(value).replace(/%/g, ".*"), "i").test(
3018
- fieldValue
3019
- );
3020
- }
3021
- throw new InvalidDomainError("could not match domain");
3022
- }
3023
- function makeOperators(record) {
3024
- const match = matchCondition.bind(null, record);
3025
- return {
3026
- "!": (x) => !match(x),
3027
- "&": (a, b) => match(a) && match(b),
3028
- "|": (a, b) => match(a) || match(b)
3029
- };
3030
- }
3031
- function matchDomain(record, domain) {
3032
- if (domain.length === 0) {
3033
- return true;
3034
- }
3035
- const operators = makeOperators(record);
3036
- const reversedDomain = Array.from(domain).reverse();
3037
- const condStack = [];
3038
- for (const item of reversedDomain) {
3039
- const operator = typeof item === "string" && operators[item];
3040
- if (operator) {
3041
- const operands = condStack.splice(-operator.length);
3042
- condStack.push(operator(...operands));
3043
- } else {
3044
- condStack.push(item);
3045
- }
3046
- }
3047
- return matchCondition(record, condStack.pop());
3048
- }
3049
-
3050
- // src/services/view-service/index.ts
3051
- var ViewService = {
3052
- async getView({
3053
- model,
3054
- views,
3055
- context = {},
3056
- options = {},
3057
- aid
3058
- }) {
3059
- const env2 = getEnv();
3060
- const defaultOptions = {
3061
- load_filters: true,
3062
- toolbar: true,
3063
- action_id: aid
3064
- };
3065
- const jsonDataView = {
3066
- model,
3067
- method: "get_fields_view_v2" /* GET_FIELD_VIEW */,
3068
- kwargs: {
3069
- views,
3070
- options: { ...options, ...defaultOptions }
3071
- },
3072
- with_context: context
3073
- };
3074
- return env2?.requests?.post("/call" /* CALL_PATH */, jsonDataView, {
3075
- headers: {
3076
- "Content-Type": "application/json"
3077
- }
3078
- });
3079
- },
3080
- async getMenu(context) {
3081
- const env2 = getEnv();
3082
- const jsonData = {
3083
- model: "ir.ui.menu" /* MENU */,
3084
- method: "web_search_read" /* WEB_SEARCH_READ */,
3085
- ids: [],
3086
- with_context: context,
3087
- kwargs: {
3088
- specification: {
3089
- active: {},
3090
- name: {},
3091
- is_display: {},
3092
- sequence: {},
3093
- complete_name: {},
3094
- action: {
3095
- fields: {
3096
- display_name: {},
3097
- type: {},
3098
- binding_view_types: {}
3099
- // res_model: {},
3100
- }
3101
- },
3102
- url_icon: {},
3103
- web_icon: {},
3104
- web_icon_data: {},
3105
- groups_id: {
3106
- fields: {
3107
- full_name: {}
3108
- },
3109
- limit: 40,
3110
- order: ""
3111
- },
3112
- display_name: {},
3113
- child_id: {
3114
- fields: {
3115
- active: {},
3116
- name: {},
3117
- is_display: {},
3118
- sequence: {},
3119
- complete_name: {},
3120
- action: {
3121
- fields: {
3122
- display_name: {},
3123
- type: {},
3124
- binding_view_types: {}
3125
- // res_model: {},
3126
- }
3127
- },
3128
- url_icon: {},
3129
- web_icon: {},
3130
- web_icon_data: {},
3131
- groups_id: {
3132
- fields: {
3133
- full_name: {}
3134
- },
3135
- limit: 40,
3136
- order: ""
3137
- },
3138
- display_name: {},
3139
- child_id: {
3140
- fields: {
3141
- active: {},
3142
- name: {},
3143
- is_display: {},
3144
- sequence: {},
3145
- complete_name: {},
3146
- action: {
3147
- fields: {
3148
- display_name: {},
3149
- type: {},
3150
- binding_view_types: {}
3151
- // res_model: {},
3152
- }
3153
- },
3154
- url_icon: {},
3155
- web_icon: {},
3156
- web_icon_data: {},
3157
- groups_id: {
3158
- fields: {
3159
- full_name: {}
3160
- },
3161
- limit: 40,
3162
- order: ""
3163
- },
3164
- display_name: {},
3165
- child_id: {
3166
- fields: {
3167
- active: {},
3168
- name: {},
3169
- is_display: {},
3170
- sequence: {},
3171
- complete_name: {},
3172
- action: {
3173
- fields: {
3174
- display_name: {},
3175
- type: {},
3176
- binding_view_types: {}
3177
- // res_model: {},
3178
- }
3179
- },
3180
- url_icon: {},
3181
- web_icon: {},
3182
- web_icon_data: {},
3183
- groups_id: {
3184
- fields: {
3185
- full_name: {}
3186
- },
3187
- limit: 40,
3188
- order: ""
3189
- },
3190
- display_name: {},
3191
- child_id: {
3192
- fields: {},
3193
- limit: 40,
3194
- order: ""
3195
- }
3196
- },
3197
- limit: 40,
3198
- order: ""
3199
- }
3200
- },
3201
- limit: 40,
3202
- order: ""
3203
- }
3204
- },
3205
- limit: 40,
3206
- order: ""
3207
- }
3208
- },
3209
- domain: [
3210
- "&",
3211
- ["is_display", "=", true],
3212
- "&",
3213
- ["active", "=", true],
3214
- ["parent_id", "=", false]
3215
- ]
3216
- }
3217
- };
3218
- return env2?.requests?.post("/call" /* CALL_PATH */, jsonData, {
3219
- headers: {
3220
- "Content-Type": "application/json"
3221
- }
3222
- });
3223
- },
3224
- async getSelectionItem({ data }) {
3225
- const env2 = getEnv();
3226
- const jsonData = {
3227
- model: data.model,
3228
- ids: [],
3229
- method: "get_data_select",
3230
- with_context: data.context,
3231
- kwargs: {
3232
- count_limit: 10001,
3233
- domain: data.domain ? data.domain : [],
3234
- offset: 0,
3235
- order: "",
3236
- specification: data?.specification ?? {
3237
- id: {},
3238
- name: {},
3239
- display_name: {}
3240
- }
3241
- }
3242
- };
3243
- return env2?.requests.post("/call" /* CALL_PATH */, jsonData, {
3244
- headers: {
3245
- "Content-Type": "application/json"
3246
- }
3247
- });
3248
- },
3249
- async loadMessages() {
3250
- const env2 = getEnv();
3251
- return env2.requests.post(
3252
- "/load_message_failures" /* LOAD_MESSAGE */,
3253
- {},
3254
- {
3255
- headers: {
3256
- "Content-Type": "application/json"
3257
- }
3258
- }
3259
- );
3260
- },
3261
- async getVersion() {
3262
- const env2 = getEnv();
3263
- return env2?.requests.get("", {
3264
- headers: {
3265
- "Content-Type": "application/json"
3266
- }
3267
- });
3268
- }
3269
- };
3270
- var view_service_default = ViewService;
3271
-
3272
- // src/provider/version-gate-provider.tsx
3273
- var import_jsx_runtime4 = require("react/jsx-runtime");
3274
50
  var VersionGate = ({ children }) => {
3275
- const queryClient = (0, import_react_query2.useQueryClient)();
3276
- const [ready, setReady] = (0, import_react2.useState)(false);
3277
- (0, import_react2.useEffect)(() => {
51
+ const queryClient = _reactquery.useQueryClient.call(void 0, );
52
+ const [ready, setReady] = _react.useState.call(void 0, false);
53
+ _react.useEffect.call(void 0, () => {
3278
54
  const clearVersion = () => {
3279
55
  queryClient.clear();
3280
56
  localStorage.removeItem("__api_version__");
3281
57
  };
3282
58
  const validateVersion = async () => {
3283
- const serverVersion = await view_service_default.getVersion();
59
+ const serverVersion = await _chunkU4CC2BBBjs.view_service_default.getVersion();
3284
60
  const cached = localStorage.getItem("__api_version__");
3285
- if (cached !== serverVersion?.api_version) {
61
+ if (cached !== _optionalChain([serverVersion, 'optionalAccess', _ => _.api_version])) {
3286
62
  clearVersion();
3287
- localStorage.setItem("__api_version__", serverVersion?.api_version);
63
+ localStorage.setItem("__api_version__", _optionalChain([serverVersion, 'optionalAccess', _2 => _2.api_version]));
3288
64
  } else {
3289
- console.log("Api version:", serverVersion?.api_version);
65
+ console.log("Api version:", _optionalChain([serverVersion, 'optionalAccess', _3 => _3.api_version]));
3290
66
  }
3291
67
  setReady(true);
3292
68
  };
@@ -3301,11 +77,10 @@ var VersionGate = ({ children }) => {
3301
77
  return () => window.removeEventListener("keydown", onKey);
3302
78
  }
3303
79
  }, [queryClient]);
3304
- return ready ? /* @__PURE__ */ (0, import_jsx_runtime4.jsx)(import_jsx_runtime4.Fragment, { children }) : null;
80
+ return ready ? /* @__PURE__ */ _jsxruntime.jsx.call(void 0, _jsxruntime.Fragment, { children }) : null;
3305
81
  };
3306
- // Annotate the CommonJS export names for ESM import in node:
3307
- 0 && (module.exports = {
3308
- MainProvider,
3309
- ReactQueryProvider,
3310
- VersionGate
3311
- });
82
+
83
+
84
+
85
+
86
+ exports.MainProvider = MainProvider; exports.ReactQueryProvider = ReactQueryProvider; exports.VersionGate = VersionGate;