@vdhewei/xlsx-template-lib 1.3.5 → 1.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js ADDED
@@ -0,0 +1,1626 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
+ // If the importer is in node compatibility mode or this is not an ESM
19
+ // file that has been converted to a CommonJS file using a Babel-
20
+ // compatible transform (i.e. "__esModule" has not been set), then set
21
+ // "default" to the CommonJS "module.exports" for node compatibility.
22
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
+ mod
24
+ ));
25
+
26
+ // src/bin.ts
27
+ var import_chalk = __toESM(require("chalk"));
28
+ var import_commander = require("commander");
29
+
30
+ // src/core.ts
31
+ var etree = __toESM(require("elementtree"));
32
+ var import_jszip = __toESM(require("jszip"));
33
+ var console2 = __toESM(require("console"));
34
+ var import_image_size = require("image-size");
35
+ var import_types = require("util/types");
36
+ var pattern = new RegExp("^(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*(\\?[;&a-z\\d%_.~+=-]*)?(\\#[-a-z\\d_]*)?$", "i");
37
+
38
+ // src/helper.ts
39
+ var import_exceljs = __toESM(require("exceljs"));
40
+ var import_stream = require("stream");
41
+ var isPureNumber = /^[0-9]+$/;
42
+ var isPureUppercase = /^[A-Z]+$/;
43
+ var exprSingle = `expr`;
44
+ var exprArr = `exprArr`;
45
+ var exprIndex = `index`;
46
+ var defaultKey = `!!`;
47
+ var numberKey = `!!number`;
48
+ var codeKey = `!!codeKey`;
49
+ var codeAliasKey = `!!codeAliasKey`;
50
+ var funcCommand = "fn:";
51
+ var RuleMapOptions = class _RuleMapOptions {
52
+ constructor(m) {
53
+ // rule configure area
54
+ this.startLine = 1;
55
+ this.startColumn = 1;
56
+ if (m === void 0) {
57
+ this.ruleKeyMap = defaultRuleTokenMap;
58
+ } else {
59
+ this.ruleKeyMap = m;
60
+ }
61
+ }
62
+ static withAllSheets(w, excludes) {
63
+ const compileSheets = [];
64
+ const options = new _RuleMapOptions();
65
+ if (excludes === void 0) {
66
+ excludes = [];
67
+ }
68
+ if (w.worksheets.length > 0 && excludes.length > 0) {
69
+ for (const [index, sheet] of w.worksheets.entries()) {
70
+ if (excludes.includes(index.toString()) || excludes.includes(sheet.name)) {
71
+ continue;
72
+ }
73
+ if (sheet.name.endsWith(".json")) {
74
+ continue;
75
+ }
76
+ compileSheets.push(sheet.name);
77
+ }
78
+ }
79
+ options.compileSheets = compileSheets;
80
+ return options;
81
+ }
82
+ parseDefault(worksheet) {
83
+ this.ruleKeyMap = mergeOption(this.ruleKeyMap, defaultRuleTokenMap);
84
+ if (this.startLine === void 0 || isNaN(this.startLine) || this.startLine < 0) {
85
+ this.startLine = 1;
86
+ }
87
+ if (this.endLine === void 0 || isNaN(this.endLine) || this.endLine < 0) {
88
+ this.endLine = worksheet.rowCount;
89
+ }
90
+ if (this.startColumn === void 0 || isNaN(this.startColumn) || this.startColumn < 0) {
91
+ this.startColumn = 1;
92
+ }
93
+ if (this.endColumn === void 0 || isNaN(this.endColumn) || this.endColumn < 0) {
94
+ this.endColumn = worksheet.columnCount;
95
+ }
96
+ return this;
97
+ }
98
+ addRuleMap(key, value) {
99
+ this.ruleKeyMap.set(key, value);
100
+ return this;
101
+ }
102
+ setStartRow(start) {
103
+ this.startLine = start;
104
+ return this;
105
+ }
106
+ setStartColumn(start) {
107
+ this.startColumn = start;
108
+ return this;
109
+ }
110
+ setEndRow(end) {
111
+ this.endLine = end;
112
+ return this;
113
+ }
114
+ setEndColumn(end) {
115
+ this.endColumn = end;
116
+ return this;
117
+ }
118
+ parseToken(value) {
119
+ if (value === "") {
120
+ return "" /* UndefinedToken */;
121
+ }
122
+ for (const [token, alias] of this.ruleKeyMap.entries()) {
123
+ if (alias === value) {
124
+ return token;
125
+ }
126
+ }
127
+ return "" /* UndefinedToken */;
128
+ }
129
+ getContextMap() {
130
+ const ctx = /* @__PURE__ */ new Map();
131
+ for (const [token, expr] of this.ruleKeyMap.entries()) {
132
+ if (!isRuleToken(token)) {
133
+ const value = [{
134
+ express: expr,
135
+ key: expr,
136
+ tokens: [token],
137
+ value: token.toString()
138
+ }];
139
+ ctx.set(token, value);
140
+ }
141
+ }
142
+ return ctx;
143
+ }
144
+ getCompileCheckHandlers() {
145
+ if (this.compileCheckers !== void 0 && this.compileCheckers.length > 0) {
146
+ return this.compileCheckers;
147
+ }
148
+ return void 0;
149
+ }
150
+ };
151
+ var CompileContext = class _CompileContext extends RuleMapOptions {
152
+ constructor(m) {
153
+ super(m);
154
+ this.aliasMap = /* @__PURE__ */ new Map();
155
+ }
156
+ static create(r) {
157
+ const ctx = new _CompileContext(r.ruleKeyMap);
158
+ Object.assign(ctx, { ...r });
159
+ return ctx.init();
160
+ }
161
+ init() {
162
+ if (this.ruleKeyMap === void 0) {
163
+ this.ruleKeyMap = defaultRuleTokenMap;
164
+ }
165
+ return this;
166
+ }
167
+ loadAlias(m) {
168
+ if (m.size <= 0 || !m.has("alias" /* AliasToken */)) {
169
+ return this;
170
+ }
171
+ const values = m.get("alias" /* AliasToken */);
172
+ for (const vs of values) {
173
+ if (typeof vs.value === "string") {
174
+ this.aliasMap.set(vs.key, vs.value);
175
+ }
176
+ }
177
+ return this;
178
+ }
179
+ /**
180
+ * 设置别名缓存
181
+ */
182
+ setAlias(key, value) {
183
+ this.aliasMap.set(key, value);
184
+ }
185
+ /**
186
+ * 获取别名缓存值
187
+ */
188
+ getAlias(key) {
189
+ return this.aliasMap.get(key);
190
+ }
191
+ /**
192
+ * 检查别名是否存在
193
+ */
194
+ hasAlias(key) {
195
+ return this.aliasMap.has(key);
196
+ }
197
+ filterSheet(sheetName) {
198
+ if (sheetName !== "" && this.compileSheets !== void 0 && this.compileSheets.length > 0) {
199
+ return this.compileSheets.includes(sheetName);
200
+ }
201
+ return false;
202
+ }
203
+ };
204
+ var defaultRuleTokenMap = /* @__PURE__ */ new Map([
205
+ ["alias" /* AliasToken */, "alias" /* AliasToken */.toString()],
206
+ ["?" /* AnyToken */, "?" /* AnyToken */.toString()],
207
+ ["cell" /* CellToken */, "cell" /* CellToken */.toString()],
208
+ ["rowCell" /* RowCellToken */, "rowCell" /* RowCellToken */.toString()],
209
+ ["mergeCell" /* MergeCellToken */, "mergeCell" /* MergeCellToken */.toString()],
210
+ ["@" /* UseAliasToken */, "@" /* UseAliasToken */.toString()],
211
+ [":" /* PosToken */, ":" /* PosToken */.toString()],
212
+ ["-" /* RangeToken */, "-" /* RangeToken */.toString()],
213
+ ["<?>" /* FunctionPatternToken */, "<?>" /* FunctionPatternToken */.toString()],
214
+ ["${?}" /* VarPatternToken */, "${?}" /* VarPatternToken */.toString()],
215
+ ["=" /* EqualToken */, "=" /* EqualToken */.toString()],
216
+ ["," /* ArgPosToken */, "," /* ArgPosToken */.toString()],
217
+ ["(" /* LparenToken */, "(" /* LparenToken */.toString()],
218
+ [")" /* RparenToken */, ")" /* RparenToken */.toString()],
219
+ ["." /* DotGetToken */, "." /* DotGetToken */.toString()],
220
+ ["compile:Macro" /* CompileMacroToken */, "compile:Macro" /* CompileMacroToken */.toString()],
221
+ ["compile:GenCell" /* CompileGenToken */, "compile:GenCell" /* CompileGenToken */.toString()]
222
+ ]);
223
+ var _getCells = (thisArg) => {
224
+ let cells = [];
225
+ for (let j = thisArg.minColumn; j <= thisArg.maxColumn; j += thisArg.stepColumn) {
226
+ for (let i = thisArg.minRow; i <= thisArg.maxRow; i += thisArg.stepRow) {
227
+ cells.push({
228
+ Row: i,
229
+ Column: j
230
+ });
231
+ }
232
+ }
233
+ return cells;
234
+ };
235
+ var TokenParserManger = class _TokenParserManger {
236
+ // T=xxx
237
+ static aliasParse(ctx, token, value) {
238
+ if (token !== "alias" /* AliasToken */) {
239
+ return {
240
+ ok: false
241
+ };
242
+ }
243
+ const parser = getTokenParser("=" /* EqualToken */);
244
+ const { values, expr, ok } = parser.handler(ctx, "=" /* EqualToken */, value);
245
+ if (!ok) {
246
+ return {
247
+ ok: false
248
+ };
249
+ }
250
+ if (typeof expr.value !== "string" || expr.value === "") {
251
+ return {
252
+ ok: false,
253
+ error: new Error(`alias express right value cannot be a empty value.`)
254
+ };
255
+ }
256
+ return {
257
+ ok: true,
258
+ expr: {
259
+ express: value,
260
+ key: expr.key,
261
+ // alias key
262
+ value: expr.value,
263
+ // alias value
264
+ tokens: [token, "=" /* EqualToken */]
265
+ // express tokens
266
+ },
267
+ values
268
+ };
269
+ }
270
+ // x=xx
271
+ static equalParse(ctx, token, value) {
272
+ if (token !== "=" /* EqualToken */) {
273
+ return {
274
+ ok: false
275
+ };
276
+ }
277
+ const equalToken = _TokenParserManger.getTokenByCtx(ctx, "=" /* EqualToken */);
278
+ const offset = equalToken.length;
279
+ const index = value.indexOf(equalToken);
280
+ if (index < 0) {
281
+ return {
282
+ ok: false
283
+ };
284
+ }
285
+ const len = value.length;
286
+ const key = value.substring(0, index);
287
+ const rightValue = value.substring(index + offset, len);
288
+ if (rightValue === "") {
289
+ return {
290
+ ok: false,
291
+ error: new Error(`equal express right value cannot be a empty value.`)
292
+ };
293
+ }
294
+ const expr = {
295
+ key,
296
+ value: rightValue,
297
+ express: value,
298
+ tokens: [token]
299
+ };
300
+ return {
301
+ ok: true,
302
+ values: [key, rightValue],
303
+ expr
304
+ };
305
+ }
306
+ //cell| X:Y=${?}
307
+ static cellParse(ctx, token, value) {
308
+ if (token !== "cell" /* CellToken */) {
309
+ return {
310
+ ok: false
311
+ };
312
+ }
313
+ const equalToken = _TokenParserManger.getTokenByCtx(ctx, "=" /* EqualToken */);
314
+ const eqOffset = equalToken.length;
315
+ const posToken = _TokenParserManger.getTokenByCtx(ctx, ":" /* PosToken */);
316
+ const eqIndex = value.indexOf(equalToken);
317
+ const posIndex = value.indexOf(posToken);
318
+ if (eqIndex < 0 || posIndex < 0) {
319
+ return {
320
+ ok: false
321
+ };
322
+ }
323
+ const parser = getTokenParser(":" /* PosToken */);
324
+ const varParser = getTokenParser("${?}" /* VarPatternToken */);
325
+ const posValue = value.substring(0, eqIndex);
326
+ const varValue = value.substring(eqIndex + eqOffset);
327
+ const posReply = parser.handler(ctx, ":" /* PosToken */, posValue);
328
+ if (!posReply.ok) {
329
+ return {
330
+ ok: false,
331
+ ...posReply
332
+ };
333
+ }
334
+ const varReply = varParser.handler(ctx, "${?}" /* VarPatternToken */, varValue);
335
+ if (!varReply.ok) {
336
+ return {
337
+ ok: false,
338
+ ...varReply
339
+ };
340
+ }
341
+ const expr = {
342
+ ...varReply.expr
343
+ };
344
+ expr.express = value;
345
+ expr.cells = posReply.expr.cells;
346
+ expr.value = varReply.expr.value;
347
+ expr.ref = varReply.expr.ref;
348
+ expr.tokens = [token, "=" /* EqualToken */, ...posReply.expr.tokens, ...varReply.expr.tokens];
349
+ return {
350
+ ok: true,
351
+ expr,
352
+ values: [posReply.values, varReply.values]
353
+ };
354
+ }
355
+ static useAliasParse(ctx, token, value) {
356
+ if (token !== "@" /* UseAliasToken */) {
357
+ return {
358
+ ok: false
359
+ };
360
+ }
361
+ const useAliasToken = _TokenParserManger.getTokenByCtx(ctx, "@" /* UseAliasToken */);
362
+ const offset = useAliasToken.length;
363
+ const has = offset !== 0 && value.indexOf(useAliasToken) >= 0;
364
+ if (!has) {
365
+ return {
366
+ ok: false
367
+ };
368
+ }
369
+ const endTokens = ["@" /* UseAliasToken */, "(" /* LparenToken */, "," /* ArgPosToken */, "." /* DotGetToken */];
370
+ const values = _TokenParserManger.scanToken(value, useAliasToken, _TokenParserManger.toList(ctx, endTokens));
371
+ if (values === void 0 || values.length <= 0) {
372
+ return {
373
+ ok: false
374
+ };
375
+ }
376
+ const keys = [];
377
+ const tokens = [];
378
+ const expr = {
379
+ express: value,
380
+ tokens,
381
+ value: keys,
382
+ ref: []
383
+ };
384
+ for (const v of values) {
385
+ tokens.push(token);
386
+ keys.push(v.token);
387
+ expr.ref.push(v.value);
388
+ }
389
+ expr.value = keys;
390
+ expr.tokens = tokens;
391
+ return {
392
+ expr,
393
+ ok: true,
394
+ values
395
+ };
396
+ }
397
+ static rangeParse(ctx, token, value) {
398
+ if (token !== "-" /* RangeToken */) {
399
+ return {
400
+ ok: false
401
+ };
402
+ }
403
+ const rangeToken = _TokenParserManger.getTokenByCtx(ctx, "-" /* RangeToken */);
404
+ const offset = rangeToken.length;
405
+ const index = value.indexOf(rangeToken);
406
+ if (index < 0 || offset <= 0) {
407
+ return {
408
+ ok: false
409
+ };
410
+ }
411
+ let setup = 1;
412
+ let startNumber = NaN;
413
+ let endNumber = NaN;
414
+ let startPos = value.substring(0, index).trim();
415
+ let endPos = value.substring(index + offset).trim();
416
+ const argPosToken = _TokenParserManger.getTokenByCtx(ctx, "," /* ArgPosToken */);
417
+ const endSetupIndex = endPos.indexOf(argPosToken);
418
+ if (endSetupIndex > 0) {
419
+ setup = Number.parseInt(endPos.substring(endSetupIndex).trim(), 10);
420
+ endPos = endPos.substring(0, endSetupIndex).trim();
421
+ }
422
+ if (isNaN(setup)) {
423
+ return {
424
+ ok: false,
425
+ error: new Error(`rangeToken parse setup NaN, ${value}`)
426
+ };
427
+ }
428
+ endNumber = _TokenParserManger.parsePosNumber(endPos);
429
+ startNumber = _TokenParserManger.parsePosNumber(startPos);
430
+ if (isNaN(startNumber) || isNaN(endNumber)) {
431
+ return {
432
+ ok: false,
433
+ error: new Error(`rangeToken parse start,end has NaN, ${value}`)
434
+ };
435
+ }
436
+ const expr = {
437
+ express: value,
438
+ tokens: [token],
439
+ value: [startNumber, endNumber, setup]
440
+ };
441
+ return {
442
+ expr,
443
+ ok: true,
444
+ values: [startNumber, endNumber, setup]
445
+ };
446
+ }
447
+ static posParse(ctx, token, value) {
448
+ if (token !== ":" /* PosToken */) {
449
+ return {
450
+ ok: false
451
+ };
452
+ }
453
+ const posToken = _TokenParserManger.getTokenByCtx(ctx, ":" /* PosToken */);
454
+ const offset = posToken.length;
455
+ const index = value.indexOf(posToken);
456
+ const len = value.length;
457
+ const column = value.substring(0, index).trim();
458
+ const row = value.substring(index + offset, len).trim();
459
+ const rangeToken = _TokenParserManger.getTokenByCtx(ctx, "-" /* RangeToken */);
460
+ const columnRange = column.indexOf(rangeToken);
461
+ const rowRange = row.indexOf(rangeToken);
462
+ if (rowRange > 0 || columnRange > 0) {
463
+ return _TokenParserManger.parseRangeValue(ctx, { rowRange, columnRange, row, column, token, express: value });
464
+ }
465
+ const cell = {
466
+ Row: Number.parseInt(row, 10),
467
+ Column: columnLetterToNumber(column)
468
+ };
469
+ const expr = {
470
+ value: cell,
471
+ cells: [cell],
472
+ express: value,
473
+ tokens: [token]
474
+ };
475
+ return {
476
+ ok: true,
477
+ values: [row, column],
478
+ expr
479
+ };
480
+ }
481
+ // value input: A-AQ:13-15=<sum(#,[compile:Macro(exprArr,[F],[13,15],!codeKey)],compile:Marco(index),0)>
482
+ // output: {
483
+ // A:13 => sum(#,[ codeKey(F:13.value),codeKey(F:14.value),codeKey(F:15.value)],1,0),
484
+ // B:13 => sum(#,[ codeKey(F:13.value),codeKey(F:14.value),codeKey(F:15.value)],2,0),
485
+ // C:13 => sum(#,[ codeKey(F:13.value),codeKey(F:14.value),codeKey(F:15.value)],3,0),
486
+ // ....,
487
+ // A:14 => sum(#,[ codeKey(F:13.value),codeKey(F:14.value),codeKey(F:15.value)],1,0),
488
+ // B:14 => sum(#,[ codeKey(F:13.value),codeKey(F:14.value),codeKey(F:15.value)],2,0),
489
+ // C:14 => sum(#,[ codeKey(F:13.value),codeKey(F:14.value),codeKey(F:15.value)],3,0),
490
+ // }
491
+ static mergeCellParse(ctx, token, value) {
492
+ if (token !== "mergeCell" /* MergeCellToken */ && token !== "rowCell" /* RowCellToken */) {
493
+ return { ok: false };
494
+ }
495
+ const equalToken = _TokenParserManger.getTokenByCtx(ctx, "=" /* EqualToken */);
496
+ const index = value.indexOf(equalToken);
497
+ const offset = equalToken.length;
498
+ if (index <= 0) return { ok: false, error: new Error(`merge cell config syntax error: ${value}`) };
499
+ const rangeStr = value.substring(0, index).trim();
500
+ const exprStr = value.substring(index + offset);
501
+ const posParser = getTokenParser(":" /* PosToken */);
502
+ const posReply = posParser.handler(ctx, ":" /* PosToken */, rangeStr);
503
+ const functionToken = getTokenParser("<?>" /* FunctionPatternToken */);
504
+ if (!posReply.ok) return { ok: false, ...posReply };
505
+ const macroGenToken = _TokenParserManger.getTokenByCtx(ctx, "compile:GenCell" /* CompileGenToken */);
506
+ const expr = {
507
+ express: value,
508
+ value: exprStr,
509
+ // The template expression
510
+ posExpr: posReply.expr,
511
+ tokens: [token, ...posReply.expr.tokens]
512
+ };
513
+ if (exprStr.startsWith(macroGenToken)) {
514
+ const argsSplitToken = _TokenParserManger.getTokenByCtx(ctx, "," /* ArgPosToken */);
515
+ const args = _TokenParserManger.split(exprStr, argsSplitToken, [`(`, `)`]);
516
+ const macro = _TokenParserManger.filterMacro(args);
517
+ const aliasTokens = _TokenParserManger.extractUseAliasTokens(ctx, args);
518
+ if (aliasTokens !== void 0 && aliasTokens.length > 0) {
519
+ expr.tokens.push(...aliasTokens);
520
+ }
521
+ if (macro !== void 0 && macro.tokens.length > 0) {
522
+ expr.macro = macro;
523
+ expr.tokens.push(...macro.tokens);
524
+ }
525
+ } else {
526
+ const exprReply = functionToken.handler(ctx, "<?>" /* FunctionPatternToken */, exprStr);
527
+ if (exprReply.error !== void 0 && exprReply.error instanceof Error) {
528
+ return {
529
+ ok: false,
530
+ ...exprReply
531
+ };
532
+ }
533
+ if (exprReply.ok && exprReply.expr !== void 0) {
534
+ expr.funcExpr = exprReply.expr;
535
+ expr.tokens.push(...exprReply.expr.tokens);
536
+ }
537
+ }
538
+ return {
539
+ ok: true,
540
+ expr,
541
+ values: [rangeStr, exprStr]
542
+ };
543
+ }
544
+ // G-AQ:12=compile:GenCell(compile:Macro(expr,F,12),'.',compile:Marco(index))
545
+ static rowCellParse(ctx, token, value) {
546
+ if (token !== "rowCell" /* RowCellToken */) {
547
+ return { ok: false };
548
+ }
549
+ return _TokenParserManger.mergeCellParse(ctx, token, value);
550
+ }
551
+ // $functionName($arg0:string,$arg1:string[],$arg2:string|number,$arg3:string|number)
552
+ // eg: func(A,[xx1,xx2],xxx3), sum(#,[F,12,13],1,0)
553
+ // $functionName not in compile:Macro,compile:GenCell
554
+ // extract => {func:$functionName, arguments:[$arg0,$arg1,$arg2,$argN...]}
555
+ // output: {func:"sum",arguments:["A",["F","12","13"],"1","0"]}
556
+ static functionPatternParse(ctx, token, value) {
557
+ if (token !== "<?>" /* FunctionPatternToken */) {
558
+ return { ok: false };
559
+ }
560
+ const wordToken = _TokenParserManger.getTokenByCtx(ctx, "?" /* AnyToken */);
561
+ const funcToken = _TokenParserManger.getTokenByCtx(ctx, "<?>" /* FunctionPatternToken */);
562
+ const splitIndex = funcToken.indexOf(wordToken);
563
+ const splitOffset = wordToken.length;
564
+ const funcStartToken = funcToken.substring(0, splitIndex);
565
+ const funcEndToken = funcToken.substring(splitIndex + splitOffset);
566
+ const rparenToken = _TokenParserManger.getTokenByCtx(ctx, ")" /* RparenToken */);
567
+ const lparenToken = _TokenParserManger.getTokenByCtx(ctx, "(" /* LparenToken */);
568
+ const argsSplitToken = _TokenParserManger.getTokenByCtx(ctx, "," /* ArgPosToken */);
569
+ if (value.startsWith(funcStartToken) && value.endsWith(funcEndToken)) {
570
+ const content = value.substring(1, value.length - 1);
571
+ const lparen = content.indexOf(lparenToken);
572
+ const rparen = content.lastIndexOf(rparenToken);
573
+ if (lparen > 0 && rparen > lparen) {
574
+ const funcName = content.substring(0, lparen);
575
+ const argsStr = content.substring(lparen + lparenToken.length, rparen);
576
+ const args = _TokenParserManger.split(argsStr, argsSplitToken, [`[`, `]`]);
577
+ const macro = _TokenParserManger.filterMacro(args);
578
+ const tokens = [token];
579
+ const expr = {
580
+ express: value,
581
+ func: funcName,
582
+ value: args,
583
+ // arguments array
584
+ tokens
585
+ };
586
+ const alias = _TokenParserManger.extractUseAliasTokens(ctx, args);
587
+ if (alias !== void 0 && alias.length > 0) {
588
+ expr.tokens.push(...alias);
589
+ }
590
+ if (macro !== void 0 && macro.tokens.length > 0) {
591
+ expr.macro = macro;
592
+ expr.tokens.push(...macro.tokens);
593
+ }
594
+ return {
595
+ ok: true,
596
+ expr,
597
+ values: [funcName, args]
598
+ };
599
+ }
600
+ }
601
+ return {
602
+ ok: false,
603
+ error: new Error(`function express systax error`)
604
+ };
605
+ }
606
+ static varPatternParse(ctx, token, value) {
607
+ if (token !== "${?}" /* VarPatternToken */) {
608
+ return { ok: false };
609
+ }
610
+ const wordToken = _TokenParserManger.getTokenByCtx(ctx, "?" /* AnyToken */);
611
+ const varToken = _TokenParserManger.getTokenByCtx(ctx, "${?}" /* VarPatternToken */);
612
+ const index = varToken.indexOf(wordToken);
613
+ const workTokenOffset = wordToken.length;
614
+ const startToken = varToken.substring(0, index);
615
+ const endToken = varToken.substring(workTokenOffset + index);
616
+ if (!value.startsWith(startToken) || !value.endsWith(endToken)) {
617
+ return {
618
+ ok: false,
619
+ error: new Error(`variable expression syntax error,\${ or } flag is miss`)
620
+ };
621
+ }
622
+ const innerContent = value.substring(startToken.length, value.length - endToken.length);
623
+ if (innerContent === "") {
624
+ return {
625
+ ok: false,
626
+ error: new Error("variable expression syntax error, variable name is empty")
627
+ };
628
+ }
629
+ const expr = {
630
+ express: value,
631
+ value: innerContent,
632
+ tokens: [token]
633
+ };
634
+ const aliasToken = _TokenParserManger.getTokenByCtx(ctx, "@" /* UseAliasToken */);
635
+ if (innerContent.indexOf(aliasToken) >= 0) {
636
+ const parser = getTokenParser("@" /* UseAliasToken */);
637
+ const aliasReply = parser.handler(ctx, "@" /* UseAliasToken */, innerContent);
638
+ if (aliasReply.ok) {
639
+ expr.ref = aliasReply.expr.ref;
640
+ expr.alias = aliasReply.values;
641
+ expr.tokens.push(...aliasReply.expr.tokens);
642
+ }
643
+ }
644
+ return {
645
+ expr,
646
+ ok: true,
647
+ values: [innerContent]
648
+ };
649
+ }
650
+ // compile:GenCell(expr1,expr2,...,) => {G:13=>`${expr1}${expr2}..`,G:14=>`${expr1}${expr2}..`,G:15=>`${expr1}${expr2}..`,...}
651
+ // compile:Macro($exprType,$X,$Y,$formater)
652
+ // $exprType: enums [ expr:(single value), exprArr:(array value) ]
653
+ // $X: column index value, number|string or number[]|string[]
654
+ // $Y: row index value, number or number[]
655
+ // $formater: enums [ codeKey(a function for format string),number(a function for string to number) ]
656
+ // compile:Macro(exprArr,[X1,X2],[Y1,Y2],!codeKey) =>
657
+ // codeKey(X1:Y1.value),codeKey(X1:Y2.value),codeKey(X2:Y1.value),codeKey(X2:Y2.value)
658
+ // compile:Macro(exprArr,[X1],[Y1,Y2],!codeKey) => codeKey(X1:Y1.value),codeKey(X1:Y2.value)
659
+ // compile:Marco(index,!number) => number(i),number(i+1),number(i+2) ,i=1
660
+ static compileExprExtract(value) {
661
+ const results = [];
662
+ const lp = "(" /* LparenToken */.toString();
663
+ const args = "," /* ArgPosToken */.toString();
664
+ const values = value.split(lp);
665
+ for (const v of values) {
666
+ let items = [];
667
+ if (v.indexOf(args) >= 0) {
668
+ items = v.split(args);
669
+ } else {
670
+ items.push(v);
671
+ }
672
+ for (const it of items) {
673
+ if (it === "compile:Macro" /* CompileMacroToken */.toString() || it.startsWith("compile:Macro" /* CompileMacroToken */) || it.endsWith("compile:Macro" /* CompileMacroToken */)) {
674
+ results.push("compile:Macro" /* CompileMacroToken */);
675
+ } else if (it === "compile:GenCell" /* CompileGenToken */.toString() || it.startsWith("compile:GenCell" /* CompileGenToken */) || it.endsWith("compile:GenCell" /* CompileGenToken */)) {
676
+ results.push("compile:GenCell" /* CompileGenToken */);
677
+ }
678
+ }
679
+ }
680
+ return results;
681
+ }
682
+ static getTokenByCtx(ctx, token) {
683
+ if (ctx.size <= 0 || !ctx.has(token)) {
684
+ return token.toString();
685
+ }
686
+ const values = ctx.get(token);
687
+ if (values.length <= 0 || values[0].key === "") {
688
+ return token.toString();
689
+ }
690
+ return values[0].key;
691
+ }
692
+ static scanToken(value, startToken, endTokens) {
693
+ let token = "";
694
+ let data = "";
695
+ let end = false;
696
+ let start = false;
697
+ const items = [];
698
+ const offset = [startToken, ...endTokens].sort((a, b) => a.length - b.length)[0].length;
699
+ const size = value.length;
700
+ for (let i = 0; i < size; i += offset) {
701
+ let leftToken;
702
+ if (value[i] === startToken) {
703
+ start = true;
704
+ if (token !== "") {
705
+ items.push({
706
+ token,
707
+ value: ""
708
+ });
709
+ }
710
+ token = startToken;
711
+ } else {
712
+ start = token === startToken;
713
+ leftToken = `${token}${value[i]}`;
714
+ }
715
+ let subfix = endTokens.filter((s) => s === leftToken);
716
+ end = endTokens.includes(value[i]) || subfix.length > 0;
717
+ if (subfix.length > 0) {
718
+ token = leftToken;
719
+ data = "";
720
+ }
721
+ if (start && end) {
722
+ continue;
723
+ }
724
+ if (!end) {
725
+ token = `${token}${value[i]}`;
726
+ data = `${data}${value[i]}`;
727
+ }
728
+ if (end || i + offset >= size) {
729
+ if (data !== "") {
730
+ items.push({
731
+ token,
732
+ value: data
733
+ });
734
+ }
735
+ token = "";
736
+ data = "";
737
+ end = false;
738
+ }
739
+ }
740
+ return items;
741
+ }
742
+ static split(argsStr, argsSplitToken, ignoreTokenRange) {
743
+ let value = "";
744
+ let depth = 0;
745
+ const items = [];
746
+ const splitLen = argsSplitToken.length;
747
+ const startLen = ignoreTokenRange[0].length;
748
+ const endLen = ignoreTokenRange[1].length;
749
+ const startToken = ignoreTokenRange[0];
750
+ const endToken = ignoreTokenRange[1];
751
+ const isToggleMode = startToken === endToken;
752
+ for (let i = 0; i < argsStr.length; ) {
753
+ const substr = argsStr.substring(i);
754
+ if (depth > 0 && substr.startsWith(endToken)) {
755
+ value += endToken;
756
+ i += endLen;
757
+ depth = isToggleMode ? 0 : depth - 1;
758
+ continue;
759
+ }
760
+ if (substr.startsWith(startToken)) {
761
+ if (!isToggleMode || depth === 0) {
762
+ value += startToken;
763
+ i += startLen;
764
+ depth++;
765
+ continue;
766
+ }
767
+ }
768
+ if (depth === 0 && substr.startsWith(argsSplitToken)) {
769
+ items.push(value);
770
+ value = "";
771
+ i += splitLen;
772
+ continue;
773
+ }
774
+ value += argsStr[i];
775
+ i++;
776
+ }
777
+ if (value !== "") {
778
+ items.push(value);
779
+ }
780
+ return items;
781
+ }
782
+ static filterMacro(values) {
783
+ const filter = {
784
+ tokens: [],
785
+ express: []
786
+ };
787
+ for (const expr of values) {
788
+ let items = _TokenParserManger.compileExprExtract(expr);
789
+ if (items === void 0 || items.length <= 0) {
790
+ continue;
791
+ }
792
+ filter.express.push(expr);
793
+ filter.tokens.push(...items);
794
+ }
795
+ return filter.tokens.push() <= 0 ? void 0 : filter;
796
+ }
797
+ static extractUseAliasTokens(ctx, args) {
798
+ const tokens = [];
799
+ const useAliasToken = _TokenParserManger.getTokenByCtx(ctx, "@" /* UseAliasToken */);
800
+ args.forEach((v) => v.startsWith(useAliasToken) && tokens.push("@" /* UseAliasToken */));
801
+ return tokens;
802
+ }
803
+ static toList(ctx, endTokens) {
804
+ const items = [];
805
+ for (const token of endTokens) {
806
+ items.push(_TokenParserManger.getTokenByCtx(ctx, token));
807
+ }
808
+ return items;
809
+ }
810
+ static parseRangeValue(ctx, options) {
811
+ let rowReply;
812
+ let columnReply;
813
+ const rangeCell = {
814
+ stepRow: 1,
815
+ stepColumn: 1,
816
+ minColumn: 0,
817
+ minRow: 0,
818
+ maxRow: 0,
819
+ maxColumn: 0,
820
+ getCells: function() {
821
+ return _getCells(this);
822
+ }
823
+ };
824
+ const { rowRange, row, column, columnRange, express, token } = options;
825
+ const rangeParse = getTokenParser("-" /* RangeToken */);
826
+ if (rowRange > 0) {
827
+ columnReply = rangeParse.handler(ctx, "-" /* RangeToken */, row);
828
+ } else {
829
+ const rowValue = Number.parseInt(row, 10);
830
+ rangeCell.maxRow = rowValue;
831
+ rangeCell.minRow = rowValue;
832
+ }
833
+ if (columnRange > 0) {
834
+ rowReply = rangeParse.handler(ctx, "-" /* RangeToken */, column);
835
+ } else {
836
+ const columnValue = columnLetterToNumber(column);
837
+ rangeCell.maxColumn = columnValue;
838
+ rangeCell.minColumn = columnValue;
839
+ }
840
+ if (columnReply !== void 0) {
841
+ if (!columnReply.ok || columnReply.values === void 0) {
842
+ return columnReply;
843
+ }
844
+ const values = columnReply.values;
845
+ let min = values[0];
846
+ let max = values[1];
847
+ let setup = values[2] ?? 1;
848
+ rangeCell.minRow = min;
849
+ rangeCell.maxRow = max;
850
+ rangeCell.stepRow = setup;
851
+ }
852
+ if (rowReply !== void 0) {
853
+ if (!rowReply.ok || rowReply.values === void 0) {
854
+ return rowReply;
855
+ }
856
+ const values = rowReply.values;
857
+ let min = values[0];
858
+ let max = values[1];
859
+ let setup = values[2] ?? 1;
860
+ rangeCell.minColumn = min;
861
+ rangeCell.maxColumn = max;
862
+ rangeCell.stepColumn = setup;
863
+ }
864
+ const expr = {
865
+ express,
866
+ tokens: [token],
867
+ // express tokens
868
+ value: rangeCell
869
+ // alias value
870
+ };
871
+ return {
872
+ ok: true,
873
+ expr,
874
+ values: rangeCell
875
+ };
876
+ }
877
+ static parsePosNumber(value) {
878
+ let num = NaN;
879
+ if (isPureNumber.test(value)) {
880
+ num = Number.parseInt(value, 10);
881
+ } else if (isPureUppercase.test(value)) {
882
+ num = columnLetterToNumber(value);
883
+ }
884
+ return !isNaN(num) && num <= 0 ? NaN : num;
885
+ }
886
+ };
887
+ var defaultRuleTokenParserMap = /* @__PURE__ */ new Map([
888
+ ["alias" /* AliasToken */, TokenParserManger.aliasParse],
889
+ ["cell" /* CellToken */, TokenParserManger.cellParse],
890
+ ["=" /* EqualToken */, TokenParserManger.equalParse],
891
+ ["mergeCell" /* MergeCellToken */, TokenParserManger.mergeCellParse],
892
+ ["rowCell" /* RowCellToken */, TokenParserManger.rowCellParse],
893
+ ["@" /* UseAliasToken */, TokenParserManger.useAliasParse],
894
+ ["-" /* RangeToken */, TokenParserManger.rangeParse],
895
+ [":" /* PosToken */, TokenParserManger.posParse],
896
+ ["${?}" /* VarPatternToken */, TokenParserManger.varPatternParse],
897
+ ["<?>" /* FunctionPatternToken */, TokenParserManger.functionPatternParse]
898
+ ]);
899
+ var macroTokens = ["compile:GenCell" /* CompileGenToken */, "compile:Macro" /* CompileMacroToken */];
900
+ function columnLetterToNumber(letter) {
901
+ let num = 0;
902
+ for (let i = 0; i < letter.length; i++) {
903
+ num = num * 26 + (letter.charCodeAt(i) - 64);
904
+ }
905
+ return num;
906
+ }
907
+ function isBase64(str) {
908
+ if (str.length < 20) return false;
909
+ if (str.includes("\\") || str.includes(" ")) return false;
910
+ if (str.indexOf("./") >= 0 || str.startsWith("file://") || str.startsWith("/") || str.startsWith(".")) {
911
+ return false;
912
+ }
913
+ const data = str.replace(/^data:.*?;base64,/, "");
914
+ const cleanedStr = data.replace(/[\r\n]/g, "");
915
+ try {
916
+ return Buffer.from(cleanedStr, "base64").toString("utf-8") !== "";
917
+ } catch (e) {
918
+ return false;
919
+ }
920
+ }
921
+ function base64ToArrayBuffer(base64) {
922
+ const data = base64.replace(/^data:.*?;base64,/, "");
923
+ const binaryString = atob(data);
924
+ const bytes = new Uint8Array(binaryString.length);
925
+ for (let i = 0; i < binaryString.length; i++) {
926
+ bytes[i] = binaryString.charCodeAt(i);
927
+ }
928
+ return bytes.buffer;
929
+ }
930
+ var resolveCompileMacroGen = (ctx, expr, currentCellIndex) => {
931
+ let parts = [];
932
+ let join = ".";
933
+ const m = ctx.getContextMap();
934
+ const aliasToken = TokenParserManger.getTokenByCtx(m, "@" /* UseAliasToken */);
935
+ const genToken = TokenParserManger.getTokenByCtx(m, "compile:GenCell" /* CompileGenToken */);
936
+ const endTokens = ["compile:GenCell" /* CompileGenToken */, "(" /* LparenToken */, "," /* ArgPosToken */, ")" /* RparenToken */];
937
+ const values = TokenParserManger.scanToken(expr, genToken, TokenParserManger.toList(m, endTokens));
938
+ for (const [_, item] of values.entries()) {
939
+ if (item.value === void 0 && item.value !== "") {
940
+ continue;
941
+ }
942
+ if (!item.token.startsWith(aliasToken) && item.value !== exprIndex) {
943
+ parts.push(item.value);
944
+ } else {
945
+ parts.push(resolveAliasExpr(ctx, item.value, currentCellIndex));
946
+ }
947
+ }
948
+ return parts.join(join);
949
+ };
950
+ var getExprEnd = function(macroExpr, matchIndex, rparenToken) {
951
+ return macroExpr.indexOf(rparenToken, matchIndex);
952
+ };
953
+ var macroFormatters = [numberKey, codeKey, codeAliasKey];
954
+ var extractMacro = function(expr, options) {
955
+ let end = NaN;
956
+ const offset = options.startToken.length;
957
+ const startIndex = expr.indexOf(options.startToken);
958
+ const endIndex = expr.indexOf(options.endToken);
959
+ const argValues = expr.substring(startIndex + offset, endIndex);
960
+ const values = argValues.split(options.argToken);
961
+ const extracResult = { type: values[0], rowParam: [], columnParam: void 0 };
962
+ if (values.length > 1) {
963
+ extracResult.columnParam = columnLetterToNumber(values[1]);
964
+ }
965
+ if (macroFormatters.includes(values[values.length - 1])) {
966
+ end = values.length - 1;
967
+ extracResult.formatter = values[end];
968
+ }
969
+ if (!isNaN(end) && values.length > 2) {
970
+ extracResult.rowParam = values.slice(2, end).map((x) => Number.parseInt(x, 10));
971
+ } else if (values.length > 2) {
972
+ extracResult.rowParam = values.slice(2, values.length).map((x) => Number.parseInt(x, 10));
973
+ }
974
+ if (extracResult.rowParam !== void 0 && extracResult.rowParam instanceof Array && extracResult.rowParam.length === 1) {
975
+ extracResult.rowParam = extracResult.rowParam[0];
976
+ }
977
+ return extracResult;
978
+ };
979
+ var __codeKey = (str) => {
980
+ const replaces = [" ", `-`, `/`, `,`, `'`, `&`, `.`, `(`, `)`, `{`, `}`, `@`, `\\`, `[`, `]`, `#`, `:`];
981
+ for (const k of replaces) {
982
+ str = str.replaceAll(k, "_").trim();
983
+ if (str.indexOf("__") >= 0) {
984
+ str = str.replaceAll("__", "_");
985
+ }
986
+ }
987
+ if (str.startsWith("_")) {
988
+ str = str.substring(1);
989
+ }
990
+ if (str.endsWith("_")) {
991
+ str = str.substring(0, str.length - 1);
992
+ }
993
+ return str.toUpperCase();
994
+ };
995
+ var __numberKey = (str) => {
996
+ return Number.parseInt(str, 10).toString();
997
+ };
998
+ var __codeAliasKey = (str) => {
999
+ const key = __codeKey(str);
1000
+ if (key !== "") {
1001
+ return `${defaultRuleTokenMap.get("@" /* UseAliasToken */)}${key}`;
1002
+ }
1003
+ return "";
1004
+ };
1005
+ var macroFormatter = /* @__PURE__ */ new Map([
1006
+ [codeKey, __codeKey],
1007
+ [numberKey, __numberKey],
1008
+ [codeAliasKey, __codeAliasKey],
1009
+ [defaultKey, (v) => v]
1010
+ ]);
1011
+ var execMacroFormat = function(value, formatter) {
1012
+ if (!macroFormatter.has(formatter)) {
1013
+ return value;
1014
+ }
1015
+ return macroFormatter.get(formatter)(value);
1016
+ };
1017
+ var toCellRow = (rowVals, setup) => {
1018
+ if (setup === void 0) {
1019
+ setup = 1;
1020
+ }
1021
+ if (rowVals.length == 2) {
1022
+ const values = [];
1023
+ for (let start = rowVals[0]; start <= rowVals[1]; start += setup) {
1024
+ values.push(start);
1025
+ }
1026
+ return values;
1027
+ }
1028
+ return rowVals;
1029
+ };
1030
+ var toCellColumn = (columnVals, setup) => {
1031
+ return toCellRow(columnVals, setup);
1032
+ };
1033
+ var toCellValue = (value) => {
1034
+ if (typeof value !== "string") {
1035
+ const rText = value;
1036
+ if (rText !== void 0 && rText.richText !== void 0 && rText.richText.length > 0) {
1037
+ const values = [];
1038
+ for (const [_, v] of rText.richText.entries()) {
1039
+ if (v === void 0 || v === null) {
1040
+ continue;
1041
+ }
1042
+ const text = v.text !== void 0 && v.text !== null ? v.text : void 0;
1043
+ if (text !== void 0 && text !== "" && text !== "[object]") {
1044
+ values.push(text.trim());
1045
+ }
1046
+ }
1047
+ return values.join(" ");
1048
+ }
1049
+ const hText = value;
1050
+ if (hText !== void 0 && hText.text !== null && hText.hyperlink !== null) {
1051
+ return `[${hText.text}](${hText.hyperlink})`;
1052
+ }
1053
+ }
1054
+ return value.toString();
1055
+ };
1056
+ var resolveCompileMacroExpr = (ctx, macroExpr, macroTokens2, currentCellIndex, totalCells) => {
1057
+ if (macroTokens2 === void 0 || macroTokens2.length <= 0) {
1058
+ return macroExpr;
1059
+ }
1060
+ const sheet = ctx.sheet;
1061
+ if (sheet === void 0) {
1062
+ throw new Error(`miss context worksheet`);
1063
+ }
1064
+ const m = ctx.getContextMap();
1065
+ const argToken = TokenParserManger.getTokenByCtx(m, "," /* ArgPosToken */);
1066
+ const rparenToken = TokenParserManger.getTokenByCtx(m, ")" /* RparenToken */);
1067
+ const lparenToken = TokenParserManger.getTokenByCtx(m, "(" /* LparenToken */);
1068
+ const genToken = TokenParserManger.getTokenByCtx(m, "compile:GenCell" /* CompileGenToken */);
1069
+ const maroToken = TokenParserManger.getTokenByCtx(m, "compile:Macro" /* CompileMacroToken */);
1070
+ const tokenMap = /* @__PURE__ */ new Map();
1071
+ for (const [index, token] of macroTokens2.entries()) {
1072
+ let items = [];
1073
+ if (tokenMap.has(token)) {
1074
+ items = tokenMap.get(token);
1075
+ }
1076
+ items.push(index);
1077
+ tokenMap.set(token, items);
1078
+ }
1079
+ const resolveArray = (param) => {
1080
+ if (param instanceof Array) {
1081
+ return param;
1082
+ }
1083
+ return [param];
1084
+ };
1085
+ if (tokenMap.has("compile:Macro" /* CompileMacroToken */)) {
1086
+ let offset = 0;
1087
+ let exprValue = macroExpr;
1088
+ const times = tokenMap.get("compile:Macro" /* CompileMacroToken */).length;
1089
+ for (let i = times; i > 0; i--) {
1090
+ const matchIndex = exprValue.indexOf(maroToken, offset);
1091
+ if (matchIndex < 0) {
1092
+ break;
1093
+ }
1094
+ offset = getExprEnd(exprValue, matchIndex, rparenToken);
1095
+ const macroCurrent = exprValue.substring(matchIndex, offset + rparenToken.length);
1096
+ const opts = { startToken: lparenToken, endToken: rparenToken, argToken };
1097
+ let { type, columnParam, rowParam, formatter } = extractMacro(macroCurrent, opts);
1098
+ let rowVals;
1099
+ let columnVals;
1100
+ const parts = [];
1101
+ if (columnParam !== void 0 && rowParam !== void 0) {
1102
+ rowVals = resolveArray(rowParam);
1103
+ columnVals = resolveArray(columnParam);
1104
+ const rowItems = toCellRow(rowVals);
1105
+ const columnItems = toCellColumn(columnVals);
1106
+ rowItems.forEach((r) => {
1107
+ columnItems.forEach((c) => {
1108
+ const cellValue = sheet.findCell(r, c);
1109
+ if (cellValue === void 0 || cellValue.value === null) {
1110
+ return;
1111
+ }
1112
+ const value = toCellValue(cellValue.value);
1113
+ let exprValue2 = execMacroFormat(value, formatter);
1114
+ parts.push(exprValue2);
1115
+ });
1116
+ });
1117
+ }
1118
+ if (type === exprArr) {
1119
+ macroExpr = macroExpr.replace(macroCurrent, parts.join(","));
1120
+ } else if (type === exprSingle) {
1121
+ macroExpr = macroExpr.replace(macroCurrent, parts[0]);
1122
+ } else if (type === exprIndex) {
1123
+ const indexValue = currentCellIndex + 1;
1124
+ macroExpr = macroExpr.replace(macroCurrent, indexValue.toString());
1125
+ }
1126
+ }
1127
+ }
1128
+ if (tokenMap.has("compile:GenCell" /* CompileGenToken */)) {
1129
+ let exprValue = macroExpr;
1130
+ const times = tokenMap.get("compile:GenCell" /* CompileGenToken */).length;
1131
+ for (let i = times; i > 0; i--) {
1132
+ const matchIndex = exprValue.indexOf(genToken);
1133
+ if (matchIndex < 0) {
1134
+ break;
1135
+ }
1136
+ const offset = getExprEnd(exprValue, matchIndex, rparenToken);
1137
+ const macroCurrent = exprValue.substring(matchIndex, offset + rparenToken.length);
1138
+ exprValue = resolveCompileMacroGen(ctx, macroCurrent, currentCellIndex);
1139
+ }
1140
+ macroExpr = exprValue;
1141
+ }
1142
+ return macroExpr;
1143
+ };
1144
+ var loadWorkbook = async function(data) {
1145
+ const w = new import_exceljs.default.Workbook();
1146
+ if (typeof data === "string") {
1147
+ if (!isBase64(data)) {
1148
+ await w.xlsx.readFile(data);
1149
+ } else {
1150
+ await w.xlsx.load(base64ToArrayBuffer(data));
1151
+ }
1152
+ } else if (data instanceof import_stream.Stream) {
1153
+ await w.xlsx.read(data);
1154
+ } else if (data instanceof ArrayBuffer) {
1155
+ await w.xlsx.load(data);
1156
+ } else if (data instanceof Buffer) {
1157
+ await w.xlsx.load(data);
1158
+ } else {
1159
+ throw new Error(`unSupport buffer type ${typeof data}`);
1160
+ }
1161
+ return w;
1162
+ };
1163
+ var compileCellTokens = ["cell" /* CellToken */, "mergeCell" /* MergeCellToken */, "rowCell" /* RowCellToken */];
1164
+ var ruleTokens = ["alias" /* AliasToken */, "cell" /* CellToken */, "mergeCell" /* MergeCellToken */, "rowCell" /* RowCellToken */];
1165
+ var isRuleToken = function(t) {
1166
+ return ruleTokens.includes(t);
1167
+ };
1168
+ var mergeOption = function(ruleKeyMap, defaultRuleTokenMap2) {
1169
+ for (const [key, value] of defaultRuleTokenMap2.entries()) {
1170
+ if (!ruleKeyMap.has(key)) {
1171
+ ruleKeyMap.set(key, value);
1172
+ }
1173
+ }
1174
+ return ruleKeyMap;
1175
+ };
1176
+ var getTokenParser = function(token) {
1177
+ if (!defaultRuleTokenParserMap.has(token)) {
1178
+ return {
1179
+ exists: false
1180
+ };
1181
+ }
1182
+ return {
1183
+ exists: true,
1184
+ handler: defaultRuleTokenParserMap.get(token)
1185
+ };
1186
+ };
1187
+ var scanWorkSheetRules = function(worksheet, options) {
1188
+ const result = { rules: options.getContextMap() };
1189
+ for (let r = options.startLine; r <= options.endLine; r++) {
1190
+ let emptyValue = false;
1191
+ let ruleToken = "" /* UndefinedToken */;
1192
+ for (let c = options.startColumn; c <= options.endColumn; c++) {
1193
+ const cell = worksheet.findCell(r, c);
1194
+ if (cell === void 0 || cell.value === void 0 || cell.value === null) {
1195
+ continue;
1196
+ }
1197
+ const cellValue = cell.value;
1198
+ const value = cellValue.toString();
1199
+ let isStartCell = c === options.startColumn;
1200
+ if (emptyValue && ruleToken === "" /* UndefinedToken */) {
1201
+ isStartCell = true;
1202
+ }
1203
+ if (value === "" && isStartCell) {
1204
+ emptyValue = true;
1205
+ continue;
1206
+ }
1207
+ if (isStartCell) {
1208
+ ruleToken = options.parseToken(value);
1209
+ continue;
1210
+ } else {
1211
+ if (!isRuleToken(ruleToken)) {
1212
+ break;
1213
+ }
1214
+ emptyValue = false;
1215
+ }
1216
+ const { handler, exists } = getTokenParser(ruleToken);
1217
+ if (!exists) {
1218
+ continue;
1219
+ }
1220
+ let values = [];
1221
+ if (result.rules.has(ruleToken)) {
1222
+ values = result.rules.get(ruleToken);
1223
+ }
1224
+ const { expr, ok } = handler(result.rules, ruleToken, value);
1225
+ if (ok && expr !== void 0) {
1226
+ values.push(expr);
1227
+ }
1228
+ result.rules.set(ruleToken, values);
1229
+ }
1230
+ }
1231
+ return result;
1232
+ };
1233
+ var parseWorkSheetRules = function(worksheet, options) {
1234
+ const result = { rules: /* @__PURE__ */ new Map() };
1235
+ if (worksheet === void 0 || worksheet === null) {
1236
+ return result;
1237
+ }
1238
+ if (options === void 0) {
1239
+ options = new RuleMapOptions();
1240
+ }
1241
+ return scanWorkSheetRules(worksheet, options.parseDefault(worksheet));
1242
+ };
1243
+ var compileCheck = function(iv, ctx) {
1244
+ if (iv.rules.size <= 0) {
1245
+ return void 0;
1246
+ }
1247
+ const errs = [];
1248
+ const values = iv.rules.get("alias" /* AliasToken */);
1249
+ if (values !== void 0 && values.length > 0) {
1250
+ const set = /* @__PURE__ */ new Set();
1251
+ for (const [idx, value] of values.entries()) {
1252
+ if (idx === 0) {
1253
+ set.add(value.key);
1254
+ continue;
1255
+ }
1256
+ if (set.has(value.key)) {
1257
+ errs.push(Error(`Duplicate alias(${value.key},${value.express}) configuration`));
1258
+ }
1259
+ }
1260
+ }
1261
+ const handlers = ctx.getCompileCheckHandlers();
1262
+ if (handlers !== void 0 && handlers.length > 0) {
1263
+ for (const h of handlers) {
1264
+ let err = h(iv, ctx);
1265
+ if (err !== void 0 && err.length > 0) {
1266
+ errs.push(...err);
1267
+ }
1268
+ }
1269
+ }
1270
+ if (errs.length > 0) {
1271
+ return errs;
1272
+ }
1273
+ return void 0;
1274
+ };
1275
+ var getMacroTokens = function(expr) {
1276
+ const tokens = [];
1277
+ for (const token of expr.tokens) {
1278
+ if (macroTokens.includes(token)) {
1279
+ tokens.push(token);
1280
+ }
1281
+ }
1282
+ return tokens;
1283
+ };
1284
+ var toRowCells = function(cells) {
1285
+ const indexes = [];
1286
+ const rows = [];
1287
+ const rowMap = /* @__PURE__ */ new Map();
1288
+ for (const cell of cells) {
1289
+ let cells2 = [];
1290
+ if (rowMap.has(cell.Row)) {
1291
+ cells2 = rowMap.get(cell.Row);
1292
+ } else {
1293
+ indexes.push(cell.Row);
1294
+ }
1295
+ cells2.push(cell);
1296
+ rowMap.set(cell.Row, cells2);
1297
+ }
1298
+ indexes.sort((a, b) => a - b);
1299
+ for (const row of indexes) {
1300
+ const values = rowMap.get(row);
1301
+ rows.push(values);
1302
+ }
1303
+ return rows;
1304
+ };
1305
+ var resolveFunctionExpr = (ctx, templateValue, expr) => {
1306
+ const anyToken = defaultRuleTokenMap.get("?" /* AnyToken */);
1307
+ const funToken = defaultRuleTokenMap.get("<?>" /* FunctionPatternToken */);
1308
+ const functionTokens = expr.tokens.filter((s) => s === "<?>" /* FunctionPatternToken */);
1309
+ if (functionTokens === void 0 || functionTokens.length <= 0) {
1310
+ return templateValue;
1311
+ }
1312
+ const [start, end] = funToken.split(anyToken);
1313
+ for (let times = functionTokens.length; times > 0; times--) {
1314
+ const index = templateValue.indexOf(start);
1315
+ const offset = templateValue.indexOf(end);
1316
+ if (offset > 0 && index >= 0) {
1317
+ templateValue = templateValue.replace(start, funcCommand).replace(end, "");
1318
+ }
1319
+ }
1320
+ return templateValue;
1321
+ };
1322
+ var searchIndexOf = (str, substr, position) => {
1323
+ let index = NaN;
1324
+ for (let sub of substr) {
1325
+ if (position === void 0 || position === null) {
1326
+ index = str.indexOf(sub);
1327
+ } else {
1328
+ index = str.indexOf(sub, position);
1329
+ }
1330
+ if (!isNaN(index) && index >= 0) {
1331
+ return index;
1332
+ }
1333
+ }
1334
+ return -1;
1335
+ };
1336
+ var resolveAliasExpr = (ctx, templateValue, index) => {
1337
+ const expr = ctx.currentExpr;
1338
+ if (expr === void 0) {
1339
+ throw new Error(`miss context expr value`);
1340
+ }
1341
+ let compileValue = templateValue;
1342
+ const aliasToken = defaultRuleTokenMap.get("@" /* UseAliasToken */);
1343
+ let aliasTokens = expr.tokens.filter((s) => s === "@" /* UseAliasToken */);
1344
+ if (aliasTokens.length <= 0) {
1345
+ const num = templateValue.split(aliasToken).length - 1;
1346
+ if (num > 0) {
1347
+ aliasTokens = new Array(num).fill(aliasToken);
1348
+ }
1349
+ }
1350
+ if (aliasTokens !== void 0 && aliasTokens.length > 0) {
1351
+ for (let i = 0; i < aliasTokens.length; ++i) {
1352
+ const token = aliasToken;
1353
+ const start = compileValue.indexOf(token);
1354
+ if (start < 0) {
1355
+ break;
1356
+ }
1357
+ const offset = aliasTokens[i].length;
1358
+ let end = searchIndexOf(compileValue, [",", ".", ")", "]"], start);
1359
+ if (end < 0) {
1360
+ end = compileValue.length;
1361
+ }
1362
+ const sv = compileValue.substring(start + offset, end);
1363
+ const pl = `${token}${sv}`;
1364
+ const value = ctx.getAlias(sv);
1365
+ if (value !== void 0) {
1366
+ if (compileValue === pl) {
1367
+ compileValue = value;
1368
+ } else {
1369
+ compileValue = compileValue.replace(`${pl}`, value);
1370
+ }
1371
+ }
1372
+ }
1373
+ }
1374
+ return compileValue;
1375
+ };
1376
+ var resolveValueExpr = (ctx, templateValue) => {
1377
+ const expr = ctx.currentExpr;
1378
+ if (expr === void 0 || expr.tokens.length <= 0) {
1379
+ return templateValue;
1380
+ }
1381
+ const m = ctx.getContextMap();
1382
+ const token = TokenParserManger.getTokenByCtx(m, "${?}" /* VarPatternToken */);
1383
+ const anyToken = TokenParserManger.getTokenByCtx(m, "?" /* AnyToken */);
1384
+ const [start, end] = token.split(anyToken);
1385
+ if (!templateValue.startsWith(start)) {
1386
+ templateValue = `${start}${templateValue}`;
1387
+ }
1388
+ if (!templateValue.endsWith(end)) {
1389
+ templateValue = `${templateValue}${end}`;
1390
+ }
1391
+ return templateValue;
1392
+ };
1393
+ var compileRowCells = function(ctx, expr, cellPoints, rowIndex, errs) {
1394
+ if (ctx.sheet === void 0) {
1395
+ errs.push(new Error(`ctx miss worksheet`));
1396
+ return;
1397
+ }
1398
+ ctx.currentExpr = expr;
1399
+ try {
1400
+ cellPoints.forEach((cellPoint, index) => {
1401
+ const r = cellPoint.Row;
1402
+ const sheet = ctx.sheet;
1403
+ const c = cellPoint.Column;
1404
+ const cell = sheet.findCell(r, c);
1405
+ if (cell === void 0 || cell.value !== void 0 && cell.value !== null && cell.value !== "") {
1406
+ return;
1407
+ }
1408
+ let templateValue = String(expr.value);
1409
+ const macroTokens2 = getMacroTokens(expr);
1410
+ templateValue = resolveFunctionExpr(ctx, templateValue, expr);
1411
+ templateValue = resolveCompileMacroExpr(ctx, templateValue, macroTokens2, index, cellPoints.length);
1412
+ templateValue = resolveAliasExpr(ctx, templateValue, index);
1413
+ cell.value = resolveValueExpr(ctx, templateValue);
1414
+ });
1415
+ } catch (err) {
1416
+ const msg = err.message;
1417
+ throw new Error(`expr:${expr.express}, resolve error: ${msg}`);
1418
+ }
1419
+ };
1420
+ var generateWorkSheetCellsPlaceholder = function(ctx, expr, sheet) {
1421
+ const errs = [];
1422
+ const posExpr = expr.posExpr;
1423
+ let cellsItems = expr.cells;
1424
+ if ((cellsItems === void 0 || cellsItems.length <= 0) && posExpr !== void 0 && posExpr.value !== void 0) {
1425
+ const r = posExpr.value;
1426
+ if (r !== void 0) {
1427
+ cellsItems = r.getCells();
1428
+ }
1429
+ }
1430
+ if (!cellsItems || cellsItems.length === 0) {
1431
+ return void 0;
1432
+ }
1433
+ ctx.sheet = sheet;
1434
+ const cells = cellsItems;
1435
+ toRowCells(cells).forEach((cellPoints, index) => compileRowCells(ctx, expr, cellPoints, index, errs));
1436
+ return errs.length > 0 ? errs : void 0;
1437
+ };
1438
+ var hasGeneratorToken = function(tokens) {
1439
+ for (const t of tokens) {
1440
+ if (compileCellTokens.includes(t)) {
1441
+ return true;
1442
+ }
1443
+ }
1444
+ return false;
1445
+ };
1446
+ var compileWorkSheetPlaceholder = function(ctx, sheet, result) {
1447
+ if (ctx.compileSheets !== void 0 && ctx.compileSheets.length > 0 && !ctx.compileSheets.includes(sheet.name)) {
1448
+ return void 0;
1449
+ }
1450
+ const errs = [];
1451
+ for (const [token, express] of result.rules.entries()) {
1452
+ if (!isRuleToken(token)) {
1453
+ continue;
1454
+ }
1455
+ for (const expr of express) {
1456
+ if (expr.tokens.length <= 0 || !hasGeneratorToken(expr.tokens)) {
1457
+ continue;
1458
+ }
1459
+ let err = generateWorkSheetCellsPlaceholder(ctx, expr, sheet);
1460
+ if (err !== void 0 && err.length > 0) {
1461
+ errs.push(...err);
1462
+ }
1463
+ }
1464
+ }
1465
+ if (errs.length > 0) {
1466
+ return errs;
1467
+ }
1468
+ return void 0;
1469
+ };
1470
+ var loadCompileSheets = (workbook, ruleSheetName) => {
1471
+ let first;
1472
+ let sheets = [];
1473
+ for (const [_, w] of workbook.worksheets.entries()) {
1474
+ if (w.name === ruleSheetName) {
1475
+ continue;
1476
+ }
1477
+ if (first === "") {
1478
+ first = w.name;
1479
+ }
1480
+ if (!w.name.endsWith(".json") && !w.name.endsWith(".config")) {
1481
+ sheets.push(w.name);
1482
+ }
1483
+ }
1484
+ if (sheets.length <= 0 && first !== "") {
1485
+ sheets.push(first);
1486
+ }
1487
+ return sheets;
1488
+ };
1489
+ var compile = async function(data, ruleSheetName, options) {
1490
+ const workbook = await loadWorkbook(data);
1491
+ const sheet = workbook.getWorksheet(ruleSheetName);
1492
+ if (sheet === void 0) {
1493
+ return {
1494
+ workbook
1495
+ };
1496
+ }
1497
+ if (workbook.worksheets === void 0) {
1498
+ return {
1499
+ workbook,
1500
+ errs: [new Error(`worksheet, ${ruleSheetName} not exists!`)]
1501
+ };
1502
+ }
1503
+ if (options === void 0) {
1504
+ const excludes = [ruleSheetName];
1505
+ options = RuleMapOptions.withAllSheets(workbook, excludes);
1506
+ }
1507
+ options = options.parseDefault(sheet);
1508
+ if (options.compileSheets === void 0 || options.compileSheets.length === 0) {
1509
+ options.compileSheets = loadCompileSheets(workbook, ruleSheetName);
1510
+ }
1511
+ const result = parseWorkSheetRules(sheet, options);
1512
+ const errs = compileCheck(result, options);
1513
+ if (errs !== void 0) {
1514
+ return {
1515
+ errs,
1516
+ workbook,
1517
+ configure: result
1518
+ };
1519
+ }
1520
+ const compileErrs = [];
1521
+ const ctx = CompileContext.create(options).loadAlias(result.rules);
1522
+ for (const [i, w] of workbook.worksheets.entries()) {
1523
+ if (w.name === ruleSheetName || i === ruleSheetName || !ctx.filterSheet(w.name)) {
1524
+ continue;
1525
+ }
1526
+ let err = compileWorkSheetPlaceholder(ctx, w, result);
1527
+ if (err !== void 0 && err.length > 0) {
1528
+ compileErrs.push(...err);
1529
+ }
1530
+ }
1531
+ if (compileErrs.length > 0) {
1532
+ return {
1533
+ workbook,
1534
+ configure: result,
1535
+ errs: compileErrs
1536
+ };
1537
+ }
1538
+ return {
1539
+ workbook,
1540
+ configure: result
1541
+ };
1542
+ };
1543
+ var fetchAlias = (m) => {
1544
+ let sv;
1545
+ const alias = /* @__PURE__ */ new Map();
1546
+ if (m !== void 0 && m !== null && !(m instanceof Map) && m?.rules !== void 0) {
1547
+ sv = m.rules;
1548
+ } else if (m instanceof Map) {
1549
+ if (m.size <= 0 || !m.has("alias" /* AliasToken */)) {
1550
+ return alias;
1551
+ }
1552
+ sv = m;
1553
+ } else {
1554
+ return alias;
1555
+ }
1556
+ const values = sv.get("alias" /* AliasToken */);
1557
+ for (const vs of values) {
1558
+ if (typeof vs.value === "string") {
1559
+ alias.set(vs.key, vs.value);
1560
+ }
1561
+ }
1562
+ return alias;
1563
+ };
1564
+ var removeUnExportSheets = (w, options) => {
1565
+ const removes = [];
1566
+ if (typeof options.skipRemoveUnExportSheet === "boolean" && options.skipRemoveUnExportSheet === true) {
1567
+ return w;
1568
+ }
1569
+ if (options.compileSheets === void 0 || options.compileSheets.length <= 0) {
1570
+ for (const [i, v] of w.worksheets.entries()) {
1571
+ const sheetName = v.name;
1572
+ if (sheetName.endsWith(".config") || sheetName.endsWith(".json")) {
1573
+ removes.push(sheetName);
1574
+ }
1575
+ }
1576
+ } else {
1577
+ for (const [i, v] of w.worksheets.entries()) {
1578
+ if (!options.compileSheets.includes(v.name)) {
1579
+ removes.push(v.name);
1580
+ }
1581
+ }
1582
+ }
1583
+ for (const [_, name] of removes.entries()) {
1584
+ w.removeWorksheet(name);
1585
+ }
1586
+ return w;
1587
+ };
1588
+ var toBuffer = async (w) => {
1589
+ const arrayBuffer = await w.xlsx.writeBuffer();
1590
+ return Buffer.from(arrayBuffer);
1591
+ };
1592
+ var ExprResolver = class {
1593
+ };
1594
+ ExprResolver.toBuffer = toBuffer;
1595
+ ExprResolver.compile = compile;
1596
+ ExprResolver.toRowCells = toRowCells;
1597
+ ExprResolver.fetchAlias = fetchAlias;
1598
+ ExprResolver.getExprEnd = getExprEnd;
1599
+ ExprResolver.compileCheck = compileCheck;
1600
+ ExprResolver.extractMacro = extractMacro;
1601
+ ExprResolver.compileRowCells = compileRowCells;
1602
+ ExprResolver.searchIndexOf = searchIndexOf;
1603
+ ExprResolver.resolveAliasExpr = resolveAliasExpr;
1604
+ ExprResolver.resolveValueExpr = resolveValueExpr;
1605
+ ExprResolver.resolveFunctionExpr = resolveFunctionExpr;
1606
+ ExprResolver.removeUnExportSheets = removeUnExportSheets;
1607
+ ExprResolver.resolveCompileMacroGen = resolveCompileMacroGen;
1608
+ ExprResolver.resolveCompileMacroExpr = resolveCompileMacroExpr;
1609
+
1610
+ // src/extends.ts
1611
+ var import_promises = __toESM(require("fs/promises"));
1612
+
1613
+ // src/bin.ts
1614
+ var program = new import_commander.Command();
1615
+ program.name("xlsx-cli").version("1.0.0");
1616
+ program.command("compile").argument("<string>", "xlsx file path").option("-s,--save <string>", "save compiled xlsx file to user dir").option("-r,--remove", "remove configure rules sheet", false).action((cmd, xlsxFile, options) => {
1617
+ const resolver = ExprResolver;
1618
+ console.log(import_chalk.default.green("xlsxFile %s"), xlsxFile);
1619
+ console.log(import_chalk.default.red("options %s"), options);
1620
+ });
1621
+ program.command("render").argument("<string>", "xlsx file path").option("-c,--compile", "auto compile flag", false).option("-s,--save <string>", "save render xlsx file to user dir").action((cmd, xlsxFile, options) => {
1622
+ console.log(import_chalk.default.green("xlsxFile %s"), xlsxFile);
1623
+ console.log(import_chalk.default.red("options %s"), options);
1624
+ });
1625
+ program.parse(process.argv);
1626
+ //# sourceMappingURL=bin.js.map