@openrewrite/rewrite 8.103.0 → 8.104.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.
Files changed (59) hide show
  1. package/dist/java/tree.d.ts +3 -0
  2. package/dist/java/tree.d.ts.map +1 -1
  3. package/dist/java/tree.js +3 -1
  4. package/dist/java/tree.js.map +1 -1
  5. package/dist/javascript/add-import.d.ts +28 -0
  6. package/dist/javascript/add-import.d.ts.map +1 -1
  7. package/dist/javascript/add-import.js +48 -25
  8. package/dist/javascript/add-import.js.map +1 -1
  9. package/dist/javascript/assertions.d.ts.map +1 -1
  10. package/dist/javascript/assertions.js +60 -67
  11. package/dist/javascript/assertions.js.map +1 -1
  12. package/dist/javascript/binding.d.ts +5 -2
  13. package/dist/javascript/binding.d.ts.map +1 -1
  14. package/dist/javascript/binding.js +58 -14
  15. package/dist/javascript/binding.js.map +1 -1
  16. package/dist/javascript/format/prettier-config-loader.d.ts +1 -0
  17. package/dist/javascript/format/prettier-config-loader.d.ts.map +1 -1
  18. package/dist/javascript/format/prettier-config-loader.js +23 -4
  19. package/dist/javascript/format/prettier-config-loader.js.map +1 -1
  20. package/dist/javascript/member-spellings.d.ts +88 -0
  21. package/dist/javascript/member-spellings.d.ts.map +1 -0
  22. package/dist/javascript/member-spellings.js +357 -0
  23. package/dist/javascript/member-spellings.js.map +1 -0
  24. package/dist/javascript/package-manager.d.ts +3 -0
  25. package/dist/javascript/package-manager.d.ts.map +1 -1
  26. package/dist/javascript/package-manager.js +49 -0
  27. package/dist/javascript/package-manager.js.map +1 -1
  28. package/dist/javascript/project-parser.d.ts.map +1 -1
  29. package/dist/javascript/project-parser.js +70 -109
  30. package/dist/javascript/project-parser.js.map +1 -1
  31. package/dist/javascript/scope.d.ts +2 -0
  32. package/dist/javascript/scope.d.ts.map +1 -1
  33. package/dist/javascript/scope.js +2 -1
  34. package/dist/javascript/scope.js.map +1 -1
  35. package/dist/json/index.d.ts +1 -0
  36. package/dist/json/index.d.ts.map +1 -1
  37. package/dist/json/index.js +1 -0
  38. package/dist/json/index.js.map +1 -1
  39. package/dist/json/path-matcher.d.ts +29 -0
  40. package/dist/json/path-matcher.d.ts.map +1 -0
  41. package/dist/json/path-matcher.js +974 -0
  42. package/dist/json/path-matcher.js.map +1 -0
  43. package/dist/rewrite-javascript-version.txt +1 -1
  44. package/dist/rpc/request/parse-project.d.ts.map +1 -1
  45. package/dist/rpc/request/parse-project.js +20 -23
  46. package/dist/rpc/request/parse-project.js.map +1 -1
  47. package/package.json +1 -1
  48. package/src/java/tree.ts +2 -0
  49. package/src/javascript/add-import.ts +58 -30
  50. package/src/javascript/assertions.ts +43 -57
  51. package/src/javascript/binding.ts +72 -17
  52. package/src/javascript/format/prettier-config-loader.ts +22 -3
  53. package/src/javascript/member-spellings.ts +374 -0
  54. package/src/javascript/package-manager.ts +51 -0
  55. package/src/javascript/project-parser.ts +17 -50
  56. package/src/javascript/scope.ts +2 -2
  57. package/src/json/index.ts +1 -0
  58. package/src/json/path-matcher.ts +1092 -0
  59. package/src/rpc/request/parse-project.ts +22 -32
