hermes-parser 0.15.1 → 0.17.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,610 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ *
8
+ * @format
9
+ */
10
+
11
+ /**
12
+ * This transform strips Flow types that are not supported past Babel 7.
13
+ *
14
+ * It is expected that all transforms create valid ESTree AST output. If
15
+ * the transform requires outputting Babel specific AST nodes then it
16
+ * should live in `ConvertESTreeToBabel.js`
17
+ */
18
+ 'use strict';
19
+
20
+ Object.defineProperty(exports, "__esModule", {
21
+ value: true
22
+ });
23
+ exports.transformProgram = transformProgram;
24
+
25
+ var _SimpleTransform = require("../transform/SimpleTransform");
26
+
27
+ var _astNodeMutationHelpers = require("../transform/astNodeMutationHelpers");
28
+
29
+ var _SimpleTraverser = require("../traverse/SimpleTraverser");
30
+
31
+ var _createSyntaxError = require("../utils/createSyntaxError");
32
+
33
+ const nodeWith = _SimpleTransform.SimpleTransform.nodeWith; // Rely on the mapper to fix up parent relationships.
34
+
35
+ const EMPTY_PARENT = null;
36
+
37
+ function createDefaultPosition() {
38
+ return {
39
+ line: 1,
40
+ column: 0
41
+ };
42
+ }
43
+
44
+ function mapDeclareComponent(node) {
45
+ return {
46
+ type: 'DeclareVariable',
47
+ id: nodeWith(node.id, {
48
+ typeAnnotation: {
49
+ type: 'TypeAnnotation',
50
+ typeAnnotation: {
51
+ type: 'AnyTypeAnnotation',
52
+ loc: node.loc,
53
+ range: node.range,
54
+ parent: EMPTY_PARENT
55
+ },
56
+ loc: node.loc,
57
+ range: node.range,
58
+ parent: EMPTY_PARENT
59
+ }
60
+ }),
61
+ kind: 'const',
62
+ loc: node.loc,
63
+ range: node.range,
64
+ parent: node.parent
65
+ };
66
+ }
67
+
68
+ function getComponentParameterName(paramName) {
69
+ switch (paramName.type) {
70
+ case 'Identifier':
71
+ return paramName.name;
72
+
73
+ case 'Literal':
74
+ return paramName.value;
75
+
76
+ default:
77
+ throw (0, _createSyntaxError.createSyntaxError)(paramName, `Unknown Component parameter name type of "${paramName.type}"`);
78
+ }
79
+ }
80
+
81
+ function createPropsTypeAnnotation(loc, range) {
82
+ // Create empty loc for type annotation nodes
83
+ const createParamsTypeLoc = () => ({
84
+ loc: {
85
+ start: (loc == null ? void 0 : loc.start) != null ? loc.start : createDefaultPosition(),
86
+ end: (loc == null ? void 0 : loc.end) != null ? loc.end : createDefaultPosition()
87
+ },
88
+ range: range != null ? range : [0, 0],
89
+ parent: EMPTY_PARENT
90
+ });
91
+
92
+ return {
93
+ type: 'TypeAnnotation',
94
+ typeAnnotation: {
95
+ type: 'GenericTypeAnnotation',
96
+ id: {
97
+ type: 'Identifier',
98
+ name: '$ReadOnly',
99
+ optional: false,
100
+ typeAnnotation: null,
101
+ ...createParamsTypeLoc()
102
+ },
103
+ typeParameters: {
104
+ type: 'TypeParameterInstantiation',
105
+ params: [{
106
+ type: 'ObjectTypeAnnotation',
107
+ callProperties: [],
108
+ properties: [],
109
+ indexers: [],
110
+ internalSlots: [],
111
+ exact: false,
112
+ inexact: true,
113
+ ...createParamsTypeLoc()
114
+ }],
115
+ ...createParamsTypeLoc()
116
+ },
117
+ ...createParamsTypeLoc()
118
+ },
119
+ ...createParamsTypeLoc()
120
+ };
121
+ }
122
+
123
+ function mapComponentParameters(params) {
124
+ if (params.length === 0) {
125
+ return {
126
+ props: null,
127
+ ref: null
128
+ };
129
+ } // Optimize `component Foo(...props: Props) {}` to `function Foo(props: Props) {}
130
+
131
+
132
+ if (params.length === 1 && params[0].type === 'RestElement' && (params[0].argument.type === 'Identifier' || params[0].argument.type === 'ObjectPattern')) {
133
+ var _restElementArgument$, _restElementArgument$2;
134
+
135
+ const restElementArgument = params[0].argument;
136
+ return {
137
+ props: nodeWith(restElementArgument, {
138
+ typeAnnotation: createPropsTypeAnnotation((_restElementArgument$ = restElementArgument.typeAnnotation) == null ? void 0 : _restElementArgument$.loc, (_restElementArgument$2 = restElementArgument.typeAnnotation) == null ? void 0 : _restElementArgument$2.range)
139
+ }),
140
+ ref: null
141
+ };
142
+ } // Filter out any ref param and capture it's details.
143
+
144
+
145
+ let refParam = null;
146
+ const paramsWithoutRef = params.filter(param => {
147
+ if (param.type === 'ComponentParameter' && getComponentParameterName(param.name) === 'ref') {
148
+ refParam = param;
149
+ return false;
150
+ }
151
+
152
+ return true;
153
+ });
154
+ const propsProperties = paramsWithoutRef.map(mapComponentParameter);
155
+ let props = null;
156
+
157
+ if (propsProperties.length === 0) {
158
+ if (refParam == null) {
159
+ throw new Error('TransformReactScriptForBabel: Invalid state, ref should always be set at this point if props are empty');
160
+ }
161
+
162
+ const emptyParamsLoc = {
163
+ start: refParam.loc.start,
164
+ end: refParam.loc.start
165
+ };
166
+ const emptyParamsRange = [refParam.range[0], refParam.range[0]]; // no properties provided (must have had a single ref)
167
+
168
+ props = {
169
+ type: 'Identifier',
170
+ name: '_$$empty_props_placeholder$$',
171
+ optional: false,
172
+ typeAnnotation: createPropsTypeAnnotation(emptyParamsLoc, emptyParamsRange),
173
+ loc: emptyParamsLoc,
174
+ range: emptyParamsRange,
175
+ parent: EMPTY_PARENT
176
+ };
177
+ } else {
178
+ const lastPropsProperty = propsProperties[propsProperties.length - 1];
179
+ props = {
180
+ type: 'ObjectPattern',
181
+ properties: propsProperties,
182
+ typeAnnotation: createPropsTypeAnnotation({
183
+ start: lastPropsProperty.loc.end,
184
+ end: lastPropsProperty.loc.end
185
+ }, [lastPropsProperty.range[1], lastPropsProperty.range[1]]),
186
+ loc: {
187
+ start: propsProperties[0].loc.start,
188
+ end: lastPropsProperty.loc.end
189
+ },
190
+ range: [propsProperties[0].range[0], lastPropsProperty.range[1]],
191
+ parent: EMPTY_PARENT
192
+ };
193
+ }
194
+
195
+ let ref = null;
196
+
197
+ if (refParam != null) {
198
+ const refType = refParam.local;
199
+ ref = {
200
+ type: 'Identifier',
201
+ name: 'ref',
202
+ optional: false,
203
+ typeAnnotation: refType.type === 'AssignmentPattern' ? refType.left.typeAnnotation : refType.typeAnnotation,
204
+ loc: refParam.loc,
205
+ range: refParam.range,
206
+ parent: EMPTY_PARENT
207
+ };
208
+ }
209
+
210
+ return {
211
+ props,
212
+ ref
213
+ };
214
+ }
215
+
216
+ function mapComponentParameter(param) {
217
+ switch (param.type) {
218
+ case 'RestElement':
219
+ {
220
+ const a = nodeWith(param, {
221
+ typeAnnotation: null,
222
+ argument: nodeWith(param.argument, {
223
+ typeAnnotation: null
224
+ })
225
+ });
226
+ return a;
227
+ }
228
+
229
+ case 'ComponentParameter':
230
+ {
231
+ if (getComponentParameterName(param.name) === 'ref') {
232
+ throw (0, _createSyntaxError.createSyntaxError)(param, 'Component parameters named "ref" are currently not supported');
233
+ }
234
+
235
+ let value;
236
+
237
+ if (param.local.type === 'AssignmentPattern') {
238
+ value = nodeWith(param.local, {
239
+ left: nodeWith(param.local.left, {
240
+ typeAnnotation: null,
241
+ optional: false
242
+ })
243
+ });
244
+ } else {
245
+ value = nodeWith(param.local, {
246
+ typeAnnotation: null,
247
+ optional: false
248
+ });
249
+ } // Shorthand params
250
+
251
+
252
+ if (param.name.type === 'Identifier' && param.shorthand && (value.type === 'Identifier' || value.type === 'AssignmentPattern')) {
253
+ return {
254
+ type: 'Property',
255
+ key: param.name,
256
+ kind: 'init',
257
+ value,
258
+ method: false,
259
+ shorthand: true,
260
+ computed: false,
261
+ loc: param.loc,
262
+ range: param.range,
263
+ parent: EMPTY_PARENT
264
+ };
265
+ } // Complex params
266
+
267
+
268
+ return {
269
+ type: 'Property',
270
+ key: param.name,
271
+ kind: 'init',
272
+ value,
273
+ method: false,
274
+ shorthand: false,
275
+ computed: false,
276
+ loc: param.loc,
277
+ range: param.range,
278
+ parent: EMPTY_PARENT
279
+ };
280
+ }
281
+
282
+ default:
283
+ {
284
+ throw (0, _createSyntaxError.createSyntaxError)(param, `Unknown Component parameter type of "${param.type}"`);
285
+ }
286
+ }
287
+ }
288
+
289
+ function createForwardRefWrapper(originalComponent) {
290
+ const internalCompId = {
291
+ type: 'Identifier',
292
+ name: `${originalComponent.id.name}_withRef`,
293
+ optional: false,
294
+ typeAnnotation: null,
295
+ loc: originalComponent.id.loc,
296
+ range: originalComponent.id.range,
297
+ parent: EMPTY_PARENT
298
+ };
299
+ return {
300
+ forwardRefStatement: {
301
+ type: 'VariableDeclaration',
302
+ kind: 'const',
303
+ declarations: [{
304
+ type: 'VariableDeclarator',
305
+ id: (0, _astNodeMutationHelpers.shallowCloneNode)(originalComponent.id),
306
+ init: {
307
+ type: 'CallExpression',
308
+ callee: {
309
+ type: 'MemberExpression',
310
+ object: {
311
+ type: 'Identifier',
312
+ name: 'React',
313
+ optional: false,
314
+ typeAnnotation: null,
315
+ loc: originalComponent.loc,
316
+ range: originalComponent.range,
317
+ parent: EMPTY_PARENT
318
+ },
319
+ property: {
320
+ type: 'Identifier',
321
+ name: 'forwardRef',
322
+ optional: false,
323
+ typeAnnotation: null,
324
+ loc: originalComponent.loc,
325
+ range: originalComponent.range,
326
+ parent: EMPTY_PARENT
327
+ },
328
+ computed: false,
329
+ optional: false,
330
+ loc: originalComponent.loc,
331
+ range: originalComponent.range,
332
+ parent: EMPTY_PARENT
333
+ },
334
+ arguments: [(0, _astNodeMutationHelpers.shallowCloneNode)(internalCompId)],
335
+ typeArguments: null,
336
+ optional: false,
337
+ loc: originalComponent.loc,
338
+ range: originalComponent.range,
339
+ parent: EMPTY_PARENT
340
+ },
341
+ loc: originalComponent.loc,
342
+ range: originalComponent.range,
343
+ parent: EMPTY_PARENT
344
+ }],
345
+ loc: originalComponent.loc,
346
+ range: originalComponent.range,
347
+ parent: originalComponent.parent
348
+ },
349
+ internalCompId: internalCompId,
350
+ forwardRefCompId: originalComponent.id
351
+ };
352
+ }
353
+
354
+ function mapComponentDeclaration(node) {
355
+ // Create empty loc for return type annotation nodes
356
+ const createRendersTypeLoc = () => ({
357
+ loc: {
358
+ start: node.body.loc.end,
359
+ end: node.body.loc.end
360
+ },
361
+ range: [node.body.range[1], node.body.range[1]],
362
+ parent: EMPTY_PARENT
363
+ });
364
+
365
+ const returnType = {
366
+ type: 'TypeAnnotation',
367
+ typeAnnotation: {
368
+ type: 'GenericTypeAnnotation',
369
+ id: {
370
+ type: 'QualifiedTypeIdentifier',
371
+ qualification: {
372
+ type: 'Identifier',
373
+ name: 'React',
374
+ optional: false,
375
+ typeAnnotation: null,
376
+ ...createRendersTypeLoc()
377
+ },
378
+ id: {
379
+ type: 'Identifier',
380
+ name: 'Node',
381
+ optional: false,
382
+ typeAnnotation: null,
383
+ ...createRendersTypeLoc()
384
+ },
385
+ ...createRendersTypeLoc()
386
+ },
387
+ typeParameters: null,
388
+ ...createRendersTypeLoc()
389
+ },
390
+ ...createRendersTypeLoc()
391
+ };
392
+ const {
393
+ props,
394
+ ref
395
+ } = mapComponentParameters(node.params);
396
+ let forwardRefDetails = null;
397
+
398
+ if (ref != null) {
399
+ forwardRefDetails = createForwardRefWrapper(node);
400
+ }
401
+
402
+ const comp = {
403
+ type: 'FunctionDeclaration',
404
+ id: forwardRefDetails != null ? (0, _astNodeMutationHelpers.shallowCloneNode)(forwardRefDetails.internalCompId) : (0, _astNodeMutationHelpers.shallowCloneNode)(node.id),
405
+ __componentDeclaration: true,
406
+ typeParameters: node.typeParameters,
407
+ params: props == null ? [] : ref == null ? [props] : [props, ref],
408
+ returnType,
409
+ body: node.body,
410
+ async: false,
411
+ generator: false,
412
+ predicate: null,
413
+ loc: node.loc,
414
+ range: node.range,
415
+ parent: node.parent
416
+ };
417
+ return {
418
+ comp,
419
+ forwardRefDetails
420
+ };
421
+ }
422
+ /**
423
+ * Scan a list of statements and return the position of the
424
+ * first statement that contains a reference to a given component
425
+ * or null of no references were found.
426
+ */
427
+
428
+
429
+ function scanForFirstComponentReference(compName, bodyList) {
430
+ for (let i = 0; i < bodyList.length; i++) {
431
+ const bodyNode = bodyList[i];
432
+ let referencePos = null;
433
+
434
+ _SimpleTraverser.SimpleTraverser.traverse(bodyNode, {
435
+ enter(node) {
436
+ switch (node.type) {
437
+ case 'Identifier':
438
+ {
439
+ if (node.name === compName) {
440
+ // We found a reference, record it and stop.
441
+ referencePos = i;
442
+ throw _SimpleTraverser.SimpleTraverser.Break;
443
+ }
444
+ }
445
+ }
446
+ },
447
+
448
+ leave(_node) {}
449
+
450
+ });
451
+
452
+ if (referencePos != null) {
453
+ return referencePos;
454
+ }
455
+ }
456
+
457
+ return null;
458
+ }
459
+
460
+ function mapComponentDeclarationIntoList(node, newBody, insertExport) {
461
+ const {
462
+ comp,
463
+ forwardRefDetails
464
+ } = mapComponentDeclaration(node);
465
+
466
+ if (forwardRefDetails != null) {
467
+ // Scan for references to our component.
468
+ const referencePos = scanForFirstComponentReference(forwardRefDetails.forwardRefCompId.name, newBody); // If a reference is found insert the forwardRef statement before it (to simulate function hoisting).
469
+
470
+ if (referencePos != null) {
471
+ newBody.splice(referencePos, 0, forwardRefDetails.forwardRefStatement);
472
+ } else {
473
+ newBody.push(forwardRefDetails.forwardRefStatement);
474
+ }
475
+
476
+ newBody.push(comp);
477
+
478
+ if (insertExport != null) {
479
+ newBody.push(insertExport(forwardRefDetails.forwardRefCompId));
480
+ }
481
+
482
+ return;
483
+ }
484
+
485
+ newBody.push(insertExport != null ? insertExport(comp) : comp);
486
+ }
487
+
488
+ function mapStatementList(stmts) {
489
+ const newBody = [];
490
+
491
+ for (const node of stmts) {
492
+ switch (node.type) {
493
+ case 'ComponentDeclaration':
494
+ {
495
+ mapComponentDeclarationIntoList(node, newBody);
496
+ break;
497
+ }
498
+
499
+ case 'ExportNamedDeclaration':
500
+ {
501
+ var _node$declaration;
502
+
503
+ if (((_node$declaration = node.declaration) == null ? void 0 : _node$declaration.type) === 'ComponentDeclaration') {
504
+ mapComponentDeclarationIntoList(node.declaration, newBody, componentOrRef => {
505
+ switch (componentOrRef.type) {
506
+ case 'FunctionDeclaration':
507
+ {
508
+ // No ref, so we can export the component directly.
509
+ return nodeWith(node, {
510
+ declaration: componentOrRef
511
+ });
512
+ }
513
+
514
+ case 'Identifier':
515
+ {
516
+ // If a ref is inserted, we should just export that id.
517
+ return {
518
+ type: 'ExportNamedDeclaration',
519
+ declaration: null,
520
+ specifiers: [{
521
+ type: 'ExportSpecifier',
522
+ exported: (0, _astNodeMutationHelpers.shallowCloneNode)(componentOrRef),
523
+ local: (0, _astNodeMutationHelpers.shallowCloneNode)(componentOrRef),
524
+ loc: node.loc,
525
+ range: node.range,
526
+ parent: EMPTY_PARENT
527
+ }],
528
+ exportKind: 'value',
529
+ source: null,
530
+ loc: node.loc,
531
+ range: node.range,
532
+ parent: node.parent
533
+ };
534
+ }
535
+ }
536
+ });
537
+ break;
538
+ }
539
+
540
+ newBody.push(node);
541
+ break;
542
+ }
543
+
544
+ case 'ExportDefaultDeclaration':
545
+ {
546
+ var _node$declaration2;
547
+
548
+ if (((_node$declaration2 = node.declaration) == null ? void 0 : _node$declaration2.type) === 'ComponentDeclaration') {
549
+ mapComponentDeclarationIntoList(node.declaration, newBody, componentOrRef => nodeWith(node, {
550
+ declaration: componentOrRef
551
+ }));
552
+ break;
553
+ }
554
+
555
+ newBody.push(node);
556
+ break;
557
+ }
558
+
559
+ default:
560
+ {
561
+ newBody.push(node);
562
+ }
563
+ }
564
+ }
565
+
566
+ return newBody;
567
+ }
568
+
569
+ function transformProgram(program, _options) {
570
+ return _SimpleTransform.SimpleTransform.transformProgram(program, {
571
+ transform(node) {
572
+ switch (node.type) {
573
+ case 'DeclareComponent':
574
+ {
575
+ return mapDeclareComponent(node);
576
+ }
577
+
578
+ case 'Program':
579
+ case 'BlockStatement':
580
+ {
581
+ return nodeWith(node, {
582
+ body: mapStatementList(node.body)
583
+ });
584
+ }
585
+
586
+ case 'SwitchCase':
587
+ {
588
+ return nodeWith(node, {
589
+ /* $FlowExpectedError[incompatible-call] We know `mapStatementList` will
590
+ not return `ModuleDeclaration` nodes if it is not passed any */
591
+ consequent: mapStatementList(node.consequent)
592
+ });
593
+ }
594
+
595
+ case 'ComponentDeclaration':
596
+ {
597
+ var _node$parent;
598
+
599
+ throw (0, _createSyntaxError.createSyntaxError)(node, `Components must be defined at the top level of a module or within a ` + `BlockStatement, instead got parent of "${(_node$parent = node.parent) == null ? void 0 : _node$parent.type}".`);
600
+ }
601
+
602
+ default:
603
+ {
604
+ return node;
605
+ }
606
+ }
607
+ }
608
+
609
+ });
610
+ }