@ticatec/dyna-js 0.0.2 → 0.0.4

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/DynaJs.js CHANGED
@@ -1,24 +1,66 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  const utils_1 = require("./utils");
4
+ /**
5
+ * DynaJs - A safe dynamic code execution library
6
+ *
7
+ * Provides secure execution of dynamic JavaScript code using new Function()
8
+ * with configurable security policies and sandboxing capabilities.
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * const loader = new DynaJs({
13
+ * defaultImports: { MyClass },
14
+ * validateCode: true,
15
+ * allowBrowserAPIs: false
16
+ * });
17
+ *
18
+ * const result = loader.executeSync(`return new MyClass()`);
19
+ * ```
20
+ */
4
21
  class DynaJs {
22
+ /**
23
+ * Creates a new DynaJs instance
24
+ *
25
+ * @param config - Configuration options for the DynaJs instance
26
+ * @param config.defaultTimeout - Default timeout for async execution in milliseconds (default: 5000)
27
+ * @param config.defaultStrict - Whether to use strict mode by default (default: true)
28
+ * @param config.allowedGlobals - Whitelist of allowed global variables (empty = allow all defaultImports)
29
+ * @param config.blockedGlobals - Blacklist of blocked global variables
30
+ * @param config.defaultImports - Pre-imported classes/functions available to dynamic code
31
+ * @param config.allowTimers - Allow setTimeout/setInterval in dynamic code (default: false)
32
+ * @param config.allowDynamicImports - Allow import()/require() in dynamic code (default: false)
33
+ * @param config.validateCode - Enable code validation before execution (default: true)
34
+ * @param config.allowBrowserAPIs - Allow access to browser APIs like window/document (default: false)
35
+ * @param config.allowNodeAPIs - Allow access to Node.js APIs like process/require (default: false)
36
+ */
5
37
  constructor(config = {}) {
6
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
38
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
7
39
  this.config = {
8
40
  defaultTimeout: (_a = config.defaultTimeout) !== null && _a !== void 0 ? _a : 5000,
9
41
  defaultStrict: (_b = config.defaultStrict) !== null && _b !== void 0 ? _b : true,
10
42
  allowedGlobals: (_c = config.allowedGlobals) !== null && _c !== void 0 ? _c : [],
11
43
  blockedGlobals: (_d = config.blockedGlobals) !== null && _d !== void 0 ? _d : [],
12
44
  defaultImports: (_e = config.defaultImports) !== null && _e !== void 0 ? _e : {},
13
- defaultInjectedKeys: (_f = config.defaultInjectedKeys) !== null && _f !== void 0 ? _f : [],
14
- useProxyByDefault: (_g = config.useProxyByDefault) !== null && _g !== void 0 ? _g : true,
15
- allowTimers: (_h = config.allowTimers) !== null && _h !== void 0 ? _h : false,
16
- allowDynamicImports: (_j = config.allowDynamicImports) !== null && _j !== void 0 ? _j : false,
17
- validateCode: (_k = config.validateCode) !== null && _k !== void 0 ? _k : true,
18
- allowBrowserAPIs: (_l = config.allowBrowserAPIs) !== null && _l !== void 0 ? _l : false,
19
- allowNodeAPIs: (_m = config.allowNodeAPIs) !== null && _m !== void 0 ? _m : false
45
+ allowTimers: (_f = config.allowTimers) !== null && _f !== void 0 ? _f : false,
46
+ allowDynamicImports: (_g = config.allowDynamicImports) !== null && _g !== void 0 ? _g : false,
47
+ validateCode: (_h = config.validateCode) !== null && _h !== void 0 ? _h : true,
48
+ allowBrowserAPIs: (_j = config.allowBrowserAPIs) !== null && _j !== void 0 ? _j : false,
49
+ allowNodeAPIs: (_k = config.allowNodeAPIs) !== null && _k !== void 0 ? _k : false
20
50
  };
21
51
  }
52
+ /**
53
+ * Asynchronously execute dynamic code with timeout support
54
+ *
55
+ * @template T - The expected return type of the executed code
56
+ * @param code - The JavaScript code to execute
57
+ * @param options - Execution options
58
+ * @param options.context - Additional context variables for the code
59
+ * @param options.timeout - Execution timeout in milliseconds (overrides defaultTimeout)
60
+ * @param options.strict - Whether to use strict mode (overrides defaultStrict)
61
+ * @param options.imports - Additional imports for this execution only
62
+ * @returns Promise resolving to the execution result
63
+ */
22
64
  async execute(code, options = {}) {
23
65
  var _a, _b;
24
66
  const startTime = performance.now();
@@ -33,17 +75,25 @@ class DynaJs {
33
75
  const timeout = (_a = options.timeout) !== null && _a !== void 0 ? _a : this.config.defaultTimeout;
34
76
  const strict = (_b = options.strict) !== null && _b !== void 0 ? _b : this.config.defaultStrict;
35
77
  const result = await this.executeWithTimeout(code, context, timeout, strict);
36
- const executionTime = performance.now() - startTime;
37
- return {
38
- result: result,
39
- executionTime
40
- };
78
+ console.info(`Build dyna code in ${performance.now() - startTime}ms`);
79
+ return result;
41
80
  }
42
81
  catch (error) {
43
82
  const executionTime = performance.now() - startTime;
44
83
  throw new Error(`Script execution failed after ${executionTime.toFixed(2)}ms: ${error instanceof Error ? error.message : String(error)}`);
45
84
  }
46
85
  }
86
+ /**
87
+ * Synchronously execute dynamic code and return result directly
88
+ *
89
+ * @template T - The expected return type of the executed code
90
+ * @param code - The JavaScript code to execute
91
+ * @param options - Execution options
92
+ * @param options.context - Additional context variables for the code
93
+ * @param options.strict - Whether to use strict mode (overrides defaultStrict)
94
+ * @param options.imports - Additional imports for this execution only
95
+ * @returns The direct result of code execution
96
+ */
47
97
  executeSync(code, options = {}) {
48
98
  var _a;
49
99
  const startTime = performance.now();
@@ -57,17 +107,26 @@ class DynaJs {
57
107
  const context = this.prepareContext(options.context, options.imports);
58
108
  const strict = (_a = options.strict) !== null && _a !== void 0 ? _a : this.config.defaultStrict;
59
109
  const result = this.executeCode(code, context, strict);
60
- const executionTime = performance.now() - startTime;
61
- return {
62
- result: result,
63
- executionTime
64
- };
110
+ console.info(`Build dyna code in ${performance.now() - startTime}ms`);
111
+ return result;
65
112
  }
66
113
  catch (error) {
67
114
  const executionTime = performance.now() - startTime;
68
115
  throw new Error(`Script execution failed after ${executionTime.toFixed(2)}ms: ${error instanceof Error ? error.message : String(error)}`);
69
116
  }
70
117
  }
118
+ /**
119
+ * Execute code with a timeout constraint
120
+ *
121
+ * @private
122
+ * @template T - The expected return type
123
+ * @param code - The JavaScript code to execute
124
+ * @param context - Execution context with available variables
125
+ * @param timeout - Maximum execution time in milliseconds
126
+ * @param strict - Whether to use strict mode
127
+ * @returns Promise resolving to the execution result
128
+ * @throws {Error} If execution exceeds timeout or runtime error occurs
129
+ */
71
130
  async executeWithTimeout(code, context, timeout, strict) {
72
131
  return new Promise((resolve, reject) => {
73
132
  const timer = setTimeout(() => {
@@ -84,6 +143,16 @@ class DynaJs {
84
143
  }
85
144
  });
86
145
  }
146
+ /**
147
+ * Core code execution engine using new Function()
148
+ *
149
+ * @private
150
+ * @param code - The JavaScript code to execute
151
+ * @param context - Execution context with available variables
152
+ * @param strict - Whether to use strict mode
153
+ * @returns The execution result
154
+ * @throws {Error} If code execution fails
155
+ */
87
156
  executeCode(code, context, strict) {
88
157
  const contextKeys = Object.keys(context);
89
158
  const contextValues = Object.values(context);
@@ -97,6 +166,29 @@ class DynaJs {
97
166
  throw new Error(`Code execution error: ${error instanceof Error ? error.message : String(error)}`);
98
167
  }
99
168
  }
169
+ /**
170
+ * Create a reusable function from dynamic code
171
+ *
172
+ * @template T - The function signature type
173
+ * @param code - The JavaScript code for the function body
174
+ * @param paramNames - Array of parameter names for the function
175
+ * @param options - Execution options
176
+ * @param options.context - Additional context variables
177
+ * @param options.strict - Whether to use strict mode
178
+ * @param options.imports - Additional imports
179
+ * @returns A function that can be called multiple times
180
+ * @throws {Error} If function creation fails
181
+ *
182
+ * @example
183
+ * ```typescript
184
+ * const validator = loader.createFunction<(data: any) => boolean>(`
185
+ * return function(data) {
186
+ * return data.name && data.email;
187
+ * };
188
+ * `);
189
+ * const isValid = validator({ name: 'John', email: 'john@example.com' });
190
+ * ```
191
+ */
100
192
  createFunction(code, paramNames = [], options = {}) {
101
193
  var _a;
102
194
  const context = this.prepareContext(options.context, options.imports);
@@ -117,79 +209,118 @@ class DynaJs {
117
209
  throw new Error(`Function creation error: ${error instanceof Error ? error.message : String(error)}`);
118
210
  }
119
211
  }
212
+ /**
213
+ * Synchronously execute code with additional temporary imports
214
+ *
215
+ * @template T - The expected return type
216
+ * @param code - The JavaScript code to execute
217
+ * @param imports - Additional imports to merge with defaultImports
218
+ * @param options - Additional execution options
219
+ * @returns The direct result of code execution
220
+ * @throws {Error} If code validation fails or runtime error occurs
221
+ *
222
+ * @example
223
+ * ```typescript
224
+ * const result = loader.executeWithImports(`
225
+ * return new CustomComponent();
226
+ * `, {
227
+ * CustomComponent: MyCustomComponent
228
+ * });
229
+ * ```
230
+ */
120
231
  executeWithImports(code, imports, options = {}) {
121
232
  return this.executeSync(code, Object.assign(Object.assign({}, options), { imports: Object.assign(Object.assign({}, this.config.defaultImports), imports) }));
122
233
  }
234
+ /**
235
+ * Asynchronously execute code with additional temporary imports
236
+ *
237
+ * @template T - The expected return type
238
+ * @param code - The JavaScript code to execute
239
+ * @param imports - Additional imports to merge with defaultImports
240
+ * @param options - Additional execution options (including timeout)
241
+ * @returns Promise resolving to the execution result
242
+ * @throws {Error} If code validation fails, execution times out, or runtime error occurs
243
+ *
244
+ * @example
245
+ * ```typescript
246
+ * const result = await loader.executeWithImportsAsync(`
247
+ * return await fetchData();
248
+ * `, {
249
+ * fetchData: myFetchFunction
250
+ * }, { timeout: 5000 });
251
+ * ```
252
+ */
123
253
  async executeWithImportsAsync(code, imports, options = {}) {
124
254
  return this.execute(code, Object.assign(Object.assign({}, options), { imports: Object.assign(Object.assign({}, this.config.defaultImports), imports) }));
125
255
  }
126
- createFormClass(code, context = {}, injectedKeys = []) {
127
- const useProxy = this.config.useProxyByDefault;
128
- const mergedContext = Object.assign(Object.assign({}, context), this.config.defaultImports);
129
- const mergedKeys = [...this.config.defaultInjectedKeys, ...injectedKeys];
130
- if (useProxy) {
131
- return this.executeWithProxy(code, mergedContext, mergedKeys);
132
- }
133
- else {
134
- return this.executeSync(code, {
135
- context: mergedContext,
136
- imports: this.config.defaultImports
137
- }).result;
138
- }
139
- }
140
- executeWithProxy(code, context, injectedKeys) {
141
- const injected = {};
142
- for (const key of injectedKeys) {
143
- if (context.window && key in context.window) {
144
- injected[key] = context.window[key];
145
- }
146
- else if (key in context) {
147
- injected[key] = context[key];
148
- }
149
- }
150
- const sandboxContext = Object.assign(Object.assign({}, context), injected);
151
- const sandbox = new Proxy(sandboxContext, {
152
- has(target, key) {
153
- if (key in target)
154
- return true;
155
- if (context.window && key in context.window)
156
- return true;
157
- return false;
158
- },
159
- get(target, key) {
160
- if (key in target)
161
- return target[key];
162
- if (context.window && key in context.window)
163
- return context.window[key];
164
- console.warn(`DynaJs: ${String(key)} not found`);
165
- return undefined;
166
- }
167
- });
168
- const wrappedCode = `
169
- with (sandbox) {
170
- ${Object.keys(sandbox).map(k => `const ${k} = sandbox.${k};`).join('\n')}
171
-
172
- ${code}
173
- }
174
- `;
175
- const fn = new Function('sandbox', wrappedCode);
176
- return fn(sandbox);
177
- }
256
+ /**
257
+ * Initialize the singleton instance of DynaJs
258
+ *
259
+ * @param config - Configuration options for the singleton instance
260
+ * @returns The initialized singleton instance
261
+ *
262
+ * @example
263
+ * ```typescript
264
+ * DynaJs.initialize({
265
+ * defaultImports: { MyClass, MyFunction },
266
+ * validateCode: true
267
+ * });
268
+ * ```
269
+ */
178
270
  static initialize(config) {
179
271
  if (DynaJs.instance == null) {
180
272
  DynaJs.instance = new DynaJs(config);
181
273
  }
182
274
  return DynaJs.instance;
183
275
  }
276
+ /**
277
+ * Get the singleton instance of DynaJs
278
+ *
279
+ * @returns The singleton instance
280
+ * @throws {Error} If DynaJs hasn't been initialized
281
+ *
282
+ * @example
283
+ * ```typescript
284
+ * const loader = DynaJs.getInstance();
285
+ * const result = loader.executeSync(`return 1 + 1`);
286
+ * ```
287
+ */
184
288
  static getInstance() {
185
289
  if (DynaJs.instance == null) {
186
290
  throw new Error("DynaJs hasn't been initialized. Call DynaJs.initialize() first.");
187
291
  }
188
292
  return DynaJs.instance;
189
293
  }
294
+ /**
295
+ * Reset the singleton instance (useful for testing)
296
+ *
297
+ * @example
298
+ * ```typescript
299
+ * DynaJs.reset();
300
+ * DynaJs.initialize(newConfig);
301
+ * ```
302
+ */
190
303
  static reset() {
191
304
  DynaJs.instance = null;
192
305
  }
306
+ /**
307
+ * Prepare the execution context by merging user context, imports, and applying security filters
308
+ *
309
+ * Execution flow:
310
+ * 1. Create safe context (filtering browser/node APIs based on config)
311
+ * 2. Merge with defaultImports and additional imports
312
+ * 3. Apply allowedGlobals whitelist filter if configured
313
+ *
314
+ * @private
315
+ * @param userContext - User-provided context variables
316
+ * @param imports - Additional imports for this execution
317
+ * @returns The final execution context
318
+ *
319
+ * @remarks
320
+ * If allowedGlobals is set and not empty, only variables in the whitelist will be available.
321
+ * This happens AFTER merging defaultImports, so make sure to include all needed imports
322
+ * in the allowedGlobals array if you use this feature.
323
+ */
193
324
  prepareContext(userContext = {}, imports = {}) {
194
325
  let context = (0, utils_1.createSafeContext)(userContext, {
195
326
  allowBrowserAPIs: this.config.allowBrowserAPIs,
@@ -209,5 +340,9 @@ class DynaJs {
209
340
  return context;
210
341
  }
211
342
  }
343
+ /**
344
+ * Singleton instance of DynaJs
345
+ * @private
346
+ */
212
347
  DynaJs.instance = null;
213
348
  exports.default = DynaJs;
package/dist/types.d.ts CHANGED
@@ -9,12 +9,6 @@ export interface ExecutionOptions {
9
9
  timeout?: number;
10
10
  strict?: boolean;
11
11
  imports?: ModuleImports;
12
- injectedKeys?: string[];
13
- useProxy?: boolean;
14
- }
15
- export interface ExecutionResult<T = any> {
16
- result: T;
17
- executionTime: number;
18
12
  }
19
13
  export interface DynaJsConfig {
20
14
  defaultTimeout?: number;
@@ -22,8 +16,6 @@ export interface DynaJsConfig {
22
16
  allowedGlobals?: string[];
23
17
  blockedGlobals?: string[];
24
18
  defaultImports?: ModuleImports;
25
- defaultInjectedKeys?: string[];
26
- useProxyByDefault?: boolean;
27
19
  allowTimers?: boolean;
28
20
  allowDynamicImports?: boolean;
29
21
  validateCode?: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,gBAAgB;IAC/B,CAAC,GAAG,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AAgB;IAC/B,OAAO,CAAC,EAAE,gBAAgB,CAAC;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB,OAAO,CAAC,EAAE,aAAa,CAAC;CACzB;AAED,MAAM,WAAW,YAAY;IAC3B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,aAAa,CAAC,EAAE,OAAO,CAAC;IACxB,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,cAAc,CAAC,EAAE,MAAM,EAAE,CAAC;IAC1B,cAAc,CAAC,EAAE,aAAa,CAAC;IAC/B,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ticatec/dyna-js",
3
- "version": "0.0.2",
3
+ "version": "0.0.4",
4
4
  "description": "A TypeScript library for dynamic code execution using new Function() that works in both Node.js and browser environments",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.esm.js",