@@ -0,0 +1,1092 @@
1
+ /*
2
+ * Copyright 2026 the original author or authors.
3
+ * <p>
4
+ * Licensed under the Moderne Source Available License (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ * <p>
8
+ * https://docs.moderne.io/licensing/moderne-source-available-license
9
+ * <p>
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import {Cursor, isTree, Tree} from "../tree";
17
+ import {getMemberKeyName, Json} from "./tree";
18
+
19
+ /**
20
+ * Matches a cursor location against a JsonPath expression, such as `$.sap.ui5.dependencies.libs.*`.
21
+ *
22
+ * A port of `org.openrewrite.json.JsonPathMatcher`, supporting the same subset of JsonPath with the same results:
23
+ * `$`, `.key`, `['key']`, `*`, `..`, array indexes and slices, and `?()` filters using `==`, `!=`, `=~`,
24
+ * `contains`, `!`, `&&` and `||`.
25
+ */
26
+ export class JsonPathMatcher {
27
+ private readonly jsonPath: string;
28
+ private parsed?: JsonPathNode;
29
+
30
+ constructor(jsonPath: string) {
31
+ this.jsonPath = jsonPath.endsWith(".") && jsonPath.length > 1 ?
32
+ jsonPath.substring(0, jsonPath.length - 1) :
33
+ jsonPath;
34
+ }
35
+
36
+ /**
37
+ * What the expression selects, evaluated along the path from the document root to the cursor: a
38
+ * `Json` element, an array of them, or `undefined` when nothing matches.
39
+ *
40
+ * @throws Error when the expression is not valid JsonPath
41
+ */
42
+ find<T = unknown>(cursor: Cursor): T | undefined {
43
+ return this.find0(cursor, resolvedAncestors(cursor)) as T | undefined;
44
+ }
45
+
46
+ /**
47
+ * Whether the element at the cursor is one that the expression selects.
48
+ *
49
+ * @throws Error when the expression is not valid JsonPath
50
+ */
51
+ matches(cursor: Cursor): boolean {
52
+ const result = this.find0(cursor, resolvedAncestors(cursor));
53
+ if (result === undefined) {
54
+ return false;
55
+ }
56
+ return Array.isArray(result) ?
57
+ result.some(r => javaEquals(r, cursor.value)) :
58
+ javaEquals(result, cursor.value);
59
+ }
60
+
61
+ private find0(cursor: Cursor, cursorPath: Tree[]): unknown {
62
+ if (cursorPath.length === 0) {
63
+ return undefined;
64
+ }
65
+ const start = this.jsonPath.startsWith(".") && !this.jsonPath.startsWith("..") ?
66
+ cursor.value :
67
+ cursorPath[0];
68
+ const parsed = this.parse();
69
+ return new Evaluator(cursorPath, start, false).visit(parsed) ?? undefined;
70
+ }
71
+
72
+ private parse(): JsonPathNode {
73
+ if (!this.parsed) {
74
+ this.parsed = new JsonPathParser(this.jsonPath).parse();
75
+ }
76
+ return this.parsed;
77
+ }
78
+ }
79
+
80
+ function resolvedAncestors(cursor: Cursor): Tree[] {
81
+ const path: Tree[] = [];
82
+ for (let c: Cursor | undefined = cursor; c; c = c.parent) {
83
+ if (isTree(c.value)) {
84
+ path.unshift(c.value);
85
+ }
86
+ }
87
+ return path;
88
+ }
89
+
90
+ function javaEquals(a: any, b: any): boolean {
91
+ if (a === b) {
92
+ return true;
93
+ }
94
+ if (Array.isArray(a) && Array.isArray(b)) {
95
+ return a.length === b.length && a.every((e, i) => javaEquals(e, b[i]));
96
+ }
97
+ return isTree(a) && isTree(b) && a.kind === b.kind && a.id === b.id;
98
+ }
99
+
100
+ interface JsonPathNode {
101
+ kind: "jsonPath";
102
+ root: boolean;
103
+ startsWithBracket: boolean;
104
+ expressions: ExpressionNode[];
105
+ }
106
+
107
+ interface ExpressionNode {
108
+ kind: "expression";
109
+ child: DotOperatorNode | RecursiveDescentNode | BracketNode;
110
+ }
111
+
112
+ interface DotOperatorNode {
113
+ kind: "dotOperator";
114
+ child: BracketNode | PropertyNode | WildcardNode;
115
+ }
116
+
117
+ interface RecursiveDescentNode {
118
+ kind: "recursiveDescent";
119
+ first: boolean;
120
+ child: DotOperatorNode;
121
+ }
122
+
123
+ interface BracketNode {
124
+ kind: "bracket";
125
+ properties: PropertyNode[];
126
+ slice?: SliceNode;
127
+ indexes?: string[];
128
+ filter?: FilterNode;
129
+ }
130
+
131
+ interface PropertyNode {
132
+ kind: "property";
133
+ name: string;
134
+ }
135
+
136
+ interface WildcardNode {
137
+ kind: "wildcard";
138
+ }
139
+
140
+ interface SliceNode {
141
+ kind: "slice";
142
+ first?: number;
143
+ last?: number;
144
+ start?: number;
145
+ end?: number;
146
+ }
147
+
148
+ interface FilterNode {
149
+ kind: "filter";
150
+ expressions: FilterExpressionNode[];
151
+ }
152
+
153
+ interface FilterExpressionNode {
154
+ kind: "filterExpression";
155
+ child: BinaryNode | RegexNode | ContainsNode | UnaryNode | NegationNode;
156
+ }
157
+
158
+ type Operand = BinaryNode | RegexNode | ContainsNode | NegationNode | UnaryNode | LiteralNode;
159
+
160
+ interface BinaryNode {
161
+ kind: "binary";
162
+ operator: "&&" | "||" | "==" | "!=";
163
+ left: Operand;
164
+ right: Operand;
165
+ }
166
+
167
+ interface RegexNode {
168
+ kind: "regex";
169
+ unary: UnaryNode;
170
+ pattern: RegExp;
171
+ }
172
+
173
+ interface ContainsNode {
174
+ kind: "contains";
175
+ unaryFirst: boolean;
176
+ unary: UnaryNode;
177
+ literal: LiteralNode;
178
+ }
179
+
180
+ interface NegationNode {
181
+ kind: "negation";
182
+ filterExpression?: FilterExpressionNode;
183
+ unary?: UnaryNode;
184
+ }
185
+
186
+ interface UnaryNode {
187
+ kind: "unary";
188
+ at: boolean;
189
+ name?: string;
190
+ jsonPath?: JsonPathNode;
191
+ /** The text of the expression's third token, which Java's `contains` takes as the key to look up. */
192
+ thirdToken?: string;
193
+ lastToken: string;
194
+ }
195
+
196
+ interface LiteralNode {
197
+ kind: "literal";
198
+ value: string | boolean | null | JsonPathNumber;
199
+ }
200
+
201
+ type PathNode = JsonPathNode | ExpressionNode | DotOperatorNode | RecursiveDescentNode | BracketNode |
202
+ PropertyNode | WildcardNode | SliceNode | FilterNode | FilterExpressionNode | Operand;
203
+
204
+ const DECIMAL = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/;
205
+
206
+ class JsonPathNumber {
207
+ private readonly canonical: string;
208
+
209
+ constructor(readonly text: string) {
210
+ const [, sign, int, fraction = "", exponent = "0"] = DECIMAL.exec(text)!;
211
+ const digits = (int + fraction).replace(/^0+/, "");
212
+ const significant = digits.replace(/0+$/, "");
213
+ this.canonical = significant.length === 0 ? "0" :
214
+ `${sign === "-" ? "-" : ""}${significant}e${Number(exponent) - fraction.length + digits.length - significant.length}`;
215
+ }
216
+
217
+ equals(other: JsonPathNumber): boolean {
218
+ return this.canonical === other.canonical;
219
+ }
220
+
221
+ toString(): string {
222
+ return this.text;
223
+ }
224
+ }
225
+
226
+ function literalValue(literal: Json.Literal): unknown {
227
+ if (typeof literal.value === "number" && Number.isFinite(literal.value) &&
228
+ /\d/.test(literal.source) && DECIMAL.test(literal.source)) {
229
+ return new JsonPathNumber(literal.source);
230
+ }
231
+ return literal.value ?? null;
232
+ }
233
+
234
+ function is<K extends keyof typeof Json.Kind>(o: any, kind: K): boolean {
235
+ return o != null && typeof o === "object" && !Array.isArray(o) && o.kind === Json.Kind[kind];
236
+ }
237
+
238
+ function membersOf(object: Json.Object): Json[] {
239
+ return object.members.map(m => m.element);
240
+ }
241
+
242
+ function valuesOf(array: Json.Array): Json[] {
243
+ return array.values.map(v => v.element);
244
+ }
245
+
246
+ function keyOf(member: Json.Member): string | undefined {
247
+ const key = getMemberKeyName(member);
248
+ return key === undefined ? undefined : escapeUnpairedSurrogates(key);
249
+ }
250
+
251
+ function flatten(results: any[]): any[] {
252
+ return results.flatMap(r => Array.isArray(r) ? r : [r]);
253
+ }
254
+
255
+ function getResultFromList(results: any): any {
256
+ if (Array.isArray(results)) {
257
+ if (results.length === 0) {
258
+ return undefined;
259
+ } else if (results.length === 1) {
260
+ return results[0];
261
+ }
262
+ }
263
+ return results;
264
+ }
265
+
266
+ function collectDescendants(node: any, descendants: any[]): void {
267
+ if (Array.isArray(node)) {
268
+ for (const o of node) {
269
+ collectDescendants(o, descendants);
270
+ }
271
+ return;
272
+ }
273
+ for (const child of childrenOf(node)) {
274
+ descendants.push(child);
275
+ collectDescendants(child, descendants);
276
+ }
277
+ }
278
+
279
+ function childrenOf(node: any): Json[] {
280
+ if (is(node, "Member")) {
281
+ return childrenOf((node as Json.Member).value);
282
+ } else if (is(node, "Object")) {
283
+ return membersOf(node);
284
+ } else if (is(node, "Array")) {
285
+ return valuesOf(node);
286
+ }
287
+ return [];
288
+ }
289
+
290
+ function notEmpty(result: any): boolean {
291
+ return result != null && (!Array.isArray(result) || result.length > 0);
292
+ }
293
+
294
+ class Evaluator {
295
+ constructor(private readonly cursorPath: Tree[],
296
+ private scope: any,
297
+ private readonly isRecursiveDescent: boolean) {
298
+ }
299
+
300
+ visit(node: PathNode): any {
301
+ switch (node.kind) {
302
+ case "jsonPath":
303
+ return this.visitJsonPath(node);
304
+ case "expression":
305
+ case "dotOperator":
306
+ case "filterExpression":
307
+ return this.visitChildren([node.child]);
308
+ case "filter":
309
+ return this.visitChildren(node.expressions);
310
+ case "recursiveDescent":
311
+ return this.visitRecursiveDescent(node);
312
+ case "bracket":
313
+ return this.visitBracketOperator(node);
314
+ case "property":
315
+ return this.visitProperty(node);
316
+ case "wildcard":
317
+ return this.visitWildcard(node);
318
+ case "slice":
319
+ return this.visitSlice(node);
320
+ case "binary":
321
+ return this.visitBinaryExpression(node);
322
+ case "regex":
323
+ return this.visitRegexExpression(node);
324
+ case "contains":
325
+ return this.visitContainsExpression(node);
326
+ case "negation":
327
+ return this.visitNegationExpression(node);
328
+ case "unary":
329
+ return this.visitUnaryExpression(node);
330
+ case "literal":
331
+ return node.value;
332
+ }
333
+ }
334
+
335
+ private visitChildren(children: PathNode[]): any {
336
+ let result = this.scope;
337
+ for (const child of children) {
338
+ if (this.scope == null) {
339
+ break;
340
+ }
341
+ result = this.scope = this.visit(child);
342
+ }
343
+ return result;
344
+ }
345
+
346
+ private visitJsonPath(node: JsonPathNode): any {
347
+ if (node.root || node.startsWithBracket) {
348
+ this.scope = this.cursorPath.find(t => is(t, "Object")) ??
349
+ (this.cursorPath.find(t => is(t, "Document") && is((t as Json.Document).value, "Object")) as Json.Document | undefined)?.value;
350
+ }
351
+ return this.visitChildren(node.expressions);
352
+ }
353
+
354
+ private visitRecursiveDescent(node: RecursiveDescentNode): any {
355
+ if (this.scope == null) {
356
+ return undefined;
357
+ }
358
+ const wildcard = node.child.child.kind === "wildcard";
359
+ if (node.first) {
360
+ const results: any[] = [];
361
+ for (const path of this.cursorPath) {
362
+ const result = new Evaluator(this.cursorPath, path, false).visit(node.child);
363
+ if (wildcard && Array.isArray(result)) {
364
+ results.push(...result);
365
+ } else if (result != null) {
366
+ results.push(result);
367
+ }
368
+ }
369
+ return results;
370
+ } else if (wildcard) {
371
+ const descendants: any[] = [];
372
+ collectDescendants(this.scope, descendants);
373
+ return getResultFromList(descendants);
374
+ }
375
+ return new Evaluator(this.cursorPath, this.scope, true).visit(node.child);
376
+ }
377
+
378
+ private visitBracketOperator(node: BracketNode): any {
379
+ if (node.properties.length > 0) {
380
+ if (node.properties.length === 1) {
381
+ return this.visitProperty(node.properties[0]);
382
+ }
383
+ return node.properties.map(p => this.visitProperty(p));
384
+ } else if (node.slice) {
385
+ return this.visitSlice(node.slice);
386
+ } else if (node.indexes) {
387
+ return this.visitIndexes(node.indexes);
388
+ } else if (node.filter) {
389
+ return this.visit(node.filter);
390
+ }
391
+ return undefined;
392
+ }
393
+
394
+ private elementsInScope(): any[] | undefined {
395
+ if (Array.isArray(this.scope)) {
396
+ return this.scope;
397
+ } else if (is(this.scope, "Array")) {
398
+ return valuesOf(this.scope);
399
+ } else if (is(this.scope, "Member")) {
400
+ this.scope = this.scope.value;
401
+ return this.elementsInScope();
402
+ }
403
+ return [];
404
+ }
405
+
406
+ private visitSlice(node: SliceNode): any {
407
+ const results = this.elementsInScope()!;
408
+ let start = 0;
409
+ let limit = Infinity;
410
+ if (node.first !== undefined) {
411
+ limit = node.first;
412
+ } else if (node.last !== undefined) {
413
+ start = Math.max(0, results.length - node.last);
414
+ } else if (node.start !== undefined) {
415
+ start = node.start;
416
+ limit = node.end !== undefined ? node.end + 1 : limit;
417
+ }
418
+ return results.slice(start, start + limit);
419
+ }
420
+
421
+ private visitIndexes(indexes: string[]): any {
422
+ const results = this.elementsInScope()!;
423
+ const selected: any[] = [];
424
+ for (const index of indexes) {
425
+ for (let i = 0; i < results.length; i++) {
426
+ if (index === String(i)) {
427
+ selected.push(results[i]);
428
+ }
429
+ }
430
+ }
431
+ return getResultFromList(selected);
432
+ }
433
+
434
+ private mapScope(elements: any[], visit: () => any): any[] {
435
+ return elements
436
+ .map(o => {
437
+ this.scope = o;
438
+ return visit();
439
+ })
440
+ .filter(r => r != null);
441
+ }
442
+
443
+ private visitProperty(node: PropertyNode): any {
444
+ const scope = this.scope;
445
+ if (is(scope, "Member")) {
446
+ const member = scope as Json.Member;
447
+ const key = keyOf(member);
448
+ if (this.isRecursiveDescent) {
449
+ const matches: any[] = [];
450
+ if (key === node.name) {
451
+ matches.push(member);
452
+ }
453
+ this.scope = member.value;
454
+ const result = getResultFromList(this.visitProperty(node));
455
+ if (result != null) {
456
+ matches.push(result);
457
+ }
458
+ return getResultFromList(matches);
459
+ } else if (is(member.value, "Literal")) {
460
+ return key === node.name ? member : undefined;
461
+ }
462
+ this.scope = member.value;
463
+ return this.visitProperty(node);
464
+ } else if (is(scope, "Object")) {
465
+ const object = scope as Json.Object;
466
+ if (this.isRecursiveDescent) {
467
+ this.scope = membersOf(object);
468
+ return getResultFromList(this.visitProperty(node));
469
+ }
470
+ for (const json of membersOf(object)) {
471
+ if (is(json, "Member") && keyOf(json as Json.Member) === node.name) {
472
+ return json;
473
+ }
474
+ }
475
+ } else if (is(scope, "Array")) {
476
+ return getResultFromList(this.mapScope(valuesOf(scope), () => this.visitProperty(node)));
477
+ } else if (Array.isArray(scope)) {
478
+ return getResultFromList(flatten(this.mapScope(scope, () => this.visitProperty(node))));
479
+ }
480
+ return undefined;
481
+ }
482
+
483
+ private visitWildcard(node: WildcardNode): any {
484
+ const scope = this.scope;
485
+ if (is(scope, "Member")) {
486
+ const value = (scope as Json.Member).value;
487
+ if (is(value, "Object")) {
488
+ return getResultFromList(membersOf(value as Json.Object));
489
+ } else if (is(value, "Array")) {
490
+ return getResultFromList(valuesOf(value as Json.Array));
491
+ }
492
+ return undefined;
493
+ } else if (Array.isArray(scope)) {
494
+ return getResultFromList(flatten(this.mapScope(scope, () => this.visitWildcard(node))));
495
+ } else if (is(scope, "Object")) {
496
+ return membersOf(scope);
497
+ } else if (is(scope, "Array")) {
498
+ return this.mapScope(valuesOf(scope), () => this.visitWildcard(node));
499
+ }
500
+ return undefined;
501
+ }
502
+
503
+ private visitUnaryExpression(node: UnaryNode): any {
504
+ if (node.at) {
505
+ const scope = this.scope;
506
+ if (is(scope, "Literal")) {
507
+ if (node.name === undefined) {
508
+ return scope;
509
+ }
510
+ } else if (is(scope, "Member")) {
511
+ const member = scope as Json.Member;
512
+ if (node.name !== undefined && keyOf(member) === node.name) {
513
+ return member;
514
+ }
515
+ this.scope = member.value;
516
+ return getResultFromList(this.visitUnaryExpression(node));
517
+ } else if (is(scope, "Object")) {
518
+ for (const json of membersOf(scope)) {
519
+ if (is(json, "Member") && node.name !== undefined && keyOf(json as Json.Member) === node.name) {
520
+ return scope;
521
+ }
522
+ }
523
+ } else if (is(scope, "Array")) {
524
+ this.scope = valuesOf(scope);
525
+ return this.visitUnaryExpression(node);
526
+ } else if (Array.isArray(scope)) {
527
+ return getResultFromList(flatten(this.mapScope(scope, () => this.visitUnaryExpression(node))));
528
+ }
529
+ } else if (node.jsonPath) {
530
+ return this.getResultByKey(this.visit(node.jsonPath), node.lastToken);
531
+ }
532
+ return undefined;
533
+ }
534
+
535
+ private visitRegexExpression(node: RegexNode): any {
536
+ if (this.scope == null || Array.isArray(this.scope) && this.scope.length === 0) {
537
+ return undefined;
538
+ }
539
+ const lhs = this.visitUnaryExpression(node.unary);
540
+ if (Array.isArray(lhs)) {
541
+ return lhs.filter(match => this.getOperatorResult(match, "=~", node.pattern) != null);
542
+ }
543
+ return this.getOperatorResult(lhs, "=~", node.pattern);
544
+ }
545
+
546
+ private visitContainsExpression(node: ContainsNode): any {
547
+ const originalScope = this.scope;
548
+ if (node.unaryFirst) {
549
+ let lhs = this.visitUnaryExpression(node.unary);
550
+ const rhs = node.literal.value;
551
+ if (is(lhs, "Object") && rhs != null) {
552
+ lhs = this.getResultByKey(lhs, node.unary.thirdToken);
553
+ if (is(lhs, "Member")) {
554
+ const value = (lhs as Json.Member).value;
555
+ if (is(value, "Array")) {
556
+ if (valuesOf(value as Json.Array).some(o => is(o, "Literal") &&
557
+ String(literalValue(o as Json.Literal)).includes(String(rhs)))) {
558
+ return originalScope;
559
+ }
560
+ } else if (is(value, "Literal") && String(literalValue(value as Json.Literal)).includes(String(rhs))) {
561
+ return originalScope;
562
+ }
563
+ }
564
+ }
565
+ } else {
566
+ const lhs = node.literal.value;
567
+ let rhs = this.visitUnaryExpression(node.unary);
568
+ if (is(rhs, "Object") && lhs != null) {
569
+ rhs = this.getResultByKey(rhs, node.unary.thirdToken);
570
+ if (is(rhs, "Member")) {
571
+ const value = (rhs as Json.Member).value;
572
+ if (is(value, "Literal") && String(literalValue(value as Json.Literal)).includes(String(lhs))) {
573
+ return originalScope;
574
+ }
575
+ }
576
+ }
577
+ }
578
+ return undefined;
579
+ }
580
+
581
+ private visitNegationExpression(node: NegationNode): any {
582
+ const originalScope = this.scope;
583
+ const inner = () => node.filterExpression ?
584
+ this.visit(node.filterExpression) :
585
+ this.visitUnaryExpression(node.unary!);
586
+
587
+ let elements: any[] | undefined;
588
+ if (Array.isArray(originalScope)) {
589
+ elements = originalScope;
590
+ } else if (is(originalScope, "Array")) {
591
+ elements = valuesOf(originalScope);
592
+ } else if (is(originalScope, "Member") && is(originalScope.value, "Array")) {
593
+ elements = valuesOf(originalScope.value);
594
+ }
595
+
596
+ if (elements) {
597
+ const results: any[] = [];
598
+ for (const element of elements) {
599
+ this.scope = element;
600
+ if (!notEmpty(inner())) {
601
+ results.push(element);
602
+ }
603
+ }
604
+ this.scope = originalScope;
605
+ return getResultFromList(results);
606
+ }
607
+
608
+ const matched = notEmpty(inner());
609
+ this.scope = originalScope;
610
+ return matched ? undefined : originalScope;
611
+ }
612
+
613
+ private visitBinaryExpression(node: BinaryNode): any {
614
+ if (node.operator === "&&" || node.operator === "||") {
615
+ const scopeOfLogicalOp = this.scope;
616
+ const lhs = this.visit(node.left);
617
+ this.scope = scopeOfLogicalOp;
618
+ const rhs = this.visit(node.right);
619
+ if (node.operator === "&&" && notEmpty(lhs) && notEmpty(rhs)) {
620
+ if (!Array.isArray(lhs) && isTree(lhs)) {
621
+ return rhs;
622
+ } else if (!Array.isArray(rhs) && isTree(rhs)) {
623
+ return lhs;
624
+ }
625
+ if (Array.isArray(lhs) && Array.isArray(rhs) && lhs.length !== rhs.length) {
626
+ return lhs.length < rhs.length ? lhs : rhs;
627
+ }
628
+ return scopeOfLogicalOp;
629
+ } else if (node.operator === "||" && (notEmpty(lhs) || notEmpty(rhs))) {
630
+ return scopeOfLogicalOp;
631
+ }
632
+ return undefined;
633
+ }
634
+
635
+ const originalScope = this.scope;
636
+ const lhs = this.visit(node.left);
637
+ const rhs = this.visit(node.right);
638
+ if (Array.isArray(lhs)) {
639
+ return lhs.filter(match => this.getOperatorResult(match, node.operator, rhs) != null);
640
+ } else if (is(originalScope, "Member")) {
641
+ if (this.getOperatorResult(lhs, node.operator, rhs) != null) {
642
+ return originalScope;
643
+ }
644
+ return undefined;
645
+ }
646
+ return this.getOperatorResult(lhs, node.operator, rhs);
647
+ }
648
+
649
+ private getOperatorResult(lhs: any, operator: string, rhs: any): Json | undefined {
650
+ if (is(lhs, "Member")) {
651
+ const value = (lhs as Json.Member).value;
652
+ if (is(value, "Literal") && this.checkObjectEquality(literalValue(value as Json.Literal), operator, rhs)) {
653
+ return lhs;
654
+ }
655
+ } else if (is(lhs, "Object")) {
656
+ for (const json of membersOf(lhs)) {
657
+ if (is(json, "Member")) {
658
+ const value = (json as Json.Member).value;
659
+ if (is(value, "Literal") && this.checkObjectEquality(literalValue(value as Json.Literal), operator, rhs)) {
660
+ return lhs;
661
+ }
662
+ }
663
+ }
664
+ } else if (is(lhs, "Literal")) {
665
+ if (this.checkObjectEquality(literalValue(lhs), operator, rhs)) {
666
+ return lhs;
667
+ }
668
+ }
669
+ return undefined;
670
+ }
671
+
672
+ private checkObjectEquality(lhs: unknown, operator: string, rhs: any): boolean {
673
+ switch (operator) {
674
+ case "==":
675
+ return valueEquals(lhs, rhs);
676
+ case "!=":
677
+ return !valueEquals(lhs, rhs);
678
+ case "=~":
679
+ return lhs != null && (rhs as RegExp).test(String(lhs));
680
+ }
681
+ return false;
682
+ }
683
+
684
+ private getResultByKey(result: any, key: string | undefined): any {
685
+ if (is(result, "Object")) {
686
+ for (const json of membersOf(result)) {
687
+ if (is(json, "Member") && is((json as Json.Member).key.element, "Literal") &&
688
+ keyOf(json as Json.Member) === key) {
689
+ return json;
690
+ }
691
+ }
692
+ } else if (is(result, "Member")) {
693
+ const member = result as Json.Member;
694
+ if (is(member.value, "Literal")) {
695
+ return keyOf(member) === key ? member : undefined;
696
+ }
697
+ } else if (Array.isArray(result)) {
698
+ for (const o of result) {
699
+ const r = this.getResultByKey(o, key);
700
+ if (r != null) {
701
+ return r;
702
+ }
703
+ }
704
+ }
705
+ return undefined;
706
+ }
707
+
708
+ }
709
+
710
+ function valueEquals(lhs: unknown, rhs: unknown): boolean {
711
+ if (lhs instanceof JsonPathNumber && rhs instanceof JsonPathNumber) {
712
+ return lhs.equals(rhs);
713
+ }
714
+ return lhs === rhs;
715
+ }
716
+
717
+ type TokenType =
718
+ "$" | "." | ".." | "*" | "[" | "]" | "(" | ")" | "@" | "?" | ":" | "!" |
719
+ "logical" | "equality" | "regex" | "string" | "positive" | "negative" | "numeric" | "identifier" |
720
+ "contains" | "true" | "false" | "null" | "eof";
721
+
722
+ interface Token {
723
+ type: TokenType;
724
+ text: string;
725
+ offset: number;
726
+ }
727
+
728
+ const KEYWORDS = new Map<string, TokenType>([["contains", "contains"], ["true", "true"], ["false", "false"], ["null", "null"]]);
729
+
730
+ function tokenize(input: string): Token[] {
731
+ const tokens: Token[] = [];
732
+ const error = (offset: number) =>
733
+ new Error(`Syntax error at offset ${offset} in JsonPath '${input}'`);
734
+ let i = 0;
735
+ while (i < input.length) {
736
+ const c = input[i];
737
+ const start = i;
738
+ if (/[ \t\n\r\f,]/.test(c)) {
739
+ i++;
740
+ continue;
741
+ }
742
+ const rest = input.substring(i);
743
+ let match: RegExpExecArray | null;
744
+ if ((match = /^=~[ \t]?'/.exec(rest))) {
745
+ const close = input.indexOf("'", i + match[0].length);
746
+ if (close < 0) {
747
+ throw error(i);
748
+ }
749
+ tokens.push({type: "regex", text: input.substring(i + match[0].length, close).replace(/^[ \t]+/, ""), offset: start});
750
+ i = close + 1;
751
+ } else if (rest.startsWith("&&") || rest.startsWith("||")) {
752
+ tokens.push({type: "logical", text: rest.substring(0, 2), offset: start});
753
+ i += 2;
754
+ } else if (rest.startsWith("==") || rest.startsWith("!=")) {
755
+ tokens.push({type: "equality", text: rest.substring(0, 2), offset: start});
756
+ i += 2;
757
+ } else if (rest.startsWith("..")) {
758
+ tokens.push({type: "..", text: "..", offset: start});
759
+ i += 2;
760
+ } else if ("$.*[]()@?:!".includes(c)) {
761
+ tokens.push({type: c as TokenType, text: c, offset: start});
762
+ i++;
763
+ } else if (c === "'" || c === '"') {
764
+ let j = i + 1;
765
+ while (j < input.length && input[j] !== c) {
766
+ j += input[j] === "\\" ? 2 : 1;
767
+ }
768
+ if (j >= input.length) {
769
+ throw error(i);
770
+ }
771
+ tokens.push({type: "string", text: input.substring(i, j + 1), offset: start});
772
+ i = j + 1;
773
+ } else if ((match = /^(-?)\d+([eE][+-]?\d+)?/.exec(rest))) {
774
+ const type: TokenType = match[2] ? "numeric" : match[1] ? "negative" : "positive";
775
+ tokens.push({type, text: match[0], offset: start});
776
+ i += match[0].length;
777
+ } else if ((match = /^[_A-Za-z][_A-Za-z0-9-]*/.exec(rest))) {
778
+ tokens.push({type: KEYWORDS.get(match[0]) ?? "identifier", text: match[0], offset: start});
779
+ i += match[0].length;
780
+ } else {
781
+ throw error(i);
782
+ }
783
+ }
784
+ tokens.push({type: "eof", text: "", offset: input.length});
785
+ return tokens;
786
+ }
787
+
788
+ class JsonPathParser {
789
+ private readonly tokens: Token[];
790
+ private pos = 0;
791
+
792
+ constructor(private readonly input: string) {
793
+ this.tokens = tokenize(input);
794
+ }
795
+
796
+ parse(): JsonPathNode {
797
+ const jsonPath = this.jsonPath();
798
+ if (this.peek().type !== "eof") {
799
+ throw this.error();
800
+ }
801
+ return jsonPath;
802
+ }
803
+
804
+ private peek(ahead = 0): Token {
805
+ return this.tokens[Math.min(this.pos + ahead, this.tokens.length - 1)];
806
+ }
807
+
808
+ private next(): Token {
809
+ return this.tokens[this.pos++];
810
+ }
811
+
812
+ private expect(type: TokenType): Token {
813
+ if (this.peek().type !== type) {
814
+ throw this.error();
815
+ }
816
+ return this.next();
817
+ }
818
+
819
+ private error(): Error {
820
+ const token = this.peek();
821
+ return new Error(token.type === "eof" ?
822
+ `Syntax error: unexpected end of JsonPath '${this.input}'` :
823
+ `Syntax error: unexpected '${token.text}' at offset ${token.offset} in JsonPath '${this.input}'`);
824
+ }
825
+
826
+ private jsonPath(): JsonPathNode {
827
+ const root = this.peek().type === "$";
828
+ if (root) {
829
+ this.next();
830
+ }
831
+ const node: JsonPathNode = {
832
+ kind: "jsonPath",
833
+ root,
834
+ startsWithBracket: !root && this.peek().type === "[",
835
+ expressions: []
836
+ };
837
+ while (["." as TokenType, "..", "["].includes(this.peek().type)) {
838
+ node.expressions.push(this.expression(node.expressions.length === 0));
839
+ }
840
+ if (!root && node.expressions.length === 0) {
841
+ throw this.error();
842
+ }
843
+ return node;
844
+ }
845
+
846
+ private expression(first: boolean): ExpressionNode {
847
+ const token = this.next();
848
+ if (token.type === ".") {
849
+ return {kind: "expression", child: this.dotOperator()};
850
+ } else if (token.type === "..") {
851
+ return {kind: "expression", child: {kind: "recursiveDescent", first, child: this.dotOperator()}};
852
+ }
853
+ this.pos--;
854
+ return {kind: "expression", child: this.bracketOperator()};
855
+ }
856
+
857
+ private dotOperator(): DotOperatorNode {
858
+ const token = this.peek();
859
+ if (token.type === "[") {
860
+ return {kind: "dotOperator", child: this.bracketOperator()};
861
+ } else if (token.type === "*") {
862
+ this.next();
863
+ return {kind: "dotOperator", child: {kind: "wildcard"}};
864
+ }
865
+ return {kind: "dotOperator", child: this.property()};
866
+ }
867
+
868
+ private property(): PropertyNode {
869
+ const token = this.next();
870
+ if (token.type === "string") {
871
+ return {kind: "property", name: decode(token.text)};
872
+ } else if (token.type === "identifier" || KEYWORDS.has(token.text)) {
873
+ return {kind: "property", name: token.text};
874
+ }
875
+ this.pos--;
876
+ throw this.error();
877
+ }
878
+
879
+ private bracketOperator(): BracketNode {
880
+ this.expect("[");
881
+ const node: BracketNode = {kind: "bracket", properties: []};
882
+ const token = this.peek();
883
+ if (token.type === "?") {
884
+ this.next();
885
+ this.expect("(");
886
+ const expressions: FilterExpressionNode[] = [];
887
+ do {
888
+ expressions.push(this.filterExpression());
889
+ } while (this.peek().type !== ")");
890
+ this.expect(")");
891
+ node.filter = {kind: "filter", expressions};
892
+ } else if (token.type === ":") {
893
+ this.next();
894
+ node.slice = {kind: "slice", first: Number(this.expect("positive").text)};
895
+ } else if (token.type === "negative" && this.peek(1).type === ":") {
896
+ this.pos += 2;
897
+ node.slice = {kind: "slice", last: -Number(token.text)};
898
+ } else if (token.type === "positive" && this.peek(1).type === ":") {
899
+ this.pos += 2;
900
+ const end = this.peek().type === "positive" ? Number(this.next().text) : undefined;
901
+ node.slice = {kind: "slice", start: Number(token.text), end};
902
+ } else if (token.type === "positive") {
903
+ node.indexes = [];
904
+ while (this.peek().type === "positive") {
905
+ node.indexes.push(this.next().text);
906
+ }
907
+ } else if (token.type === "*") {
908
+ this.next();
909
+ node.slice = {kind: "slice"};
910
+ } else {
911
+ do {
912
+ node.properties.push(this.property());
913
+ } while (this.peek().type !== "]");
914
+ }
915
+ this.expect("]");
916
+ return node;
917
+ }
918
+
919
+ private filterExpression(): FilterExpressionNode {
920
+ let operand = this.operand();
921
+ if (this.peek().type === "logical") {
922
+ if (operand.kind === "unary") {
923
+ throw this.error();
924
+ }
925
+ while (this.peek().type === "logical") {
926
+ const operator = this.next().text as "&&" | "||";
927
+ const right = this.operand();
928
+ if (right.kind === "unary") {
929
+ throw this.error();
930
+ }
931
+ operand = {kind: "binary", operator, left: operand, right};
932
+ }
933
+ }
934
+ return {kind: "filterExpression", child: operand};
935
+ }
936
+
937
+ private operand(): BinaryNode | RegexNode | ContainsNode | NegationNode | UnaryNode {
938
+ const token = this.peek();
939
+ if (token.type === "!") {
940
+ this.next();
941
+ if (this.peek().type === "(") {
942
+ this.next();
943
+ const filterExpression = this.filterExpression();
944
+ this.expect(")");
945
+ return {kind: "negation", filterExpression};
946
+ }
947
+ return {kind: "negation", unary: this.unary()};
948
+ } else if (["string" as TokenType, "positive", "negative", "numeric", "true", "false", "null"].includes(token.type)) {
949
+ const literal = this.literal();
950
+ const operator = this.next();
951
+ if (operator.type === "equality") {
952
+ return {kind: "binary", operator: operator.text as "==" | "!=", left: literal, right: this.unary()};
953
+ } else if (operator.type === "contains") {
954
+ return {kind: "contains", unaryFirst: false, unary: this.unary(), literal};
955
+ }
956
+ this.pos--;
957
+ throw this.error();
958
+ }
959
+ const unary = this.unary();
960
+ const operator = this.peek();
961
+ if (operator.type === "equality") {
962
+ this.next();
963
+ return {kind: "binary", operator: operator.text as "==" | "!=", left: unary, right: this.literal()};
964
+ } else if (operator.type === "contains") {
965
+ this.next();
966
+ return {kind: "contains", unaryFirst: true, unary, literal: this.literal()};
967
+ } else if (operator.type === "regex") {
968
+ this.next();
969
+ return {kind: "regex", unary, pattern: new RegExp(`^(?:${operator.text})$`)};
970
+ }
971
+ return unary;
972
+ }
973
+
974
+ private unary(): UnaryNode {
975
+ const start = this.pos;
976
+ let node: UnaryNode;
977
+ if (this.peek().type === "@") {
978
+ this.next();
979
+ node = {kind: "unary", at: true, lastToken: ""};
980
+ if (this.peek().type === "." && this.peek(1).type !== "[") {
981
+ this.next();
982
+ node.name = this.property().name;
983
+ } else if (this.peek().type === "[" || this.peek().type === "." && this.peek(1).type === "[") {
984
+ if (this.peek().type === ".") {
985
+ this.next();
986
+ }
987
+ this.expect("[");
988
+ node.name = decode(this.expect("string").text);
989
+ this.expect("]");
990
+ }
991
+ node.thirdToken = this.pos - start > 2 ? this.tokens[start + 2].text : undefined;
992
+ } else {
993
+ node = {kind: "unary", at: false, jsonPath: this.jsonPath(), lastToken: ""};
994
+ }
995
+ node.lastToken = this.tokens[this.pos - 1].text;
996
+ return node;
997
+ }
998
+
999
+ private literal(): LiteralNode {
1000
+ const token = this.next();
1001
+ switch (token.type) {
1002
+ case "string":
1003
+ return {kind: "literal", value: decode(token.text)};
1004
+ case "positive":
1005
+ case "negative":
1006
+ case "numeric":
1007
+ return {kind: "literal", value: new JsonPathNumber(token.text)};
1008
+ case "true":
1009
+ case "false":
1010
+ return {kind: "literal", value: token.type === "true"};
1011
+ case "null":
1012
+ return {kind: "literal", value: null};
1013
+ }
1014
+ this.pos--;
1015
+ throw this.error();
1016
+ }
1017
+ }
1018
+
1019
+ /**
1020
+ * The string that a single- or double-quoted JSON5 literal stands for. Mirrors
1021
+ * `org.openrewrite.json.internal.JsonString.decode`.
1022
+ */
1023
+ function decode(literal: string): string {
1024
+ const body = literal.substring(1, literal.length - 1);
1025
+ if (!body.includes("\\")) {
1026
+ return body;
1027
+ }
1028
+ let out = "";
1029
+ for (let i = 0; i < body.length; i++) {
1030
+ const c = body[i];
1031
+ if (c !== "\\" || i + 1 === body.length) {
1032
+ out += c;
1033
+ continue;
1034
+ }
1035
+ const escaped = body[++i];
1036
+ switch (escaped) {
1037
+ case "b":
1038
+ out += "\b";
1039
+ break;
1040
+ case "f":
1041
+ out += "\f";
1042
+ break;
1043
+ case "n":
1044
+ out += "\n";
1045
+ break;
1046
+ case "r":
1047
+ out += "\r";
1048
+ break;
1049
+ case "t":
1050
+ out += "\t";
1051
+ break;
1052
+ case "v":
1053
+ out += "\v";
1054
+ break;
1055
+ case "0":
1056
+ out += "\0";
1057
+ break;
1058
+ case "x":
1059
+ case "u": {
1060
+ const digits = escaped === "x" ? 2 : 4;
1061
+ const hex = body.substring(i + 1, i + 1 + digits);
1062
+ if (hex.length === digits && /^[0-9a-fA-F]+$/.test(hex)) {
1063
+ out += String.fromCharCode(parseInt(hex, 16));
1064
+ i += digits;
1065
+ } else {
1066
+ out += "\\" + escaped;
1067
+ }
1068
+ break;
1069
+ }
1070
+ case "\r":
1071
+ if (body[i + 1] === "\n") {
1072
+ i++;
1073
+ }
1074
+ break;
1075
+ case "\n":
1076
+ case "
":
1077
+ case "
":
1078
+ break;
1079
+ default:
1080
+ out += escaped;
1081
+ }
1082
+ }
1083
+ return escapeUnpairedSurrogates(out);
1084
+ }
1085
+
1086
+ /**
1087
+ * Keeps a surrogate with no partner as a lower-case `\uXXXX` escape, as `JsonString.decode` and the parser's
1088
+ * literal values do. `getMemberKeyName` decodes keys from source and so yields the bare surrogate.
1089
+ */
1090
+ function escapeUnpairedSurrogates(value: string): string {
1091
+ return value.replace(/[\ud800-\udfff]/gu, surrogate => `\\u${surrogate.charCodeAt(0).toString(16)}`);
1092
+ }