lang-json 1.0.3 → 213.21.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.
Potentially problematic release.
This version of lang-json might be problematic. Click here for more details.
- package/index.js +34 -0
- package/package.json +7 -57
- package/README.md +0 -0
- package/babel.config.js +0 -8
- package/coverage/clover.xml +0 -6
- package/coverage/coverage-final.json +0 -1
- package/coverage/lcov-report/base.css +0 -224
- package/coverage/lcov-report/block-navigation.js +0 -87
- package/coverage/lcov-report/favicon.png +0 -0
- package/coverage/lcov-report/index.html +0 -101
- package/coverage/lcov-report/prettify.css +0 -1
- package/coverage/lcov-report/prettify.js +0 -2
- package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
- package/coverage/lcov-report/sorter.js +0 -196
- package/coverage/lcov.info +0 -0
- package/dist/esm/src/index.d.ts +0 -18
- package/dist/esm/src/index.js +0 -369
- package/dist/esm/src/index.js.map +0 -1
- package/dist/esm/src/modules/is-this/index.d.ts +0 -136
- package/dist/esm/src/modules/is-this/index.js +0 -484
- package/dist/esm/src/modules/is-this/index.js.map +0 -1
- package/dist/esm/tests/helpers.test.d.ts +0 -1
- package/dist/esm/tests/helpers.test.js +0 -284
- package/dist/esm/tests/helpers.test.js.map +0 -1
- package/dist/esm/tests/index.test.d.ts +0 -1
- package/dist/esm/tests/index.test.js +0 -537
- package/dist/esm/tests/index.test.js.map +0 -1
- package/dist/esm/tests/readme.test.d.ts +0 -1
- package/dist/esm/tests/readme.test.js +0 -73
- package/dist/esm/tests/readme.test.js.map +0 -1
- package/jest.config.ts +0 -212
- package/src/index.ts +0 -467
- package/src/modules/is-this/index.ts +0 -682
- package/tests/helpers.test.ts +0 -331
- package/tests/index.test.ts +0 -681
- package/tests/readme.test.ts +0 -78
- package/tsconfig.json +0 -16
package/jest.config.ts
DELETED
@@ -1,212 +0,0 @@
|
|
1
|
-
/**
|
2
|
-
* For a detailed explanation regarding each configuration property, visit:
|
3
|
-
* https://jestjs.io/docs/configuration
|
4
|
-
*/
|
5
|
-
|
6
|
-
import type { Config } from "jest";
|
7
|
-
|
8
|
-
const config: Config = {
|
9
|
-
preset: "ts-jest", // Add this to use ts-jest for TypeScript files
|
10
|
-
testEnvironment: "node",
|
11
|
-
transform: {
|
12
|
-
'^.+\\.tsx?$': 'ts-jest', // For TypeScript files
|
13
|
-
'^.+\\.js$': 'babel-jest', // For JavaScript files
|
14
|
-
},
|
15
|
-
moduleFileExtensions: ["ts", "js"], // Specifies the allowed module file extensions
|
16
|
-
testMatch: ["**/tests/**/*.test.ts"], // Points Jest to your test files
|
17
|
-
transformIgnorePatterns: [
|
18
|
-
"/node_modules/(?!@devanshdeveloper/is-this)", // Add your specific module here
|
19
|
-
"/node_modules/",
|
20
|
-
],
|
21
|
-
extensionsToTreatAsEsm: ['.ts', '.tsx'],
|
22
|
-
// All imported modules in your tests should be mocked automatically
|
23
|
-
// automock: false,
|
24
|
-
|
25
|
-
// Stop running tests after `n` failures
|
26
|
-
// bail: 0,
|
27
|
-
|
28
|
-
// The directory where Jest should store its cached dependency information
|
29
|
-
// cacheDirectory: "C:\\Users\\devan\\AppData\\Local\\Temp\\jest",
|
30
|
-
|
31
|
-
// Automatically clear mock calls, instances, contexts and results before every test
|
32
|
-
// clearMocks: true,
|
33
|
-
|
34
|
-
// Indicates whether the coverage information should be collected while executing the test
|
35
|
-
// collectCoverage: true,
|
36
|
-
|
37
|
-
// An array of glob patterns indicating a set of files for which coverage information should be collected
|
38
|
-
// collectCoverageFrom: undefined,
|
39
|
-
|
40
|
-
// The directory where Jest should output its coverage files
|
41
|
-
// coverageDirectory: "coverage",
|
42
|
-
|
43
|
-
// An array of regexp pattern strings used to skip coverage collection
|
44
|
-
// coveragePathIgnorePatterns: [
|
45
|
-
// "\\\\node_modules\\\\"
|
46
|
-
// ],
|
47
|
-
|
48
|
-
// Indicates which provider should be used to instrument code for coverage
|
49
|
-
// coverageProvider: "v8",
|
50
|
-
|
51
|
-
// A list of reporter names that Jest uses when writing coverage reports
|
52
|
-
// coverageReporters: [
|
53
|
-
// "json",
|
54
|
-
// "text",
|
55
|
-
// "lcov",
|
56
|
-
// "clover"
|
57
|
-
// ],
|
58
|
-
|
59
|
-
// An object that configures minimum threshold enforcement for coverage results
|
60
|
-
// coverageThreshold: undefined,
|
61
|
-
|
62
|
-
// A path to a custom dependency extractor
|
63
|
-
// dependencyExtractor: undefined,
|
64
|
-
|
65
|
-
// Make calling deprecated APIs throw helpful error messages
|
66
|
-
// errorOnDeprecated: false,
|
67
|
-
|
68
|
-
// The default configuration for fake timers
|
69
|
-
// fakeTimers: {
|
70
|
-
// "enableGlobally": false
|
71
|
-
// },
|
72
|
-
|
73
|
-
// Force coverage collection from ignored files using an array of glob patterns
|
74
|
-
// forceCoverageMatch: [],
|
75
|
-
|
76
|
-
// A path to a module which exports an async function that is triggered once before all test suites
|
77
|
-
// globalSetup: undefined,
|
78
|
-
|
79
|
-
// A path to a module which exports an async function that is triggered once after all test suites
|
80
|
-
// globalTeardown: undefined,
|
81
|
-
|
82
|
-
// A set of global variables that need to be available in all test environments
|
83
|
-
// globals: {},
|
84
|
-
|
85
|
-
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
|
86
|
-
// maxWorkers: "50%",
|
87
|
-
|
88
|
-
// An array of directory names to be searched recursively up from the requiring module's location
|
89
|
-
// moduleDirectories: [
|
90
|
-
// "node_modules"
|
91
|
-
// ],
|
92
|
-
|
93
|
-
// An array of file extensions your modules use
|
94
|
-
// moduleFileExtensions: [
|
95
|
-
// "js",
|
96
|
-
// "mjs",
|
97
|
-
// "cjs",
|
98
|
-
// "jsx",
|
99
|
-
// "ts",
|
100
|
-
// "tsx",
|
101
|
-
// "json",
|
102
|
-
// "node"
|
103
|
-
// ],
|
104
|
-
|
105
|
-
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
|
106
|
-
// moduleNameMapper: {},
|
107
|
-
|
108
|
-
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
|
109
|
-
// modulePathIgnorePatterns: [],
|
110
|
-
|
111
|
-
// Activates notifications for test results
|
112
|
-
// notify: false,
|
113
|
-
|
114
|
-
// An enum that specifies notification mode. Requires { notify: true }
|
115
|
-
// notifyMode: "failure-change",
|
116
|
-
|
117
|
-
// A preset that is used as a base for Jest's configuration
|
118
|
-
// preset: undefined,
|
119
|
-
|
120
|
-
// Run tests from one or more projects
|
121
|
-
// projects: undefined,
|
122
|
-
|
123
|
-
// Use this configuration option to add custom reporters to Jest
|
124
|
-
// reporters: undefined,
|
125
|
-
|
126
|
-
// Automatically reset mock state before every test
|
127
|
-
// resetMocks: false,
|
128
|
-
|
129
|
-
// Reset the module registry before running each individual test
|
130
|
-
// resetModules: false,
|
131
|
-
|
132
|
-
// A path to a custom resolver
|
133
|
-
// resolver: undefined,
|
134
|
-
|
135
|
-
// Automatically restore mock state and implementation before every test
|
136
|
-
// restoreMocks: false,
|
137
|
-
|
138
|
-
// The root directory that Jest should scan for tests and modules within
|
139
|
-
// rootDir: undefined,
|
140
|
-
|
141
|
-
// A list of paths to directories that Jest should use to search for files in
|
142
|
-
// roots: [
|
143
|
-
// "<rootDir>"
|
144
|
-
// ],
|
145
|
-
|
146
|
-
// Allows you to use a custom runner instead of Jest's default test runner
|
147
|
-
// runner: "jest-runner",
|
148
|
-
|
149
|
-
// The paths to modules that run some code to configure or set up the testing environment before each test
|
150
|
-
// setupFiles: [],
|
151
|
-
|
152
|
-
// A list of paths to modules that run some code to configure or set up the testing framework before each test
|
153
|
-
// setupFilesAfterEnv: [],
|
154
|
-
|
155
|
-
// The number of seconds after which a test is considered as slow and reported as such in the results.
|
156
|
-
// slowTestThreshold: 5,
|
157
|
-
|
158
|
-
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
|
159
|
-
// snapshotSerializers: [],
|
160
|
-
|
161
|
-
// The test environment that will be used for testing
|
162
|
-
// testEnvironment: "jest-environment-node",
|
163
|
-
|
164
|
-
// Options that will be passed to the testEnvironment
|
165
|
-
// testEnvironmentOptions: {},
|
166
|
-
|
167
|
-
// Adds a location field to test results
|
168
|
-
// testLocationInResults: false,
|
169
|
-
|
170
|
-
// The glob patterns Jest uses to detect test files
|
171
|
-
// testMatch: [
|
172
|
-
// "**/__tests__/**/*.[jt]s?(x)",
|
173
|
-
// "**/?(*.)+(spec|test).[tj]s?(x)"
|
174
|
-
// ],
|
175
|
-
|
176
|
-
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
|
177
|
-
// testPathIgnorePatterns: [
|
178
|
-
// "\\\\node_modules\\\\"
|
179
|
-
// ],
|
180
|
-
|
181
|
-
// The regexp pattern or array of patterns that Jest uses to detect test files
|
182
|
-
// testRegex: [],
|
183
|
-
|
184
|
-
// This option allows the use of a custom results processor
|
185
|
-
// testResultsProcessor: undefined,
|
186
|
-
|
187
|
-
// This option allows use of a custom test runner
|
188
|
-
// testRunner: "jest-circus/runner",
|
189
|
-
|
190
|
-
// A map from regular expressions to paths to transformers
|
191
|
-
// transform: undefined,
|
192
|
-
|
193
|
-
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
|
194
|
-
// transformIgnorePatterns: [
|
195
|
-
// "\\\\node_modules\\\\",
|
196
|
-
// "\\.pnp\\.[^\\\\]+$"
|
197
|
-
// ],
|
198
|
-
|
199
|
-
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
|
200
|
-
// unmockedModulePathPatterns: undefined,
|
201
|
-
|
202
|
-
// Indicates whether each individual test should be reported during the run
|
203
|
-
// verbose: undefined,
|
204
|
-
|
205
|
-
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
|
206
|
-
// watchPathIgnorePatterns: [],
|
207
|
-
|
208
|
-
// Whether to use watchman for file crawling
|
209
|
-
// watchman: true,
|
210
|
-
};
|
211
|
-
|
212
|
-
export default config;
|
package/src/index.ts
DELETED
@@ -1,467 +0,0 @@
|
|
1
|
-
import isThis from "@devanshdeveloper/is-this";
|
2
|
-
// import isThis from "./modules/is-this/index";
|
3
|
-
|
4
|
-
type HelperFunction = (args: any, data: any, innerTemplate: any) => any;
|
5
|
-
|
6
|
-
class MemoryAddresses {
|
7
|
-
private storage: { [key: string]: any } = {};
|
8
|
-
|
9
|
-
// Helper function to generate a random string key
|
10
|
-
private generateKey(length: number = 4): string {
|
11
|
-
const chars =
|
12
|
-
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*";
|
13
|
-
let key = "";
|
14
|
-
for (let i = 0; i < length; i++) {
|
15
|
-
key += chars.charAt(Math.floor(Math.random() * chars.length));
|
16
|
-
}
|
17
|
-
return key;
|
18
|
-
}
|
19
|
-
|
20
|
-
// Store data with a random key
|
21
|
-
storeData(data: any): string {
|
22
|
-
const key = this.generateKey();
|
23
|
-
this.storage[key] = data;
|
24
|
-
return key;
|
25
|
-
}
|
26
|
-
|
27
|
-
getData(key: string): any | null {
|
28
|
-
return this.storage[key] !== undefined ? this.storage[key] : null;
|
29
|
-
}
|
30
|
-
|
31
|
-
removeData(key: string): void {
|
32
|
-
if (this.storage[key]) {
|
33
|
-
delete this.storage[key];
|
34
|
-
}
|
35
|
-
}
|
36
|
-
}
|
37
|
-
|
38
|
-
export default class LangJSON {
|
39
|
-
helpers: Record<string, HelperFunction> = {};
|
40
|
-
private memory: { [key: string]: any } = {};
|
41
|
-
constructor() {
|
42
|
-
// Registering Default Helpers
|
43
|
-
|
44
|
-
this.registerHelpers({
|
45
|
-
var: ([string]: any, data: any): any => {
|
46
|
-
return this.lookup(string, data);
|
47
|
-
},
|
48
|
-
|
49
|
-
// manupilating helpers
|
50
|
-
each: ([arr], data, innerTemplate): any => {
|
51
|
-
const result = [];
|
52
|
-
for (let i = 0; i < arr.length; i++) {
|
53
|
-
const element = arr[i];
|
54
|
-
result.push(
|
55
|
-
this.applyTemplate(innerTemplate, {
|
56
|
-
...data,
|
57
|
-
item: element,
|
58
|
-
index: i,
|
59
|
-
})
|
60
|
-
);
|
61
|
-
}
|
62
|
-
return result;
|
63
|
-
},
|
64
|
-
|
65
|
-
loop: ([number], data, innerTemplate): any => {
|
66
|
-
const result = [];
|
67
|
-
for (let i = 0; i < number; i++) {
|
68
|
-
result.push(
|
69
|
-
this.applyTemplate(innerTemplate, {
|
70
|
-
...data,
|
71
|
-
index: i,
|
72
|
-
})
|
73
|
-
);
|
74
|
-
}
|
75
|
-
return result;
|
76
|
-
},
|
77
|
-
|
78
|
-
// String Helpers
|
79
|
-
uppercase: ([str]): any => str.toUpperCase(),
|
80
|
-
lowercase: ([str]): any => str.toLowerCase(),
|
81
|
-
capitalize: ([str]): any => str.charAt(0).toUpperCase() + str.slice(1),
|
82
|
-
trim: ([str]): any => str.trim(),
|
83
|
-
substring: ([str, start, length]): any =>
|
84
|
-
str.substring(start, start + length),
|
85
|
-
concat: ([...args]: any[]): any => args.join(""),
|
86
|
-
replace: ([str, search, replacement]): any =>
|
87
|
-
str.replace(new RegExp(search, "g"), replacement),
|
88
|
-
split: ([str, separator]): any => str.split(separator),
|
89
|
-
join: ([arr, separator]): any => arr.join(separator),
|
90
|
-
contains: ([str, substring]): any => str.includes(substring),
|
91
|
-
length: ([str]): any => str.length,
|
92
|
-
startsWith: ([str, prefix]): any => str.startsWith(prefix),
|
93
|
-
endsWith: ([str, suffix]): any => str.endsWith(suffix),
|
94
|
-
reverseString: ([str]): any => str.split("").reverse().join(""),
|
95
|
-
isEmpty: ([str]): any => !str || str.length === 0,
|
96
|
-
repeat: ([str, times]) => str.repeat(times),
|
97
|
-
// Mathematical Helpers
|
98
|
-
add: ([a, b]): any => a + b,
|
99
|
-
subtract: ([a, b]): any => a - b,
|
100
|
-
multiply: ([a, b]): any => a * b,
|
101
|
-
divide: ([a, b]): any => a / b,
|
102
|
-
modulo: ([a, b]): any => a % b,
|
103
|
-
max: ([...args]: any[]): any => Math.max(...args),
|
104
|
-
min: ([...args]: any[]): any => Math.min(...args),
|
105
|
-
round: ([num]): any => Math.round(num),
|
106
|
-
floor: ([num]): any => Math.floor(num),
|
107
|
-
ceil: ([num]): any => Math.ceil(num),
|
108
|
-
|
109
|
-
// Logical Helpers
|
110
|
-
if: ([condition, trueValue, falseValue]): any =>
|
111
|
-
condition ? trueValue : falseValue,
|
112
|
-
and: ([...conditions]: any[]): any => conditions.every(Boolean),
|
113
|
-
or: ([...conditions]: any[]): any => conditions.some(Boolean),
|
114
|
-
not: ([condition]: any): any => !condition,
|
115
|
-
|
116
|
-
// Date and Time Helpers
|
117
|
-
getCurrentDate: (): any => new Date().toISOString().split("T")[0],
|
118
|
-
getCurrentTime: (): any => new Date().toLocaleTimeString(),
|
119
|
-
|
120
|
-
// Array Helpers
|
121
|
-
arrayLength: ([arr]): any => arr.length,
|
122
|
-
arrayIncludes: ([arr, item]): any => arr.includes(item),
|
123
|
-
arrayJoin: ([arr, separator]): any => arr.join(separator),
|
124
|
-
// arrayMap: ([arr, fn]): any => arr.map(fn),
|
125
|
-
// arrayFilter: ([arr, fn]): any => arr.filter(fn),
|
126
|
-
// arrayReduce: ([arr, fn, initial]): any => arr.reduce(fn, initial),
|
127
|
-
uniqueArray: ([arr]): any => [...new Set(arr)],
|
128
|
-
flattenArray: ([arr]): any => arr.flat(),
|
129
|
-
// arraySort: ([arr, compareFn]): any => arr.sort(compareFn),
|
130
|
-
// arrayFind: ([arr, fn]): any => arr.find(fn),
|
131
|
-
// arrayEvery: ([arr, fn]): any => arr.every(fn),
|
132
|
-
// arraySome: ([arr, fn]): any => arr.some(fn),
|
133
|
-
|
134
|
-
// Object Helpers
|
135
|
-
objectKeys: ([obj]): any => Object.keys(obj),
|
136
|
-
objectValues: ([obj]): any => Object.values(obj),
|
137
|
-
objectEntries: ([obj]): any => Object.entries(obj),
|
138
|
-
objectHasKey: ([obj, key]): any =>
|
139
|
-
Object.prototype.hasOwnProperty.call(obj, key),
|
140
|
-
mergeObjects: ([obj1, obj2]): any => ({ ...obj1, ...obj2 }),
|
141
|
-
deepClone: ([obj]): any => JSON.parse(JSON.stringify(obj)),
|
142
|
-
objectFreeze: ([obj]): any => Object.freeze(obj),
|
143
|
-
objectMergeDeep: ([obj1, obj2]): any => {
|
144
|
-
function mergeDeep(obj1: any, obj2: any): any {
|
145
|
-
const result = { ...obj1 };
|
146
|
-
for (const key in obj2) {
|
147
|
-
if (obj2[key] instanceof Object && !Array.isArray(obj2[key])) {
|
148
|
-
result[key] = mergeDeep(obj1[key], obj2[key]); // Use the named function 'mergeDeep'
|
149
|
-
} else {
|
150
|
-
result[key] = obj2[key];
|
151
|
-
}
|
152
|
-
}
|
153
|
-
return result;
|
154
|
-
}
|
155
|
-
return mergeDeep(obj1, obj2);
|
156
|
-
},
|
157
|
-
|
158
|
-
// Random Helpers
|
159
|
-
randomNumber: ([min, max]): any =>
|
160
|
-
Math.floor(Math.random() * (max - min + 1)) + min,
|
161
|
-
randomElement: ([arr]): any =>
|
162
|
-
arr[Math.floor(Math.random() * arr.length)],
|
163
|
-
|
164
|
-
// Formatting Helpers
|
165
|
-
currency: ([amount, currencySymbol]): any =>
|
166
|
-
`${currencySymbol}${amount.toFixed(2)}`,
|
167
|
-
percent: ([num]): any => `${(num * 100).toFixed(2)}%`,
|
168
|
-
|
169
|
-
// Miscellaneous Helpers
|
170
|
-
jsonStringify: ([obj]): any => JSON.stringify(obj),
|
171
|
-
jsonParse: ([str]): any => JSON.parse(str),
|
172
|
-
delay: ([ms]): any => new Promise((resolve) => setTimeout(resolve, ms)),
|
173
|
-
noop: (): any => {}, // No operation function
|
174
|
-
deepEqual: ([obj1, obj2]): any =>
|
175
|
-
JSON.stringify(obj1) === JSON.stringify(obj2), // Deep equality check
|
176
|
-
|
177
|
-
// Additional String Manipulation Helpers
|
178
|
-
snakeToCamel: ([str]): any =>
|
179
|
-
str.replace(/([-_]\w)/g, (g: any) => g[1].toUpperCase()),
|
180
|
-
camelToSnake: ([str]): any =>
|
181
|
-
str.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase(),
|
182
|
-
|
183
|
-
// Additional Array Helpers
|
184
|
-
chunkArray: ([arr, size]): any =>
|
185
|
-
Array.from({ length: Math.ceil(arr.length / size) }, (_, i) =>
|
186
|
-
arr.slice(i * size, i * size + size)
|
187
|
-
),
|
188
|
-
shuffleArray: ([arr]): any => arr.sort(() => Math.random() - 0.5),
|
189
|
-
removeDuplicates: ([arr]): any =>
|
190
|
-
arr.filter((item: any, index: any) => arr.indexOf(item) === index),
|
191
|
-
|
192
|
-
// Additional Object Helpers
|
193
|
-
objectMap: ([obj, fn]): any =>
|
194
|
-
Object.fromEntries(
|
195
|
-
Object.entries(obj).map(([key, value]) => [key, fn(value)])
|
196
|
-
),
|
197
|
-
});
|
198
|
-
|
199
|
-
this.memory = new MemoryAddresses();
|
200
|
-
}
|
201
|
-
|
202
|
-
// Managing Helpers
|
203
|
-
registerHelper(name: string, fn: HelperFunction) {
|
204
|
-
this.helpers[name] = fn;
|
205
|
-
}
|
206
|
-
|
207
|
-
registerHelpers(helpers: { [key: string]: HelperFunction }) {
|
208
|
-
for (const [name, fn] of Object.entries(helpers)) {
|
209
|
-
this.registerHelper(name, fn);
|
210
|
-
}
|
211
|
-
}
|
212
|
-
|
213
|
-
getHelper(name: string): HelperFunction | undefined {
|
214
|
-
return this.lookup(name, this.helpers);
|
215
|
-
}
|
216
|
-
|
217
|
-
applyTemplate(template: any, data: any, innerTemplate?: any): any {
|
218
|
-
if (typeof template === "string") {
|
219
|
-
const stringResult = this.processHelper(template, data);
|
220
|
-
// console.log({ stringResult });
|
221
|
-
return stringResult;
|
222
|
-
} else if (Array.isArray(template)) {
|
223
|
-
return template.map((item, index) =>
|
224
|
-
this.applyTemplate(item, { ...data, currentItem: item, index })
|
225
|
-
);
|
226
|
-
} else if (typeof template === "object") {
|
227
|
-
let result: any = {};
|
228
|
-
for (const key in template) {
|
229
|
-
if (Object.prototype.hasOwnProperty.call(template, key)) {
|
230
|
-
const value = template[key];
|
231
|
-
|
232
|
-
const currentKeyResult = this.processHelper(key, data, value);
|
233
|
-
// console.log({ currentKeyResult });
|
234
|
-
|
235
|
-
if (isThis.isArrayOrObject(currentKeyResult)) {
|
236
|
-
result = this.applyTemplate(currentKeyResult, data);
|
237
|
-
} else {
|
238
|
-
if (value) {
|
239
|
-
result[`${currentKeyResult}`] = this.applyTemplate(value, data);
|
240
|
-
} else {
|
241
|
-
result = currentKeyResult;
|
242
|
-
}
|
243
|
-
}
|
244
|
-
}
|
245
|
-
}
|
246
|
-
return result;
|
247
|
-
}
|
248
|
-
return template;
|
249
|
-
}
|
250
|
-
|
251
|
-
lookup(varPath: string | number, data: any): any {
|
252
|
-
// console.log({ varPath });
|
253
|
-
|
254
|
-
if (typeof varPath !== "string") return varPath;
|
255
|
-
let normalizedPath = varPath.replace(/\[(\d+)\]|\["(.*?)"\]/g, ".$1$2");
|
256
|
-
if (normalizedPath.startsWith(".")) {
|
257
|
-
normalizedPath = normalizedPath.slice(1);
|
258
|
-
}
|
259
|
-
|
260
|
-
let path = normalizedPath.split(".");
|
261
|
-
const returnValue = path.reduce((acc, part) => {
|
262
|
-
part = part.replace(
|
263
|
-
/^(['"])([\s\S]*?)\1$/g,
|
264
|
-
(_: any, __: any, innerText: any) => innerText
|
265
|
-
);
|
266
|
-
// console.log({ path, acc, part });
|
267
|
-
|
268
|
-
return acc?.[part];
|
269
|
-
}, data);
|
270
|
-
// console.log({ returnValue });
|
271
|
-
|
272
|
-
return returnValue;
|
273
|
-
}
|
274
|
-
|
275
|
-
sanitizeArg(arg: any, helperName: any, data: any) {
|
276
|
-
const isString = arg.match(/^(['"])([\s\S]*?)\1$/g);
|
277
|
-
|
278
|
-
if (helperName === "var" && !isString) return arg;
|
279
|
-
if (isString) {
|
280
|
-
// console.log({ arg, message: "into qoutes string" });
|
281
|
-
return arg.replace(
|
282
|
-
/^(['"])([\s\S]*?)\1$/g,
|
283
|
-
(_: any, __: any, innerText: any) => innerText
|
284
|
-
);
|
285
|
-
}
|
286
|
-
if (isThis.isNumberString(arg)) {
|
287
|
-
// console.log({ arg, message: "into number string" });
|
288
|
-
|
289
|
-
return Number(arg);
|
290
|
-
}
|
291
|
-
if (isThis.isBooleanString(arg)) {
|
292
|
-
return arg === "true";
|
293
|
-
}
|
294
|
-
const lookUpValue = this.lookup(arg, data);
|
295
|
-
const memoryValue = this.memory.getData(arg);
|
296
|
-
// console.log({ lookUpValue, memoryValue, arg });
|
297
|
-
|
298
|
-
if (!isThis.isNullOrUndefined(memoryValue)) {
|
299
|
-
return memoryValue;
|
300
|
-
}
|
301
|
-
if (!isThis.isUndefined(lookUpValue)) {
|
302
|
-
return lookUpValue;
|
303
|
-
}
|
304
|
-
return arg;
|
305
|
-
}
|
306
|
-
|
307
|
-
handleSpitStringArgs(stringArg: string) {
|
308
|
-
let currentQuote: string | null = null;
|
309
|
-
let result: string[] = [];
|
310
|
-
let currentPart = "";
|
311
|
-
for (let i = 0; i < stringArg.length; i++) {
|
312
|
-
const char = stringArg[i];
|
313
|
-
|
314
|
-
if (char === " " && currentQuote === null) {
|
315
|
-
if (currentPart) {
|
316
|
-
result.push(currentPart);
|
317
|
-
currentPart = "";
|
318
|
-
}
|
319
|
-
continue;
|
320
|
-
}
|
321
|
-
|
322
|
-
if (char === '"' || char === "'") {
|
323
|
-
if (currentQuote === char) {
|
324
|
-
currentQuote = null;
|
325
|
-
} else if (currentQuote === null) {
|
326
|
-
currentQuote = char;
|
327
|
-
}
|
328
|
-
}
|
329
|
-
|
330
|
-
currentPart += char;
|
331
|
-
}
|
332
|
-
|
333
|
-
if (currentPart) {
|
334
|
-
result.push(currentPart);
|
335
|
-
}
|
336
|
-
return result;
|
337
|
-
}
|
338
|
-
|
339
|
-
processHelperArgs(helperArgs: string, data: any, innerTemplate: any): any {
|
340
|
-
const helperArgsMatches = [...helperArgs.matchAll(/\(([^()]+)\)/g)]?.[0];
|
341
|
-
|
342
|
-
if (helperArgsMatches) {
|
343
|
-
const innerString = helperArgsMatches[1];
|
344
|
-
const splitedInnerArgs = this.handleSpitStringArgs(innerString);
|
345
|
-
const helperName = splitedInnerArgs[0];
|
346
|
-
const helperArgsArray = splitedInnerArgs.slice(1);
|
347
|
-
const helper = this.getHelper(helperName);
|
348
|
-
if (!helper) {
|
349
|
-
throw new Error("Missing helper: " + helperName);
|
350
|
-
}
|
351
|
-
const splittedArgs = helperArgsArray.map((e: any) =>
|
352
|
-
this.sanitizeArg(e, helperName, data)
|
353
|
-
) as any[];
|
354
|
-
// console.log({ helperName, helperArgs, helperArgsArray, splittedArgs });
|
355
|
-
let helperResult = helper(splittedArgs, data, innerTemplate);
|
356
|
-
// console.log({ helperResult });
|
357
|
-
let memorykey = null;
|
358
|
-
if (isThis.isArrayOrObject(helperResult)) {
|
359
|
-
memorykey = this.memory.storeData(helperResult);
|
360
|
-
}
|
361
|
-
const returnValue = helperArgs.replace(
|
362
|
-
helperArgsMatches[0],
|
363
|
-
memorykey ? memorykey : `"${helperResult}"`
|
364
|
-
);
|
365
|
-
return this.processHelperArgs(returnValue, data, innerTemplate);
|
366
|
-
} else {
|
367
|
-
return helperArgs;
|
368
|
-
}
|
369
|
-
}
|
370
|
-
|
371
|
-
processHelper(
|
372
|
-
string: string,
|
373
|
-
data: any,
|
374
|
-
innerTemplate?: any,
|
375
|
-
stringMatches?: any
|
376
|
-
): any {
|
377
|
-
stringMatches = stringMatches
|
378
|
-
? stringMatches
|
379
|
-
: [...string.matchAll(/{{#(\w+)\s*([^}]*)}}/g)]?.[0];
|
380
|
-
|
381
|
-
if (stringMatches) {
|
382
|
-
const capturedString = stringMatches[0];
|
383
|
-
const helperName = stringMatches[1];
|
384
|
-
const helperArgs = stringMatches[2];
|
385
|
-
const helper = this.getHelper(helperName);
|
386
|
-
if (!helper) {
|
387
|
-
throw new Error("Missing helper : " + helperName);
|
388
|
-
}
|
389
|
-
let splitedArgs = [];
|
390
|
-
if (!isThis.isEmptyString(helperArgs)) {
|
391
|
-
const processedHelperArgs = this.processHelperArgs(
|
392
|
-
helperArgs,
|
393
|
-
data,
|
394
|
-
innerTemplate
|
395
|
-
);
|
396
|
-
|
397
|
-
splitedArgs = this.handleSpitStringArgs(processedHelperArgs).map(
|
398
|
-
(e: any) => this.sanitizeArg(e, helperName, data)
|
399
|
-
) as any[];
|
400
|
-
// console.log({
|
401
|
-
// string,
|
402
|
-
// helperName,
|
403
|
-
// helperArgs,
|
404
|
-
// processedHelperArgs,
|
405
|
-
// splitedArgs,
|
406
|
-
// });
|
407
|
-
}
|
408
|
-
|
409
|
-
const helperResult = helper(splitedArgs, data, innerTemplate);
|
410
|
-
// console.log({ helperResult });
|
411
|
-
|
412
|
-
if (isThis.isArrayOrObject(helperResult)) {
|
413
|
-
return helperResult;
|
414
|
-
}
|
415
|
-
|
416
|
-
const resultString = string.replace(capturedString, helperResult);
|
417
|
-
stringMatches = [...resultString.matchAll(/{{#(\w+)\s*([^}]*)}}/g)]?.[0];
|
418
|
-
// console.log({ resultString, stringMatches });
|
419
|
-
|
420
|
-
if (stringMatches) {
|
421
|
-
return this.processHelper(
|
422
|
-
resultString,
|
423
|
-
data,
|
424
|
-
innerTemplate,
|
425
|
-
stringMatches
|
426
|
-
);
|
427
|
-
} else {
|
428
|
-
if (
|
429
|
-
isThis.isBooleanString(resultString) &&
|
430
|
-
isThis.isBoolean(helperResult)
|
431
|
-
) {
|
432
|
-
return helperResult;
|
433
|
-
}
|
434
|
-
if (isThis.isNullString(resultString) && isThis.isNull(helperResult)) {
|
435
|
-
return null;
|
436
|
-
}
|
437
|
-
if (
|
438
|
-
isThis.isUndefinedString(resultString) ||
|
439
|
-
isThis.isUndefined(helperResult)
|
440
|
-
) {
|
441
|
-
return undefined;
|
442
|
-
}
|
443
|
-
if (
|
444
|
-
(isThis.isNumberString(resultString) ||
|
445
|
-
isThis.isNumber(helperResult)) &&
|
446
|
-
helperResult === parseFloat(resultString)
|
447
|
-
) {
|
448
|
-
return helperResult;
|
449
|
-
}
|
450
|
-
return resultString;
|
451
|
-
}
|
452
|
-
} else {
|
453
|
-
return string;
|
454
|
-
}
|
455
|
-
}
|
456
|
-
}
|
457
|
-
// const langJson = new LangJSON();
|
458
|
-
// const template = {
|
459
|
-
// "{{#loop items.length}}": { name: "{{#var items[(var index)]}}" },
|
460
|
-
// };
|
461
|
-
// const result = langJson.applyTemplate(template, {
|
462
|
-
// items: ["Apple", "Banana", "Grapes"],
|
463
|
-
// });
|
464
|
-
// const returnValue = {
|
465
|
-
// 1: result,
|
466
|
-
// };
|
467
|
-
// console.log(JSON.stringify(returnValue, null, 2));
|