@apify/actor-memory-expression 0.1.15 → 0.1.17

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/cjs/index.cjs CHANGED
@@ -63,20 +63,23 @@ var math = (0, import_mathjs.create)({
63
63
  nullishDependencies: import_mathjs.nullishDependencies
64
64
  });
65
65
  var { compile } = math;
66
- math.import({
67
- // We disable evaluate to prevent users from calling it inside their expressions.
68
- // For example: defaultMemoryMbytes = "evaluate('2 + 2')"
69
- evaluate() {
70
- throw new Error("Function evaluate is disabled.");
71
- },
72
- compile() {
73
- throw new Error("Function compile is disabled.");
66
+ math.import(
67
+ {
68
+ // We disable evaluate to prevent users from calling it inside their expressions.
69
+ // For example: defaultMemoryMbytes = "evaluate('2 + 2')"
70
+ evaluate() {
71
+ throw new Error("Function evaluate is disabled.");
72
+ },
73
+ compile() {
74
+ throw new Error("Function compile is disabled.");
75
+ },
76
+ // We need to disable it, because compileDependencies imports parseDependencies.
77
+ parse() {
78
+ throw new Error("Function parse is disabled.");
79
+ }
74
80
  },
75
- // We need to disable it, because compileDependencies imports parseDependencies.
76
- parse() {
77
- throw new Error("Function parse is disabled.");
78
- }
79
- }, { override: true });
81
+ { override: true }
82
+ );
80
83
  var customGetFunc = /* @__PURE__ */ __name((obj, path, defaultVal) => {
81
84
  return path.split(".").reduce((current, key) => current?.[key], obj) ?? defaultVal;
82
85
  }, "customGetFunc");
@@ -94,26 +97,23 @@ var roundToClosestPowerOf2 = /* @__PURE__ */ __name((num) => {
94
97
  }, "roundToClosestPowerOf2");
95
98
  var processTemplateVariables = /* @__PURE__ */ __name((defaultMemoryMbytes) => {
96
99
  const variableRegex = /{{\s*([a-zA-Z0-9_.]+)\s*}}/g;
97
- const processedExpression = defaultMemoryMbytes.replace(
98
- variableRegex,
99
- (_, variableName) => {
100
- if (variableName.startsWith("input.")) {
101
- return variableName;
102
- }
103
- if (variableName.startsWith("runOptions.")) {
104
- const key = variableName.slice("runOptions.".length);
105
- if (!ALLOWED_RUN_OPTION_KEYS.has(key)) {
106
- throw new Error(
107
- `Invalid variable '{{${variableName}}}' in expression. Only the following runOptions are allowed: ${Array.from(ALLOWED_RUN_OPTION_KEYS).map((k) => `runOptions.${k}`).join(", ")}.`
108
- );
109
- }
110
- return variableName;
100
+ const processedExpression = defaultMemoryMbytes.replace(variableRegex, (_, variableName) => {
101
+ if (variableName.startsWith("input.")) {
102
+ return variableName;
103
+ }
104
+ if (variableName.startsWith("runOptions.")) {
105
+ const key = variableName.slice("runOptions.".length);
106
+ if (!ALLOWED_RUN_OPTION_KEYS.has(key)) {
107
+ throw new Error(
108
+ `Invalid variable '{{${variableName}}}' in expression. Only the following runOptions are allowed: ${Array.from(
109
+ ALLOWED_RUN_OPTION_KEYS
110
+ ).map((k) => `runOptions.${k}`).join(", ")}.`
111
+ );
111
112
  }
112
- throw new Error(
113
- `Invalid variable '{{${variableName}}}' in expression.`
114
- );
113
+ return variableName;
115
114
  }
116
- );
115
+ throw new Error(`Invalid variable '{{${variableName}}}' in expression.`);
116
+ });
117
117
  return processedExpression;
118
118
  }, "processTemplateVariables");
119
119
  var getCompiledExpression = /* @__PURE__ */ __name(async (expression, cache) => {
@@ -129,7 +129,9 @@ var getCompiledExpression = /* @__PURE__ */ __name(async (expression, cache) =>
129
129
  }, "getCompiledExpression");
130
130
  var calculateRunDynamicMemory = /* @__PURE__ */ __name(async (defaultMemoryMbytes, context, options = void 0) => {
131
131
  if (defaultMemoryMbytes.length > DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH) {
132
- throw new Error(`The defaultMemoryMbytes expression is too long. Max length is ${DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH} characters.`);
132
+ throw new Error(
133
+ `The defaultMemoryMbytes expression is too long. Max length is ${DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH} characters.`
134
+ );
133
135
  }
134
136
  const preprocessedExpression = processTemplateVariables(defaultMemoryMbytes);
135
137
  const preparedContext = {
package/cjs/index.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts","../../src/memory_calculator.ts"],"sourcesContent":["export * from './memory_calculator';\nexport * from './types';\n","// MathJS bundle with only numbers is ~2x smaller than the default one.\nimport {\n addDependencies,\n andDependencies,\n compileDependencies,\n create,\n divideDependencies,\n evaluateDependencies,\n maxDependencies,\n minDependencies,\n multiplyDependencies,\n notDependencies,\n nullishDependencies,\n orDependencies,\n subtractDependencies,\n xorDependencies,\n} from 'mathjs';\n\nimport { ACTOR_LIMITS } from '@apify/consts';\n\nimport type { ActorRunOptions, CompilationCache, CompilationResult, MemoryEvaluationContext } from './types.js';\n\n// In theory, users could create expressions longer than 1000 characters,\n// but in practice, it's unlikely anyone would need that much complexity.\n// Later we can increase this limit if needed.\nexport const DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH = 1000;\n\n/**\n * A Set of allowed keys from ActorRunOptions that can be used in\n * the {{runOptions.variable}} syntax.\n */\nconst ALLOWED_RUN_OPTION_KEYS = new Set<keyof ActorRunOptions>([\n 'build',\n 'timeoutSecs',\n 'memoryMbytes',\n 'diskMbytes',\n 'maxItems',\n 'maxTotalChargeUsd',\n 'restartOnError',\n]);\n\n/**\n * Create a mathjs instance with selected dependencies, then disable potentially dangerous ones.\n * MathJS security recommendations: https://mathjs.org/docs/expressions/security.html\n */\nconst math = create({\n // expression dependencies\n // Required for compiling and evaluating root expressions.\n // We disable it below to prevent users from calling `evaluate()` inside their expressions.\n // For example: defaultMemoryMbytes = \"evaluate('2 + 2')\"\n compileDependencies,\n evaluateDependencies,\n\n // arithmetic dependencies\n addDependencies,\n subtractDependencies,\n multiplyDependencies,\n divideDependencies,\n // statistics dependencies\n maxDependencies,\n minDependencies,\n // logical dependencies\n andDependencies,\n notDependencies,\n orDependencies,\n xorDependencies,\n // without that dependency 'null ?? 5', won't work\n nullishDependencies,\n});\nconst { compile } = math;\n\n// Disable potentially dangerous functions\nmath.import({\n // We disable evaluate to prevent users from calling it inside their expressions.\n // For example: defaultMemoryMbytes = \"evaluate('2 + 2')\"\n evaluate() { throw new Error('Function evaluate is disabled.'); },\n compile() { throw new Error('Function compile is disabled.'); },\n // We need to disable it, because compileDependencies imports parseDependencies.\n parse() { throw new Error('Function parse is disabled.'); },\n}, { override: true });\n\n/**\n * Safely retrieves a nested property from an object using a dot-notation string path.\n *\n * This is custom function designed to be injected into the math expression evaluator,\n * allowing expressions like `get(input, 'user.settings.memory', 512)` or `get(input, 'startUrls.length', 10)` to get array length.\n *\n * @param obj The source object to search within.\n * @param path A dot-separated string representing the nested path (e.g., \"input.payload.size\").\n * @param defaultVal The value to return if the path is not found or the value is `null` or `undefined`.\n * @returns The retrieved value, or `defaultVal` if the path is unreachable.\n*/\nconst customGetFunc = (obj: any, path: string, defaultVal?: number) => {\n return (path.split('.').reduce((current, key) => current?.[key], obj)) ?? defaultVal;\n};\n\n/**\n * Rounds a number to the closest power of 2.\n * The result is clamped to the allowed range (ACTOR_LIMITS.MIN_RUN_MEMORY_MBYTES - ACTOR_LIMITS.MAX_RUN_MEMORY_MBYTES).\n * @param num The number to round.\n * @returns The closest power of 2 within min/max range.\n*/\nconst roundToClosestPowerOf2 = (num: number): number => {\n if (typeof num !== 'number' || Number.isNaN(num) || !Number.isFinite(num)) {\n throw new Error(`Calculated memory value is not a valid number: ${num}.`);\n }\n\n // Handle 0 or negative values.\n if (num <= 0) {\n throw new Error(`Calculated memory value must be a positive number, greater than 0, got: ${num}.`);\n }\n\n const log2n = Math.log2(num);\n\n const roundedLog = Math.round(log2n);\n const result = 2 ** roundedLog;\n\n return Math.max(ACTOR_LIMITS.MIN_RUN_MEMORY_MBYTES, Math.min(result, ACTOR_LIMITS.MAX_RUN_MEMORY_MBYTES));\n};\n\n/**\n * Replaces all `{{variable}}` placeholders in an expression into direct\n * property access (e.g. `{{runOptions.memoryMbytes}}` → `runOptions.memoryMbytes`).\n *\n * All `input.*` values are accepted, while `runOptions.*` are validated (7 variables from ALLOWED_RUN_OPTION_KEYS).\n *\n * Note: While not really needed for Math.js, this approach allows developers\n * to use a consistent double-brace templating syntax `{{runOptions.timeoutSecs}}`\n * across the Apify platform. We also want to avoid compiling the expression with the\n * actual values as that would make caching less effective.\n *\n * @example\n * // Returns \"runOptions.memoryMbytes + 1024\"\n * preprocessDefaultMemoryExpression(\"{{runOptions.memoryMbytes}} + 1024\");\n *\n * @param defaultMemoryMbytes The raw string expression, e.g., \"{{runOptions.memoryMbytes}} * 2\".\n * @returns A safe, processed expression for evaluation, e.g., \"runOptions.memoryMbytes * 2\".\n */\nconst processTemplateVariables = (defaultMemoryMbytes: string): string => {\n const variableRegex = /{{\\s*([a-zA-Z0-9_.]+)\\s*}}/g;\n\n const processedExpression = defaultMemoryMbytes.replace(\n variableRegex,\n (_, variableName: string) => {\n // 1. Check if the variable is accessing input (e.g. {{input.someValue}})\n // We do not validate the specific property name because `input` is dynamic.\n if (variableName.startsWith('input.')) {\n return variableName;\n }\n\n // 2. Check if the variable is accessing runOptions (e.g. {{runOptions.memoryMbytes}}) and validate the keys.\n if (variableName.startsWith('runOptions.')) {\n const key = variableName.slice('runOptions.'.length);\n if (!ALLOWED_RUN_OPTION_KEYS.has(key as keyof ActorRunOptions)) {\n throw new Error(\n `Invalid variable '{{${variableName}}}' in expression. Only the following runOptions are allowed: ${Array.from(ALLOWED_RUN_OPTION_KEYS).map((k) => `runOptions.${k}`).join(', ')}.`,\n );\n }\n return variableName;\n }\n\n // 3. Throw error for unrecognized variables (e.g. {{someVariable}})\n throw new Error(\n `Invalid variable '{{${variableName}}}' in expression.`,\n );\n },\n );\n\n return processedExpression;\n};\n\n/*\n* Retrieves a compiled expression from the cache or compiles it if not present.\n*\n* @param expression The expression string to compile.\n* @param cache An optional cache to store/retrieve compiled expressions.\n* @returns The compiled CompilationResult.\n*/\nconst getCompiledExpression = async (expression: string, cache: CompilationCache | undefined): Promise<CompilationResult> => {\n if (!cache) {\n return compile(expression);\n }\n\n let compiledExpression = await cache.get(expression);\n\n if (!compiledExpression) {\n compiledExpression = compile(expression);\n await cache.set(expression, compiledExpression!);\n }\n\n return compiledExpression;\n};\n\n/**\n * Evaluates a dynamic memory expression string using the provided context.\n * Result is rounded to the closest power of 2 and clamped within allowed limits.\n *\n * @param defaultMemoryMbytes The string expression to evaluate (e.g., `get(input, 'urls.length', 10) * 1024` for `input = { urls: ['url1', 'url2'] }`).\n * @param context The `MemoryEvaluationContext` (containing `input` and `runOptions`) available to the expression.\n * @param options.cache Optional synchronous cache. Since compiled functions cannot be saved to a database/Redis, they are kept in local memory.\n * @returns The calculated memory value rounded to the closest power of 2 and clamped within allowed limits.\n*/\nexport const calculateRunDynamicMemory = async (\n defaultMemoryMbytes: string,\n context: MemoryEvaluationContext,\n options: { cache: CompilationCache } | undefined = undefined,\n) => {\n if (defaultMemoryMbytes.length > DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH) {\n throw new Error(`The defaultMemoryMbytes expression is too long. Max length is ${DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH} characters.`);\n }\n\n // Replaces all occurrences of {{variable}} with variable\n // e.g., \"{{runOptions.memoryMbytes}} + 1024\" becomes \"runOptions.memoryMbytes + 1024\"\n const preprocessedExpression = processTemplateVariables(defaultMemoryMbytes);\n\n const preparedContext = {\n ...context,\n get: customGetFunc,\n };\n\n const compiledExpression = await getCompiledExpression(preprocessedExpression, options?.cache);\n\n let finalResult: number | { entries: number[] } = compiledExpression.evaluate(preparedContext);\n\n // Mathjs wraps multi-line expressions in an object, so we need to extract the last entry.\n // Note: one-line expressions return a number directly.\n if (finalResult && typeof finalResult === 'object' && 'entries' in finalResult) {\n const { entries } = finalResult;\n finalResult = entries[entries.length - 1];\n }\n\n return roundToClosestPowerOf2(finalResult);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,oBAeO;AAEP,oBAA6B;AAOtB,IAAM,8CAA8C;A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E7F,MAAI,cAA8C,mBAAmB,SAAS,eAAe;AAI7F,MAAI,eAAe,OAAO,gBAAgB,YAAY,aAAa,aAAa;AAC5E,UAAM,EAAE,QAAQ,IAAI;AACpB,kBAAc,QAAQ,QAAQ,SAAS,CAAC;AAAA,EAC5C;AAEA,SAAO,uBAAuB,WAAW;AAC7C,GA9ByC;","names":[]}
1
+ {"version":3,"sources":["../../src/index.ts","../../src/memory_calculator.ts"],"sourcesContent":["export * from './memory_calculator';\nexport * from './types';\n","// MathJS bundle with only numbers is ~2x smaller than the default one.\nimport {\n addDependencies,\n andDependencies,\n compileDependencies,\n create,\n divideDependencies,\n evaluateDependencies,\n maxDependencies,\n minDependencies,\n multiplyDependencies,\n notDependencies,\n nullishDependencies,\n orDependencies,\n subtractDependencies,\n xorDependencies,\n} from 'mathjs';\n\nimport { ACTOR_LIMITS } from '@apify/consts';\n\nimport type { ActorRunOptions, CompilationCache, CompilationResult, MemoryEvaluationContext } from './types.js';\n\n// In theory, users could create expressions longer than 1000 characters,\n// but in practice, it's unlikely anyone would need that much complexity.\n// Later we can increase this limit if needed.\nexport const DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH = 1000;\n\n/**\n * A Set of allowed keys from ActorRunOptions that can be used in\n * the {{runOptions.variable}} syntax.\n */\nconst ALLOWED_RUN_OPTION_KEYS = new Set<keyof ActorRunOptions>([\n 'build',\n 'timeoutSecs',\n 'memoryMbytes',\n 'diskMbytes',\n 'maxItems',\n 'maxTotalChargeUsd',\n 'restartOnError',\n]);\n\n/**\n * Create a mathjs instance with selected dependencies, then disable potentially dangerous ones.\n * MathJS security recommendations: https://mathjs.org/docs/expressions/security.html\n */\nconst math = create({\n // expression dependencies\n // Required for compiling and evaluating root expressions.\n // We disable it below to prevent users from calling `evaluate()` inside their expressions.\n // For example: defaultMemoryMbytes = \"evaluate('2 + 2')\"\n compileDependencies,\n evaluateDependencies,\n\n // arithmetic dependencies\n addDependencies,\n subtractDependencies,\n multiplyDependencies,\n divideDependencies,\n // statistics dependencies\n maxDependencies,\n minDependencies,\n // logical dependencies\n andDependencies,\n notDependencies,\n orDependencies,\n xorDependencies,\n // without that dependency 'null ?? 5', won't work\n nullishDependencies,\n});\nconst { compile } = math;\n\n// Disable potentially dangerous functions\nmath.import(\n {\n // We disable evaluate to prevent users from calling it inside their expressions.\n // For example: defaultMemoryMbytes = \"evaluate('2 + 2')\"\n evaluate() {\n throw new Error('Function evaluate is disabled.');\n },\n compile() {\n throw new Error('Function compile is disabled.');\n },\n // We need to disable it, because compileDependencies imports parseDependencies.\n parse() {\n throw new Error('Function parse is disabled.');\n },\n },\n { override: true },\n);\n\n/**\n * Safely retrieves a nested property from an object using a dot-notation string path.\n *\n * This is custom function designed to be injected into the math expression evaluator,\n * allowing expressions like `get(input, 'user.settings.memory', 512)` or `get(input, 'startUrls.length', 10)` to get array length.\n *\n * @param obj The source object to search within.\n * @param path A dot-separated string representing the nested path (e.g., \"input.payload.size\").\n * @param defaultVal The value to return if the path is not found or the value is `null` or `undefined`.\n * @returns The retrieved value, or `defaultVal` if the path is unreachable.\n */\nconst customGetFunc = (obj: any, path: string, defaultVal?: number) => {\n return path.split('.').reduce((current, key) => current?.[key], obj) ?? defaultVal;\n};\n\n/**\n * Rounds a number to the closest power of 2.\n * The result is clamped to the allowed range (ACTOR_LIMITS.MIN_RUN_MEMORY_MBYTES - ACTOR_LIMITS.MAX_RUN_MEMORY_MBYTES).\n * @param num The number to round.\n * @returns The closest power of 2 within min/max range.\n */\nconst roundToClosestPowerOf2 = (num: number): number => {\n if (typeof num !== 'number' || Number.isNaN(num) || !Number.isFinite(num)) {\n throw new Error(`Calculated memory value is not a valid number: ${num}.`);\n }\n\n // Handle 0 or negative values.\n if (num <= 0) {\n throw new Error(`Calculated memory value must be a positive number, greater than 0, got: ${num}.`);\n }\n\n const log2n = Math.log2(num);\n\n const roundedLog = Math.round(log2n);\n const result = 2 ** roundedLog;\n\n return Math.max(ACTOR_LIMITS.MIN_RUN_MEMORY_MBYTES, Math.min(result, ACTOR_LIMITS.MAX_RUN_MEMORY_MBYTES));\n};\n\n/**\n * Replaces all `{{variable}}` placeholders in an expression into direct\n * property access (e.g. `{{runOptions.memoryMbytes}}` → `runOptions.memoryMbytes`).\n *\n * All `input.*` values are accepted, while `runOptions.*` are validated (7 variables from ALLOWED_RUN_OPTION_KEYS).\n *\n * Note: While not really needed for Math.js, this approach allows developers\n * to use a consistent double-brace templating syntax `{{runOptions.timeoutSecs}}`\n * across the Apify platform. We also want to avoid compiling the expression with the\n * actual values as that would make caching less effective.\n *\n * @example\n * // Returns \"runOptions.memoryMbytes + 1024\"\n * preprocessDefaultMemoryExpression(\"{{runOptions.memoryMbytes}} + 1024\");\n *\n * @param defaultMemoryMbytes The raw string expression, e.g., \"{{runOptions.memoryMbytes}} * 2\".\n * @returns A safe, processed expression for evaluation, e.g., \"runOptions.memoryMbytes * 2\".\n */\nconst processTemplateVariables = (defaultMemoryMbytes: string): string => {\n const variableRegex = /{{\\s*([a-zA-Z0-9_.]+)\\s*}}/g;\n\n const processedExpression = defaultMemoryMbytes.replace(variableRegex, (_, variableName: string) => {\n // 1. Check if the variable is accessing input (e.g. {{input.someValue}})\n // We do not validate the specific property name because `input` is dynamic.\n if (variableName.startsWith('input.')) {\n return variableName;\n }\n\n // 2. Check if the variable is accessing runOptions (e.g. {{runOptions.memoryMbytes}}) and validate the keys.\n if (variableName.startsWith('runOptions.')) {\n const key = variableName.slice('runOptions.'.length);\n if (!ALLOWED_RUN_OPTION_KEYS.has(key as keyof ActorRunOptions)) {\n throw new Error(\n `Invalid variable '{{${variableName}}}' in expression. Only the following runOptions are allowed: ${Array.from(\n ALLOWED_RUN_OPTION_KEYS,\n )\n .map((k) => `runOptions.${k}`)\n .join(', ')}.`,\n );\n }\n return variableName;\n }\n\n // 3. Throw error for unrecognized variables (e.g. {{someVariable}})\n throw new Error(`Invalid variable '{{${variableName}}}' in expression.`);\n });\n\n return processedExpression;\n};\n\n/*\n * Retrieves a compiled expression from the cache or compiles it if not present.\n *\n * @param expression The expression string to compile.\n * @param cache An optional cache to store/retrieve compiled expressions.\n * @returns The compiled CompilationResult.\n */\nconst getCompiledExpression = async (\n expression: string,\n cache: CompilationCache | undefined,\n): Promise<CompilationResult> => {\n if (!cache) {\n return compile(expression);\n }\n\n let compiledExpression = await cache.get(expression);\n\n if (!compiledExpression) {\n compiledExpression = compile(expression);\n await cache.set(expression, compiledExpression!);\n }\n\n return compiledExpression;\n};\n\n/**\n * Evaluates a dynamic memory expression string using the provided context.\n * Result is rounded to the closest power of 2 and clamped within allowed limits.\n *\n * @param defaultMemoryMbytes The string expression to evaluate (e.g., `get(input, 'urls.length', 10) * 1024` for `input = { urls: ['url1', 'url2'] }`).\n * @param context The `MemoryEvaluationContext` (containing `input` and `runOptions`) available to the expression.\n * @param options.cache Optional synchronous cache. Since compiled functions cannot be saved to a database/Redis, they are kept in local memory.\n * @returns The calculated memory value rounded to the closest power of 2 and clamped within allowed limits.\n */\nexport const calculateRunDynamicMemory = async (\n defaultMemoryMbytes: string,\n context: MemoryEvaluationContext,\n options: { cache: CompilationCache } | undefined = undefined,\n) => {\n if (defaultMemoryMbytes.length > DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH) {\n throw new Error(\n `The defaultMemoryMbytes expression is too long. Max length is ${DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH} characters.`,\n );\n }\n\n // Replaces all occurrences of {{variable}} with variable\n // e.g., \"{{runOptions.memoryMbytes}} + 1024\" becomes \"runOptions.memoryMbytes + 1024\"\n const preprocessedExpression = processTemplateVariables(defaultMemoryMbytes);\n\n const preparedContext = {\n ...context,\n get: customGetFunc,\n };\n\n const compiledExpression = await getCompiledExpression(preprocessedExpression, options?.cache);\n\n let finalResult: number | { entries: number[] } = compiledExpression.evaluate(preparedContext);\n\n // Mathjs wraps multi-line expressions in an object, so we need to extract the last entry.\n // Note: one-line expressions return a number directly.\n if (finalResult && typeof finalResult === 'object' && 'entries' in finalResult) {\n const { entries } = finalResult;\n finalResult = entries[entries.length - 1];\n }\n\n return roundToClosestPowerOf2(finalResult);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,oBAeO;AAEP,oBAA6B;AAOtB,IAAM,8CAA8C;AAM3D,IAAM,0BAA0B,oBAAI,IAA2B;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,CAAC;AAMD,IAAM,WAAO,sBAAO;AAAA;AAAA;AAAA;AAAA;AAAA,EAKhB;AAAA,EACA;AAAA;AAAA,EAGA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AACJ,CAAC;AACD,IAAM,EAAE,QAAQ,IAAI;AAGpB,KAAK;AAAA,EACD;AAAA;AAAA;AAAA,IAGI,WAAW;AACP,YAAM,IAAI,MAAM,gCAAgC;AAAA,IACpD;AAAA,IACA,UAAU;AACN,YAAM,IAAI,MAAM,+BAA+B;AAAA,IACnD;AAAA;AAAA,IAEA,QAAQ;AACJ,YAAM,IAAI,MAAM,6BAA6B;AAAA,IACjD;AAAA,EACJ;AAAA,EACA,EAAE,UAAU,KAAK;AACrB;AAaA,IAAM,gBAAgB,wBAAC,KAAU,MAAc,eAAwB;AACnE,SAAO,KAAK,MAAM,GAAG,EAAE,OAAO,CAAC,SAAS,QAAQ,UAAU,GAAG,GAAG,GAAG,KAAK;AAC5E,GAFsB;AAUtB,IAAM,yBAAyB,wBAAC,QAAwB;AACpD,MAAI,OAAO,QAAQ,YAAY,OAAO,MAAM,GAAG,KAAK,CAAC,OAAO,SAAS,GAAG,GAAG;AACvE,UAAM,IAAI,MAAM,kDAAkD,GAAG,GAAG;AAAA,EAC5E;AAGA,MAAI,OAAO,GAAG;AACV,U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,MACN,iEAAiE,2CAA2C;AAAA,IAChH;AAAA,EACJ;AAIA,QAAM,yBAAyB,yBAAyB,mBAAmB;AAE3E,QAAM,kBAAkB;AAAA,IACpB,GAAG;AAAA,IACH,KAAK;AAAA,EACT;AAEA,QAAM,qBAAqB,MAAM,sBAAsB,wBAAwB,SAAS,KAAK;AAE7F,MAAI,cAA8C,mBAAmB,SAAS,eAAe;AAI7F,MAAI,eAAe,OAAO,gBAAgB,YAAY,aAAa,aAAa;AAC5E,UAAM,EAAE,QAAQ,IAAI;AACpB,kBAAc,QAAQ,QAAQ,SAAS,CAAC;AAAA,EAC5C;AAEA,SAAO,uBAAuB,WAAW;AAC7C,GAhCyC;","names":[]}
package/cjs/index.d.ts CHANGED
@@ -29,7 +29,7 @@ declare const DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH = 1000;
29
29
  * @param context The `MemoryEvaluationContext` (containing `input` and `runOptions`) available to the expression.
30
30
  * @param options.cache Optional synchronous cache. Since compiled functions cannot be saved to a database/Redis, they are kept in local memory.
31
31
  * @returns The calculated memory value rounded to the closest power of 2 and clamped within allowed limits.
32
- */
32
+ */
33
33
  declare const calculateRunDynamicMemory: (defaultMemoryMbytes: string, context: MemoryEvaluationContext, options?: {
34
34
  cache: CompilationCache;
35
35
  } | undefined) => Promise<number>;
package/esm/index.d.mts CHANGED
@@ -29,7 +29,7 @@ declare const DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH = 1000;
29
29
  * @param context The `MemoryEvaluationContext` (containing `input` and `runOptions`) available to the expression.
30
30
  * @param options.cache Optional synchronous cache. Since compiled functions cannot be saved to a database/Redis, they are kept in local memory.
31
31
  * @returns The calculated memory value rounded to the closest power of 2 and clamped within allowed limits.
32
- */
32
+ */
33
33
  declare const calculateRunDynamicMemory: (defaultMemoryMbytes: string, context: MemoryEvaluationContext, options?: {
34
34
  cache: CompilationCache;
35
35
  } | undefined) => Promise<number>;
package/esm/index.mjs CHANGED
@@ -53,20 +53,23 @@ var math = create({
53
53
  nullishDependencies
54
54
  });
55
55
  var { compile } = math;
56
- math.import({
57
- // We disable evaluate to prevent users from calling it inside their expressions.
58
- // For example: defaultMemoryMbytes = "evaluate('2 + 2')"
59
- evaluate() {
60
- throw new Error("Function evaluate is disabled.");
61
- },
62
- compile() {
63
- throw new Error("Function compile is disabled.");
56
+ math.import(
57
+ {
58
+ // We disable evaluate to prevent users from calling it inside their expressions.
59
+ // For example: defaultMemoryMbytes = "evaluate('2 + 2')"
60
+ evaluate() {
61
+ throw new Error("Function evaluate is disabled.");
62
+ },
63
+ compile() {
64
+ throw new Error("Function compile is disabled.");
65
+ },
66
+ // We need to disable it, because compileDependencies imports parseDependencies.
67
+ parse() {
68
+ throw new Error("Function parse is disabled.");
69
+ }
64
70
  },
65
- // We need to disable it, because compileDependencies imports parseDependencies.
66
- parse() {
67
- throw new Error("Function parse is disabled.");
68
- }
69
- }, { override: true });
71
+ { override: true }
72
+ );
70
73
  var customGetFunc = /* @__PURE__ */ __name((obj, path, defaultVal) => {
71
74
  return path.split(".").reduce((current, key) => current?.[key], obj) ?? defaultVal;
72
75
  }, "customGetFunc");
@@ -84,26 +87,23 @@ var roundToClosestPowerOf2 = /* @__PURE__ */ __name((num) => {
84
87
  }, "roundToClosestPowerOf2");
85
88
  var processTemplateVariables = /* @__PURE__ */ __name((defaultMemoryMbytes) => {
86
89
  const variableRegex = /{{\s*([a-zA-Z0-9_.]+)\s*}}/g;
87
- const processedExpression = defaultMemoryMbytes.replace(
88
- variableRegex,
89
- (_, variableName) => {
90
- if (variableName.startsWith("input.")) {
91
- return variableName;
92
- }
93
- if (variableName.startsWith("runOptions.")) {
94
- const key = variableName.slice("runOptions.".length);
95
- if (!ALLOWED_RUN_OPTION_KEYS.has(key)) {
96
- throw new Error(
97
- `Invalid variable '{{${variableName}}}' in expression. Only the following runOptions are allowed: ${Array.from(ALLOWED_RUN_OPTION_KEYS).map((k) => `runOptions.${k}`).join(", ")}.`
98
- );
99
- }
100
- return variableName;
90
+ const processedExpression = defaultMemoryMbytes.replace(variableRegex, (_, variableName) => {
91
+ if (variableName.startsWith("input.")) {
92
+ return variableName;
93
+ }
94
+ if (variableName.startsWith("runOptions.")) {
95
+ const key = variableName.slice("runOptions.".length);
96
+ if (!ALLOWED_RUN_OPTION_KEYS.has(key)) {
97
+ throw new Error(
98
+ `Invalid variable '{{${variableName}}}' in expression. Only the following runOptions are allowed: ${Array.from(
99
+ ALLOWED_RUN_OPTION_KEYS
100
+ ).map((k) => `runOptions.${k}`).join(", ")}.`
101
+ );
101
102
  }
102
- throw new Error(
103
- `Invalid variable '{{${variableName}}}' in expression.`
104
- );
103
+ return variableName;
105
104
  }
106
- );
105
+ throw new Error(`Invalid variable '{{${variableName}}}' in expression.`);
106
+ });
107
107
  return processedExpression;
108
108
  }, "processTemplateVariables");
109
109
  var getCompiledExpression = /* @__PURE__ */ __name(async (expression, cache) => {
@@ -119,7 +119,9 @@ var getCompiledExpression = /* @__PURE__ */ __name(async (expression, cache) =>
119
119
  }, "getCompiledExpression");
120
120
  var calculateRunDynamicMemory = /* @__PURE__ */ __name(async (defaultMemoryMbytes, context, options = void 0) => {
121
121
  if (defaultMemoryMbytes.length > DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH) {
122
- throw new Error(`The defaultMemoryMbytes expression is too long. Max length is ${DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH} characters.`);
122
+ throw new Error(
123
+ `The defaultMemoryMbytes expression is too long. Max length is ${DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH} characters.`
124
+ );
123
125
  }
124
126
  const preprocessedExpression = processTemplateVariables(defaultMemoryMbytes);
125
127
  const preparedContext = {
package/esm/index.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/memory_calculator.ts"],"sourcesContent":["// MathJS bundle with only numbers is ~2x smaller than the default one.\nimport {\n addDependencies,\n andDependencies,\n compileDependencies,\n create,\n divideDependencies,\n evaluateDependencies,\n maxDependencies,\n minDependencies,\n multiplyDependencies,\n notDependencies,\n nullishDependencies,\n orDependencies,\n subtractDependencies,\n xorDependencies,\n} from 'mathjs';\n\nimport { ACTOR_LIMITS } from '@apify/consts';\n\nimport type { ActorRunOptions, CompilationCache, CompilationResult, MemoryEvaluationContext } from './types.js';\n\n// In theory, users could create expressions longer than 1000 characters,\n// but in practice, it's unlikely anyone would need that much complexity.\n// Later we can increase this limit if needed.\nexport const DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH = 1000;\n\n/**\n * A Set of allowed keys from ActorRunOptions that can be used in\n * the {{runOptions.variable}} syntax.\n */\nconst ALLOWED_RUN_OPTION_KEYS = new Set<keyof ActorRunOptions>([\n 'build',\n 'timeoutSecs',\n 'memoryMbytes',\n 'diskMbytes',\n 'maxItems',\n 'maxTotalChargeUsd',\n 'restartOnError',\n]);\n\n/**\n * Create a mathjs instance with selected dependencies, then disable potentially dangerous ones.\n * MathJS security recommendations: https://mathjs.org/docs/expressions/security.html\n */\nconst math = create({\n // expression dependencies\n // Required for compiling and evaluating root expressions.\n // We disable it below to prevent users from calling `evaluate()` inside their expressions.\n // For example: defaultMemoryMbytes = \"evaluate('2 + 2')\"\n compileDependencies,\n evaluateDependencies,\n\n // arithmetic dependencies\n addDependencies,\n subtractDependencies,\n multiplyDependencies,\n divideDependencies,\n // statistics dependencies\n maxDependencies,\n minDependencies,\n // logical dependencies\n andDependencies,\n notDependencies,\n orDependencies,\n xorDependencies,\n // without that dependency 'null ?? 5', won't work\n nullishDependencies,\n});\nconst { compile } = math;\n\n// Disable potentially dangerous functions\nmath.import({\n // We disable evaluate to prevent users from calling it inside their expressions.\n // For example: defaultMemoryMbytes = \"evaluate('2 + 2')\"\n evaluate() { throw new Error('Function evaluate is disabled.'); },\n compile() { throw new Error('Function compile is disabled.'); },\n // We need to disable it, because compileDependencies imports parseDependencies.\n parse() { throw new Error('Function parse is disabled.'); },\n}, { override: true });\n\n/**\n * Safely retrieves a nested property from an object using a dot-notation string path.\n *\n * This is custom function designed to be injected into the math expression evaluator,\n * allowing expressions like `get(input, 'user.settings.memory', 512)` or `get(input, 'startUrls.length', 10)` to get array length.\n *\n * @param obj The source object to search within.\n * @param path A dot-separated string representing the nested path (e.g., \"input.payload.size\").\n * @param defaultVal The value to return if the path is not found or the value is `null` or `undefined`.\n * @returns The retrieved value, or `defaultVal` if the path is unreachable.\n*/\nconst customGetFunc = (obj: any, path: string, defaultVal?: number) => {\n return (path.split('.').reduce((current, key) => current?.[key], obj)) ?? defaultVal;\n};\n\n/**\n * Rounds a number to the closest power of 2.\n * The result is clamped to the allowed range (ACTOR_LIMITS.MIN_RUN_MEMORY_MBYTES - ACTOR_LIMITS.MAX_RUN_MEMORY_MBYTES).\n * @param num The number to round.\n * @returns The closest power of 2 within min/max range.\n*/\nconst roundToClosestPowerOf2 = (num: number): number => {\n if (typeof num !== 'number' || Number.isNaN(num) || !Number.isFinite(num)) {\n throw new Error(`Calculated memory value is not a valid number: ${num}.`);\n }\n\n // Handle 0 or negative values.\n if (num <= 0) {\n throw new Error(`Calculated memory value must be a positive number, greater than 0, got: ${num}.`);\n }\n\n const log2n = Math.log2(num);\n\n const roundedLog = Math.round(log2n);\n const result = 2 ** roundedLog;\n\n return Math.max(ACTOR_LIMITS.MIN_RUN_MEMORY_MBYTES, Math.min(result, ACTOR_LIMITS.MAX_RUN_MEMORY_MBYTES));\n};\n\n/**\n * Replaces all `{{variable}}` placeholders in an expression into direct\n * property access (e.g. `{{runOptions.memoryMbytes}}` → `runOptions.memoryMbytes`).\n *\n * All `input.*` values are accepted, while `runOptions.*` are validated (7 variables from ALLOWED_RUN_OPTION_KEYS).\n *\n * Note: While not really needed for Math.js, this approach allows developers\n * to use a consistent double-brace templating syntax `{{runOptions.timeoutSecs}}`\n * across the Apify platform. We also want to avoid compiling the expression with the\n * actual values as that would make caching less effective.\n *\n * @example\n * // Returns \"runOptions.memoryMbytes + 1024\"\n * preprocessDefaultMemoryExpression(\"{{runOptions.memoryMbytes}} + 1024\");\n *\n * @param defaultMemoryMbytes The raw string expression, e.g., \"{{runOptions.memoryMbytes}} * 2\".\n * @returns A safe, processed expression for evaluation, e.g., \"runOptions.memoryMbytes * 2\".\n */\nconst processTemplateVariables = (defaultMemoryMbytes: string): string => {\n const variableRegex = /{{\\s*([a-zA-Z0-9_.]+)\\s*}}/g;\n\n const processedExpression = defaultMemoryMbytes.replace(\n variableRegex,\n (_, variableName: string) => {\n // 1. Check if the variable is accessing input (e.g. {{input.someValue}})\n // We do not validate the specific property name because `input` is dynamic.\n if (variableName.startsWith('input.')) {\n return variableName;\n }\n\n // 2. Check if the variable is accessing runOptions (e.g. {{runOptions.memoryMbytes}}) and validate the keys.\n if (variableName.startsWith('runOptions.')) {\n const key = variableName.slice('runOptions.'.length);\n if (!ALLOWED_RUN_OPTION_KEYS.has(key as keyof ActorRunOptions)) {\n throw new Error(\n `Invalid variable '{{${variableName}}}' in expression. Only the following runOptions are allowed: ${Array.from(ALLOWED_RUN_OPTION_KEYS).map((k) => `runOptions.${k}`).join(', ')}.`,\n );\n }\n return variableName;\n }\n\n // 3. Throw error for unrecognized variables (e.g. {{someVariable}})\n throw new Error(\n `Invalid variable '{{${variableName}}}' in expression.`,\n );\n },\n );\n\n return processedExpression;\n};\n\n/*\n* Retrieves a compiled expression from the cache or compiles it if not present.\n*\n* @param expression The expression string to compile.\n* @param cache An optional cache to store/retrieve compiled expressions.\n* @returns The compiled CompilationResult.\n*/\nconst getCompiledExpression = async (expression: string, cache: CompilationCache | undefined): Promise<CompilationResult> => {\n if (!cache) {\n return compile(expression);\n }\n\n let compiledExpression = await cache.get(expression);\n\n if (!compiledExpression) {\n compiledExpression = compile(expression);\n await cache.set(expression, compiledExpression!);\n }\n\n return compiledExpression;\n};\n\n/**\n * Evaluates a dynamic memory expression string using the provided context.\n * Result is rounded to the closest power of 2 and clamped within allowed limits.\n *\n * @param defaultMemoryMbytes The string expression to evaluate (e.g., `get(input, 'urls.length', 10) * 1024` for `input = { urls: ['url1', 'url2'] }`).\n * @param context The `MemoryEvaluationContext` (containing `input` and `runOptions`) available to the expression.\n * @param options.cache Optional synchronous cache. Since compiled functions cannot be saved to a database/Redis, they are kept in local memory.\n * @returns The calculated memory value rounded to the closest power of 2 and clamped within allowed limits.\n*/\nexport const calculateRunDynamicMemory = async (\n defaultMemoryMbytes: string,\n context: MemoryEvaluationContext,\n options: { cache: CompilationCache } | undefined = undefined,\n) => {\n if (defaultMemoryMbytes.length > DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH) {\n throw new Error(`The defaultMemoryMbytes expression is too long. Max length is ${DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH} characters.`);\n }\n\n // Replaces all occurrences of {{variable}} with variable\n // e.g., \"{{runOptions.memoryMbytes}} + 1024\" becomes \"runOptions.memoryMbytes + 1024\"\n const preprocessedExpression = processTemplateVariables(defaultMemoryMbytes);\n\n const preparedContext = {\n ...context,\n get: customGetFunc,\n };\n\n const compiledExpression = await getCompiledExpression(preprocessedExpression, options?.cache);\n\n let finalResult: number | { entries: number[] } = compiledExpression.evaluate(preparedContext);\n\n // Mathjs wraps multi-line expressions in an object, so we need to extract the last entry.\n // Note: one-line expressions return a number directly.\n if (finalResult && typeof finalResult === 'object' && 'entries' in finalResult) {\n const { entries } = finalResult;\n finalResult = entries[entries.length - 1];\n }\n\n return roundToClosestPowerOf2(finalResult);\n};\n"],"mappings":";;;;AACA;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AAEP,SAAS,oBAAoB;AAOtB,IAAM,8CAA8C;AAM3D,IAAM,0BAA0B,oBAAI,IAA2B;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,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AACpB,kBAAc,QAAQ,QAAQ,SAAS,CAAC;AAAA,EAC5C;AAEA,SAAO,uBAAuB,WAAW;AAC7C,GA9ByC;","names":[]}
1
+ {"version":3,"sources":["../../src/memory_calculator.ts"],"sourcesContent":["// MathJS bundle with only numbers is ~2x smaller than the default one.\nimport {\n addDependencies,\n andDependencies,\n compileDependencies,\n create,\n divideDependencies,\n evaluateDependencies,\n maxDependencies,\n minDependencies,\n multiplyDependencies,\n notDependencies,\n nullishDependencies,\n orDependencies,\n subtractDependencies,\n xorDependencies,\n} from 'mathjs';\n\nimport { ACTOR_LIMITS } from '@apify/consts';\n\nimport type { ActorRunOptions, CompilationCache, CompilationResult, MemoryEvaluationContext } from './types.js';\n\n// In theory, users could create expressions longer than 1000 characters,\n// but in practice, it's unlikely anyone would need that much complexity.\n// Later we can increase this limit if needed.\nexport const DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH = 1000;\n\n/**\n * A Set of allowed keys from ActorRunOptions that can be used in\n * the {{runOptions.variable}} syntax.\n */\nconst ALLOWED_RUN_OPTION_KEYS = new Set<keyof ActorRunOptions>([\n 'build',\n 'timeoutSecs',\n 'memoryMbytes',\n 'diskMbytes',\n 'maxItems',\n 'maxTotalChargeUsd',\n 'restartOnError',\n]);\n\n/**\n * Create a mathjs instance with selected dependencies, then disable potentially dangerous ones.\n * MathJS security recommendations: https://mathjs.org/docs/expressions/security.html\n */\nconst math = create({\n // expression dependencies\n // Required for compiling and evaluating root expressions.\n // We disable it below to prevent users from calling `evaluate()` inside their expressions.\n // For example: defaultMemoryMbytes = \"evaluate('2 + 2')\"\n compileDependencies,\n evaluateDependencies,\n\n // arithmetic dependencies\n addDependencies,\n subtractDependencies,\n multiplyDependencies,\n divideDependencies,\n // statistics dependencies\n maxDependencies,\n minDependencies,\n // logical dependencies\n andDependencies,\n notDependencies,\n orDependencies,\n xorDependencies,\n // without that dependency 'null ?? 5', won't work\n nullishDependencies,\n});\nconst { compile } = math;\n\n// Disable potentially dangerous functions\nmath.import(\n {\n // We disable evaluate to prevent users from calling it inside their expressions.\n // For example: defaultMemoryMbytes = \"evaluate('2 + 2')\"\n evaluate() {\n throw new Error('Function evaluate is disabled.');\n },\n compile() {\n throw new Error('Function compile is disabled.');\n },\n // We need to disable it, because compileDependencies imports parseDependencies.\n parse() {\n throw new Error('Function parse is disabled.');\n },\n },\n { override: true },\n);\n\n/**\n * Safely retrieves a nested property from an object using a dot-notation string path.\n *\n * This is custom function designed to be injected into the math expression evaluator,\n * allowing expressions like `get(input, 'user.settings.memory', 512)` or `get(input, 'startUrls.length', 10)` to get array length.\n *\n * @param obj The source object to search within.\n * @param path A dot-separated string representing the nested path (e.g., \"input.payload.size\").\n * @param defaultVal The value to return if the path is not found or the value is `null` or `undefined`.\n * @returns The retrieved value, or `defaultVal` if the path is unreachable.\n */\nconst customGetFunc = (obj: any, path: string, defaultVal?: number) => {\n return path.split('.').reduce((current, key) => current?.[key], obj) ?? defaultVal;\n};\n\n/**\n * Rounds a number to the closest power of 2.\n * The result is clamped to the allowed range (ACTOR_LIMITS.MIN_RUN_MEMORY_MBYTES - ACTOR_LIMITS.MAX_RUN_MEMORY_MBYTES).\n * @param num The number to round.\n * @returns The closest power of 2 within min/max range.\n */\nconst roundToClosestPowerOf2 = (num: number): number => {\n if (typeof num !== 'number' || Number.isNaN(num) || !Number.isFinite(num)) {\n throw new Error(`Calculated memory value is not a valid number: ${num}.`);\n }\n\n // Handle 0 or negative values.\n if (num <= 0) {\n throw new Error(`Calculated memory value must be a positive number, greater than 0, got: ${num}.`);\n }\n\n const log2n = Math.log2(num);\n\n const roundedLog = Math.round(log2n);\n const result = 2 ** roundedLog;\n\n return Math.max(ACTOR_LIMITS.MIN_RUN_MEMORY_MBYTES, Math.min(result, ACTOR_LIMITS.MAX_RUN_MEMORY_MBYTES));\n};\n\n/**\n * Replaces all `{{variable}}` placeholders in an expression into direct\n * property access (e.g. `{{runOptions.memoryMbytes}}` → `runOptions.memoryMbytes`).\n *\n * All `input.*` values are accepted, while `runOptions.*` are validated (7 variables from ALLOWED_RUN_OPTION_KEYS).\n *\n * Note: While not really needed for Math.js, this approach allows developers\n * to use a consistent double-brace templating syntax `{{runOptions.timeoutSecs}}`\n * across the Apify platform. We also want to avoid compiling the expression with the\n * actual values as that would make caching less effective.\n *\n * @example\n * // Returns \"runOptions.memoryMbytes + 1024\"\n * preprocessDefaultMemoryExpression(\"{{runOptions.memoryMbytes}} + 1024\");\n *\n * @param defaultMemoryMbytes The raw string expression, e.g., \"{{runOptions.memoryMbytes}} * 2\".\n * @returns A safe, processed expression for evaluation, e.g., \"runOptions.memoryMbytes * 2\".\n */\nconst processTemplateVariables = (defaultMemoryMbytes: string): string => {\n const variableRegex = /{{\\s*([a-zA-Z0-9_.]+)\\s*}}/g;\n\n const processedExpression = defaultMemoryMbytes.replace(variableRegex, (_, variableName: string) => {\n // 1. Check if the variable is accessing input (e.g. {{input.someValue}})\n // We do not validate the specific property name because `input` is dynamic.\n if (variableName.startsWith('input.')) {\n return variableName;\n }\n\n // 2. Check if the variable is accessing runOptions (e.g. {{runOptions.memoryMbytes}}) and validate the keys.\n if (variableName.startsWith('runOptions.')) {\n const key = variableName.slice('runOptions.'.length);\n if (!ALLOWED_RUN_OPTION_KEYS.has(key as keyof ActorRunOptions)) {\n throw new Error(\n `Invalid variable '{{${variableName}}}' in expression. Only the following runOptions are allowed: ${Array.from(\n ALLOWED_RUN_OPTION_KEYS,\n )\n .map((k) => `runOptions.${k}`)\n .join(', ')}.`,\n );\n }\n return variableName;\n }\n\n // 3. Throw error for unrecognized variables (e.g. {{someVariable}})\n throw new Error(`Invalid variable '{{${variableName}}}' in expression.`);\n });\n\n return processedExpression;\n};\n\n/*\n * Retrieves a compiled expression from the cache or compiles it if not present.\n *\n * @param expression The expression string to compile.\n * @param cache An optional cache to store/retrieve compiled expressions.\n * @returns The compiled CompilationResult.\n */\nconst getCompiledExpression = async (\n expression: string,\n cache: CompilationCache | undefined,\n): Promise<CompilationResult> => {\n if (!cache) {\n return compile(expression);\n }\n\n let compiledExpression = await cache.get(expression);\n\n if (!compiledExpression) {\n compiledExpression = compile(expression);\n await cache.set(expression, compiledExpression!);\n }\n\n return compiledExpression;\n};\n\n/**\n * Evaluates a dynamic memory expression string using the provided context.\n * Result is rounded to the closest power of 2 and clamped within allowed limits.\n *\n * @param defaultMemoryMbytes The string expression to evaluate (e.g., `get(input, 'urls.length', 10) * 1024` for `input = { urls: ['url1', 'url2'] }`).\n * @param context The `MemoryEvaluationContext` (containing `input` and `runOptions`) available to the expression.\n * @param options.cache Optional synchronous cache. Since compiled functions cannot be saved to a database/Redis, they are kept in local memory.\n * @returns The calculated memory value rounded to the closest power of 2 and clamped within allowed limits.\n */\nexport const calculateRunDynamicMemory = async (\n defaultMemoryMbytes: string,\n context: MemoryEvaluationContext,\n options: { cache: CompilationCache } | undefined = undefined,\n) => {\n if (defaultMemoryMbytes.length > DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH) {\n throw new Error(\n `The defaultMemoryMbytes expression is too long. Max length is ${DEFAULT_MEMORY_MBYTES_EXPRESSION_MAX_LENGTH} characters.`,\n );\n }\n\n // Replaces all occurrences of {{variable}} with variable\n // e.g., \"{{runOptions.memoryMbytes}} + 1024\" becomes \"runOptions.memoryMbytes + 1024\"\n const preprocessedExpression = processTemplateVariables(defaultMemoryMbytes);\n\n const preparedContext = {\n ...context,\n get: customGetFunc,\n };\n\n const compiledExpression = await getCompiledExpression(preprocessedExpression, options?.cache);\n\n let finalResult: number | { entries: number[] } = compiledExpression.evaluate(preparedContext);\n\n // Mathjs wraps multi-line expressions in an object, so we need to extract the last entry.\n // Note: one-line expressions return a number directly.\n if (finalResult && typeof finalResult === 'object' && 'entries' in finalResult) {\n const { entries } = finalResult;\n finalResult = entries[entries.length - 1];\n }\n\n return roundToClosestPowerOf2(finalResult);\n};\n"],"mappings":";;;;AACA;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA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yB,yBAAyB,mBAAmB;AAE3E,QAAM,kBAAkB;AAAA,IACpB,GAAG;AAAA,IACH,KAAK;AAAA,EACT;AAEA,QAAM,qBAAqB,MAAM,sBAAsB,wBAAwB,SAAS,KAAK;AAE7F,MAAI,cAA8C,mBAAmB,SAAS,eAAe;AAI7F,MAAI,eAAe,OAAO,gBAAgB,YAAY,aAAa,aAAa;AAC5E,UAAM,EAAE,QAAQ,IAAI;AACpB,kBAAc,QAAQ,QAAQ,SAAS,CAAC;AAAA,EAC5C;AAEA,SAAO,uBAAuB,WAAW;AAC7C,GAhCyC;","names":[]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@apify/actor-memory-expression",
3
- "version": "0.1.15",
3
+ "version": "0.1.17",
4
4
  "description": "Utility to evaluate dynamic memory expressions for Apify actors.",
5
5
  "main": "./cjs/index.cjs",
6
6
  "module": "./esm/index.mjs",
@@ -48,9 +48,9 @@
48
48
  "access": "public"
49
49
  },
50
50
  "dependencies": {
51
- "@apify/consts": "^2.53.0",
52
- "@apify/log": "^2.5.38",
51
+ "@apify/consts": "^2.53.2",
52
+ "@apify/log": "^2.5.40",
53
53
  "mathjs": "^15.2.0"
54
54
  },
55
- "gitHead": "c65d95f47e7ab8391707f8861c64fed8e8f3bf8a"
55
+ "gitHead": "98f72db71b4fb9eddea5dc71a7bd8b1119ee9861"
56
56
  }