@vertesia/jst 1.6.0-dev.20261004.085740Z → 1.6.0-dev.20261008.064737Z

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.
@@ -1 +1 @@
1
- {"version":3,"file":"vertesia-jst.js","names":["baseV"],"sources":["system.js","handlebars/index.js","validation.js","script.js","functions/addLineNumbers.js","functions/csv.js","template.js"],"sourcesContent":["export const TEMPLATE_SYSTEM_VARIABLES = [\n {\n name: '_now',\n type: 'string',\n description: 'Current date and time as an ISO 8601 string (UTC)',\n },\n {\n name: '_model',\n type: 'string',\n description: 'Identifier of the model the prompt is executed with',\n },\n];\nexport const TEMPLATE_SYSTEM_VARIABLE_NAMES = TEMPLATE_SYSTEM_VARIABLES.map((v) => v.name);\nconst SYSTEM_VARIABLE_NAME_SET = new Set(TEMPLATE_SYSTEM_VARIABLE_NAMES);\nexport function isTemplateSystemVariable(name) {\n return SYSTEM_VARIABLE_NAME_SET.has(name);\n}\n/** Compute the system variable values for one rendering. */\nexport function buildTemplateSystemVariables(context = {}) {\n const values = {\n _now: (context.now ?? new Date()).toISOString(),\n };\n if (context.model) {\n values._model = context.model;\n }\n return values;\n}\n/**\n * Return the template data with the system variables added. System values win over caller input\n * of the same name: the names are reserved, so a caller cannot spoof `_model` or `_now`.\n */\nexport function withTemplateSystemVariables(input, context = {}) {\n return { ...input, ...buildTemplateSystemVariables(context) };\n}\n/** One-line summary of the system variables, for tool descriptions and error messages. */\nexport function describeTemplateSystemVariables() {\n return TEMPLATE_SYSTEM_VARIABLES.map((v) => `${v.name} (${v.description})`).join(', ');\n}\n//# sourceMappingURL=system.js.map","import Handlebars from 'handlebars';\nimport { TEMPLATE_SYSTEM_VARIABLE_NAMES } from '../system.js';\n/**\n * System variables (see ../system.ts) are injected into the template data. Each one is also\n * registered as a helper returning that injected value, because Handlebars resolves a name\n * differently by position: a bare `{{_now}}` or a subexpression `(_now)` looks up helpers first,\n * while an argument (`{{#if _now}}`) reads the data only. Registering both makes every position\n * render the same value. `_now` falls back to the current time when no value was injected, which\n * keeps templates rendered by callers that do not inject system variables working.\n */\nfunction systemVariableHelper(name) {\n return (...args) => {\n const options = args[args.length - 1];\n const root = options?.data?.root;\n const value = root && typeof root === 'object' ? root[name] : undefined;\n if (value !== undefined && value !== null) {\n return value;\n }\n return name === '_now' ? new Date().toISOString() : '';\n };\n}\nfunction stringifyHelper(value) {\n if (value === null || value === undefined)\n return '';\n if (typeof value === 'string')\n return value;\n return new Handlebars.SafeString(JSON.stringify(value));\n}\nconst CUSTOM_HELPERS = {\n ...Object.fromEntries(TEMPLATE_SYSTEM_VARIABLE_NAMES.map((name) => [name, systemVariableHelper(name)])),\n stringify: stringifyHelper,\n};\n/**\n * Prompt templates render with a private Handlebars environment, so helpers another module\n * registers on the global instance never become available to prompts without the validator\n * knowing about them.\n */\nconst promptHandlebars = Handlebars.create();\nfor (const [name, helper] of Object.entries(CUSTOM_HELPERS)) {\n promptHandlebars.registerHelper(name, helper);\n // Kept on the global instance for code that compiled templates with the global Handlebars\n // after importing this module, which used to be where these helpers were registered.\n Handlebars.registerHelper(name, helper);\n}\n/**\n * Every helper available to prompt templates: Handlebars' built-ins (`if`, `each`, `with`,\n * `lookup`, ...) plus the custom ones above. Read from the environment itself so it cannot drift.\n */\nexport const HANDLEBARS_HELPER_NAMES = Object.keys(promptHandlebars.helpers)\n // Internal fallbacks Handlebars invokes itself; templates never call them by name.\n .filter((name) => name !== 'helperMissing' && name !== 'blockHelperMissing')\n .sort();\nconst HELPER_NAME_SET = new Set(HANDLEBARS_HELPER_NAMES);\nexport function isHandlebarsHelper(name) {\n return HELPER_NAME_SET.has(name);\n}\n/** Built-in block helpers that render their block with a new context (`this` is the item). */\nexport const HANDLEBARS_CONTEXT_HELPERS = ['each', 'with'];\nexport function renderHandlebarsTemplate(template, input) {\n const compiled = promptHandlebars.compile(template);\n return compiled(input);\n}\n//# sourceMappingURL=index.js.map","import { parse, } from 'acorn';\nimport { base as baseV, recursive as recursiveWalk } from 'acorn-walk';\nconst baseVisitor = baseV;\nconst UnknownPosition = {\n line: 0,\n column: 0,\n};\nexport class ValidationError extends Error {\n node;\n constructor(message, node) {\n super(message);\n this.node = node;\n this.name = 'ValidationError';\n }\n get range() {\n const loc = this.node.loc;\n return loc ? [loc.start, loc.end] : [UnknownPosition, UnknownPosition];\n }\n get start() {\n return this.node.loc?.start || UnknownPosition;\n }\n get end() {\n return this.node.loc?.end || UnknownPosition;\n }\n get location() {\n if (this.node.loc) {\n return `${this.node.loc.start.line}:${this.node.loc.start.column}`;\n }\n else {\n return `${this.node.range}`;\n }\n }\n}\nexport class Scope {\n name;\n node;\n parent;\n errors;\n children = [];\n locals = new Set();\n constructor(name, node, parent) {\n this.name = name;\n this.node = node;\n this.parent = parent;\n parent?.children.push(this);\n this.errors = parent ? parent.errors : [];\n node.$scope = this;\n }\n define(name) {\n this.locals.add(name);\n }\n isDefined(name) {\n if (this.locals.has(name)) {\n return true;\n }\n if (this.parent) {\n return this.parent.isDefined(name);\n }\n return false;\n }\n pushError(message, node) {\n this.errors.push(new ValidationError(message, node));\n }\n hasErrors() {\n return this.errors.length > 0;\n }\n get ok() {\n return this.errors.length === 0;\n }\n print() {\n console.log(this.name, '=>', this.locals);\n for (const child of this.children) {\n child.print();\n }\n }\n}\nfunction addFunctionParams(node, scope) {\n for (const param of node.params) {\n if (param.type === 'Identifier') {\n scope.locals.add(param.name);\n markSafeIdentifier(param);\n }\n else if (param.type === 'AssignmentPattern') {\n if (param.left.type === 'Identifier') {\n scope.locals.add(param.left.name);\n markSafeIdentifier(param.left);\n }\n }\n else if (param.type === 'RestElement') {\n if (param.argument.type === 'Identifier') {\n scope.locals.add(param.argument.name);\n markSafeIdentifier(param.argument);\n }\n }\n }\n}\nfunction markSafeIdentifier(node) {\n node.___safe_identifier = true;\n}\nfunction isSafeIdentifier(node) {\n return !!node.___safe_identifier;\n}\nconst defaultAcornOpts = {\n ecmaVersion: 2020,\n sourceType: 'script',\n};\n/**\n * Parse `code` and build the scope tree (one full AST walk). The returned root scope\n * has `locals` populated for every nested function/block and has unsafe-construct\n * errors accumulated in `root.errors`. Identifier resolution (the \"Unknown identifier\"\n * check) is a separate second walk done by `validate` / `getFreeVariables`.\n */\nfunction buildScopeTree(code, opts) {\n const acornOpts = opts.acorn ? { ...defaultAcornOpts, ...opts.acorn } : defaultAcornOpts;\n const program = parse(code, acornOpts);\n const root = new Scope('#root', program, null);\n if (opts.globals) {\n for (const identifier of opts.globals) {\n root.locals.add(identifier);\n }\n program.$scope = root;\n }\n const propsBlacklist = new Set(opts.propsBlacklist ? opts.propsBlacklist : ['constructor', 'prototype', '__proto__']);\n recursiveWalk(program, root, {\n WithStatement(node, state, c) {\n state.pushError('\"with\" keyword is not supported', node);\n baseVisitor.WithStatement(node, state, c);\n },\n ForStatement(node, state, c) {\n state.pushError('\"for\" keyword is not supported', node);\n baseVisitor.ForStatement(node, state, c);\n },\n WhileStatement(node, state, c) {\n state.pushError('\"while\" keyword is not supported', node);\n baseVisitor.WhileStatement(node, state, c);\n },\n ImportExpression(node, state, c) {\n state.pushError('\"import\" keyword is not supported', node);\n baseVisitor.ImportExpression(node, state, c);\n },\n ImportDeclaration(node, state, c) {\n state.pushError('\"import\" keyword is not supported', node);\n baseVisitor.ImportDeclaration(node, state, c);\n },\n Class(node, state, c) {\n state.pushError('Classes are not supported', node);\n baseVisitor.Class(node, state, c);\n },\n ThisExpression(node, state, c) {\n if (!opts.allowThis) {\n state.pushError('\"this\" keyword is not supported', node);\n }\n baseVisitor.ThisExpression(node, state, c);\n },\n ObjectPattern(node, state, c) {\n for (const prop of node.properties) {\n if (prop.type === 'Property') {\n if (prop.key.type === 'Identifier') {\n markSafeIdentifier(prop.key);\n if (prop.kind === 'init' && propsBlacklist.has(prop.key.name)) {\n state.pushError(`Property \"${prop.key.name}\" is not allowed`, prop.key);\n }\n }\n }\n else if (prop.type === 'RestElement') {\n if (prop.argument.type === 'Identifier') {\n markSafeIdentifier(prop.argument);\n }\n }\n }\n baseVisitor.ObjectPattern(node, state, c);\n },\n ArrayPattern(node, state, c) {\n for (const prop of node.elements) {\n if (prop) {\n if (prop.type === 'Identifier') {\n markSafeIdentifier(prop);\n //TODO is this really needed?\n // if (propBlacklist.has(prop.name)) {\n // state.pushError(`Property \"${prop.name}\" is not allowed`, prop);\n // }\n }\n else if (prop.type === 'RestElement') {\n if (prop.argument.type === 'Identifier') {\n markSafeIdentifier(prop.argument);\n }\n }\n }\n }\n baseVisitor.ArrayPattern(node, state, c);\n },\n MemberExpression(node, state, c) {\n const prop = node.property;\n if (prop.type === 'Identifier') {\n markSafeIdentifier(prop);\n if (propsBlacklist.has(prop.name)) {\n state.pushError(`Property \"${prop.name}\" is not allowed`, prop);\n }\n }\n else if (prop.type === 'Literal') {\n if (propsBlacklist.has(String(prop.value))) {\n state.pushError(`Property \"${prop.value}\" is not allowed`, prop);\n }\n }\n else {\n state.pushError('Dynamic property lookup is not supported', prop);\n }\n baseVisitor.MemberExpression(node, state, c);\n },\n Function(node, state, c) {\n const name = node.id?.name;\n if (name) {\n // arrow functions have no name\n state.define(name);\n }\n const scope = new Scope(name || '#anonymous', node, state);\n addFunctionParams(node, scope);\n baseVisitor.Function(node, scope, c);\n },\n VariableDeclaration(node, state, c) {\n for (const decl of node.declarations) {\n if (decl.id.type === 'Identifier') {\n markSafeIdentifier(decl.id);\n state.define(decl.id.name);\n }\n else if (decl.id.type === 'ObjectPattern') {\n //the ObjectPattern rule will call markSafeIdentifier\n for (const prop of decl.id.properties) {\n if (prop.type === 'Property') {\n if (prop.value.type === 'Identifier')\n state.define(prop.value.name);\n }\n else if (prop.type === 'RestElement') {\n if (prop.argument.type === 'Identifier')\n state.define(prop.argument.name);\n }\n }\n }\n else if (decl.id.type === 'ArrayPattern') {\n //the ArrayPattern rule will call markSafeIdentifier\n for (const prop of decl.id.elements) {\n if (prop.type === 'Identifier') {\n state.define(prop.name);\n }\n else if (prop.type === 'RestElement') {\n if (prop.argument.type === 'Identifier')\n state.define(prop.argument.name);\n }\n }\n }\n }\n baseVisitor.VariableDeclaration(node, state, c);\n },\n });\n return { root, program };\n}\nexport function validate(code, opts = {}) {\n const { root, program } = buildScopeTree(code, opts);\n recursiveWalk(program, root, {\n Function(node, state, c) {\n baseVisitor.Function(node, node.$scope || state, c);\n },\n Identifier(node, state, c) {\n const identifier = node;\n if (!isSafeIdentifier(node) && !state.isDefined(identifier.name)) {\n state.pushError(`Unknown identifier \"${identifier.name}\"`, node);\n }\n baseVisitor.Identifier(node, state, c);\n },\n });\n return root;\n}\n/**\n * Walk `code` and return every identifier that is referenced but not bound by any\n * enclosing function/variable declaration and not listed in `opts.globals`. Pass\n * known runtime-injected names (e.g. JST's `_`, `Array`, `Set`) in `opts.globals`\n * so they don't appear as free vars. Also surfaces unsafe-construct errors from\n * the same parse pass.\n */\nexport function getFreeVariables(code, opts = {}) {\n const { root, program } = buildScopeTree(code, opts);\n const vars = new Set();\n recursiveWalk(program, root, {\n Function(node, state, c) {\n baseVisitor.Function(node, node.$scope || state, c);\n },\n Identifier(node, state, c) {\n const identifier = node;\n if (!isSafeIdentifier(node) && !state.isDefined(identifier.name)) {\n vars.add(identifier.name);\n }\n baseVisitor.Identifier(node, state, c);\n },\n });\n return { vars, errors: root.errors };\n}\nexport class CompositeError extends Error {\n errors;\n constructor(errors, message) {\n super(`${message || 'Composite Error'}\\n${errors.map((err) => err.message).join('\\n* ')}`);\n this.errors = errors;\n this.errors = errors;\n this.name = 'CompositeError';\n }\n}\n//# sourceMappingURL=validation.js.map","import { validate } from './validation.js';\nexport class Script {\n code;\n globals;\n fn;\n constructor(code, globals) {\n this.code = code;\n this.globals = globals;\n const args = globals && globals.length > 0 ? `{${globals.join(',')}}` : '';\n this.fn = new Function(args, `return (function(){\"use strict\";${code}})()`);\n }\n validate(opts = {}) {\n return validate(this.code, Object.assign({ globals: this.globals }, opts));\n }\n run(context) {\n return this.fn(context);\n }\n}\n//# sourceMappingURL=script.js.map","//add line numbers with {% addLineNumbers(content) %}\nexport function addLineNumbers(content) {\n const lines = content.split('\\n');\n const width = Math.ceil(Math.log10(lines.length));\n return lines\n .map((line, index) => {\n const number = (index + 1).toString().padStart(width, ' ');\n return `{% ${number} %} ${line}`;\n })\n .join('\\n');\n}\n//# sourceMappingURL=addLineNumbers.js.map","import Papa from 'papaparse';\nexport function loadCsv(content, options = {}) {\n return Papa.parse(content, options);\n}\nexport function jsonToCsv(obj, options = {}) {\n return Papa.unparse(obj, options);\n}\n//# sourceMappingURL=csv.js.map","import dayjs from 'dayjs';\nimport { addLineNumbers } from './functions/addLineNumbers.js';\nimport { jsonToCsv, loadCsv } from './functions/csv.js';\nimport { Script } from './script.js';\nimport { TEMPLATE_SYSTEM_VARIABLE_NAMES } from './system.js';\nimport { CompositeError } from './validation.js';\n/** Identifiers every JST template can read besides its declared inputs. */\nexport const JST_TEMPLATE_GLOBALS = ['_', 'Array', 'Set', ...TEMPLATE_SYSTEM_VARIABLE_NAMES];\nexport class CompiledTemplate extends Script {\n constructor(code, globals) {\n // Deduplicate: the globals become a destructured parameter list, where a repeated name\n // (e.g. a schema that also declares `_model`) is a syntax error.\n super(code, [...new Set([...globals, ...JST_TEMPLATE_GLOBALS])]);\n }\n validate() {\n return super.validate({\n acorn: {\n allowReturnOutsideFunction: true,\n locations: true,\n },\n });\n }\n run(context) {\n return super.run({ ...context, Set: Set, Array: Array });\n }\n}\nexport function renderJsTemplate(code, globals, data) {\n const script = new CompiledTemplate(code, globals);\n const state = script.validate();\n if (state.hasErrors()) {\n throw new CompositeError(state.errors, 'Validation errors');\n }\n const content = script.run({\n ...data,\n _: {\n loadCsv,\n jsonToCsv,\n stringify: JSON.stringify,\n addLineNumbers: addLineNumbers,\n dayjs: dayjs,\n },\n });\n return content;\n}\n//# sourceMappingURL=template.js.map"],"mappings":"uJAAA,MAAa,EAA4B,CACrC,CACI,KAAM,OACN,KAAM,SACN,YAAa,mDACjB,EACA,CACI,KAAM,SACN,KAAM,SACN,YAAa,q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OAAO,MAAM,IAAI,CAAE,GAAG,EAAc,IAAY,KAAM,CAAC,CAC3D,CACJ,EACA,SAAgB,EAAiB,EAAM,EAAS,EAAM,CAClD,IAAM,EAAS,IAAI,EAAiB,EAAM,CAAO,EAC3C,EAAQ,EAAO,SAAS,EAC9B,GAAI,EAAM,UAAU,EAChB,MAAM,IAAI,EAAe,EAAM,OAAQ,mBAAmB,EAY9D,OAVgB,EAAO,IAAI,CACvB,GAAG,EACH,EAAG,CACC,UACA,YACA,UAAW,KAAK,UACA,iBACT,OACX,CACJ,CACa,CACjB"}
1
+ {"version":3,"file":"vertesia-jst.js","names":["baseV","Handlebars","dayjs","Papa","TEMPLATE_SYSTEM_VARIABLES","TEMPLATE_SYSTEM_VARIABLE_NAMES","v","SYSTEM_VARIABLE_NAME_SET","isTemplateSystemVariable","name","buildTemplateSystemVariables","values","context","withTemplateSystemVariables","input","describeTemplateSystemVariables","systemVariableHelper","args","root","stringifyHelper","value","CUSTOM_HELPERS","promptHandlebars","helper","HANDLEBARS_HELPER_NAMES","HELPER_NAME_SET","isHandlebarsHelper","HANDLEBARS_CONTEXT_HELPERS","renderHandlebarsTemplate","template","baseVisitor","base","UnknownPosition","ValidationError","message","node","loc","Scope","parent","child","addFunctionParams","param","scope","markSafeIdentifier","isSafeIdentifier","defaultAcornOpts","buildScopeTree","acornOpts","opts","program","parse","code","identifier","propsBlacklist","recursive","state","c","prop","decl","validate","getFreeVariables","vars","CompositeError","errors","err","Script","globals","addLineNumbers","lines","content","width","index","line","loadCsv","options","jsonToCsv","obj","JST_TEMPLATE_GLOBALS","CompiledTemplate","renderJsTemplate","script","data"],"sources":["system.js","handlebars/index.js","validation.js","script.js","functions/addLineNumbers.js","functions/csv.js","template.js"],"sourcesContent":["export const TEMPLATE_SYSTEM_VARIABLES = [\n {\n name: '_now',\n type: 'string',\n description: 'Current date and time as an ISO 8601 string (UTC)',\n },\n {\n name: '_model',\n type: 'string',\n description: 'Identifier of the model the prompt is executed with',\n },\n];\nexport const TEMPLATE_SYSTEM_VARIABLE_NAMES = TEMPLATE_SYSTEM_VARIABLES.map((v) => v.name);\nconst SYSTEM_VARIABLE_NAME_SET = new Set(TEMPLATE_SYSTEM_VARIABLE_NAMES);\nexport function isTemplateSystemVariable(name) {\n return SYSTEM_VARIABLE_NAME_SET.has(name);\n}\n/** Compute the system variable values for one rendering. */\nexport function buildTemplateSystemVariables(context = {}) {\n const values = {\n _now: (context.now ?? new Date()).toISOString(),\n };\n if (context.model) {\n values._model = context.model;\n }\n return values;\n}\n/**\n * Return the template data with the system variables added. System values win over caller input\n * of the same name: the names are reserved, so a caller cannot spoof `_model` or `_now`.\n */\nexport function withTemplateSystemVariables(input, context = {}) {\n return { ...input, ...buildTemplateSystemVariables(context) };\n}\n/** One-line summary of the system variables, for tool descriptions and error messages. */\nexport function describeTemplateSystemVariables() {\n return TEMPLATE_SYSTEM_VARIABLES.map((v) => `${v.name} (${v.description})`).join(', ');\n}\n//# sourceMappingURL=system.js.map","import Handlebars from 'handlebars';\nimport { TEMPLATE_SYSTEM_VARIABLE_NAMES } from '../system.js';\n/**\n * System variables (see ../system.ts) are injected into the template data. Each one is also\n * registered as a helper returning that injected value, because Handlebars resolves a name\n * differently by position: a bare `{{_now}}` or a subexpression `(_now)` looks up helpers first,\n * while an argument (`{{#if _now}}`) reads the data only. Registering both makes every position\n * render the same value. `_now` falls back to the current time when no value was injected, which\n * keeps templates rendered by callers that do not inject system variables working.\n */\nfunction systemVariableHelper(name) {\n return (...args) => {\n const options = args[args.length - 1];\n const root = options?.data?.root;\n const value = root && typeof root === 'object' ? root[name] : undefined;\n if (value !== undefined && value !== null) {\n return value;\n }\n return name === '_now' ? new Date().toISOString() : '';\n };\n}\nfunction stringifyHelper(value) {\n if (value === null || value === undefined)\n return '';\n if (typeof value === 'string')\n return value;\n return new Handlebars.SafeString(JSON.stringify(value));\n}\nconst CUSTOM_HELPERS = {\n ...Object.fromEntries(TEMPLATE_SYSTEM_VARIABLE_NAMES.map((name) => [name, systemVariableHelper(name)])),\n stringify: stringifyHelper,\n};\n/**\n * Prompt templates render with a private Handlebars environment, so helpers another module\n * registers on the global instance never become available to prompts without the validator\n * knowing about them.\n */\nconst promptHandlebars = Handlebars.create();\nfor (const [name, helper] of Object.entries(CUSTOM_HELPERS)) {\n promptHandlebars.registerHelper(name, helper);\n // Kept on the global instance for code that compiled templates with the global Handlebars\n // after importing this module, which used to be where these helpers were registered.\n Handlebars.registerHelper(name, helper);\n}\n/**\n * Every helper available to prompt templates: Handlebars' built-ins (`if`, `each`, `with`,\n * `lookup`, ...) plus the custom ones above. Read from the environment itself so it cannot drift.\n */\nexport const HANDLEBARS_HELPER_NAMES = Object.keys(promptHandlebars.helpers)\n // Internal fallbacks Handlebars invokes itself; templates never call them by name.\n .filter((name) => name !== 'helperMissing' && name !== 'blockHelperMissing')\n .sort();\nconst HELPER_NAME_SET = new Set(HANDLEBARS_HELPER_NAMES);\nexport function isHandlebarsHelper(name) {\n return HELPER_NAME_SET.has(name);\n}\n/** Built-in block helpers that render their block with a new context (`this` is the item). */\nexport const HANDLEBARS_CONTEXT_HELPERS = ['each', 'with'];\nexport function renderHandlebarsTemplate(template, input) {\n const compiled = promptHandlebars.compile(template);\n return compiled(input);\n}\n//# sourceMappingURL=index.js.map","import { parse, } from 'acorn';\nimport { base as baseV, recursive as recursiveWalk } from 'acorn-walk';\nconst baseVisitor = baseV;\nconst UnknownPosition = {\n line: 0,\n column: 0,\n};\nexport class ValidationError extends Error {\n node;\n constructor(message, node) {\n super(message);\n this.node = node;\n this.name = 'ValidationError';\n }\n get range() {\n const loc = this.node.loc;\n return loc ? [loc.start, loc.end] : [UnknownPosition, UnknownPosition];\n }\n get start() {\n return this.node.loc?.start || UnknownPosition;\n }\n get end() {\n return this.node.loc?.end || UnknownPosition;\n }\n get location() {\n if (this.node.loc) {\n return `${this.node.loc.start.line}:${this.node.loc.start.column}`;\n }\n else {\n return `${this.node.range}`;\n }\n }\n}\nexport class Scope {\n name;\n node;\n parent;\n errors;\n children = [];\n locals = new Set();\n constructor(name, node, parent) {\n this.name = name;\n this.node = node;\n this.parent = parent;\n parent?.children.push(this);\n this.errors = parent ? parent.errors : [];\n node.$scope = this;\n }\n define(name) {\n this.locals.add(name);\n }\n isDefined(name) {\n if (this.locals.has(name)) {\n return true;\n }\n if (this.parent) {\n return this.parent.isDefined(name);\n }\n return false;\n }\n pushError(message, node) {\n this.errors.push(new ValidationError(message, node));\n }\n hasErrors() {\n return this.errors.length > 0;\n }\n get ok() {\n return this.errors.length === 0;\n }\n print() {\n console.log(this.name, '=>', this.locals);\n for (const child of this.children) {\n child.print();\n }\n }\n}\nfunction addFunctionParams(node, scope) {\n for (const param of node.params) {\n if (param.type === 'Identifier') {\n scope.locals.add(param.name);\n markSafeIdentifier(param);\n }\n else if (param.type === 'AssignmentPattern') {\n if (param.left.type === 'Identifier') {\n scope.locals.add(param.left.name);\n markSafeIdentifier(param.left);\n }\n }\n else if (param.type === 'RestElement') {\n if (param.argument.type === 'Identifier') {\n scope.locals.add(param.argument.name);\n markSafeIdentifier(param.argument);\n }\n }\n }\n}\nfunction markSafeIdentifier(node) {\n node.___safe_identifier = true;\n}\nfunction isSafeIdentifier(node) {\n return !!node.___safe_identifier;\n}\nconst defaultAcornOpts = {\n ecmaVersion: 2020,\n sourceType: 'script',\n};\n/**\n * Parse `code` and build the scope tree (one full AST walk). The returned root scope\n * has `locals` populated for every nested function/block and has unsafe-construct\n * errors accumulated in `root.errors`. Identifier resolution (the \"Unknown identifier\"\n * check) is a separate second walk done by `validate` / `getFreeVariables`.\n */\nfunction buildScopeTree(code, opts) {\n const acornOpts = opts.acorn ? { ...defaultAcornOpts, ...opts.acorn } : defaultAcornOpts;\n const program = parse(code, acornOpts);\n const root = new Scope('#root', program, null);\n if (opts.globals) {\n for (const identifier of opts.globals) {\n root.locals.add(identifier);\n }\n program.$scope = root;\n }\n const propsBlacklist = new Set(opts.propsBlacklist ? opts.propsBlacklist : ['constructor', 'prototype', '__proto__']);\n recursiveWalk(program, root, {\n WithStatement(node, state, c) {\n state.pushError('\"with\" keyword is not supported', node);\n baseVisitor.WithStatement(node, state, c);\n },\n ForStatement(node, state, c) {\n state.pushError('\"for\" keyword is not supported', node);\n baseVisitor.ForStatement(node, state, c);\n },\n WhileStatement(node, state, c) {\n state.pushError('\"while\" keyword is not supported', node);\n baseVisitor.WhileStatement(node, state, c);\n },\n ImportExpression(node, state, c) {\n state.pushError('\"import\" keyword is not supported', node);\n baseVisitor.ImportExpression(node, state, c);\n },\n ImportDeclaration(node, state, c) {\n state.pushError('\"import\" keyword is not supported', node);\n baseVisitor.ImportDeclaration(node, state, c);\n },\n Class(node, state, c) {\n state.pushError('Classes are not supported', node);\n baseVisitor.Class(node, state, c);\n },\n ThisExpression(node, state, c) {\n if (!opts.allowThis) {\n state.pushError('\"this\" keyword is not supported', node);\n }\n baseVisitor.ThisExpression(node, state, c);\n },\n ObjectPattern(node, state, c) {\n for (const prop of node.properties) {\n if (prop.type === 'Property') {\n if (prop.key.type === 'Identifier') {\n markSafeIdentifier(prop.key);\n if (prop.kind === 'init' && propsBlacklist.has(prop.key.name)) {\n state.pushError(`Property \"${prop.key.name}\" is not allowed`, prop.key);\n }\n }\n }\n else if (prop.type === 'RestElement') {\n if (prop.argument.type === 'Identifier') {\n markSafeIdentifier(prop.argument);\n }\n }\n }\n baseVisitor.ObjectPattern(node, state, c);\n },\n ArrayPattern(node, state, c) {\n for (const prop of node.elements) {\n if (prop) {\n if (prop.type === 'Identifier') {\n markSafeIdentifier(prop);\n //TODO is this really needed?\n // if (propBlacklist.has(prop.name)) {\n // state.pushError(`Property \"${prop.name}\" is not allowed`, prop);\n // }\n }\n else if (prop.type === 'RestElement') {\n if (prop.argument.type === 'Identifier') {\n markSafeIdentifier(prop.argument);\n }\n }\n }\n }\n baseVisitor.ArrayPattern(node, state, c);\n },\n MemberExpression(node, state, c) {\n const prop = node.property;\n if (prop.type === 'Identifier') {\n markSafeIdentifier(prop);\n if (propsBlacklist.has(prop.name)) {\n state.pushError(`Property \"${prop.name}\" is not allowed`, prop);\n }\n }\n else if (prop.type === 'Literal') {\n if (propsBlacklist.has(String(prop.value))) {\n state.pushError(`Property \"${prop.value}\" is not allowed`, prop);\n }\n }\n else {\n state.pushError('Dynamic property lookup is not supported', prop);\n }\n baseVisitor.MemberExpression(node, state, c);\n },\n Function(node, state, c) {\n const name = node.id?.name;\n if (name) {\n // arrow functions have no name\n state.define(name);\n }\n const scope = new Scope(name || '#anonymous', node, state);\n addFunctionParams(node, scope);\n baseVisitor.Function(node, scope, c);\n },\n VariableDeclaration(node, state, c) {\n for (const decl of node.declarations) {\n if (decl.id.type === 'Identifier') {\n markSafeIdentifier(decl.id);\n state.define(decl.id.name);\n }\n else if (decl.id.type === 'ObjectPattern') {\n //the ObjectPattern rule will call markSafeIdentifier\n for (const prop of decl.id.properties) {\n if (prop.type === 'Property') {\n if (prop.value.type === 'Identifier')\n state.define(prop.value.name);\n }\n else if (prop.type === 'RestElement') {\n if (prop.argument.type === 'Identifier')\n state.define(prop.argument.name);\n }\n }\n }\n else if (decl.id.type === 'ArrayPattern') {\n //the ArrayPattern rule will call markSafeIdentifier\n for (const prop of decl.id.elements) {\n if (prop.type === 'Identifier') {\n state.define(prop.name);\n }\n else if (prop.type === 'RestElement') {\n if (prop.argument.type === 'Identifier')\n state.define(prop.argument.name);\n }\n }\n }\n }\n baseVisitor.VariableDeclaration(node, state, c);\n },\n });\n return { root, program };\n}\nexport function validate(code, opts = {}) {\n const { root, program } = buildScopeTree(code, opts);\n recursiveWalk(program, root, {\n Function(node, state, c) {\n baseVisitor.Function(node, node.$scope || state, c);\n },\n Identifier(node, state, c) {\n const identifier = node;\n if (!isSafeIdentifier(node) && !state.isDefined(identifier.name)) {\n state.pushError(`Unknown identifier \"${identifier.name}\"`, node);\n }\n baseVisitor.Identifier(node, state, c);\n },\n });\n return root;\n}\n/**\n * Walk `code` and return every identifier that is referenced but not bound by any\n * enclosing function/variable declaration and not listed in `opts.globals`. Pass\n * known runtime-injected names (e.g. JST's `_`, `Array`, `Set`) in `opts.globals`\n * so they don't appear as free vars. Also surfaces unsafe-construct errors from\n * the same parse pass.\n */\nexport function getFreeVariables(code, opts = {}) {\n const { root, program } = buildScopeTree(code, opts);\n const vars = new Set();\n recursiveWalk(program, root, {\n Function(node, state, c) {\n baseVisitor.Function(node, node.$scope || state, c);\n },\n Identifier(node, state, c) {\n const identifier = node;\n if (!isSafeIdentifier(node) && !state.isDefined(identifier.name)) {\n vars.add(identifier.name);\n }\n baseVisitor.Identifier(node, state, c);\n },\n });\n return { vars, errors: root.errors };\n}\nexport class CompositeError extends Error {\n errors;\n constructor(errors, message) {\n super(`${message || 'Composite Error'}\\n${errors.map((err) => err.message).join('\\n* ')}`);\n this.errors = errors;\n this.errors = errors;\n this.name = 'CompositeError';\n }\n}\n//# sourceMappingURL=validation.js.map","import { validate } from './validation.js';\nexport class Script {\n code;\n globals;\n fn;\n constructor(code, globals) {\n this.code = code;\n this.globals = globals;\n const args = globals && globals.length > 0 ? `{${globals.join(',')}}` : '';\n this.fn = new Function(args, `return (function(){\"use strict\";${code}})()`);\n }\n validate(opts = {}) {\n return validate(this.code, Object.assign({ globals: this.globals }, opts));\n }\n run(context) {\n return this.fn(context);\n }\n}\n//# sourceMappingURL=script.js.map","//add line numbers with {% addLineNumbers(content) %}\nexport function addLineNumbers(content) {\n const lines = content.split('\\n');\n const width = Math.ceil(Math.log10(lines.length));\n return lines\n .map((line, index) => {\n const number = (index + 1).toString().padStart(width, ' ');\n return `{% ${number} %} ${line}`;\n })\n .join('\\n');\n}\n//# sourceMappingURL=addLineNumbers.js.map","import Papa from 'papaparse';\nexport function loadCsv(content, options = {}) {\n return Papa.parse(content, options);\n}\nexport function jsonToCsv(obj, options = {}) {\n return Papa.unparse(obj, options);\n}\n//# sourceMappingURL=csv.js.map","import dayjs from 'dayjs';\nimport { addLineNumbers } from './functions/addLineNumbers.js';\nimport { jsonToCsv, loadCsv } from './functions/csv.js';\nimport { Script } from './script.js';\nimport { TEMPLATE_SYSTEM_VARIABLE_NAMES } from './system.js';\nimport { CompositeError } from './validation.js';\n/** Identifiers every JST template can read besides its declared inputs. */\nexport const JST_TEMPLATE_GLOBALS = ['_', 'Array', 'Set', ...TEMPLATE_SYSTEM_VARIABLE_NAMES];\nexport class CompiledTemplate extends Script {\n constructor(code, globals) {\n // Deduplicate: the globals become a destructured parameter list, where a repeated name\n // (e.g. a schema that also declares `_model`) is a syntax error.\n super(code, [...new Set([...globals, ...JST_TEMPLATE_GLOBALS])]);\n }\n validate() {\n return super.validate({\n acorn: {\n allowReturnOutsideFunction: true,\n locations: true,\n },\n });\n }\n run(context) {\n return super.run({ ...context, Set: Set, Array: Array });\n }\n}\nexport function renderJsTemplate(code, globals, data) {\n const script = new CompiledTemplate(code, globals);\n const state = script.validate();\n if (state.hasErrors()) {\n throw new CompositeError(state.errors, 'Validation errors');\n }\n const content = script.run({\n ...data,\n _: {\n loadCsv,\n jsonToCsv,\n stringify: JSON.stringify,\n addLineNumbers: addLineNumbers,\n dayjs: dayjs,\n },\n });\n return content;\n}\n//# sourceMappingURL=template.js.map"],"mappings":"uJAAA,MAAaI,EAA4B,CACrC,CACI,KAAM,OACN,KAAM,SACN,YAAa,mDACjB,EACA,CACI,KAAM,SACN,KAAM,SACN,YAAa,qDACjB,CACJ,EACaC,EAAiCD,EAA0B,IAAK,GAAME,EAAE,IAAI,EACnFC,EAA2B,IAAI,IAAIF,CAA8B,EACvE,SAAgBG,EAAyB,EAAM,CAC3C,OAAOD,EAAyB,IAAIE,CAAI,CAC5C,CAEA,SAAgBC,EAA6B,EAAU,CAAC,EAAG,CACvD,IAAMC,EAAS,CACX,MAAOC,EAAQ,qBAAO,IAAI,KAAK,CAAG,YAAY,CAClD,EAIA,OAHIA,EAAQ,QACR,EAAO,OAASA,EAAQ,OAErBD,CACX,CAKA,SAAgBE,EAA4B,EAAO,EAAU,CAAC,EAAG,CAC7D,MAAO,CAAE,GAAGC,EAA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AW,CACP,OAAO,MAAM,SAAS,CAClB,MAAO,CACH,2BAA4B,GAC5B,UAAW,EACf,CACJ,CAAC,CACL,CACA,IAAI,EAAS,CACT,OAAO,MAAM,IAAI,CAAE,GAAGjE,EAAc,IAAY,KAAM,CAAC,CAC3D,CACJ,EACA,SAAgBmE,EAAiB,EAAM,EAAS,EAAM,CAClD,IAAMC,EAAS,IAAIF,EAAiB3B,EAAMe,CAAO,EAC3CX,EAAQyB,EAAO,SAAS,EAC9B,GAAIzB,EAAM,UAAU,EAChB,MAAM,IAAIO,EAAeP,EAAM,OAAQ,mBAAmB,EAY9D,OAVgByB,EAAO,IAAI,CACvB,GAAGC,EACH,EAAG,CACC,UACA,YACA,UAAW,KAAK,UACA,iBACT,OACX,CACJ,CACa,CACjB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vertesia/jst",
3
- "version": "1.6.0-dev.20261004.085740Z",
3
+ "version": "1.6.0-dev.20261008.064737Z",
4
4
  "type": "module",
5
5
  "description": "Javascript text template",
6
6
  "license": "Apache-2.0",
@@ -30,12 +30,12 @@
30
30
  "@types/estree": "^1.0.9",
31
31
  "@types/papaparse": "^5.5.2",
32
32
  "@vertesia/tsconfig": "0.1.0",
33
- "rolldown": "1.2.9",
33
+ "rolldown": "1.2.11",
34
34
  "typescript": "7.0.2",
35
- "vitest": "5.0.1"
35
+ "vitest": "5.0.2"
36
36
  },
37
37
  "dependencies": {
38
- "@types/node": "^24.13.6",
38
+ "@types/node": "^24.19.0",
39
39
  "acorn": "8.18.0",
40
40
  "acorn-walk": "8.3.5",
41
41
  "dayjs": "^1.11.23",