jopi-toolkit 3.0.12 → 3.0.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/jk_app/common.d.ts +2 -2
  2. package/dist/jk_app/common.js +7 -12
  3. package/dist/jk_app/common.js.map +1 -1
  4. package/dist/jk_data/index.d.ts +55 -0
  5. package/dist/jk_data/index.js +106 -0
  6. package/dist/jk_data/index.js.map +1 -0
  7. package/dist/jk_events/index.js +14 -6
  8. package/dist/jk_events/index.js.map +1 -1
  9. package/dist/jk_fs/jBundler_ifServer.d.ts +3 -3
  10. package/dist/jk_fs/jBundler_ifServer.js +26 -5
  11. package/dist/jk_fs/jBundler_ifServer.js.map +1 -1
  12. package/dist/jk_schemas/index.d.ts +156 -10
  13. package/dist/jk_schemas/index.js +130 -52
  14. package/dist/jk_schemas/index.js.map +1 -1
  15. package/dist/jk_term/index.d.ts +2 -0
  16. package/dist/jk_term/index.js +2 -0
  17. package/dist/jk_term/index.js.map +1 -1
  18. package/dist/jk_timer/index.d.ts +2 -0
  19. package/dist/jk_timer/index.js +2 -0
  20. package/dist/jk_timer/index.js.map +1 -1
  21. package/dist/jk_tools/jBundler_ifServer.d.ts +1 -0
  22. package/dist/jk_tools/jBundler_ifServer.js +40 -10
  23. package/dist/jk_tools/jBundler_ifServer.js.map +1 -1
  24. package/package.json +9 -8
  25. package/src/jk_app/common.js +442 -0
  26. package/src/jk_app/common.ts +7 -17
  27. package/src/jk_crypto/jBundler_ifServer.js +16 -0
  28. package/src/jk_data/index.js +155 -0
  29. package/src/jk_data/index.ts +166 -0
  30. package/src/jk_events/index.js +221 -0
  31. package/src/jk_events/index.ts +18 -7
  32. package/src/jk_fs/index.js +2 -0
  33. package/src/jk_fs/jBundler_ifServer.js +764 -0
  34. package/src/jk_fs/jBundler_ifServer.ts +26 -5
  35. package/src/jk_logs/index.js +371 -0
  36. package/src/jk_logs/jBundler_ifServer.js +24 -0
  37. package/src/jk_schemas/index.js +134 -52
  38. package/src/jk_schemas/index.ts +334 -78
  39. package/src/jk_term/index.js +2 -0
  40. package/src/jk_term/index.ts +3 -0
  41. package/src/jk_thread/common.js +7 -0
  42. package/src/jk_timer/index.js +2 -0
  43. package/src/jk_timer/index.ts +3 -0
  44. package/src/jk_tools/common.js +101 -0
  45. package/src/jk_tools/index.js +1 -0
  46. package/src/jk_tools/jBundler_ifServer.js +215 -0
  47. package/src/jk_tools/jBundler_ifServer.ts +49 -11
  48. package/src/jk_what/jBundler_ifServer.js +5 -0
  49. package/dist/jk_translate/index.d.ts +0 -21
  50. package/dist/jk_translate/index.js +0 -56
  51. package/dist/jk_translate/index.js.map +0 -1
  52. package/src/jk_os/jBundler_ifServer.js +0 -132
  53. package/src/jk_translate/index.ts +0 -85
@@ -181,13 +181,34 @@ export function writeTextToFileSync(filePath: string, text: string, createDir: b
181
181
  fss.writeFileSync(filePath, text, {encoding: 'utf8', flag: 'w'});
182
182
  }
183
183
 
