sfmc-sql-converter 0.0.0-stage → 0.1.0

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,1412 @@
1
+ /**
2
+ * Reads Engagement SSJS data extension lookups back into the SQL AST of `parseSql`:
3
+ * WSProxy `retrieve("DataExtensionObject[Key]", …)`, `DataExtension.Init(…).Rows.Retrieve(…)`,
4
+ * `Platform.Function.LookupRows(…)` / `LookupOrderedRows(…)` and bare filter objects.
5
+ *
6
+ * The code is read as text with a small literal parser; it is never executed. Never throws.
7
+ */
8
+
9
+ import { likeFilterValue } from './clauses.js';
10
+ import { SYNTAX_ERROR } from './messages.js';
11
+ import {
12
+ ARGUMENT_COUNT,
13
+ FROM_NAME_FROM_KEY,
14
+ FROM_UNKNOWN,
15
+ INVALID_ARGUMENT,
16
+ INVALID_COUNT,
17
+ INVALID_FILTER,
18
+ INVALID_FILTER_VALUE,
19
+ INVALID_LOGICAL_OPERATOR,
20
+ INVALID_OBJECT_TYPE,
21
+ LIKE_MATCHES_ANYWHERE,
22
+ MULTIPLE_LOOKUPS,
23
+ NO_LOOKUP_FOUND,
24
+ UNKNOWN_FILTER_OPERATOR,
25
+ UNSUPPORTED_EXPRESSION,
26
+ UNSUPPORTED_FILTER_OPERATOR,
27
+ VARIABLE_VALUE,
28
+ } from './messages.js';
29
+ import {
30
+ andChain,
31
+ createContext,
32
+ expressionEnd,
33
+ fail,
34
+ failUnclosedCall,
35
+ findScriptRegions,
36
+ isIdent,
37
+ isPunct,
38
+ makeLoc,
39
+ makeValue,
40
+ parseOrderString,
41
+ readHeader,
42
+ rejectEmpty,
43
+ report,
44
+ runParser,
45
+ tokenAt,
46
+ tokenize,
47
+ } from './reverse-common.js';
48
+
49
+ /**
50
+ * @typedef {object} Literal
51
+ * @property {'object'|'array'|'string'|'number'|'boolean'|'null'|'ref'} kind literal kind
52
+ * @property {number} start 0-based start offset
53
+ * @property {number} end 0-based exclusive end offset
54
+ * @property {string} [value] string value, number text, boolean text or variable name
55
+ * @property {{key: string, value: Literal}[]} [entries] object entries
56
+ * @property {Literal[]} [items] array items
57
+ */
58
+
59
+ /**
60
+ * @typedef {object} VariableEntry
61
+ * @property {number} start offset of the assignment
62
+ * @property {'literal'|'deInit'|'other'} kind what the variable is set to
63
+ * @property {Literal} [node] the literal (kind literal) or the Init argument (kind deInit)
64
+ */
65
+
66
+ const COMPARE_OPERATORS = new Map(
67
+ Object.entries({
68
+ equals: '=',
69
+ notequals: '<>',
70
+ greaterthan: '>',
71
+ greaterthanorequal: '>=',
72
+ lessthan: '<',
73
+ lessthanorequal: '<=',
74
+ }),
75
+ );
76
+
77
+ const REJECTED_OPERATORS = new Map(
78
+ Object.entries({
79
+ existsinstring: "use like with '%value%'",
80
+ existsinstringasaword: "use like with '%value%'",
81
+ notexistsinstring: 'filter the rows in your code',
82
+ beginswith: "use like with 'value%'",
83
+ endswith: "use like with '%value'",
84
+ contains: "use like with '%value%'",
85
+ notcontains: 'filter the rows in your code',
86
+ isanniversary: 'filter the rows in your code',
87
+ isnotanniversary: 'filter the rows in your code',
88
+ greaterthananniversary: 'filter the rows in your code',
89
+ lessthananniversary: 'filter the rows in your code',
90
+ }),
91
+ );
92
+
93
+ const LOGICAL_KEYS = ['leftoperand', 'logicaloperator', 'rightoperand'];
94
+ const VALUE_END = new Set([',', ')', ']', '}', ';', ':']);
95
+ const MAX_VARIABLE_DEPTH = 32;
96
+
97
+ // ------------------------------------------------------------------------------------------
98
+ // Literal parser
99
+ // ------------------------------------------------------------------------------------------
100
+
101
+ /**
102
+ * Fails with UNSUPPORTED_EXPRESSION for the expression starting at a token index.
103
+ *
104
+ * @param {object} context parse context
105
+ * @param {number} index token index of the expression start
106
+ * @param {string} detail what kind of expression it is
107
+ * @returns {never} always throws ParseStop
108
+ */
109
+ function failExpression(context, index, detail) {
110
+ const start = tokenAt(context, index).start;
111
+ fail(
112
+ context,
113
+ UNSUPPORTED_EXPRESSION,
114
+ `${detail} can't be converted. Only fixed values (text in quotes, numbers, arrays and filter objects) and variables set to them can be read; replace it with the value itself.`,
115
+ start,
116
+ Math.max(expressionEnd(context, index), start + 1),
117
+ );
118
+ }
119
+
120
+ /**
121
+ * Parses an object literal starting at "{".
122
+ *
123
+ * @param {object} context parse context
124
+ * @returns {Literal} object literal
125
+ */
126
+ function parseObject(context) {
127
+ const open = tokenAt(context, context.pos++);
128
+ const entries = [];
129
+ for (;;) {
130
+ const token = tokenAt(context, context.pos);
131
+ if (isPunct(token, '}')) {
132
+ context.pos++;
133
+ return { kind: 'object', entries, start: open.start, end: token.end };
134
+ }
135
+ if (token.type !== 'ident' && token.type !== 'string' && token.type !== 'number') {
136
+ if (token.type === 'eof') {
137
+ fail(
138
+ context,
139
+ SYNTAX_ERROR,
140
+ 'This object is never closed. Add a closing brace }.',
141
+ open.start,
142
+ open.end,
143
+ );
144
+ }
145
+ fail(
146
+ context,
147
+ SYNTAX_ERROR,
148
+ 'Expected a property name such as Property, SimpleOperator or Value here.',
149
+ token.start,
150
+ token.end,
151
+ );
152
+ }
153
+ context.pos++;
154
+ if (!isPunct(tokenAt(context, context.pos), ':')) {
155
+ const colon = tokenAt(context, context.pos);
156
+ fail(
157
+ context,
158
+ SYNTAX_ERROR,
159
+ `Expected ":" after the property name ${token.value}.`,
160
+ colon.start,
161
+ colon.end,
162
+ );
163
+ }
164
+ context.pos++;
165
+ entries.push({ key: token.value, value: parseLiteral(context) });
166
+ const separator = tokenAt(context, context.pos);
167
+ if (isPunct(separator, ',')) {
168
+ context.pos++;
169
+ } else if (!isPunct(separator, '}')) {
170
+ fail(
171
+ context,
172
+ SYNTAX_ERROR,
173
+ 'Separate the properties of an object with commas and close it with }.',
174
+ separator.start,
175
+ separator.end,
176
+ );
177
+ }
178
+ }
179
+ }
180
+
181
+ /**
182
+ * Parses an array literal starting at "[".
183
+ *
184
+ * @param {object} context parse context
185
+ * @returns {Literal} array literal
186
+ */
187
+ function parseArray(context) {
188
+ const open = tokenAt(context, context.pos++);
189
+ const items = [];
190
+ for (;;) {
191
+ const token = tokenAt(context, context.pos);
192
+ if (isPunct(token, ']')) {
193
+ context.pos++;
194
+ return { kind: 'array', items, start: open.start, end: token.end };
195
+ }
196
+ if (token.type === 'eof') {
197
+ fail(
198
+ context,
199
+ SYNTAX_ERROR,
200
+ 'This array is never closed. Add a closing bracket ].',
201
+ open.start,
202
+ open.end,
203
+ );
204
+ }
205
+ items.push(parseLiteral(context));
206
+ const separator = tokenAt(context, context.pos);
207
+ if (isPunct(separator, ',')) {
208
+ context.pos++;
209
+ } else if (!isPunct(separator, ']')) {
210
+ fail(
211
+ context,
212
+ SYNTAX_ERROR,
213
+ 'Separate the array items with commas and close the array with ].',
214
+ separator.start,
215
+ separator.end,
216
+ );
217
+ }
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Parses one literal value (object, array, string, number, boolean, null or a variable name),
223
+ * rejecting calls, operators and other expressions.
224
+ *
225
+ * @param {object} context parse context
226
+ * @returns {Literal} literal
227
+ */
228
+ function parseLiteral(context) {
229
+ const startIndex = context.pos;
230
+ const token = tokenAt(context, startIndex);
231
+ let node;
232
+ if (isPunct(token, '{')) {
233
+ node = parseObject(context);
234
+ } else if (isPunct(token, '[')) {
235
+ node = parseArray(context);
236
+ } else if (token.type === 'string') {
237
+ context.pos++;
238
+ node = { kind: 'string', value: token.value, start: token.start, end: token.end };
239
+ } else if (token.type === 'number') {
240
+ context.pos++;
241
+ node = { kind: 'number', value: token.value, start: token.start, end: token.end };
242
+ } else if (isPunct(token, '-') && tokenAt(context, startIndex + 1).type === 'number') {
243
+ const number = tokenAt(context, startIndex + 1);
244
+ context.pos += 2;
245
+ node = { kind: 'number', value: `-${number.value}`, start: token.start, end: number.end };
246
+ } else if (token.type === 'ident') {
247
+ node = parseWord(context, token);
248
+ } else if (token.type === 'eof') {
249
+ return fail(
250
+ context,
251
+ SYNTAX_ERROR,
252
+ 'The code ends where a value is expected.',
253
+ token.start,
254
+ token.end,
255
+ );
256
+ } else {
257
+ return fail(
258
+ context,
259
+ SYNTAX_ERROR,
260
+ `Expected a value but found "${token.value}". Write text in quotes, a number, an array or a filter object.`,
261
+ token.start,
262
+ token.end,
263
+ );
264
+ }
265
+ const next = tokenAt(context, context.pos);
266
+ if (next.type === 'punct' && !VALUE_END.has(next.value)) {
267
+ failExpression(context, startIndex, 'This calculated value');
268
+ }
269
+ return node;
270
+ }
271
+
272
+ /**
273
+ * Parses a bare word: true / false / null / undefined or a variable reference.
274
+ *
275
+ * @param {object} context parse context
276
+ * @param {object} token the identifier token
277
+ * @returns {Literal} literal
278
+ */
279
+ function parseWord(context, token) {
280
+ const following = tokenAt(context, context.pos + 1);
281
+ if (token.value === 'new') {
282
+ failExpression(context, context.pos, `"new ${following.value ?? ''}"`.trim());
283
+ }
284
+ if (isPunct(following, '(') || isPunct(following, '.')) {
285
+ failExpression(
286
+ context,
287
+ context.pos,
288
+ `The function call or property access starting with ${token.value}`,
289
+ );
290
+ }
291
+ context.pos++;
292
+ if (token.value === 'true' || token.value === 'false') {
293
+ return { kind: 'boolean', value: token.value, start: token.start, end: token.end };
294
+ }
295
+ if (token.value === 'null' || token.value === 'undefined') {
296
+ return { kind: 'null', value: token.value, start: token.start, end: token.end };
297
+ }
298
+ return { kind: 'ref', value: token.value, start: token.start, end: token.end };
299
+ }
300
+
301
+ /**
302
+ * Parses an argument list starting at "(".
303
+ *
304
+ * @param {object} context parse context
305
+ * @returns {{args: Literal[], end: number}} arguments and the end offset of ")"
306
+ */
307
+ function parseArguments(context) {
308
+ const open = tokenAt(context, context.pos++);
309
+ const args = [];
310
+ for (;;) {
311
+ const token = tokenAt(context, context.pos);
312
+ if (isPunct(token, ')')) {
313
+ context.pos++;
314
+ return { args, end: token.end };
315
+ }
316
+ if (token.type === 'eof') {
317
+ failUnclosedCall(context, open);
318
+ }
319
+ args.push(parseLiteral(context));
320
+ const separator = tokenAt(context, context.pos);
321
+ if (isPunct(separator, ',')) {
322
+ context.pos++;
323
+ } else if (separator.type === 'eof') {
324
+ failUnclosedCall(context, open);
325
+ } else if (!isPunct(separator, ')')) {
326
+ fail(
327
+ context,
328
+ SYNTAX_ERROR,
329
+ 'Separate the arguments with commas and close the call with ).',
330
+ separator.start,
331
+ separator.end,
332
+ );
333
+ }
334
+ }
335
+ }
336
+
337
+ /**
338
+ * Tries to parse a literal at a token index without recording messages.
339
+ *
340
+ * @param {object} context parse context
341
+ * @param {number} index token index
342
+ * @returns {Literal|null} literal or null
343
+ */
344
+ function tryLiteral(context, index) {
345
+ const saved = { pos: context.pos, count: context.messages.length };
346
+ context.pos = index;
347
+ try {
348
+ return parseLiteral(context);
349
+ } catch {
350
+ return null;
351
+ } finally {
352
+ context.pos = saved.pos;
353
+ context.messages.length = saved.count;
354
+ }
355
+ }
356
+
357
+ // ------------------------------------------------------------------------------------------
358
+ // Variables
359
+ // ------------------------------------------------------------------------------------------
360
+
361
+ /**
362
+ * Checks whether the tokens at an index are `DataExtension.Init(`.
363
+ *
364
+ * @param {object} context parse context
365
+ * @param {number} index token index
366
+ * @returns {boolean} true when they are
367
+ */
368
+ function isDataExtensionInit(context, index) {
369
+ return (
370
+ isIdent(tokenAt(context, index), 'DataExtension') &&
371
+ isPunct(tokenAt(context, index + 1), '.') &&
372
+ isIdent(tokenAt(context, index + 2), 'Init') &&
373
+ isPunct(tokenAt(context, index + 3), '(')
374
+ );
375
+ }
376
+
377
+ /**
378
+ * Collects every `name = …` assignment: literals, `DataExtension.Init(…)` and anything else.
379
+ *
380
+ * @param {object} context parse context
381
+ * @returns {Map<string, VariableEntry[]>} assignments per variable name in source order
382
+ */
383
+ function collectVariables(context) {
384
+ const variables = new Map();
385
+ const { tokens } = context;
386
+ for (let index = 0; index < tokens.length - 1; index++) {
387
+ const token = tokens[index];
388
+ if (token.type !== 'ident' || !isPunct(tokens[index + 1], '=')) {
389
+ continue;
390
+ }
391
+ if (index > 0 && isPunct(tokens[index - 1], '.')) {
392
+ continue;
393
+ }
394
+ let entry = { start: token.start, kind: 'other' };
395
+ if (isDataExtensionInit(context, index + 2)) {
396
+ const argument = tryLiteral(context, index + 6);
397
+ if (
398
+ argument &&
399
+ isPunct(tokenAt(context, index + 6 + countTokens(context, argument)), ')')
400
+ ) {
401
+ entry = { start: token.start, kind: 'deInit', node: argument };
402
+ }
403
+ } else {
404
+ const node = tryLiteral(context, index + 2);
405
+ if (node) {
406
+ entry = { start: token.start, kind: 'literal', node };
407
+ }
408
+ }
409
+ if (!variables.has(token.value)) {
410
+ variables.set(token.value, []);
411
+ }
412
+ variables.get(token.value).push(entry);
413
+ }
414
+ return variables;
415
+ }
416
+
417
+ /**
418
+ * Counts the tokens a literal spans.
419
+ *
420
+ * @param {object} context parse context
421
+ * @param {Literal} node literal
422
+ * @returns {number} number of tokens
423
+ */
424
+ function countTokens(context, node) {
425
+ return context.tokens.filter((token) => token.start >= node.start && token.end <= node.end)
426
+ .length;
427
+ }
428
+
429
+ /**
430
+ * Finds the last assignment of a variable before an offset.
431
+ *
432
+ * @param {Map<string, VariableEntry[]>} variables collected assignments
433
+ * @param {string} name variable name
434
+ * @param {number} offset offset of the use
435
+ * @returns {VariableEntry|undefined} assignment
436
+ */
437
+ function lookupVariable(variables, name, offset) {
438
+ const entries = variables.get(name) ?? [];
439
+ return entries.findLast((entry) => entry.start < offset);
440
+ }
441
+
442
+ /**
443
+ * Replaces a variable reference by the literal it is set to.
444
+ *
445
+ * @param {object} state parser state
446
+ * @param {Literal} node literal or reference
447
+ * @returns {Literal} resolved literal (never a reference)
448
+ */
449
+ function resolve(state, node) {
450
+ let current = node;
451
+ for (let depth = 0; current.kind === 'ref'; depth++) {
452
+ const entry = lookupVariable(state.variables, current.value, current.start);
453
+ if (!entry || entry.kind !== 'literal' || depth > MAX_VARIABLE_DEPTH) {
454
+ fail(
455
+ state.context,
456
+ VARIABLE_VALUE,
457
+ entry
458
+ ? `The variable ${current.value} is not set to a fixed value in this code, so its value can't be converted. Replace it with the value itself.`
459
+ : `The variable ${current.value} is not set anywhere before this point, so its value can't be converted. Replace it with the value itself or paste the line that sets it.`,
460
+ node.start,
461
+ node.end,
462
+ );
463
+ }
464
+ current = entry.node;
465
+ }
466
+ return current;
467
+ }
468
+
469
+ // ------------------------------------------------------------------------------------------
470
+ // Filters
471
+ // ------------------------------------------------------------------------------------------
472
+
473
+ /**
474
+ * Converts a scalar literal (string, number, boolean) into an AST Value.
475
+ *
476
+ * @param {object} state parser state
477
+ * @param {Literal} node literal or reference
478
+ * @param {string} column column name for messages
479
+ * @returns {{kind: 'string'|'number', value: string, loc: object}} value
480
+ */
481
+ function toValue(state, node, column) {
482
+ const literal = resolve(state, node);
483
+ if (literal.kind === 'string' || literal.kind === 'boolean') {
484
+ return makeValue(state.context, literal.value, literal.start, literal.end);
485
+ }
486
+ if (literal.kind === 'number') {
487
+ return makeValue(state.context, literal.value, literal.start, literal.end, true);
488
+ }
489
+ const hint =
490
+ literal.kind === 'null'
491
+ ? ` To find empty values use SimpleOperator "isNull" (SQL: ${column} IS NULL).`
492
+ : ' Use a single text value or number.';
493
+ return fail(
494
+ state.context,
495
+ INVALID_FILTER_VALUE,
496
+ `This value can't be compared with ${column}.${hint}`,
497
+ node.start,
498
+ node.end,
499
+ );
500
+ }
501
+
502
+ /**
503
+ * Returns the object's entries keyed by lower-case property name.
504
+ *
505
+ * @param {Literal} object object literal
506
+ * @returns {Map<string, Literal>} entries
507
+ */
508
+ function entriesByKey(object) {
509
+ const map = new Map();
510
+ for (const entry of object.entries) {
511
+ map.set(entry.key.toLowerCase(), entry.value);
512
+ }
513
+ return map;
514
+ }
515
+
516
+ /**
517
+ * Converts a filter object (SimpleFilterPart / ComplexFilterPart) into an AST expression.
518
+ *
519
+ * @param {object} state parser state
520
+ * @param {Literal} node literal or reference
521
+ * @returns {object} expression node
522
+ */
523
+ function toExpr(state, node) {
524
+ const { context } = state;
525
+ const object = resolve(state, node);
526
+ if (object.kind !== 'object') {
527
+ fail(
528
+ context,
529
+ INVALID_FILTER,
530
+ 'A filter must be an object such as {Property: "Name", SimpleOperator: "equals", Value: "x"} or {LeftOperand: …, LogicalOperator: "AND", RightOperand: …}.',
531
+ node.start,
532
+ node.end,
533
+ );
534
+ }
535
+ const entries = entriesByKey(object);
536
+ const loc = makeLoc(context, object.start, object.end);
537
+ if (LOGICAL_KEYS.some((key) => entries.has(key))) {
538
+ const missing = ['LeftOperand', 'LogicalOperator', 'RightOperand'].filter(
539
+ (key) => !entries.has(key.toLowerCase()),
540
+ );
541
+ if (missing.length) {
542
+ fail(
543
+ context,
544
+ INVALID_FILTER,
545
+ `This combined filter has no ${missing.join(' and no ')}. Add it.`,
546
+ object.start,
547
+ object.end,
548
+ );
549
+ }
550
+ const operatorNode = entries.get('logicaloperator');
551
+ const operator = resolve(state, operatorNode);
552
+ const type = operator.kind === 'string' ? operator.value.toLowerCase() : '';
553
+ if (type !== 'and' && type !== 'or') {
554
+ fail(
555
+ context,
556
+ INVALID_LOGICAL_OPERATOR,
557
+ 'LogicalOperator must be "AND" or "OR".',
558
+ operatorNode.start,
559
+ operatorNode.end,
560
+ );
561
+ }
562
+ return {
563
+ type,
564
+ left: toExpr(state, entries.get('leftoperand')),
565
+ right: toExpr(state, entries.get('rightoperand')),
566
+ loc,
567
+ };
568
+ }
569
+ if (!entries.has('property') || !entries.has('simpleoperator')) {
570
+ fail(
571
+ context,
572
+ INVALID_FILTER,
573
+ 'This filter needs Property and SimpleOperator, e.g. {Property: "Name", SimpleOperator: "equals", Value: "x"}.',
574
+ object.start,
575
+ object.end,
576
+ );
577
+ }
578
+ return toCondition(state, entries, loc);
579
+ }
580
+
581
+ /**
582
+ * Converts a SimpleFilterPart into a condition node.
583
+ *
584
+ * @param {object} state parser state
585
+ * @param {Map<string, Literal>} entries filter properties by lower-case key
586
+ * @param {object} loc location of the filter object
587
+ * @returns {object} condition node
588
+ */
589
+ function toCondition(state, entries, loc) {
590
+ const { context } = state;
591
+ const propertyNode = entries.get('property');
592
+ const property = resolve(state, propertyNode);
593
+ if (property.kind !== 'string' || !property.value.trim()) {
594
+ fail(
595
+ context,
596
+ INVALID_FILTER,
597
+ 'Property must be the column name in quotes.',
598
+ propertyNode.start,
599
+ propertyNode.end,
600
+ );
601
+ }
602
+ const column = property.value;
603
+ const operatorNode = entries.get('simpleoperator');
604
+ const operatorLiteral = resolve(state, operatorNode);
605
+ const operator = operatorLiteral.kind === 'string' ? operatorLiteral.value.toLowerCase() : '';
606
+ if (operator === 'isnull' || operator === 'isnotnull') {
607
+ return { type: 'null', negated: operator === 'isnotnull', column, loc };
608
+ }
609
+ if (REJECTED_OPERATORS.has(operator)) {
610
+ fail(
611
+ context,
612
+ UNSUPPORTED_FILTER_OPERATOR,
613
+ `The operator "${operatorLiteral.value}" is not accepted for data extension rows and has no SQL equivalent here; ${REJECTED_OPERATORS.get(operator)}.`,
614
+ operatorNode.start,
615
+ operatorNode.end,
616
+ );
617
+ }
618
+ if (!COMPARE_OPERATORS.has(operator) && !['like', 'in', 'between'].includes(operator)) {
619
+ fail(
620
+ context,
621
+ UNKNOWN_FILTER_OPERATOR,
622
+ 'Unknown SimpleOperator. Use equals, notEquals, greaterThan, greaterThanOrEqual, lessThan, lessThanOrEqual, like, IN, between, isNull or isNotNull.',
623
+ operatorNode.start,
624
+ operatorNode.end,
625
+ );
626
+ }
627
+ const valueNode = entries.get('value') ?? entries.get('datevalue');
628
+ if (!valueNode) {
629
+ fail(
630
+ context,
631
+ INVALID_FILTER_VALUE,
632
+ `This filter on ${column} has no Value. Add Value: "…".`,
633
+ loc.start,
634
+ loc.end,
635
+ );
636
+ }
637
+ if (operator === 'in' || operator === 'between') {
638
+ return toListCondition(state, operator, column, valueNode, loc);
639
+ }
640
+ const value = resolve(state, valueNode);
641
+ if (value.kind === 'array' || value.kind === 'object') {
642
+ fail(
643
+ context,
644
+ INVALID_FILTER_VALUE,
645
+ `"${operatorLiteral.value}" needs a single value, not a list.`,
646
+ valueNode.start,
647
+ valueNode.end,
648
+ );
649
+ }
650
+ if (operator === 'like') {
651
+ const raw = toValue(state, valueNode, column);
652
+ const inner = raw.value.replace(/^%+/, '').replace(/%+$/, '');
653
+ // the like filter always matches anywhere: it wraps its value in %…%
654
+ const node = {
655
+ type: 'like',
656
+ column,
657
+ pattern: { ...raw, kind: 'string', value: inner ? `%${inner}%` : '%' },
658
+ loc,
659
+ };
660
+ state.likeFilters.set(node, raw.value);
661
+ return node;
662
+ }
663
+ return {
664
+ type: 'compare',
665
+ op: COMPARE_OPERATORS.get(operator),
666
+ column,
667
+ value: spaceAsEmpty(toValue(state, valueNode, column)),
668
+ loc,
669
+ };
670
+ }
671
+
672
+ /**
673
+ * Maps a filter Value of exactly one space back to '' (the emitters send `= ''` as `" "`,
674
+ * because the filter rejects an empty Value).
675
+ *
676
+ * @param {{kind: string, value: string, loc: object}} value AST value
677
+ * @returns {{kind: string, value: string, loc: object}} value
678
+ */
679
+ function spaceAsEmpty(value) {
680
+ return value.value === ' ' ? { ...value, kind: 'string', value: '' } : value;
681
+ }
682
+
683
+ /**
684
+ * Converts an IN or between filter (array Value) into a condition node.
685
+ *
686
+ * @param {object} state parser state
687
+ * @param {'in'|'between'} operator lower-case operator
688
+ * @param {string} column column name
689
+ * @param {Literal} valueNode the Value literal
690
+ * @param {object} loc location of the filter object
691
+ * @returns {object} in or between node
692
+ */
693
+ function toListCondition(state, operator, column, valueNode, loc) {
694
+ const list = resolve(state, valueNode);
695
+ const isBetween = operator === 'between';
696
+ if (list.kind !== 'array' || (isBetween ? list.items.length !== 2 : list.items.length === 0)) {
697
+ fail(
698
+ state.context,
699
+ INVALID_FILTER_VALUE,
700
+ isBetween
701
+ ? 'between needs an array with exactly two values: [low, high].'
702
+ : 'IN needs an array with at least one value, e.g. ["a", "b"].',
703
+ valueNode.start,
704
+ valueNode.end,
705
+ );
706
+ }
707
+ const values = list.items.map((item) => toValue(state, item, column));
708
+ if (isBetween) {
709
+ return { type: 'between', column, low: values[0], high: values[1], loc };
710
+ }
711
+ return {
712
+ type: 'in',
713
+ negated: false,
714
+ column,
715
+ values: values.map((value) => spaceAsEmpty(value)),
716
+ loc,
717
+ };
718
+ }
719
+
720
+ /**
721
+ * Returns the conditions of an AND tree in source order.
722
+ *
723
+ * @param {object} expression expression node
724
+ * @returns {object[]} leaf conditions
725
+ */
726
+ function andLeaves(expression) {
727
+ return expression.type === 'and'
728
+ ? [...andLeaves(expression.left), ...andLeaves(expression.right)]
729
+ : [expression];
730
+ }
731
+
732
+ /**
733
+ * Folds AND chains of `<>` on one column back into NOT IN (only used when the header marks
734
+ * that the emitter produced them).
735
+ *
736
+ * @param {object|null} expression expression node
737
+ * @returns {object|null} folded expression
738
+ */
739
+ function foldNotIn(expression) {
740
+ if (!expression || (expression.type !== 'and' && expression.type !== 'or')) {
741
+ return expression;
742
+ }
743
+ if (expression.type === 'and') {
744
+ const leaves = andLeaves(expression);
745
+ const column = leaves[0].column?.toLowerCase();
746
+ if (
747
+ leaves.every(
748
+ (leaf) =>
749
+ leaf.type === 'compare' &&
750
+ leaf.op === '<>' &&
751
+ leaf.column.toLowerCase() === column,
752
+ )
753
+ ) {
754
+ return {
755
+ type: 'in',
756
+ negated: true,
757
+ column: leaves[0].column,
758
+ values: leaves.map((leaf) => leaf.value),
759
+ loc: expression.loc,
760
+ };
761
+ }
762
+ }
763
+ return { ...expression, left: foldNotIn(expression.left), right: foldNotIn(expression.right) };
764
+ }
765
+
766
+ /**
767
+ * Reads every `sqlLike(row["Col"], "pattern")` call of the code (the exact LIKE check the
768
+ * emitters add after a wider `like` filter).
769
+ *
770
+ * @param {object} context parse context
771
+ * @returns {{column: string, pattern: string}[]} checks in source order
772
+ */
773
+ function findLikeChecks(context) {
774
+ const checks = [];
775
+ const { tokens } = context;
776
+ for (let index = 0; index < tokens.length; index++) {
777
+ const at = (offset) => tokenAt(context, index + offset);
778
+ if (
779
+ isIdent(tokens[index], 'sqlLike') &&
780
+ !(index > 0 && isIdent(tokens[index - 1], 'function')) &&
781
+ isPunct(at(1), '(') &&
782
+ at(2).type === 'ident' &&
783
+ isPunct(at(3), '[') &&
784
+ at(4).type === 'string' &&
785
+ isPunct(at(5), ']') &&
786
+ isPunct(at(6), ',') &&
787
+ at(7).type === 'string' &&
788
+ isPunct(at(8), ')')
789
+ ) {
790
+ checks.push({ column: at(4).value, pattern: at(7).value });
791
+ }
792
+ }
793
+ return checks;
794
+ }
795
+
796
+ /**
797
+ * Puts the exact LIKE patterns of the `sqlLike` checks back into the matching like conditions
798
+ * (same column, filter Value equal to the wider value of the pattern). A like condition without
799
+ * a check keeps its `%value%` pattern; when that differs from the filter Value an info message
800
+ * says that the filter matches anywhere.
801
+ *
802
+ * @param {object} state parser state (`likeFilters`: like node → filter Value)
803
+ * @param {object|null} expression expression node
804
+ * @param {{column: string, pattern: string}[]} checks unused checks (consumed when applied)
805
+ * @returns {object|null} expression with the exact patterns
806
+ */
807
+ function applyLikeChecks(state, expression, checks) {
808
+ if (!expression) {
809
+ return expression;
810
+ }
811
+ if (expression.type === 'and' || expression.type === 'or') {
812
+ return {
813
+ ...expression,
814
+ left: applyLikeChecks(state, expression.left, checks),
815
+ right: applyLikeChecks(state, expression.right, checks),
816
+ };
817
+ }
818
+ if (expression.type !== 'like') {
819
+ return expression;
820
+ }
821
+ const filterValue = state.likeFilters.get(expression) ?? expression.pattern.value;
822
+ const index = checks.findIndex(
823
+ (check) =>
824
+ check.column.toLowerCase() === expression.column.toLowerCase() &&
825
+ likeFilterValue(check.pattern) === filterValue,
826
+ );
827
+ if (index === -1) {
828
+ if (filterValue !== expression.pattern.value) {
829
+ const { loc } = expression;
830
+ report(
831
+ state.context,
832
+ 'info',
833
+ LIKE_MATCHES_ANYWHERE,
834
+ `The like filter of WSProxy and Rows.Retrieve matches the value anywhere in ${expression.column}, so Value "${filterValue}" reads back as LIKE '${expression.pattern.value.replaceAll("'", "''")}'.`,
835
+ loc.start,
836
+ loc.end,
837
+ );
838
+ }
839
+ return expression;
840
+ }
841
+ const [check] = checks.splice(index, 1);
842
+ return { ...expression, pattern: { ...expression.pattern, value: check.pattern } };
843
+ }
844
+
845
+ // ------------------------------------------------------------------------------------------
846
+ // Calls
847
+ // ------------------------------------------------------------------------------------------
848
+
849
+ /**
850
+ * Finds the "(" index matching the ")" at a token index, walking backwards.
851
+ *
852
+ * @param {object} context parse context
853
+ * @param {number} closeIndex token index of ")"
854
+ * @returns {number} token index of "(" or -1
855
+ */
856
+ function matchingOpen(context, closeIndex) {
857
+ let depth = 0;
858
+ for (let index = closeIndex; index >= 0; index--) {
859
+ const token = context.tokens[index];
860
+ if (isPunct(token, ')')) {
861
+ depth++;
862
+ } else if (isPunct(token, '(')) {
863
+ depth--;
864
+ if (depth === 0) {
865
+ return index;
866
+ }
867
+ }
868
+ }
869
+ return -1;
870
+ }
871
+
872
+ /**
873
+ * Identifies a `.Rows.Retrieve(` call whose `.Retrieve` identifier is at an index.
874
+ *
875
+ * @param {object} context parse context
876
+ * @param {number} index token index of Retrieve
877
+ * @returns {{kind: string, index: number, start: number, owner: object}|null} call candidate
878
+ */
879
+ function rowsRetrieveCall(context, index) {
880
+ const ownerEnd = tokenAt(context, index - 4);
881
+ if (index >= 4 && ownerEnd.type === 'ident') {
882
+ return { kind: 'rows', index, start: ownerEnd.start, owner: { variable: ownerEnd } };
883
+ }
884
+ if (isPunct(ownerEnd, ')')) {
885
+ const open = matchingOpen(context, index - 4);
886
+ if (open >= 3 && isDataExtensionInit(context, open - 3)) {
887
+ return {
888
+ kind: 'rows',
889
+ index,
890
+ start: tokenAt(context, open - 3).start,
891
+ owner: { argumentIndex: open + 1 },
892
+ };
893
+ }
894
+ }
895
+ return null;
896
+ }
897
+
898
+ /**
899
+ * Finds every supported lookup call.
900
+ *
901
+ * @param {object} context parse context
902
+ * @returns {{kind: string, index: number, start: number, owner?: object}[]} call candidates in source order
903
+ */
904
+ function findCalls(context) {
905
+ const calls = [];
906
+ const { tokens } = context;
907
+ for (let index = 0; index < tokens.length; index++) {
908
+ const token = tokens[index];
909
+ if (token.type !== 'ident' || !isPunct(tokenAt(context, index + 1), '(')) {
910
+ continue;
911
+ }
912
+ const hasDot = index > 0 && isPunct(tokens[index - 1], '.');
913
+ const name = token.value.toLowerCase();
914
+ if (name === 'retrieve' && hasDot) {
915
+ if (
916
+ isIdent(tokenAt(context, index - 2), 'Rows') &&
917
+ isPunct(tokenAt(context, index - 3), '.')
918
+ ) {
919
+ const call = rowsRetrieveCall(context, index);
920
+ if (call) {
921
+ calls.push(call);
922
+ }
923
+ } else if (tokenAt(context, index - 2).type === 'ident') {
924
+ calls.push({ kind: 'wsproxy', index, start: tokenAt(context, index - 2).start });
925
+ }
926
+ } else if (name === 'lookuprows' || name === 'lookuporderedrows') {
927
+ const isPlatform =
928
+ hasDot &&
929
+ isIdent(tokenAt(context, index - 2), 'Function') &&
930
+ isPunct(tokenAt(context, index - 3), '.') &&
931
+ isIdent(tokenAt(context, index - 4), 'Platform');
932
+ if (!hasDot || isPlatform) {
933
+ calls.push({
934
+ kind: name,
935
+ index,
936
+ start: isPlatform ? tokenAt(context, index - 4).start : token.start,
937
+ });
938
+ }
939
+ }
940
+ }
941
+ return calls;
942
+ }
943
+
944
+ /**
945
+ * Drops the WSProxy calls that only read the next batch of the first retrieve (paging with
946
+ * `props.ContinueRequest = result.RequestID`): later retrieve calls whose first argument is
947
+ * written the same way as the first call's.
948
+ *
949
+ * @param {object} context parse context
950
+ * @param {{kind: string, index: number}[]} calls call candidates in source order
951
+ * @returns {{kind: string, index: number}[]} calls without the continuation calls
952
+ */
953
+ function withoutContinuations(context, calls) {
954
+ const [first] = calls;
955
+ if (first?.kind !== 'wsproxy') {
956
+ return calls;
957
+ }
958
+ const objectType = tokenAt(context, first.index + 2);
959
+ return calls.filter((call, position) => {
960
+ if (position === 0 || call.kind !== 'wsproxy') {
961
+ return true;
962
+ }
963
+ const argument = tokenAt(context, call.index + 2);
964
+ return argument.type !== objectType.type || argument.value !== objectType.value;
965
+ });
966
+ }
967
+
968
+ /**
969
+ * Resolves a literal that must be a non-empty string.
970
+ *
971
+ * @param {object} state parser state
972
+ * @param {Literal} node literal or reference
973
+ * @param {string} what what the argument is, for the message
974
+ * @returns {string} the text
975
+ */
976
+ function requireString(state, node, what) {
977
+ const literal = resolve(state, node);
978
+ if (literal.kind !== 'string' || !literal.value.trim()) {
979
+ fail(
980
+ state.context,
981
+ INVALID_ARGUMENT,
982
+ `${what} must be text in quotes.`,
983
+ node.start,
984
+ node.end,
985
+ );
986
+ }
987
+ return literal.value;
988
+ }
989
+
990
+ /**
991
+ * Builds the FROM node and meta data from a data extension external key plus the header.
992
+ *
993
+ * @param {object} state parser state
994
+ * @param {Literal} keyNode literal holding the key
995
+ * @param {string} key external key
996
+ * @returns {{name: string, loc: object}} from node
997
+ */
998
+ function fromKey(state, keyNode, key) {
999
+ const { context, header, meta } = state;
1000
+ meta.deKey = key;
1001
+ if (header.name) {
1002
+ meta.deName = header.name;
1003
+ return { name: header.name, loc: header.nameLoc };
1004
+ }
1005
+ report(
1006
+ context,
1007
+ 'info',
1008
+ FROM_NAME_FROM_KEY,
1009
+ 'The code only names the external key of the data extension, so the key is used as the name after FROM. Replace it with the data extension name if they differ.',
1010
+ keyNode.start,
1011
+ keyNode.end,
1012
+ );
1013
+ return { name: key, loc: makeLoc(context, keyNode.start, keyNode.end) };
1014
+ }
1015
+
1016
+ /**
1017
+ * Reads `proxy.retrieve("DataExtensionObject[Key]", [columns], filter, …)`.
1018
+ *
1019
+ * @param {object} state parser state
1020
+ * @param {Literal[]} args call arguments
1021
+ * @param {object} callLoc location of the call
1022
+ * @returns {object} partial AST
1023
+ */
1024
+ function readWsproxy(state, args, callLoc) {
1025
+ const { context } = state;
1026
+ if (args.length < 2 || args.length > 5) {
1027
+ fail(
1028
+ context,
1029
+ ARGUMENT_COUNT,
1030
+ 'retrieve needs the object type, the column list and optionally a filter: retrieve("DataExtensionObject[Key]", ["Col"], filter).',
1031
+ callLoc.start,
1032
+ callLoc.end,
1033
+ );
1034
+ }
1035
+ const typeText = requireString(state, args[0], 'The object type');
1036
+ const match = /^DataExtensionObject\[(.+)\]$/i.exec(typeText.trim());
1037
+ if (!match) {
1038
+ fail(
1039
+ context,
1040
+ INVALID_OBJECT_TYPE,
1041
+ 'Only data extension rows can be converted. The first argument must be "DataExtensionObject[ExternalKey]".',
1042
+ args[0].start,
1043
+ args[0].end,
1044
+ );
1045
+ }
1046
+ state.meta.target = 'ssjs-wsproxy';
1047
+ const from = fromKey(state, args[0], match[1]);
1048
+ const list = resolve(state, args[1]);
1049
+ if (list.kind !== 'array' || list.items.length === 0) {
1050
+ fail(
1051
+ context,
1052
+ INVALID_ARGUMENT,
1053
+ 'The columns must be an array of column names, e.g. ["FirstName", "Email"].',
1054
+ args[1].start,
1055
+ args[1].end,
1056
+ );
1057
+ }
1058
+ const columns = list.items.map((item) => {
1059
+ const name = requireString(state, item, 'Each column name');
1060
+ const literal = resolve(state, item);
1061
+ return { name, loc: makeLoc(context, literal.start, literal.end) };
1062
+ });
1063
+ const filter = args[2] && resolve(state, args[2]);
1064
+ return {
1065
+ // a `// SQL: SELECT` header names the selected columns when cols reads more of them
1066
+ columns: state.header.columns ?? columns,
1067
+ from,
1068
+ where: !filter || filter.kind === 'null' ? null : toExpr(state, args[2]),
1069
+ top: null,
1070
+ orderBy: [],
1071
+ };
1072
+ }
1073
+
1074
+ /**
1075
+ * Reads `DataExtension.Init("Key").Rows.Retrieve(filter?)` (also via a variable).
1076
+ *
1077
+ * @param {object} state parser state
1078
+ * @param {object} call call candidate
1079
+ * @param {Literal[]} args call arguments
1080
+ * @param {object} callLoc location of the call
1081
+ * @returns {object} partial AST
1082
+ */
1083
+ function readRowsRetrieve(state, call, args, callLoc) {
1084
+ const { context } = state;
1085
+ let keyNode;
1086
+ if (call.owner.variable) {
1087
+ const variable = call.owner.variable;
1088
+ const entry = lookupVariable(state.variables, variable.value, variable.start);
1089
+ if (!entry || entry.kind !== 'deInit') {
1090
+ fail(
1091
+ context,
1092
+ VARIABLE_VALUE,
1093
+ `${variable.value} is not set to DataExtension.Init("Key") in this code. Paste the line that sets it, or write DataExtension.Init("Key").Rows.Retrieve(…).`,
1094
+ variable.start,
1095
+ variable.end,
1096
+ );
1097
+ }
1098
+ keyNode = entry.node;
1099
+ } else {
1100
+ context.pos = call.owner.argumentIndex;
1101
+ keyNode = parseLiteral(context);
1102
+ }
1103
+ const key = requireString(state, keyNode, 'The data extension external key');
1104
+ if (args.length > 1) {
1105
+ fail(
1106
+ context,
1107
+ ARGUMENT_COUNT,
1108
+ 'Rows.Retrieve takes at most one argument: the filter object.',
1109
+ callLoc.start,
1110
+ callLoc.end,
1111
+ );
1112
+ }
1113
+ state.meta.target = 'ssjs-rows-retrieve';
1114
+ const from = fromKey(state, keyNode, key);
1115
+ const filter = args[0] && resolve(state, args[0]);
1116
+ return {
1117
+ columns: state.header.columns ?? '*',
1118
+ from,
1119
+ where: !filter || filter.kind === 'null' ? null : toExpr(state, args[0]),
1120
+ top: null,
1121
+ orderBy: [],
1122
+ };
1123
+ }
1124
+
1125
+ /**
1126
+ * Reads the column / value pairs of a Platform.Function lookup (single values or arrays).
1127
+ *
1128
+ * @param {object} state parser state
1129
+ * @param {Literal} columnsNode column name or array of names
1130
+ * @param {Literal} valuesNode value or array of values
1131
+ * @returns {object} AND chain of equals conditions
1132
+ */
1133
+ function readPairs(state, columnsNode, valuesNode) {
1134
+ const { context } = state;
1135
+ const columns = resolve(state, columnsNode);
1136
+ const values = resolve(state, valuesNode);
1137
+ const columnItems = columns.kind === 'array' ? columns.items : [columnsNode];
1138
+ const valueItems = values.kind === 'array' ? values.items : [valuesNode];
1139
+ if (
1140
+ columnItems.length === 0 ||
1141
+ columnItems.length !== valueItems.length ||
1142
+ (columns.kind === 'array') !== (values.kind === 'array')
1143
+ ) {
1144
+ fail(
1145
+ context,
1146
+ INVALID_ARGUMENT,
1147
+ 'The column names and the values must match: either one name and one value, or two arrays of the same length.',
1148
+ columnsNode.start,
1149
+ valuesNode.end,
1150
+ );
1151
+ }
1152
+ const conditions = columnItems.map((columnNode, index) => {
1153
+ const column = requireString(state, columnNode, 'Each column name');
1154
+ const value = toValue(state, valueItems[index], column);
1155
+ const start = resolve(state, columnNode).start;
1156
+ return {
1157
+ type: 'compare',
1158
+ op: '=',
1159
+ column,
1160
+ value,
1161
+ loc: makeLoc(context, Math.min(start, value.loc.start), Math.max(start, value.loc.end)),
1162
+ };
1163
+ });
1164
+ return andChain(context, conditions);
1165
+ }
1166
+
1167
+ /**
1168
+ * Reads `Platform.Function.LookupRows(name, cols, values)` and
1169
+ * `LookupOrderedRows(name, count, order, cols, values)`.
1170
+ *
1171
+ * @param {object} state parser state
1172
+ * @param {boolean} isOrdered true for LookupOrderedRows
1173
+ * @param {Literal[]} args call arguments
1174
+ * @param {object} callLoc location of the call
1175
+ * @returns {object} partial AST
1176
+ */
1177
+ function readLookupRows(state, isOrdered, args, callLoc) {
1178
+ const { context } = state;
1179
+ const expected = isOrdered ? 5 : 3;
1180
+ if (args.length !== expected) {
1181
+ fail(
1182
+ context,
1183
+ ARGUMENT_COUNT,
1184
+ isOrdered
1185
+ ? 'LookupOrderedRows needs 5 arguments: (data extension name, count, "Col ASC", column(s), value(s)).'
1186
+ : 'LookupRows needs 3 arguments: (data extension name, column(s), value(s)).',
1187
+ callLoc.start,
1188
+ callLoc.end,
1189
+ );
1190
+ }
1191
+ const name = requireString(state, args[0], 'The data extension name');
1192
+ const nameLiteral = resolve(state, args[0]);
1193
+ state.meta.target = isOrdered ? 'ssjs-lookuporderedrows' : 'ssjs-lookuprows';
1194
+ state.meta.deName = name;
1195
+ let top = null;
1196
+ let orderBy = [];
1197
+ if (isOrdered) {
1198
+ top = readCount(state, args[1]);
1199
+ requireString(state, args[2], 'The sort order');
1200
+ orderBy = parseOrderString(context, resolve(state, args[2]));
1201
+ }
1202
+ return {
1203
+ columns: state.header.columns ?? '*',
1204
+ from: { name, loc: makeLoc(context, nameLiteral.start, nameLiteral.end) },
1205
+ where: readPairs(state, args[expected - 2], args[expected - 1]),
1206
+ top,
1207
+ orderBy,
1208
+ };
1209
+ }
1210
+
1211
+ /**
1212
+ * Reads the row count of LookupOrderedRows (0 or -1 = all rows → no TOP).
1213
+ *
1214
+ * @param {object} state parser state
1215
+ * @param {Literal} node count literal
1216
+ * @returns {number|null} TOP value
1217
+ */
1218
+ function readCount(state, node) {
1219
+ const literal = resolve(state, node);
1220
+ const text = literal.kind === 'number' || literal.kind === 'string' ? literal.value.trim() : '';
1221
+ if (!/^-?\d+$/.test(text)) {
1222
+ fail(
1223
+ state.context,
1224
+ INVALID_COUNT,
1225
+ 'The row count must be a whole number (0 or -1 for all rows).',
1226
+ node.start,
1227
+ node.end,
1228
+ );
1229
+ }
1230
+ const count = Number(text);
1231
+ return count > 0 ? count : null;
1232
+ }
1233
+
1234
+ /**
1235
+ * Reads a bare filter object (no call): the whole input is `{…}`, or the last variable set to
1236
+ * a filter object.
1237
+ *
1238
+ * @param {object} state parser state
1239
+ * @returns {object|null} partial AST, or null when there is no filter object
1240
+ */
1241
+ function readBareFilter(state) {
1242
+ const { context } = state;
1243
+ let node = null;
1244
+ if (
1245
+ isPunct(tokenAt(context, 0), '{') ||
1246
+ (isPunct(tokenAt(context, 0), '(') && isPunct(tokenAt(context, 1), '{'))
1247
+ ) {
1248
+ context.pos = isPunct(tokenAt(context, 0), '(') ? 1 : 0;
1249
+ node = parseLiteral(context);
1250
+ } else {
1251
+ for (const entries of state.variables.values()) {
1252
+ for (const entry of entries) {
1253
+ if (
1254
+ entry.kind === 'literal' &&
1255
+ isFilterObject(entry.node) &&
1256
+ (!node || entry.start > node.assignedAt)
1257
+ ) {
1258
+ node = { ...entry.node, assignedAt: entry.start };
1259
+ }
1260
+ }
1261
+ }
1262
+ }
1263
+ if (!node) {
1264
+ return null;
1265
+ }
1266
+ state.meta.target = 'ssjs-filter';
1267
+ const { header } = state;
1268
+ let from;
1269
+ if (header.name) {
1270
+ state.meta.deName = header.name;
1271
+ from = { name: header.name, loc: header.nameLoc };
1272
+ } else {
1273
+ report(
1274
+ context,
1275
+ 'warning',
1276
+ FROM_UNKNOWN,
1277
+ 'This filter does not say which data extension it reads, so the name after FROM is left empty. Enter the data extension name in the settings.',
1278
+ node.start,
1279
+ node.end,
1280
+ );
1281
+ from = { name: '', loc: makeLoc(context, node.start, node.start) };
1282
+ }
1283
+ if (header.key) {
1284
+ state.meta.deKey = header.key;
1285
+ }
1286
+ return {
1287
+ columns: header.columns ?? '*',
1288
+ from,
1289
+ where: toExpr(state, node),
1290
+ top: null,
1291
+ orderBy: [],
1292
+ start: node.start,
1293
+ end: node.end,
1294
+ };
1295
+ }
1296
+
1297
+ /**
1298
+ * Checks whether a literal looks like a WSProxy filter object.
1299
+ *
1300
+ * @param {Literal} node literal
1301
+ * @returns {boolean} true for an object with Property or LeftOperand
1302
+ */
1303
+ function isFilterObject(node) {
1304
+ return (
1305
+ node.kind === 'object' &&
1306
+ node.entries.some((entry) => ['property', 'leftoperand'].includes(entry.key.toLowerCase()))
1307
+ );
1308
+ }
1309
+
1310
+ /**
1311
+ * Parses the lookup call (or bare filter) and builds the AST.
1312
+ *
1313
+ * @param {object} state parser state
1314
+ * @returns {object} SELECT AST
1315
+ */
1316
+ function parseProgram(state) {
1317
+ const { context } = state;
1318
+ const calls = withoutContinuations(context, findCalls(context));
1319
+ let partial;
1320
+ let start;
1321
+ let end;
1322
+ if (calls.length === 0) {
1323
+ partial = readBareFilter(state);
1324
+ if (!partial) {
1325
+ fail(
1326
+ context,
1327
+ NO_LOOKUP_FOUND,
1328
+ 'No supported lookup was found. Paste a WSProxy retrieve call, DataExtension.Init(…).Rows.Retrieve(…), Platform.Function.LookupRows / LookupOrderedRows, or a filter object.',
1329
+ 0,
1330
+ context.text.length,
1331
+ );
1332
+ }
1333
+ ({ start, end } = partial);
1334
+ delete partial.start;
1335
+ delete partial.end;
1336
+ } else {
1337
+ const call = calls[0];
1338
+ if (calls.length > 1) {
1339
+ const second = calls[1];
1340
+ report(
1341
+ context,
1342
+ 'warning',
1343
+ MULTIPLE_LOOKUPS,
1344
+ 'The code contains more than one lookup; only the first one is converted.',
1345
+ second.start,
1346
+ tokenAt(context, second.index).end,
1347
+ );
1348
+ }
1349
+ context.pos = call.index + 1;
1350
+ const { args, end: callEnd } = parseArguments(context);
1351
+ start = call.start;
1352
+ end = callEnd;
1353
+ const callLoc = makeLoc(context, start, end);
1354
+ if (call.kind === 'wsproxy') {
1355
+ partial = readWsproxy(state, args, callLoc);
1356
+ } else if (call.kind === 'rows') {
1357
+ partial = readRowsRetrieve(state, call, args, callLoc);
1358
+ } else {
1359
+ partial = readLookupRows(state, call.kind === 'lookuporderedrows', args, callLoc);
1360
+ }
1361
+ }
1362
+ if (state.header.foldNotIn) {
1363
+ state.meta.foldNotIn = true;
1364
+ partial.where = foldNotIn(partial.where);
1365
+ }
1366
+ partial.where = applyLikeChecks(state, partial.where, findLikeChecks(context));
1367
+ return {
1368
+ type: 'select',
1369
+ top: partial.top,
1370
+ columns: partial.columns,
1371
+ from: partial.from,
1372
+ where: partial.where,
1373
+ orderBy: partial.orderBy,
1374
+ loc: makeLoc(context, start, end),
1375
+ };
1376
+ }
1377
+
1378
+ /**
1379
+ * Reads an SSJS data extension lookup back into the SQL AST. Never throws.
1380
+ *
1381
+ * Accepted: `proxy.retrieve("DataExtensionObject[Key]", [cols], filter[, opts[, props]])`,
1382
+ * `DataExtension.Init("Key").Rows.Retrieve(filter?)` (also via a variable),
1383
+ * `[Platform.Function.]LookupRows(name, col|[cols], value|[values])`,
1384
+ * `[Platform.Function.]LookupOrderedRows(name, count, "Col ASC", col|[cols], value|[values])`
1385
+ * and a bare filter object. Filters and arguments may be variables set to literals.
1386
+ * A `// SQL: FROM [Name] (external key Key)` / `// SQL: SELECT a, b` header comment supplies
1387
+ * what the code cannot carry (for WSProxy the SELECT header wins over the cols array); a
1388
+ * `NOT IN` in the header folds `<>` chains back into NOT IN. `sqlLike(row["Col"], "pattern")`
1389
+ * checks restore the exact LIKE pattern of the wider `like` filter, and a filter Value of
1390
+ * exactly one space reads back as ''.
1391
+ *
1392
+ * @param {string} text SSJS code
1393
+ * @returns {{ast: object|null, messages: import('./messages.js').Message[], meta: {target: string|null, deName?: string, deKey?: string, foldNotIn?: boolean}}} AST (null on error), messages and meta data
1394
+ */
1395
+ export function parseSsjs(text) {
1396
+ const source = typeof text === 'string' ? text : '';
1397
+ const context = createContext(source);
1398
+ const meta = { target: null };
1399
+ const ast = runParser(context, () => {
1400
+ tokenize(context, 'js', findScriptRegions(source));
1401
+ rejectEmpty(context);
1402
+ const state = {
1403
+ context,
1404
+ meta,
1405
+ header: readHeader(context),
1406
+ variables: collectVariables(context),
1407
+ likeFilters: new Map(),
1408
+ };
1409
+ return parseProgram(state);
1410
+ });
1411
+ return { ast, messages: context.messages, meta };
1412
+ }