@pdfme/common 5.3.5 → 5.3.7-dev.1

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.
@@ -0,0 +1,239 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getDynamicTemplate = void 0;
4
+ const helper_1 = require("./helper");
5
+ class LayoutNode {
6
+ constructor({ width = 0, height = 0 } = {}) {
7
+ Object.defineProperty(this, "index", {
8
+ enumerable: true,
9
+ configurable: true,
10
+ writable: true,
11
+ value: 0
12
+ });
13
+ Object.defineProperty(this, "schema", {
14
+ enumerable: true,
15
+ configurable: true,
16
+ writable: true,
17
+ value: void 0
18
+ });
19
+ Object.defineProperty(this, "children", {
20
+ enumerable: true,
21
+ configurable: true,
22
+ writable: true,
23
+ value: []
24
+ });
25
+ Object.defineProperty(this, "width", {
26
+ enumerable: true,
27
+ configurable: true,
28
+ writable: true,
29
+ value: 0
30
+ });
31
+ Object.defineProperty(this, "height", {
32
+ enumerable: true,
33
+ configurable: true,
34
+ writable: true,
35
+ value: 0
36
+ });
37
+ Object.defineProperty(this, "padding", {
38
+ enumerable: true,
39
+ configurable: true,
40
+ writable: true,
41
+ value: [0, 0, 0, 0]
42
+ });
43
+ Object.defineProperty(this, "position", {
44
+ enumerable: true,
45
+ configurable: true,
46
+ writable: true,
47
+ value: { x: 0, y: 0 }
48
+ });
49
+ this.width = width;
50
+ this.height = height;
51
+ }
52
+ setIndex(index) {
53
+ this.index = index;
54
+ }
55
+ setSchema(schema) {
56
+ this.schema = schema;
57
+ }
58
+ setWidth(width) {
59
+ this.width = width;
60
+ }
61
+ setHeight(height) {
62
+ this.height = height;
63
+ }
64
+ setPadding(padding) {
65
+ this.padding = padding;
66
+ }
67
+ setPosition(position) {
68
+ this.position = position;
69
+ }
70
+ insertChild(child) {
71
+ const index = this.getChildCount();
72
+ child.setIndex(index);
73
+ this.children.splice(index, 0, child);
74
+ }
75
+ getChildCount() {
76
+ return this.children.length;
77
+ }
78
+ getChild(index) {
79
+ return this.children[index];
80
+ }
81
+ }
82
+ function createPage(basePdf) {
83
+ const page = new LayoutNode({ ...basePdf });
84
+ page.setPadding(basePdf.padding);
85
+ return page;
86
+ }
87
+ function createNode(arg) {
88
+ const { position, width, height, schema } = arg;
89
+ const node = new LayoutNode({ width, height });
90
+ node.setPosition(position);
91
+ node.setSchema(schema);
92
+ return node;
93
+ }
94
+ function resortChildren(page, orderMap) {
95
+ page.children = page.children
96
+ .sort((a, b) => {
97
+ const orderA = orderMap.get(a.schema?.name);
98
+ const orderB = orderMap.get(b.schema?.name);
99
+ if (orderA === undefined || orderB === undefined) {
100
+ throw new Error('[@pdfme/common] order is not defined');
101
+ }
102
+ return orderA - orderB;
103
+ })
104
+ .map((child, index) => {
105
+ child.setIndex(index);
106
+ return child;
107
+ });
108
+ }
109
+ async function createOnePage(arg) {
110
+ const { basePdf, schemaPage, orderMap, input, options, _cache, getDynamicHeights } = arg;
111
+ const page = createPage(basePdf);
112
+ const schemaPositions = [];
113
+ const sortedSchemaEntries = (0, helper_1.cloneDeep)(schemaPage).sort((a, b) => a.position.y - b.position.y);
114
+ const diffMap = new Map();
115
+ for (const schema of sortedSchemaEntries) {
116
+ const { position, width } = schema;
117
+ const opt = { schema, basePdf, options, _cache };
118
+ const value = (schema.readOnly ? schema.content : input?.[schema.name]) || '';
119
+ const heights = await getDynamicHeights(value, opt);
120
+ const heightsSum = heights.reduce((acc, cur) => acc + cur, 0);
121
+ const originalHeight = schema.height;
122
+ if (heightsSum !== originalHeight) {
123
+ diffMap.set(position.y + originalHeight, heightsSum - originalHeight);
124
+ }
125
+ heights.forEach((height, index) => {
126
+ let y = schema.position.y + heights.reduce((acc, cur, i) => (i < index ? acc + cur : acc), 0);
127
+ for (const [diffY, diff] of diffMap.entries()) {
128
+ if (diffY <= schema.position.y) {
129
+ y += diff;
130
+ }
131
+ }
132
+ const node = createNode({ schema, position: { ...position, y }, width, height });
133
+ schemaPositions.push(y + height + basePdf.padding[2]);
134
+ page.insertChild(node);
135
+ });
136
+ }
137
+ const pageHeight = Math.max(...schemaPositions, basePdf.height - basePdf.padding[2]);
138
+ page.setHeight(pageHeight);
139
+ resortChildren(page, orderMap);
140
+ return page;
141
+ }
142
+ function breakIntoPages(arg) {
143
+ const { longPage, orderMap, basePdf } = arg;
144
+ const pages = [createPage(basePdf)];
145
+ const [paddingTop, , paddingBottom] = basePdf.padding;
146
+ const yAdjustments = [];
147
+ const getPageHeight = (pageIndex) => basePdf.height - paddingBottom - (pageIndex > 0 ? paddingTop : 0);
148
+ const calculateNewY = (y, pageIndex) => {
149
+ const newY = y - pageIndex * (basePdf.height - paddingTop - paddingBottom);
150
+ while (pages.length <= pageIndex) {
151
+ if (!pages[pageIndex]) {
152
+ pages.push(createPage(basePdf));
153
+ yAdjustments.push({ page: pageIndex, value: (newY - paddingTop) * -1 });
154
+ }
155
+ }
156
+ return newY + (yAdjustments.find((adj) => adj.page === pageIndex)?.value || 0);
157
+ };
158
+ const children = longPage.children.sort((a, b) => a.position.y - b.position.y);
159
+ for (let i = 0; i < children.length; i++) {
160
+ const { schema, position, height, width } = children[i];
161
+ const { y, x } = position;
162
+ let targetPageIndex = Math.floor(y / getPageHeight(pages.length - 1));
163
+ let newY = calculateNewY(y, targetPageIndex);
164
+ if (newY + height > basePdf.height - paddingBottom) {
165
+ targetPageIndex++;
166
+ newY = calculateNewY(y, targetPageIndex);
167
+ }
168
+ if (!schema)
169
+ throw new Error('[@pdfme/common] schema is undefined');
170
+ const clonedElement = createNode({ schema, position: { x, y: newY }, width, height });
171
+ pages[targetPageIndex].insertChild(clonedElement);
172
+ }
173
+ pages.forEach((page) => resortChildren(page, orderMap));
174
+ return pages;
175
+ }
176
+ function createNewTemplate(pages, basePdf) {
177
+ const newTemplate = {
178
+ schemas: Array.from({ length: pages.length }, () => []),
179
+ basePdf: basePdf,
180
+ };
181
+ const nameToSchemas = new Map();
182
+ (0, helper_1.cloneDeep)(pages).forEach((page, pageIndex) => {
183
+ page.children.forEach((child) => {
184
+ const { schema } = child;
185
+ if (!schema)
186
+ throw new Error('[@pdfme/common] schema is undefined');
187
+ const name = schema.name;
188
+ if (!nameToSchemas.has(name)) {
189
+ nameToSchemas.set(name, []);
190
+ }
191
+ nameToSchemas.get(name).push(child);
192
+ const sameNameSchemas = page.children.filter((c) => c.schema?.name === name);
193
+ const start = nameToSchemas.get(name).length - sameNameSchemas.length;
194
+ if (sameNameSchemas.length > 0) {
195
+ if (!sameNameSchemas[0].schema) {
196
+ throw new Error('[@pdfme/common] schema is undefined');
197
+ }
198
+ // Use the first schema to get the schema and position
199
+ const schema = sameNameSchemas[0].schema;
200
+ const height = sameNameSchemas.reduce((acc, cur) => acc + cur.height, 0);
201
+ const position = sameNameSchemas[0].position;
202
+ // Currently, __bodyRange exists for table schemas, but if we make it more abstract,
203
+ // it could be used for other schemas as well to render schemas that have been split by page breaks, starting from the middle.
204
+ schema.__bodyRange = {
205
+ start: Math.max(start - 1, 0),
206
+ end: start + sameNameSchemas.length - 1,
207
+ };
208
+ // Currently, this is used to determine whether to display the header when a table is split.
209
+ schema.__isSplit = start > 0;
210
+ const newSchema = Object.assign({}, schema, { position, height });
211
+ const index = newTemplate.schemas[pageIndex].findIndex((s) => s.name === name);
212
+ if (index !== -1) {
213
+ newTemplate.schemas[pageIndex][index] = newSchema;
214
+ }
215
+ else {
216
+ newTemplate.schemas[pageIndex].push(newSchema);
217
+ }
218
+ }
219
+ });
220
+ });
221
+ return newTemplate;
222
+ }
223
+ const getDynamicTemplate = async (arg) => {
224
+ const { template } = arg;
225
+ if (!(0, helper_1.isBlankPdf)(template.basePdf)) {
226
+ return template;
227
+ }
228
+ const basePdf = template.basePdf;
229
+ const pages = [];
230
+ for (const schemaPage of template.schemas) {
231
+ const orderMap = new Map(schemaPage.map((schema, index) => [schema.name, index]));
232
+ const longPage = await createOnePage({ basePdf, schemaPage, orderMap, ...arg });
233
+ const brokenPages = breakIntoPages({ longPage, basePdf, orderMap });
234
+ pages.push(...brokenPages);
235
+ }
236
+ return createNewTemplate(pages, template.basePdf);
237
+ };
238
+ exports.getDynamicTemplate = getDynamicTemplate;
239
+ //# sourceMappingURL=dynamicTemplate.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dynamicTemplate.js","sourceRoot":"","sources":["../../../src/dynamicTemplate.ts"],"names":[],"mappings":";;;AACA,qCAAiD;AAajD,MAAM,UAAU;IAYd,YAAY,EAAE,KAAK,GAAG,CAAC,EAAE,MAAM,GAAG,CAAC,EAAE,GAAG,EAAE;QAX1C;;;;mBAAQ,CAAC;WAAC;QAEV;;;;;WAAgB;QAEhB;;;;mBAAyB,EAAE;WAAC;QAE5B;;;;mBAAQ,CAAC;WAAC;QACV;;;;mBAAS,CAAC;WAAC;QACX;;;;mBAA4C,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC;WAAC;QACzD;;;;mBAAqC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE;WAAC;QAGlD,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED,QAAQ,CAAC,KAAa;QACpB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAED,SAAS,CAAC,MAAc;QACtB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED,QAAQ,CAAC,KAAa;QACpB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;IACrB,CAAC;IAED,SAAS,CAAC,MAAc;QACtB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;IAED,UAAU,CAAC,OAAyC;QAClD,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACzB,CAAC;IAED,WAAW,CAAC,QAAkC;QAC5C,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC3B,CAAC;IAED,WAAW,CAAC,KAA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SAAS,CAAC,CAAC;iBAChD;aACF;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO,WAAW,CAAC;AACrB,CAAC;AAEM,MAAM,kBAAkB,GAAG,KAAK,EACrC,GAAqC,EAClB,EAAE;IACrB,MAAM,EAAE,QAAQ,EAAE,GAAG,GAAG,CAAC;IACzB,IAAI,CAAC,IAAA,mBAAU,EAAC,QAAQ,CAAC,OAAO,CAAC,EAAE;QACjC,OAAO,QAAQ,CAAC;KACjB;IAED,MAAM,OAAO,GAAG,QAAQ,CAAC,OAAmB,CAAC;IAC7C,MAAM,KAAK,GAAiB,EAAE,CAAC;IAE/B,KAAK,MAAM,UAAU,IAAI,QAAQ,CAAC,OAAO,EAAE;QACzC,MAAM,QAAQ,GAAG,IAAI,GAAG,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC;QAClF,MAAM,QAAQ,GAAG,MAAM,aAAa,CAAC,EAAE,OAAO,EAAE,UAAU,EAAE,QAAQ,EAAE,GAAG,GAAG,EAAE,CAAC,CAAC;QAChF,MAAM,WAAW,GAAG,cAAc,CAAC,EAAE,QAAQ,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;QACpE,KAAK,CAAC,IAAI,CAAC,GAAG,WAAW,CAAC,CAAC;KAC5B;IAED,OAAO,iBAAiB,CAAC,KAAK,EAAE,QAAQ,CAAC,OAAO,CAAC,CAAC;AACpD,CAAC,CAAC;AAnBW,QAAA,kBAAkB,sBAmB7B"}
@@ -0,0 +1,408 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.replacePlaceholders = void 0;
27
+ const acorn = __importStar(require("acorn"));
28
+ const expressionCache = new Map();
29
+ const parseDataCache = new Map();
30
+ const parseData = (data) => {
31
+ const key = JSON.stringify(data);
32
+ if (parseDataCache.has(key)) {
33
+ return parseDataCache.get(key);
34
+ }
35
+ const parsed = Object.fromEntries(Object.entries(data).map(([key, value]) => {
36
+ if (typeof value === 'string') {
37
+ try {
38
+ const parsedValue = JSON.parse(value);
39
+ return [key, parsedValue];
40
+ }
41
+ catch {
42
+ return [key, value];
43
+ }
44
+ }
45
+ return [key, value];
46
+ }));
47
+ parseDataCache.set(key, parsed);
48
+ return parsed;
49
+ };
50
+ const padZero = (num) => String(num).padStart(2, '0');
51
+ const formatDate = (date) => `${date.getFullYear()}/${padZero(date.getMonth() + 1)}/${padZero(date.getDate())}`;
52
+ const formatDateTime = (date) => `${formatDate(date)} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
53
+ const allowedGlobals = {
54
+ Math,
55
+ String,
56
+ Number,
57
+ Boolean,
58
+ Array,
59
+ Object,
60
+ Date,
61
+ JSON,
62
+ isNaN,
63
+ parseFloat,
64
+ parseInt,
65
+ decodeURI,
66
+ decodeURIComponent,
67
+ encodeURI,
68
+ encodeURIComponent,
69
+ };
70
+ const validateAST = (node) => {
71
+ switch (node.type) {
72
+ case 'Literal':
73
+ case 'Identifier':
74
+ break;
75
+ case 'BinaryExpression':
76
+ case 'LogicalExpression': {
77
+ const binaryNode = node;
78
+ validateAST(binaryNode.left);
79
+ validateAST(binaryNode.right);
80
+ break;
81
+ }
82
+ case 'UnaryExpression': {
83
+ const unaryNode = node;
84
+ validateAST(unaryNode.argument);
85
+ break;
86
+ }
87
+ case 'ConditionalExpression': {
88
+ const condNode = node;
89
+ validateAST(condNode.test);
90
+ validateAST(condNode.consequent);
91
+ validateAST(condNode.alternate);
92
+ break;
93
+ }
94
+ case 'MemberExpression': {
95
+ const memberNode = node;
96
+ validateAST(memberNode.object);
97
+ if (memberNode.computed) {
98
+ validateAST(memberNode.property);
99
+ }
100
+ else {
101
+ const propName = memberNode.property.name;
102
+ if (['constructor', '__proto__', 'prototype'].includes(propName)) {
103
+ throw new Error('Access to prohibited property');
104
+ }
105
+ const prohibitedMethods = ['toLocaleString', 'valueOf'];
106
+ if (typeof propName === 'string' && prohibitedMethods.includes(propName)) {
107
+ throw new Error(`Access to prohibited method: ${propName}`);
108
+ }
109
+ }
110
+ break;
111
+ }
112
+ case 'CallExpression': {
113
+ const callNode = node;
114
+ validateAST(callNode.callee);
115
+ callNode.arguments.forEach(validateAST);
116
+ break;
117
+ }
118
+ case 'ArrayExpression': {
119
+ const arrayNode = node;
120
+ arrayNode.elements.forEach((elem) => {
121
+ if (elem)
122
+ validateAST(elem);
123
+ });
124
+ break;
125
+ }
126
+ case 'ObjectExpression': {
127
+ const objectNode = node;
128
+ objectNode.properties.forEach((prop) => {
129
+ const propNode = prop;
130
+ validateAST(propNode.key);
131
+ validateAST(propNode.value);
132
+ });
133
+ break;
134
+ }
135
+ case 'ArrowFunctionExpression': {
136
+ const arrowFuncNode = node;
137
+ arrowFuncNode.params.forEach((param) => {
138
+ if (param.type !== 'Identifier') {
139
+ throw new Error('Only identifier parameters are supported in arrow functions');
140
+ }
141
+ validateAST(param);
142
+ });
143
+ validateAST(arrowFuncNode.body);
144
+ break;
145
+ }
146
+ default:
147
+ throw new Error(`Unsupported syntax in placeholder: ${node.type}`);
148
+ }
149
+ };
150
+ const evaluateAST = (node, context) => {
151
+ switch (node.type) {
152
+ case 'Literal': {
153
+ const literalNode = node;
154
+ return literalNode.value;
155
+ }
156
+ case 'Identifier': {
157
+ const idNode = node;
158
+ if (Object.prototype.hasOwnProperty.call(context, idNode.name)) {
159
+ return context[idNode.name];
160
+ }
161
+ else if (Object.prototype.hasOwnProperty.call(allowedGlobals, idNode.name)) {
162
+ return allowedGlobals[idNode.name];
163
+ }
164
+ else {
165
+ throw new Error(`Undefined variable: ${idNode.name}`);
166
+ }
167
+ }
168
+ case 'BinaryExpression': {
169
+ const binaryNode = node;
170
+ const left = evaluateAST(binaryNode.left, context);
171
+ const right = evaluateAST(binaryNode.right, context);
172
+ switch (binaryNode.operator) {
173
+ case '+':
174
+ return left + right;
175
+ case '-':
176
+ return left - right;
177
+ case '*':
178
+ return left * right;
179
+ case '/':
180
+ return left / right;
181
+ case '%':
182
+ return left % right;
183
+ case '**':
184
+ return left ** right;
185
+ case '==':
186
+ return left == right;
187
+ case '!=':
188
+ return left != right;
189
+ case '===':
190
+ return left === right;
191
+ case '!==':
192
+ return left !== right;
193
+ case '<':
194
+ return left < right;
195
+ case '>':
196
+ return left > right;
197
+ case '<=':
198
+ return left <= right;
199
+ case '>=':
200
+ return left >= right;
201
+ default:
202
+ throw new Error(`Unsupported operator: ${binaryNode.operator}`);
203
+ }
204
+ }
205
+ case 'LogicalExpression': {
206
+ const logicalNode = node;
207
+ const leftLogical = evaluateAST(logicalNode.left, context);
208
+ const rightLogical = evaluateAST(logicalNode.right, context);
209
+ switch (logicalNode.operator) {
210
+ case '&&':
211
+ return leftLogical && rightLogical;
212
+ case '||':
213
+ return leftLogical || rightLogical;
214
+ default:
215
+ throw new Error(`Unsupported operator: ${logicalNode.operator}`);
216
+ }
217
+ }
218
+ case 'UnaryExpression': {
219
+ const unaryNode = node;
220
+ const arg = evaluateAST(unaryNode.argument, context);
221
+ switch (unaryNode.operator) {
222
+ case '+':
223
+ return +arg;
224
+ case '-':
225
+ return -arg;
226
+ case '!':
227
+ return !arg;
228
+ default:
229
+ throw new Error(`Unsupported operator: ${unaryNode.operator}`);
230
+ }
231
+ }
232
+ case 'ConditionalExpression': {
233
+ const condNode = node;
234
+ const test = evaluateAST(condNode.test, context);
235
+ return test
236
+ ? evaluateAST(condNode.consequent, context)
237
+ : evaluateAST(condNode.alternate, context);
238
+ }
239
+ case 'MemberExpression': {
240
+ const memberNode = node;
241
+ const obj = evaluateAST(memberNode.object, context);
242
+ let prop;
243
+ if (memberNode.computed) {
244
+ prop = evaluateAST(memberNode.property, context);
245
+ }
246
+ else {
247
+ prop = memberNode.property.name;
248
+ }
249
+ if (typeof prop === 'string' || typeof prop === 'number') {
250
+ if (typeof prop === 'string' && ['constructor', '__proto__', 'prototype'].includes(prop)) {
251
+ throw new Error('Access to prohibited property');
252
+ }
253
+ return obj[prop];
254
+ }
255
+ else {
256
+ throw new Error('Invalid property access');
257
+ }
258
+ }
259
+ case 'CallExpression': {
260
+ const callNode = node;
261
+ const callee = evaluateAST(callNode.callee, context);
262
+ const args = callNode.arguments.map((argNode) => evaluateAST(argNode, context));
263
+ if (typeof callee === 'function') {
264
+ if (callNode.callee.type === 'MemberExpression') {
265
+ const memberExpr = callNode.callee;
266
+ const obj = evaluateAST(memberExpr.object, context);
267
+ if (obj !== null &&
268
+ (typeof obj === 'object' ||
269
+ typeof obj === 'number' ||
270
+ typeof obj === 'string' ||
271
+ typeof obj === 'boolean')) {
272
+ return callee.call(obj, ...args);
273
+ }
274
+ else {
275
+ throw new Error('Invalid object in member function call');
276
+ }
277
+ }
278
+ else {
279
+ return callee(...args);
280
+ }
281
+ }
282
+ else {
283
+ throw new Error('Attempted to call a non-function');
284
+ }
285
+ }
286
+ case 'ArrowFunctionExpression': {
287
+ const arrowFuncNode = node;
288
+ const params = arrowFuncNode.params.map((param) => param.name);
289
+ const body = arrowFuncNode.body;
290
+ return (...args) => {
291
+ const newContext = { ...context };
292
+ params.forEach((param, index) => {
293
+ newContext[param] = args[index];
294
+ });
295
+ return evaluateAST(body, newContext);
296
+ };
297
+ }
298
+ case 'ArrayExpression': {
299
+ const arrayNode = node;
300
+ return arrayNode.elements.map((elem) => (elem ? evaluateAST(elem, context) : null));
301
+ }
302
+ case 'ObjectExpression': {
303
+ const objectNode = node;
304
+ const objResult = {};
305
+ objectNode.properties.forEach((prop) => {
306
+ const propNode = prop;
307
+ let key;
308
+ if (propNode.key.type === 'Identifier') {
309
+ key = propNode.key.name;
310
+ }
311
+ else {
312
+ const evaluatedKey = evaluateAST(propNode.key, context);
313
+ if (typeof evaluatedKey !== 'string' && typeof evaluatedKey !== 'number') {
314
+ throw new Error('Object property keys must be strings or numbers');
315
+ }
316
+ key = String(evaluatedKey);
317
+ }
318
+ const value = evaluateAST(propNode.value, context);
319
+ objResult[key] = value;
320
+ });
321
+ return objResult;
322
+ }
323
+ default:
324
+ throw new Error(`Unsupported syntax in placeholder: ${node.type}`);
325
+ }
326
+ };
327
+ const evaluatePlaceholders = (arg) => {
328
+ const { content, context } = arg;
329
+ let resultContent = '';
330
+ let index = 0;
331
+ while (index < content.length) {
332
+ const startIndex = content.indexOf('{', index);
333
+ if (startIndex === -1) {
334
+ resultContent += content.slice(index);
335
+ break;
336
+ }
337
+ resultContent += content.slice(index, startIndex);
338
+ let braceCount = 1;
339
+ let endIndex = startIndex + 1;
340
+ while (endIndex < content.length && braceCount > 0) {
341
+ if (content[endIndex] === '{') {
342
+ braceCount++;
343
+ }
344
+ else if (content[endIndex] === '}') {
345
+ braceCount--;
346
+ }
347
+ endIndex++;
348
+ }
349
+ if (braceCount === 0) {
350
+ const code = content.slice(startIndex + 1, endIndex - 1).trim();
351
+ if (expressionCache.has(code)) {
352
+ const evalFunc = expressionCache.get(code);
353
+ try {
354
+ const value = evalFunc(context);
355
+ resultContent += String(value);
356
+ }
357
+ catch {
358
+ resultContent += content.slice(startIndex, endIndex);
359
+ }
360
+ }
361
+ else {
362
+ try {
363
+ const ast = acorn.parseExpressionAt(code, 0, { ecmaVersion: 'latest' });
364
+ validateAST(ast);
365
+ const evalFunc = (ctx) => evaluateAST(ast, ctx);
366
+ expressionCache.set(code, evalFunc);
367
+ const value = evalFunc(context);
368
+ resultContent += String(value);
369
+ }
370
+ catch {
371
+ resultContent += content.slice(startIndex, endIndex);
372
+ }
373
+ }
374
+ index = endIndex;
375
+ }
376
+ else {
377
+ throw new Error('Invalid placeholder');
378
+ }
379
+ }
380
+ return resultContent;
381
+ };
382
+ const replacePlaceholders = (arg) => {
383
+ const { content, variables, schemas } = arg;
384
+ if (!content || typeof content !== 'string' || !content.includes('{') || !content.includes('}')) {
385
+ return content;
386
+ }
387
+ const date = new Date();
388
+ const formattedDate = formatDate(date);
389
+ const formattedDateTime = formatDateTime(date);
390
+ const data = {
391
+ ...Object.fromEntries(schemas.flat().map((schema) => [schema.name, schema.readOnly ? schema.content || '' : ''])),
392
+ ...variables,
393
+ };
394
+ const parsedInput = parseData(data);
395
+ const context = {
396
+ date: formattedDate,
397
+ dateTime: formattedDateTime,
398
+ ...parsedInput,
399
+ };
400
+ Object.entries(context).forEach(([key, value]) => {
401
+ if (typeof value === 'string' && value.includes('{') && value.includes('}')) {
402
+ context[key] = evaluatePlaceholders({ content: value, context });
403
+ }
404
+ });
405
+ return evaluatePlaceholders({ content, context });
406
+ };
407
+ exports.replacePlaceholders = replacePlaceholders;
408
+ //# sourceMappingURL=expression.js.map