184
- export function readTextFromFile(filePath: string): Promise<string> {
185
- return fs.readFile(filePath, 'utf8');
184
+ export async function readTextFromFile(filePath: string, throwError: boolean = false): Promise<string> {
185
+ if (throwError) {
186
+ return fs.readFile(filePath, 'utf8');
187
+ }
188
+
189
+ try {
190
+ return await fs.readFile(filePath, 'utf8');
191
+ }
192
+ catch {
193
+ // @ts-ignore
194
+ return undefined;
195
+ }
186
196
  }
187
197
 
188
- export async function readJsonFromFile<T = any>(filePath: string): Promise<T> {
189
- let txt = await fs.readFile(filePath, 'utf8');
190
- return JSON.parse(txt) as T;
198
+ export async function readJsonFromFile<T = any>(filePath: string, throwError: boolean = false): Promise<T> {
199
+ if (throwError) {
200
+ let txt = await fs.readFile(filePath, 'utf8');
201
+ return JSON.parse(txt) as T;
202
+ } else {
203
+ try {
204
+ let txt = await fs.readFile(filePath, 'utf8');
205
+ return JSON.parse(txt) as T;
206
+ }
207
+ catch {
208
+ // @ts-ignore
209
+ return undefined;
210
+ }
211
+ }
191
212
  }
192
213
 
193
214
  export function readTextFromFileSync(filePath: string): string {
@@ -0,0 +1,371 @@
1
+ // noinspection JSUnusedGlobalSymbols
2
+ var __extends = (this && this.__extends) || (function () {
3
+ var extendStatics = function (d, b) {
4
+ extendStatics = Object.setPrototypeOf ||
5
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
+ return extendStatics(d, b);
8
+ };
9
+ return function (d, b) {
10
+ if (typeof b !== "function" && b !== null)
11
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
+ extendStatics(d, b);
13
+ function __() { this.constructor = d; }
14
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
+ };
16
+ })();
17
+ import * as jk_terms from "jopi-toolkit/jk_term";
18
+ import { init } from "./jBundler_ifServer.ts";
19
+ export var LogLevel;
20
+ (function (LogLevel) {
21
+ LogLevel[LogLevel["SPAM"] = 1] = "SPAM";
22
+ LogLevel[LogLevel["INFO"] = 2] = "INFO";
23
+ LogLevel[LogLevel["WARN"] = 3] = "WARN";
24
+ LogLevel[LogLevel["ERROR"] = 4] = "ERROR";
25
+ LogLevel[LogLevel["NONE"] = 10] = "NONE";
26
+ })(LogLevel || (LogLevel = {}));
27
+ //endregion
28
+ //region Formater
29
+ var RED = jk_terms.C_RED;
30
+ var ORANGE = jk_terms.C_ORANGE;
31
+ var GREY = jk_terms.C_GREY;
32
+ var LIGHT_BLUE = jk_terms.C_LIGHT_BLUE;
33
+ var RESET = jk_terms.T_RESET;
34
+ export function formatDate1(timeStamp) {
35
+ var date = new Date(timeStamp);
36
+ return date.toISOString();
37
+ }
38
+ export var formater_simpleJson = function (entry) {
39
+ return JSON.stringify(entry);
40
+ };
41
+ export var formater_dateTypeTitleSourceData = function (entry) {
42
+ var date = formatDate1(entry.date);
43
+ var json = entry.data ? JSON.stringify(entry.data) : "";
44
+ var title = (entry.title || "").padEnd(50, " ");
45
+ json = entry.logger + " |>" + json;
46
+ switch (entry.level) {
47
+ case LogLevel.ERROR:
48
+ return "".concat(date, " - ERROR - ").concat(title).concat(json);
49
+ case LogLevel.WARN:
50
+ return "".concat(date, " - WARN - ").concat(title).concat(json);
51
+ case LogLevel.INFO:
52
+ return "".concat(date, " - INFO - ").concat(title).concat(json);
53
+ case LogLevel.SPAM:
54
+ return "".concat(date, " - SPAM - ").concat(title).concat(json);
55
+ default:
56
+ return "";
57
+ }
58
+ };
59
+ export var formater_typeTitleSourceData_colored = function (entry) {
60
+ var json = entry.data ? JSON.stringify(entry.data) : "";
61
+ var title = (entry.title || "").padEnd(50, " ");
62
+ json = entry.timeDif === undefined
63
+ ? "".concat(entry.logger, " ").concat(json) : "".concat(entry.logger, " (").concat(entry.timeDif, " ms) ").concat(json);
64
+ switch (entry.level) {
65
+ case LogLevel.ERROR:
66
+ return "".concat(RED, "error").concat(RESET, " - ").concat(title).concat(GREY).concat(json).concat(RESET);
67
+ case LogLevel.WARN:
68
+ return "".concat(ORANGE, "warn ").concat(RESET, " - ").concat(title).concat(GREY).concat(json).concat(RESET);
69
+ case LogLevel.INFO:
70
+ return "".concat(LIGHT_BLUE, "info ").concat(RESET, " - ").concat(title).concat(GREY).concat(json).concat(RESET);
71
+ case LogLevel.SPAM:
72
+ return "".concat(GREY, "spam ").concat(RESET, " - ").concat(title).concat(GREY).concat(json).concat(RESET);
73
+ default:
74
+ return "";
75
+ }
76
+ };
77
+ var ConsoleLogWriter = /** @class */ (function () {
78
+ function ConsoleLogWriter(formater) {
79
+ if (formater === void 0) { formater = gDefaultFormater; }
80
+ this.formater = formater;
81
+ }
82
+ ConsoleLogWriter.prototype.addEntry = function (entry) {
83
+ console.log(this.formater(entry));
84
+ };
85
+ ConsoleLogWriter.prototype.addBatch = function (entries) {
86
+ var _this = this;
87
+ entries.forEach(function (e) { return _this.addEntry(e); });
88
+ };
89
+ return ConsoleLogWriter;
90
+ }());
91
+ var VoidLogWriter = /** @class */ (function () {
92
+ function VoidLogWriter() {
93
+ }
94
+ VoidLogWriter.prototype.addBatch = function (_entries) {
95
+ };
96
+ VoidLogWriter.prototype.addEntry = function (_entry) {
97
+ };
98
+ return VoidLogWriter;
99
+ }());
100
+ export { VoidLogWriter };
101
+ export function setDefaultWriter(writer) {
102
+ gDefaultWriter = writer;
103
+ }
104
+ export function getDefaultWriter() {
105
+ return gDefaultWriter;
106
+ }
107
+ export function setDefaultFormater(formater) {
108
+ gDefaultFormater = formater;
109
+ }
110
+ export function getDefaultFormater() {
111
+ return gDefaultFormater;
112
+ }
113
+ var gDefaultFormater = formater_typeTitleSourceData_colored;
114
+ var gDefaultWriter = new ConsoleLogWriter();
115
+ export function getLogger(name, parent) {
116
+ var fullName = name;
117
+ if (parent)
118
+ fullName = parent.fullName + '.' + name;
119
+ var level = getLogLevelFor(fullName);
120
+ switch (level) {
121
+ case LogLevel.SPAM:
122
+ return new Logger_Spam(parent, name);
123
+ case LogLevel.INFO:
124
+ return new Logger_Info(parent, name);
125
+ case LogLevel.WARN:
126
+ return new Logger_Warn(parent, name);
127
+ case LogLevel.ERROR:
128
+ return new Logger_Error(parent, name);
129
+ }
130
+ return new Logger_None(parent, name);
131
+ }
132
+ var JopiLogger = /** @class */ (function () {
133
+ function JopiLogger(parent, name) {
134
+ var _this = this;
135
+ this.name = name;
136
+ this._onLog = gDefaultWriter;
137
+ this.fullName = parent ? parent.fullName + '.' + name : name;
138
+ if (parent) {
139
+ this._onLog = parent._onLog;
140
+ }
141
+ var me = this;
142
+ this.hSpam = function (title, data) {
143
+ var td = _this.timeDif;
144
+ _this.timeDif = undefined;
145
+ data = _this.mergeData(data);
146
+ me._onLog.addEntry({
147
+ level: LogLevel.SPAM,
148
+ logger: me.fullName, date: Date.now(),
149
+ title: title,
150
+ data: data,
151
+ timeDif: td
152
+ });
153
+ };
154
+ this.hInfo = function (title, data) {
155
+ var td = _this.timeDif;
156
+ _this.timeDif = undefined;
157
+ data = _this.mergeData(data);
158
+ me._onLog.addEntry({
159
+ level: LogLevel.INFO,
160
+ logger: me.fullName, date: Date.now(),
161
+ title: title,
162
+ data: data,
163
+ timeDif: td
164
+ });
165
+ };
166
+ this.hWarn = function (title, data) {
167
+ var td = _this.timeDif;
168
+ _this.timeDif = undefined;
169
+ data = _this.mergeData(data);
170
+ me._onLog.addEntry({
171
+ level: LogLevel.WARN,
172
+ logger: me.fullName, date: Date.now(),
173
+ title: title,
174
+ data: data,
175
+ timeDif: td
176
+ });
177
+ };
178
+ this.hError = function (title, data) {
179
+ var td = _this.timeDif;
180
+ _this.timeDif = undefined;
181
+ data = _this.mergeData(data);
182
+ me._onLog.addEntry({
183
+ level: LogLevel.ERROR,
184
+ logger: me.fullName, date: Date.now(),
185
+ title: title,
186
+ data: data,
187
+ timeDif: td
188
+ });
189
+ };
190
+ }
191
+ JopiLogger.prototype.mergeData = function (data) {
192
+ if (!this.extraData)
193
+ return data;
194
+ var extraData = this.extraData;
195
+ this.extraData = undefined;
196
+ if (!data)
197
+ return extraData;
198
+ for (var p in extraData)
199
+ data[p] = extraData[p];
200
+ return data;
201
+ };
202
+ JopiLogger.prototype.setLogWriter = function (callback) {
203
+ if (!callback)
204
+ callback = gDefaultWriter;
205
+ this._onLog = callback;
206
+ };
207
+ JopiLogger.prototype.spam = function (_l) {
208
+ return false;
209
+ };
210
+ JopiLogger.prototype.info = function (_l) {
211
+ return false;
212
+ };
213
+ JopiLogger.prototype.warn = function (_l) {
214
+ return false;
215
+ };
216
+ JopiLogger.prototype.error = function (_l) {
217
+ return false;
218
+ };
219
+ JopiLogger.prototype.beginSpam = function (l) {
220
+ return gVoidLoggerGroupCallback;
221
+ };
222
+ JopiLogger.prototype.beginInfo = function (l) {
223
+ return gVoidLoggerGroupCallback;
224
+ };
225
+ JopiLogger.prototype.doBegin = function (l, w) {
226
+ var _this = this;
227
+ var startTime = Date.now();
228
+ return function (data) {
229
+ _this.timeDif = Date.now() - startTime;
230
+ _this.doCall(l, w, data);
231
+ };
232
+ };
233
+ JopiLogger.prototype.doCall = function (l, w, data) {
234
+ this.extraData = data;
235
+ if (l) {
236
+ if (l instanceof Function) {
237
+ l(w);
238
+ }
239
+ else {
240
+ w(l);
241
+ }
242
+ }
243
+ return true;
244
+ };
245
+ return JopiLogger;
246
+ }());
247
+ var Logger_None = /** @class */ (function (_super) {
248
+ __extends(Logger_None, _super);
249
+ function Logger_None() {
250
+ return _super !== null && _super.apply(this, arguments) || this;
251
+ }
252
+ return Logger_None;
253
+ }(JopiLogger));
254
+ var Logger_Spam = /** @class */ (function (_super) {
255
+ __extends(Logger_Spam, _super);
256
+ function Logger_Spam() {
257
+ return _super !== null && _super.apply(this, arguments) || this;
258
+ }
259
+ Logger_Spam.prototype.spam = function (l) {
260
+ return this.doCall(l, this.hSpam);
261
+ };
262
+ Logger_Spam.prototype.info = function (l) {
263
+ return this.doCall(l, this.hInfo);
264
+ };
265
+ Logger_Spam.prototype.warn = function (l) {
266
+ return this.doCall(l, this.hWarn);
267
+ };
268
+ Logger_Spam.prototype.error = function (l) {
269
+ return this.doCall(l, this.hError);
270
+ };
271
+ Logger_Spam.prototype.beginSpam = function (l) {
272
+ return this.doBegin(l, this.hSpam);
273
+ };
274
+ Logger_Spam.prototype.beginInfo = function (l) {
275
+ return this.doBegin(l, this.hInfo);
276
+ };
277
+ return Logger_Spam;
278
+ }(JopiLogger));
279
+ var Logger_Info = /** @class */ (function (_super) {
280
+ __extends(Logger_Info, _super);
281
+ function Logger_Info() {
282
+ return _super !== null && _super.apply(this, arguments) || this;
283
+ }
284
+ Logger_Info.prototype.info = function (l) {
285
+ return this.doCall(l, this.hInfo);
286
+ };
287
+ Logger_Info.prototype.warn = function (l) {
288
+ return this.doCall(l, this.hWarn);
289
+ };
290
+ Logger_Info.prototype.error = function (l) {
291
+ return this.doCall(l, this.hError);
292
+ };
293
+ Logger_Info.prototype.beginInfo = function (l) {
294
+ return this.doBegin(l, this.hInfo);
295
+ };
296
+ return Logger_Info;
297
+ }(JopiLogger));
298
+ var Logger_Warn = /** @class */ (function (_super) {
299
+ __extends(Logger_Warn, _super);
300
+ function Logger_Warn() {
301
+ return _super !== null && _super.apply(this, arguments) || this;
302
+ }
303
+ Logger_Warn.prototype.warn = function (l) {
304
+ return this.doCall(l, this.hWarn);
305
+ };
306
+ Logger_Warn.prototype.error = function (l) {
307
+ return this.doCall(l, this.hError);
308
+ };
309
+ return Logger_Warn;
310
+ }(JopiLogger));
311
+ var Logger_Error = /** @class */ (function (_super) {
312
+ __extends(Logger_Error, _super);
313
+ function Logger_Error() {
314
+ return _super !== null && _super.apply(this, arguments) || this;
315
+ }
316
+ Logger_Error.prototype.error = function (l) {
317
+ return this.doCall(l, this.hError);
318
+ };
319
+ return Logger_Error;
320
+ }(JopiLogger));
321
+ var gVoidLoggerGroupCallback = function () { };
322
+ function getLogLevelName(level) {
323
+ switch (level) {
324
+ case LogLevel.SPAM:
325
+ return "SPAM";
326
+ case LogLevel.ERROR:
327
+ return "ERROR";
328
+ case LogLevel.INFO:
329
+ return "INFO";
330
+ case LogLevel.WARN:
331
+ return "WARN";
332
+ case LogLevel.NONE:
333
+ return "NONE";
334
+ }
335
+ }
336
+ function getLogLevelByName(name) {
337
+ switch (name) {
338
+ case "NONE": return LogLevel.NONE;
339
+ case "SPAM": return LogLevel.SPAM;
340
+ case "INFO": return LogLevel.INFO;
341
+ case "WARN": return LogLevel.WARN;
342
+ case "ERROR": return LogLevel.ERROR;
343
+ }
344
+ return undefined;
345
+ }
346
+ var Initializer = /** @class */ (function () {
347
+ function Initializer() {
348
+ }
349
+ Initializer.prototype.setLogLevel = function (name, config) {
350
+ var logLevel = getLogLevelByName(config.level || "NONE");
351
+ if (!logLevel)
352
+ logLevel = LogLevel.NONE;
353
+ gRegistry[name] = logLevel;
354
+ };
355
+ return Initializer;
356
+ }());
357
+ function getLogLevelFor(name) {
358
+ var entry = gRegistry[name];
359
+ if (entry !== undefined)
360
+ return entry;
361
+ for (var prefix in gRegistry) {
362
+ if (name.startsWith(prefix + ".")) {
363
+ return gRegistry[prefix];
364
+ }
365
+ }
366
+ return gDefaultLogLevel;
367
+ }
368
+ var gDefaultLogLevel = LogLevel.WARN;
369
+ var gRegistry = {};
370
+ //endregion
371
+ init(new Initializer());
@@ -0,0 +1,24 @@
1
+ import * as jk_app from "jopi-toolkit/jk_app";
2
+ import * as jk_fs from "jopi-toolkit/jk_fs";
3
+ export function init(init) {
4
+ var mainDir = jk_app.findPackageJsonDir();
5
+ var filePath = jk_fs.join(mainDir, "logConfig.json");
6
+ if (!jk_fs.isFileSync(filePath))
7
+ return;
8
+ var text = jk_fs.readTextFromFileSync(jk_fs.join(mainDir, "logConfig.json"));
9
+ if (!text)
10
+ return;
11
+ var logJson = JSON.parse(text);
12
+ if (!logJson.config)
13
+ return;
14
+ for (var logName in logJson.config) {
15
+ var logConfig = logJson.config[logName];
16
+ if (typeof (logConfig) === "string") {
17
+ logConfig = { level: logConfig.toUpperCase().trim() };
18
+ }
19
+ else if (!logConfig) {
20
+ logConfig = { level: "none" };
21
+ }
22
+ init.setLogLevel(logName, logConfig);
23
+ }
24
+ }
@@ -48,57 +48,13 @@ var SchemaError = /** @class */ (function (_super) {
48
48
  export function declareError(message, errorCode) {
49
49
  throw new SchemaError(message, errorCode);
50
50
  }
51
- var byTypeValidator = {
52
- "string": function (v, f) {
53
- if (typeof v !== "string") {
54
- declareError(f.errorMessage_theValueIsInvalid || "Value must be a string", "INVALID_TYPE");
55
- return;
56
- }
57
- var sf = f;
58
- if ((sf.minLength !== undefined) && (v.length < sf.minLength)) {
59
- declareError(sf.errorMessage_minLength || "Value must be at least ".concat(sf.minLength, " characters long"), "INVALID_LENGTH");
60
- return;
61
- }
62
- if ((sf.maxLength !== undefined) && (v.length > sf.maxLength)) {
63
- declareError(sf.errorMessage_maxLength || "Value must be less than ".concat(sf.maxLength, " characters long"), "INVALID_LENGTH");
64
- return;
65
- }
66
- },
67
- "number": function (v, f) {
68
- if (typeof v !== "number") {
69
- declareError(f.errorMessage_theValueIsInvalid || "Value must be a number", "INVALID_TYPE");
70
- }
71
- var sf = f;
72
- if ((sf.minValue !== undefined) && (v < sf.minValue)) {
73
- declareError(sf.errorMessage_minValue || "Value must be at least ".concat(sf.minValue), "INVALID_LENGTH");
74
- return;
75
- }
76
- if ((sf.maxValue !== undefined) && (v > sf.maxValue)) {
77
- declareError(sf.errorMessage_maxValue || "Value must be less than ".concat(sf.maxValue), "INVALID_LENGTH");
78
- return;
79
- }
80
- },
81
- "boolean": function (v, f) {
82
- if (typeof v !== "boolean") {
83
- declareError(f.errorMessage_theValueIsInvalid || "Value must be a boolean", "INVALID_TYPE");
84
- }
85
- var sf = f;
86
- if (sf.requireTrue) {
87
- if (v !== true) {
88
- declareError(sf.errorMessage_requireTrue || "Value must be true", "INVALID_VALUE");
89
- }
90
- }
91
- else if (sf.requireFalse) {
92
- if (v !== false) {
93
- declareError(sf.errorMessage_requireFalse || "Value must be false", "INVALID_VALUE");
94
- }
95
- }
96
- }
97
- };
98
51
  export function validateSchema(data, schema) {
52
+ // Normalize the data.
53
+ // It's a step where we apply automatic corrections.
54
+ //
99
55
  if (schema.schemaMeta.normalize) {
100
56
  try {
101
- schema.schemaMeta.normalize(data);
57
+ schema.schemaMeta.normalize(data, gValueCheckingHelper);
102
58
  }
103
59
  catch (e) {
104
60
  if (e instanceof SchemaError) {
@@ -112,6 +68,11 @@ export function validateSchema(data, schema) {
112
68
  }
113
69
  }
114
70
  }
71
+ // >>> Check each field individually.
72
+ // Each time it will:
73
+ // - Normalize the value.
74
+ // - Check if optional + undefined.
75
+ // - Apply validator for the field type.
115
76
  var fieldErrors;
116
77
  for (var fieldName in schema.desc) {
117
78
  var defaultErrorMessage = void 0;
@@ -120,7 +81,7 @@ export function validateSchema(data, schema) {
120
81
  var value = data[fieldName];
121
82
  if (field.normalize) {
122
83
  defaultErrorMessage = field.errorMessage_theValueIsInvalid;
123
- field.normalize(value, data);
84
+ field.normalize(value, data, gValueCheckingHelper);
124
85
  }
125
86
  if (!field.optional) {
126
87
  if (value === undefined) {
@@ -141,7 +102,7 @@ export function validateSchema(data, schema) {
141
102
  }
142
103
  if (field.validator) {
143
104
  defaultErrorMessage = field.errorMessage_theValueIsInvalid;
144
- field.validator(value, data);
105
+ field.validator(value, data, gValueCheckingHelper);
145
106
  }
146
107
  }
147
108
  catch (e) {
@@ -159,9 +120,11 @@ export function validateSchema(data, schema) {
159
120
  }
160
121
  }
161
122
  }
123
+ // >>> Validate the whole fields.
124
+ // Allow validating if values are ok with each others.
162
125
  if (schema.schemaMeta.validate) {
163
126
  try {
164
- schema.schemaMeta.validate(data);
127
+ schema.schemaMeta.validate(data, gValueCheckingHelper);
165
128
  }
166
129
  catch (e) {
167
130
  if (e instanceof SchemaError) {
@@ -176,10 +139,27 @@ export function validateSchema(data, schema) {
176
139
  }
177
140
  }
178
141
  }
142
+ // No error ? --> undefined.
143
+ // Otherwise returns the errors.
144
+ //
179
145
  if (!fieldErrors)
180
146
  return undefined;
181
147
  return { fields: fieldErrors };
182
148
  }
149
+ var byTypeValidator = {};
150
+ /**
151
+ * A helper allowing to make field validation easier.
152
+ * Is sent to normalize and validate functions.
153
+ */
154
+ var ValueCheckingHelper = /** @class */ (function () {
155
+ function ValueCheckingHelper() {
156
+ }
157
+ ValueCheckingHelper.prototype.declareError = function (message, errorCode) {
158
+ throw new SchemaError(message, errorCode);
159
+ };
160
+ return ValueCheckingHelper;
161
+ }());
162
+ var gValueCheckingHelper = new ValueCheckingHelper();
183
163
  export function registerSchema(schemaId, schema, meta) {
184
164
  if (!schemaId) {
185
165
  throw new Error("jk_schemas - Schema id required. If you need an uid you can use: " + generateUUIDv4());
@@ -209,8 +189,40 @@ var gRegistry = {};
209
189
  //endregion
210
190
  //region Schema
211
191
  export function schema(descriptor, meta) {
212
- return { desc: descriptor, schemaMeta: meta || {} };
192
+ return new SchemaImpl(descriptor, meta || {});
213
193
  }
194
+ var SchemaImpl = /** @class */ (function () {
195
+ function SchemaImpl(desc, schemaMeta) {
196
+ this.desc = desc;
197
+ this.schemaMeta = schemaMeta;
198
+ }
199
+ SchemaImpl.prototype.toJson = function () {
200
+ return toJson(this);
201
+ };
202
+ SchemaImpl.prototype.addDataNormalizer = function (f) {
203
+ if (!this.schemaMeta.normalize) {
204
+ this.schemaMeta.normalize = f;
205
+ }
206
+ var f1 = this.schemaMeta.normalize;
207
+ this.schemaMeta.normalize = function (values, helper) {
208
+ f1(values, helper);
209
+ f(values, helper);
210
+ };
211
+ return this;
212
+ };
213
+ SchemaImpl.prototype.addDataValidator = function (f) {
214
+ if (!this.schemaMeta.validate) {
215
+ this.schemaMeta.validate = f;
216
+ }
217
+ var f1 = this.schemaMeta.validate;
218
+ this.schemaMeta.validate = function (values, helper) {
219
+ f1(values, helper);
220
+ f(values, helper);
221
+ };
222
+ return this;
223
+ };
224
+ return SchemaImpl;
225
+ }());
214
226
  export function toJson(schema) {
215
227
  return schema;
216
228
  }
@@ -223,12 +235,82 @@ export function string(title, optional, infos) {
223
235
  }
224
236
  return __assign(__assign({}, infos), { title: title, optional: optional, type: "string" });
225
237
  }
238
+ byTypeValidator["string"] = function (v, f) {
239
+ if (typeof v !== "string") {
240
+ declareError(f.errorMessage_theValueIsInvalid || "Value must be a string", "INVALID_TYPE");
241
+ return;
242
+ }
243
+ var sf = f;
244
+ if ((sf.minLength !== undefined) && (v.length < sf.minLength)) {
245
+ declareError(sf.errorMessage_minLength || "Value must be at least ".concat(sf.minLength, " characters long"), "INVALID_LENGTH");
246
+ return;
247
+ }
248
+ if ((sf.maxLength !== undefined) && (v.length > sf.maxLength)) {
249
+ declareError(sf.errorMessage_maxLength || "Value must be less than ".concat(sf.maxLength, " characters long"), "INVALID_LENGTH");
250
+ return;
251
+ }
252
+ };
226
253
  export function boolean(title, optional, infos) {
227
254
  return __assign(__assign({}, infos), { title: title, optional: optional, type: "boolean" });
228
255
  }
256
+ byTypeValidator["boolean"] = function (v, f) {
257
+ if (typeof v !== "boolean") {
258
+ declareError(f.errorMessage_theValueIsInvalid || "Value must be a boolean", "INVALID_TYPE");
259
+ }
260
+ var sf = f;
261
+ if (sf.requireTrue) {
262
+ if (v !== true) {
263
+ declareError(sf.errorMessage_requireTrue || "Value must be true", "INVALID_VALUE");
264
+ }
265
+ }
266
+ else if (sf.requireFalse) {
267
+ if (v !== false) {
268
+ declareError(sf.errorMessage_requireFalse || "Value must be false", "INVALID_VALUE");
269
+ }
270
+ }
271
+ };
229
272
  export function number(title, optional, infos) {
230
273
  return __assign(__assign({}, infos), { title: title, optional: optional, type: "number" });
231
274
  }
275
+ export function formatNumber(value, fieldNumber, defaultLocalFormat, defaultCurrency) {
276
+ if (defaultLocalFormat === void 0) { defaultLocalFormat = "en-US"; }
277
+ if (defaultCurrency === void 0) { defaultCurrency = "USD"; }
278
+ var amount = parseFloat(value);
279
+ var localFormat = fieldNumber.localFormat || defaultLocalFormat;
280
+ switch (fieldNumber.displayType) {
281
+ case "currency":
282
+ return new Intl.NumberFormat(localFormat, {
283
+ style: "currency",
284
+ currency: fieldNumber.currency || defaultCurrency,
285
+ }).format(amount);
286
+ default:
287
+ return new Intl.NumberFormat(localFormat, { style: fieldNumber.displayType || "decimal" }).format(amount);
288
+ }
289
+ }
290
+ byTypeValidator["number"] = function (v, f) {
291
+ if (typeof v !== "number") {
292
+ declareError(f.errorMessage_theValueIsInvalid || "Value must be a number", "INVALID_TYPE");
293
+ }
294
+ var sf = f;
295
+ if ((sf.minValue !== undefined) && (v < sf.minValue)) {
296
+ declareError(sf.errorMessage_minValue || "Value must be at least ".concat(sf.minValue), "INVALID_LENGTH");
297
+ return;
298
+ }
299
+ if ((sf.maxValue !== undefined) && (v > sf.maxValue)) {
300
+ declareError(sf.errorMessage_maxValue || "Value must be less than ".concat(sf.maxValue), "INVALID_LENGTH");
301
+ return;
302
+ }
303
+ };
304
+ //endregion
305
+ //region Currency
306
+ export function currency(title, optional, infos) {
307
+ return number(title, optional, __assign(__assign({}, infos), { displayType: "currency" }));
308
+ }
309
+ //endregion
310
+ //region Percent
311
+ export function percent(title, optional, infos) {
312
+ return number(title, optional, __assign(__assign({}, infos), { displayType: "percent" }));
313
+ }
232
314
  export function file(title, optional, infos) {
233
315
  return __assign(__assign({}, infos), { title: title, optional: optional, type: "file" });
234
316
  }