Best JavaScript code snippet using playwright-internal
Schema.js
Source:Schema.js
...375 if (!innerType) {376 return;377 }378 if (innerType instanceof NonNull) {379 throw createCompilerError(380 'Unable to wrap non-nullable type with non-null wrapper.',381 );382 }383 const cacheKey = `${this.getTypeString(innerType)}!`;384 let type = this._typeWrappersMap.get(cacheKey);385 if (type) {386 return type;387 }388 type = new NonNull(innerType);389 this._typeWrappersMap.set(cacheKey, type);390 return type;391 } else if (typeNode.kind === 'ListType') {392 const innerType = this.getTypeFromAST(typeNode.type);393 if (!innerType) {394 return;395 }396 const cacheKey = `[${this.getTypeString(innerType)}]`;397 let type = this._typeWrappersMap.get(cacheKey);398 if (type) {399 return type;400 }401 type = new List(innerType);402 this._typeWrappersMap.set(cacheKey, type);403 return type;404 }405 return this._typeMap.getTypeByName(typeNode.name.value);406 }407 _getRawType(typeName: TypeMapKey): ?TypeID {408 const type = this._typeWrappersMap.get(typeName);409 if (type) {410 return type;411 }412 if (typeof typeName === 'string') {413 return this.getTypeFromAST(parseType(typeName));414 } else {415 let operationType;416 if (typeName === QUERY_TYPE_KEY) {417 operationType = this._typeMap.getQueryType();418 } else if (typeName === MUTATION_TYPE_KEY) {419 operationType = this._typeMap.getMutationType();420 } else if (typeName === SUBSCRIPTION_TYPE_KEY) {421 operationType = this._typeMap.getSubscriptionType();422 }423 if (operationType instanceof ObjectType) {424 return operationType;425 }426 }427 }428 getTypeFromString(typeName: string): ?TypeID {429 return this._getRawType(typeName);430 }431 expectTypeFromString(typeName: string): TypeID {432 const type = this.getTypeFromString(typeName);433 if (type == null) {434 throw createCompilerError(`Unknown type: '${typeName}'.`);435 }436 return type;437 }438 expectTypeFromAST(ast: TypeNode): TypeID {439 const type = this.getTypeFromAST(ast);440 if (type == null) {441 throw createCompilerError(`Unknown type: '${print(ast)}'.`, null, [ast]);442 }443 return type;444 }445 getNonNullType(type: TypeID): TypeID {446 if (type instanceof NonNull) {447 return type;448 }449 const cacheKey = `${String(type)}!`;450 let nonNullType = this._typeWrappersMap.get(cacheKey);451 if (nonNullType) {452 return nonNullType;453 }454 nonNullType = new NonNull(type);455 this._typeWrappersMap.set(cacheKey, nonNullType);456 return nonNullType;457 }458 getRawType(type: TypeID): TypeID {459 return unwrap(type);460 }461 getNullableType(type: TypeID): TypeID {462 if (type instanceof NonNull) {463 return type.ofType;464 }465 return type;466 }467 getListItemType(type: TypeID): TypeID {468 if (type instanceof List) {469 return type.ofType;470 }471 return type;472 }473 mapListItemType(type: TypeID, mapper: (inner: TypeID) => TypeID): TypeID {474 if (!(type instanceof List)) {475 throw createCompilerError('Expected List type');476 }477 const innerType = mapper(type.ofType);478 const cacheKey = `[${this.getTypeString(innerType)}]`;479 let newType = this._typeWrappersMap.get(cacheKey);480 if (newType) {481 return newType;482 }483 newType = new List(innerType);484 this._typeWrappersMap.set(cacheKey, newType);485 return newType;486 }487 areEqualTypes(typeA: TypeID, typeB: TypeID): boolean {488 if (typeA === typeB) {489 return true;490 }491 if (typeA instanceof NonNull && typeB instanceof NonNull) {492 return this.areEqualTypes(typeA.ofType, typeB.ofType);493 }494 if (typeA instanceof List && typeB instanceof List) {495 return this.areEqualTypes(typeA.ofType, typeB.ofType);496 }497 if (isBaseType(typeA) && isBaseType(typeB)) {498 return typeA.name === typeB.name;499 }500 return false;501 }502 /**503 * Determine if the given type may implement the named type:504 * - it is the named type505 * - it implements the named interface506 * - it is an abstract type and *some* of its concrete types may507 * implement the named type508 */509 mayImplement(type: CompositeTypeID, interfaceType: InterfaceTypeID): boolean {510 return (511 this.areEqualTypes(type, interfaceType) ||512 this.implementsInterface(type, interfaceType) ||513 (this.isAbstractType(type) &&514 hasConcreteTypeThatImplements(this, type, interfaceType))515 );516 }517 implementsInterface(518 type: CompositeTypeID,519 interfaceType: InterfaceTypeID,520 ): boolean {521 return this.getInterfaces(type).some(typeInterface =>522 this.areEqualTypes(typeInterface, interfaceType),523 );524 }525 canHaveSelections(type: TypeID): boolean {526 return this.isObject(type) || this.isInterface(type);527 }528 getTypeString(type: TypeID): string {529 return type.toString();530 }531 isTypeSubTypeOf(maybeSubType: TypeID, superType: TypeID): boolean {532 // Equivalent type is a valid subtype533 if (maybeSubType === superType) {534 return true;535 }536 // If superType is non-null, maybeSubType must also be non-null.537 if (superType instanceof NonNull) {538 if (maybeSubType instanceof NonNull) {539 return this.isTypeSubTypeOf(maybeSubType.ofType, superType.ofType);540 }541 return false;542 }543 if (maybeSubType instanceof NonNull) {544 // If superType is nullable, maybeSubType may be non-null or nullable.545 return this.isTypeSubTypeOf(maybeSubType.ofType, superType);546 }547 // If superType type is a list, maybeSubType type must also be a list.548 if (superType instanceof List) {549 if (maybeSubType instanceof List) {550 return this.isTypeSubTypeOf(maybeSubType.ofType, superType.ofType);551 }552 return false;553 }554 if (maybeSubType instanceof List) {555 // If superType is not a list, maybeSubType must also be not a list.556 return false;557 }558 // If superType type is an abstract type, maybeSubType type may be a currently559 // possible object type.560 if (561 this.isAbstractType(superType) &&562 this.isObject(maybeSubType) &&563 this.isPossibleType(564 this.assertAbstractType(superType),565 this.assertObjectType(maybeSubType),566 )567 ) {568 return true;569 }570 // Otherwise, maybeSubType is not a valid subtype of the superType.571 return false;572 }573 /**574 * Provided two composite types, determine if they "overlap". Two composite575 * types overlap when the Sets of possible concrete types for each intersect.576 *577 * This is often used to determine if a fragment of a given type could possibly578 * be visited in a context of another type.579 *580 * This function is commutative.581 */582 doTypesOverlap(typeA: CompositeTypeID, typeB: CompositeTypeID): boolean {583 // Equivalent types overlap584 if (typeA === typeB) {585 return true;586 }587 if (isAbstractType(typeA)) {588 if (isAbstractType(typeB)) {589 // If both types are abstract, then determine if there is any intersection590 // between possible concrete types of each.591 return Array.from(this.getPossibleTypes(typeA)).some(type => {592 if (isObject(type)) {593 return this.isPossibleType(typeB, type);594 }595 });596 }597 // Determine if the latter type is a possible concrete type of the former.598 return this.isPossibleType(typeA, typeB);599 }600 if (isAbstractType(typeB)) {601 // Determine if the former type is a possible concrete type of the latter.602 return this.isPossibleType(typeB, typeA);603 }604 // Otherwise the types do not overlap.605 return false;606 }607 isPossibleType(608 superType: AbstractTypeID,609 maybeSubType: ObjectTypeID,610 ): boolean {611 return this._typeMap.getPossibleTypeSet(superType).has(maybeSubType);612 }613 assertScalarFieldType(type: mixed): ScalarFieldTypeID {614 // Scalar type fields can be wrappers / or can be scalars/enums615 if (616 (isWrapper(type) && !isScalar(unwrap(type)) && !isEnum(unwrap(type))) ||617 (!isWrapper(type) && !isScalar(type) && !isEnum(type))618 ) {619 throw createCompilerError(620 `Expected ${String(type)} to be a Scalar or Enum type.`,621 );622 }623 return type;624 }625 assertLinkedFieldType(type: mixed): LinkedFieldTypeID {626 // Linked Field types can be wrappers / or can be composite types627 if (628 (isWrapper(type) && !isCompositeType(unwrap(type))) ||629 (!isWrapper(type) && !isCompositeType(type))630 ) {631 throw createCompilerError(632 `Expected ${String(type)} to be a Object, Interface or a Union Type.`,633 );634 }635 return type;636 }637 assertInputType(type: mixed): InputTypeID {638 // Input type fields can be wrappers / or can be scalars/enums639 if (640 (isWrapper(type) && !isInputType(unwrap(type))) ||641 (!isWrapper(type) && !isInputType(type))642 ) {643 throw createCompilerError(644 `Expected ${String(type)} to be a Input, Scalar or Enum type.`,645 );646 }647 return type;648 }649 asCompositeType(type: mixed): ?CompositeTypeID {650 if (isCompositeType(type)) {651 return type;652 }653 }654 asInputType(type: mixed): ?InputTypeID {655 if (656 (isWrapper(type) && isInputType(unwrap(type))) ||657 (!isWrapper(type) && isInputType(type))658 ) {659 return type;660 }661 }662 asScalarFieldType(type: mixed): ?ScalarFieldTypeID {663 if (isScalar(type) || isEnum(type)) {664 return type;665 }666 }667 assertScalarType(type: TypeID): ScalarTypeID {668 if (!isScalar(type)) {669 throw createCompilerError(670 `Expected ${this.getTypeString(671 type,672 )} to be a scalar type, got ${this.getTypeString(type)}.`,673 );674 }675 return type;676 }677 assertObjectType(type: TypeID): ObjectTypeID {678 if (!isObject(type)) {679 throw createCompilerError(680 `Expected ${this.getTypeString(type)} to be an object type.`,681 );682 }683 return type;684 }685 assertInputObjectType(type: TypeID): InputObjectTypeID {686 if (!isInputObject(type)) {687 throw createCompilerError(688 `Expected ${this.getTypeString(type)} to be an input type.`,689 );690 }691 return type;692 }693 asInputObjectType(type: TypeID): ?InputObjectTypeID {694 if (!isInputObject(type)) {695 return null;696 }697 return type;698 }699 assertInterfaceType(type: TypeID): InterfaceTypeID {700 if (!isInterface(type)) {701 throw createCompilerError(702 `Expected ${this.getTypeString(type)} to be an interface type.`,703 );704 }705 return type;706 }707 assertCompositeType(type: TypeID): CompositeTypeID {708 if (!isCompositeType(type)) {709 throw createCompilerError(710 `Expected ${this.getTypeString(type)} to be a composite type.`,711 );712 }713 return type;714 }715 assertAbstractType(type: TypeID): AbstractTypeID {716 if (!isAbstractType(type)) {717 throw createCompilerError(718 `Expected ${this.getTypeString(type)} to be an abstract type.`,719 );720 }721 return type;722 }723 assertLeafType(type: TypeID): TypeID {724 if (!this.isLeafType(type)) {725 throw createCompilerError(726 `Expected ${this.getTypeString(type)} to be a leaf type.`,727 );728 }729 return type;730 }731 assertUnionType(type: TypeID): UnionTypeID {732 if (!isUnion(type)) {733 throw createCompilerError(734 `Expected ${this.getTypeString(type)} to be a union type.`,735 );736 }737 return type;738 }739 assertEnumType(type: TypeID): EnumTypeID {740 if (!isEnum(type)) {741 throw createCompilerError(`Expected ${String(type)} to be an enum type.`);742 }743 return type;744 }745 assertIntType(type: TypeID): ScalarTypeID {746 if (!isScalar(type) || !this.isInt(type)) {747 throw createCompilerError(748 `Expected ${String(type)} to be an 'Int' type.`,749 );750 }751 return type;752 }753 assertFloatType(type: TypeID): ScalarTypeID {754 if (!isScalar(type) || !this.isFloat(type)) {755 throw createCompilerError(756 `Expected ${this.getTypeString(type)} to be a 'Float' type.`,757 );758 }759 return type;760 }761 assertBooleanType(type: TypeID): ScalarTypeID {762 if (!isScalar(type) || !this.isBoolean(type)) {763 throw createCompilerError(764 `Expected ${this.getTypeString(type)} to be a 'Boolean' type.`,765 );766 }767 return type;768 }769 assertStringType(type: TypeID): ScalarTypeID {770 if (!isScalar(type) || !this.isString(type)) {771 throw createCompilerError(772 `Expected ${this.getTypeString(type)} to be a 'String' type.`,773 );774 }775 return type;776 }777 assertIdType(type: TypeID): ScalarTypeID {778 if (!isScalar(type) || !this.isId(type)) {779 throw createCompilerError(780 `Expected ${this.getTypeString(type)} to be an ID type.`,781 );782 }783 return type;784 }785 expectBooleanType(): ScalarTypeID {786 return this.assertScalarType(this.expectTypeFromString('Boolean'));787 }788 expectIntType(): ScalarTypeID {789 return this.assertScalarType(this.expectTypeFromString('Int'));790 }791 expectFloatType(): ScalarTypeID {792 return this.assertScalarType(this.expectTypeFromString('Float'));793 }794 expectStringType(): ScalarTypeID {795 return this.assertScalarType(this.expectTypeFromString('String'));796 }797 expectIdType(): ScalarTypeID {798 return this.assertScalarType(this.expectTypeFromString('ID'));799 }800 getQueryType(): ?ObjectTypeID {801 const queryType = this._getRawType(QUERY_TYPE_KEY);802 if (queryType && isObject(queryType)) {803 return queryType;804 }805 }806 getMutationType(): ?ObjectTypeID {807 const mutationType = this._getRawType(MUTATION_TYPE_KEY);808 if (mutationType && isObject(mutationType)) {809 return mutationType;810 }811 }812 getSubscriptionType(): ?ObjectTypeID {813 const subscriptionType = this._getRawType(SUBSCRIPTION_TYPE_KEY);814 if (subscriptionType && isObject(subscriptionType)) {815 return subscriptionType;816 }817 }818 expectQueryType(): ObjectTypeID {819 const queryType = this.getQueryType();820 if (queryType == null) {821 throw createCompilerError('Query type is not defined on the Schema');822 }823 return queryType;824 }825 expectMutationType(): ObjectTypeID {826 const mutationType = this.getMutationType();827 if (mutationType == null) {828 throw createCompilerError('Mutation type is not defined the Schema');829 }830 return mutationType;831 }832 expectSubscriptionType(): ObjectTypeID {833 const subscriptionType = this.getSubscriptionType();834 if (subscriptionType == null) {835 throw createCompilerError('Subscription type is not defined the Schema');836 }837 return subscriptionType;838 }839 isNonNull(type: TypeID): boolean {840 return type instanceof NonNull;841 }842 isList(type: TypeID): boolean {843 return type instanceof List;844 }845 isWrapper(type: TypeID): boolean {846 return isWrapper(type);847 }848 isScalar(type: TypeID): boolean {849 return isScalar(type);850 }851 isObject(type: TypeID): boolean {852 return isObject(type);853 }854 isEnum(type: TypeID): boolean {855 return isEnum(type);856 }857 isUnion(type: TypeID): boolean {858 return isUnion(type);859 }860 isInputObject(type: TypeID): boolean {861 return isInputObject(type);862 }863 isInterface(type: TypeID): boolean {864 return isInterface(type);865 }866 isInputType(type: TypeID): boolean {867 // Wrappers can be input types (so it's save to check unwrapped type here)868 return isInputType(type) || (isWrapper(type) && isInputType(unwrap(type)));869 }870 isCompositeType(type: TypeID): boolean {871 return isCompositeType(type);872 }873 isAbstractType(type: TypeID): boolean {874 return isAbstractType(type);875 }876 isLeafType(type: TypeID): boolean {877 return this.isScalar(type) || this.isEnum(type);878 }879 isId(type: TypeID): boolean {880 if (type instanceof ScalarType) {881 return type.name === 'ID';882 }883 return false;884 }885 isInt(type: TypeID): boolean {886 if (type instanceof ScalarType) {887 return type.name === 'Int';888 }889 return false;890 }891 isFloat(type: TypeID): boolean {892 if (type instanceof ScalarType) {893 return type.name === 'Float';894 }895 return false;896 }897 isBoolean(type: TypeID): boolean {898 if (type instanceof ScalarType) {899 return type.name === 'Boolean';900 }901 return false;902 }903 isString(type: TypeID): boolean {904 if (type instanceof ScalarType) {905 return type.name === 'String';906 }907 return false;908 }909 hasField(910 type: CompositeTypeID | InputObjectTypeID,911 fieldName: string,912 ): boolean {913 const canHaveTypename = this.isObject(type) || this.isAbstractType(type);914 // Special case for __typename field915 if (916 canHaveTypename &&917 (fieldName === TYPENAME_FIELD || fieldName === CLIENT_ID_FIELD)918 ) {919 return true;920 }921 if (type instanceof ObjectType || type instanceof InterfaceType) {922 return this._typeMap.getField(type, fieldName) != null;923 } else if (type instanceof InputObjectType) {924 return this._typeMap.getInputField(type, fieldName) != null;925 }926 return false;927 }928 hasId(type: CompositeTypeID): boolean {929 if (!this.hasField(type, 'id')) {930 return false;931 }932 const idField = this.expectField(type, 'id');933 return this.areEqualTypes(934 this.getNullableType(this.getFieldType(idField)),935 this.expectIdType(),936 );937 }938 getFields(939 type: CompositeTypeID | InputObjectTypeID,940 ): $ReadOnlyArray<FieldID> {941 const fieldsMap = this._getFieldsMap(type);942 return Array.from(fieldsMap.values());943 }944 _getFieldsMap(type: CompositeTypeID | InputObjectTypeID): FieldsMap {945 const cachedMap = this._fieldsMap.get(type);946 if (cachedMap != null) {947 return cachedMap;948 }949 const fieldsMap = new Map();950 if (type instanceof ObjectType || type instanceof InterfaceType) {951 const fields = this._typeMap.getFieldMap(type);952 if (fields) {953 for (const [fieldName, fieldDefinition] of fields) {954 const fieldType = this.expectTypeFromAST(fieldDefinition.type);955 fieldsMap.set(956 fieldName,957 new Field(958 this,959 fieldName,960 fieldType,961 this.assertCompositeType(type),962 fieldDefinition.arguments,963 fieldDefinition.directives,964 fieldDefinition.isClient,965 ),966 );967 }968 }969 } else if (type instanceof InputObjectType) {970 const fields = this._typeMap.getInputFieldMap(type);971 if (fields) {972 for (const [fieldName, typeNode] of fields) {973 const fieldType = this.expectTypeFromAST(typeNode);974 fieldsMap.set(975 fieldName,976 new Field(this, fieldName, fieldType, type, [], null, false),977 );978 }979 }980 }981 if (fieldsMap.size === 0) {982 throw createCompilerError(983 `_getFieldsMap: Type '${type.name}' should have fields.`,984 );985 }986 this._fieldsMap.set(type, fieldsMap);987 return fieldsMap;988 }989 getFieldByName(990 type: CompositeTypeID | InputObjectTypeID,991 fieldName: string,992 ): ?FieldID {993 if (!this.hasField(type, fieldName)) {994 return;995 }996 // A "special" case for __typename and __id fields - which should997 // not be in the list of type fields, but should be fine to select998 if (fieldName === TYPENAME_FIELD) {999 let typename = this._typeNameMap.get(type);1000 if (!typename) {1001 typename = new Field(1002 this,1003 TYPENAME_FIELD,1004 this.getNonNullType(this.expectStringType()),1005 type,1006 [],1007 null,1008 false, // isClient === false1009 );1010 this._typeNameMap.set(type, typename);1011 }1012 return typename;1013 }1014 if (fieldName === CLIENT_ID_FIELD) {1015 let clientId = this._clientIdMap.get(type);1016 if (!clientId) {1017 clientId = new Field(1018 this,1019 CLIENT_ID_FIELD,1020 this.getNonNullType(this.expectIdType()),1021 type,1022 [],1023 null,1024 true, // isClient === true1025 );1026 this._clientIdMap.set(type, clientId);1027 }1028 return clientId;1029 }1030 if (isUnion(type)) {1031 throw createCompilerError(1032 `Unexpected union type '${this.getTypeString(1033 type,1034 )}' in the 'getFieldByName(...)'. Expected type with fields`,1035 );1036 }1037 const fieldsMap = this._getFieldsMap(type);1038 return fieldsMap.get(fieldName);1039 }1040 expectField(1041 type: CompositeTypeID | InputObjectTypeID,1042 fieldName: string,1043 ): FieldID {1044 const field = this.getFieldByName(type, fieldName);1045 if (!field) {1046 throw createCompilerError(1047 `Unknown field '${fieldName}' on type '${this.getTypeString(type)}'.`,1048 );1049 }1050 return field;1051 }1052 getFieldConfig(1053 field: FieldID,1054 ): {|1055 type: TypeID,1056 args: $ReadOnlyArray<Argument>,1057 |} {1058 return {1059 type: field.type,1060 args: Array.from(field.args.values()),1061 };1062 }1063 getFieldName(field: FieldID): string {1064 return field.name;1065 }1066 getFieldType(field: FieldID): TypeID {1067 return field.type;1068 }1069 getFieldParentType(field: FieldID): TypeID {1070 return field.belongsTo;1071 }1072 getFieldArgs(field: FieldID): $ReadOnlyArray<Argument> {1073 return Array.from(field.args.values());1074 }1075 getFieldArgByName(field: FieldID, argName: string): ?Argument {1076 return field.args.get(argName);1077 }1078 getEnumValues(type: EnumTypeID): $ReadOnlyArray<string> {1079 return type.values;1080 }1081 getUnionTypes(type: UnionTypeID): $ReadOnlyArray<TypeID> {1082 return Array.from(this._typeMap.getPossibleTypeSet(type));1083 }1084 getInterfaces(type: CompositeTypeID): $ReadOnlyArray<TypeID> {1085 if (type instanceof ObjectType) {1086 return this._typeMap.getInterfaces(type);1087 }1088 return [];1089 }1090 getPossibleTypes(type: AbstractTypeID): $ReadOnlySet<ObjectTypeID> {1091 return this._typeMap.getPossibleTypeSet(type);1092 }1093 getFetchableFieldName(type: ObjectTypeID): ?string {1094 return this._typeMap.getFetchableFieldName(type);1095 }1096 parseLiteral(type: ScalarTypeID | EnumTypeID, valueNode: ValueNode): mixed {1097 if (type instanceof EnumType && valueNode.kind === 'EnumValue') {1098 return this.parseValue(type, valueNode.value);1099 } else if (type instanceof ScalarType) {1100 if (valueNode.kind === 'BooleanValue' && type.name === 'Boolean') {1101 return GraphQLBoolean.parseLiteral(valueNode);1102 } else if (valueNode.kind === 'FloatValue' && type.name === 'Float') {1103 return GraphQLFloat.parseLiteral(valueNode);1104 } else if (1105 valueNode.kind === 'IntValue' &&1106 (type.name === 'Int' || type.name === 'ID' || type.name === 'Float')1107 ) {1108 return GraphQLInt.parseLiteral(valueNode);1109 } else if (1110 valueNode.kind === 'StringValue' &&1111 (type.name === 'String' || type.name === 'ID')1112 ) {1113 return GraphQLString.parseLiteral(valueNode);1114 } else if (!isDefaultScalar(type.name)) {1115 return valueFromASTUntyped(valueNode);1116 }1117 }1118 }1119 parseValue(type: ScalarTypeID | EnumTypeID, value: mixed): mixed {1120 if (type instanceof EnumType) {1121 return type.values.includes(value) ? value : undefined;1122 } else if (type instanceof ScalarType) {1123 switch (type.name) {1124 case 'Boolean':1125 return GraphQLBoolean.parseValue(value);1126 case 'Float':1127 return GraphQLFloat.parseValue(value);1128 case 'Int':1129 return GraphQLInt.parseValue(value);1130 case 'String':1131 return GraphQLString.parseValue(value);1132 case 'ID':1133 return GraphQLID.parseValue(value);1134 default:1135 return value;1136 }1137 }1138 }1139 serialize(type: ScalarTypeID | EnumTypeID, value: mixed): mixed {1140 if (type instanceof EnumType) {1141 return type.values.includes(value) ? value : undefined;1142 } else if (type instanceof ScalarType) {1143 switch (type.name) {1144 case 'Boolean':1145 return GraphQLBoolean.serialize(value);1146 case 'Float':1147 return GraphQLFloat.serialize(value);1148 case 'Int':1149 return GraphQLInt.serialize(value);1150 case 'String':1151 return GraphQLString.serialize(value);1152 case 'ID':1153 return GraphQLID.serialize(value);1154 default:1155 return value;1156 }1157 }1158 }1159 getDirectives(): $ReadOnlyArray<Directive> {1160 return Array.from(this._directiveMap.values());1161 }1162 getDirective(directiveName: string): ?Directive {1163 return this._directiveMap.get(directiveName);1164 }1165 isServerType(type: TypeID): boolean {1166 const unwrapped = unwrap(type);1167 return unwrapped.isClient === false;1168 }1169 isServerField(field: FieldID): boolean {1170 return field.isClient === false;1171 }1172 isServerDirective(directiveName: string): boolean {1173 const directive = this._directiveMap.get(directiveName);1174 return directive?.isClient === false;1175 }1176 isServerDefinedField(type: CompositeTypeID, field: IRField): boolean {1177 return (1178 (this.isAbstractType(type) &&1179 field.directives.some(({name}) => name === 'fixme_fat_interface')) ||1180 (this.hasField(type, field.name) &&1181 this.isServerField(this.expectField(type, field.name)))1182 );1183 }1184 isClientDefinedField(type: CompositeTypeID, field: IRField): boolean {1185 return !this.isServerDefinedField(type, field);1186 }1187 extend(extensions: DocumentNode | $ReadOnlyArray<string>): Schema {1188 const doc = Array.isArray(extensions)1189 ? parse(extensions.join('\n'))1190 : extensions;1191 const schemaExtensions = [];1192 doc.definitions.forEach(definition => {1193 if (isSchemaDefinitionAST(definition)) {1194 schemaExtensions.push(definition);1195 }1196 });1197 if (schemaExtensions.length > 0) {1198 return new Schema(this._typeMap.extend(schemaExtensions));1199 }1200 return this;1201 }1202}1203class TypeMap {1204 _mutationTypeName: string;1205 _queryTypeName: string;1206 _subscriptionTypeName: string;1207 +_directives: InternalDirectiveMap;1208 +_extensions: $ReadOnlyArray<ExtensionNode>;1209 +_fetchable: Map<TypeID, Fetchable>;1210 +_fields: Map<InterfaceType | ObjectType, Map<string, FieldDefinition>>;1211 +_inputFields: Map<InputObjectType, Map<string, TypeNode>>;1212 +_interfaceImplementations: Map<InterfaceType, Set<ObjectType>>;1213 +_source: Source;1214 +_typeInterfaces: Map<TypeID, $ReadOnlyArray<InterfaceType>>;1215 +_types: Map<string, BaseType>;1216 +_unionTypes: Map<TypeID, Set<ObjectType>>;1217 constructor(source: Source, extensions: $ReadOnlyArray<ExtensionNode>) {1218 this._types = new Map([1219 ['ID', new ScalarType('ID', false)],1220 ['String', new ScalarType('String', false)],1221 ['Boolean', new ScalarType('Boolean', false)],1222 ['Float', new ScalarType('Float', false)],1223 ['Int', new ScalarType('Int', false)],1224 ]);1225 this._typeInterfaces = new Map();1226 this._unionTypes = new Map();1227 this._interfaceImplementations = new Map();1228 this._fields = new Map();1229 this._inputFields = new Map();1230 this._directives = new Map([1231 [1232 'include',1233 {1234 name: 'include',1235 isClient: false,1236 locations: ['FIELD', 'FRAGMENT_SPREAD', 'INLINE_FRAGMENT'],1237 args: [1238 {1239 name: 'if',1240 typeNode: parseType('Boolean!'),1241 defaultValue: undefined,1242 },1243 ],1244 },1245 ],1246 [1247 'skip',1248 {1249 name: 'skip',1250 isClient: false,1251 locations: ['FIELD', 'FRAGMENT_SPREAD', 'INLINE_FRAGMENT'],1252 args: [1253 {1254 name: 'if',1255 typeNode: parseType('Boolean!'),1256 defaultValue: undefined,1257 },1258 ],1259 },1260 ],1261 [1262 'deprecated',1263 {1264 name: 'deprecated',1265 isClient: false,1266 locations: ['FIELD_DEFINITION', 'ENUM_VALUE'],1267 args: [1268 {1269 name: 'reason',1270 typeNode: parseType('String'),1271 defaultValue: {1272 kind: 'StringValue',1273 value: 'No longer supported',1274 },1275 },1276 ],1277 },1278 ],1279 ]);1280 this._queryTypeName = 'Query';1281 this._mutationTypeName = 'Mutation';1282 this._subscriptionTypeName = 'Subscription';1283 this._source = source;1284 this._extensions = extensions;1285 this._fetchable = new Map();1286 this._parse(source);1287 this._extend(extensions);1288 }1289 _parse(source: Source) {1290 const document = parse(source, {1291 noLocation: true,1292 });1293 document.definitions.forEach(definition => {1294 switch (definition.kind) {1295 case 'SchemaDefinition': {1296 this._parseSchemaDefinition(definition);1297 break;1298 }1299 case 'ScalarTypeDefinition': {1300 this._parseScalarNode(definition, false);1301 break;1302 }1303 case 'EnumTypeDefinition': {1304 this._parseEnumNode(definition, false);1305 break;1306 }1307 case 'ObjectTypeDefinition': {1308 this._parseObjectTypeNode(definition, false);1309 break;1310 }1311 case 'InputObjectTypeDefinition': {1312 this._parseInputObjectTypeNode(definition, false);1313 break;1314 }1315 case 'UnionTypeDefinition': {1316 this._parseUnionNode(definition, false);1317 break;1318 }1319 case 'InterfaceTypeDefinition': {1320 this._parseInterfaceNode(definition, false);1321 break;1322 }1323 case 'DirectiveDefinition': {1324 this._parseDirective(definition, false);1325 break;1326 }1327 }1328 });1329 }1330 _parseSchemaDefinition(node: SchemaDefinitionNode) {1331 node.operationTypes.forEach(operationType => {1332 switch (operationType.operation) {1333 case 'query':1334 this._queryTypeName = operationType.type.name.value;1335 break;1336 case 'mutation':1337 this._mutationTypeName = operationType.type.name.value;1338 break;1339 case 'subscription':1340 this._subscriptionTypeName = operationType.type.name.value;1341 break;1342 }1343 });1344 }1345 _parseScalarNode(node: ScalarTypeDefinitionNode, isClient: boolean) {1346 const name = node.name.value;1347 if (!isDefaultScalar(name) && this._types.has(name)) {1348 throw createCompilerError(1349 `_parseScalarNode: Duplicate definition for type ${name}.`,1350 null,1351 [node],1352 );1353 }1354 this._types.set(name, new ScalarType(name, isClient));1355 }1356 _parseEnumNode(node: EnumTypeDefinitionNode, isClient: boolean) {1357 const name = node.name.value;1358 if (this._types.has(name)) {1359 throw createCompilerError(1360 `_parseEnumNode: Duplicate definition for type ${name}.`,1361 null,1362 [node],1363 );1364 }1365 // SDL doesn't have information about the actual ENUM values1366 const values = node.values1367 ? node.values.map(value => value.name.value)1368 : [];1369 this._types.set(name, new EnumType(name, values, isClient));1370 }1371 _parseObjectTypeNode(node: ObjectTypeDefinitionNode, isClient: boolean) {1372 const name = node.name.value;1373 // Objects may be created by _parseUnionNode1374 const type = this._types.get(name) ?? new ObjectType(name, isClient);1375 if (!(type instanceof ObjectType)) {1376 throw createCompilerError(1377 `_parseObjectTypeNode: Expected object type, got ${String(type)}`,1378 null,1379 [node],1380 );1381 }1382 if (type.isClient !== isClient) {1383 throw createCompilerError(1384 `_parseObjectTypeNode: Cannot create object type '${name}' defined as a client type.`,1385 null,1386 [node],1387 );1388 }1389 const typeInterfaces: Array<InterfaceType> = [];1390 node.interfaces &&1391 node.interfaces.forEach(interfaceTypeNode => {1392 const interfaceName = interfaceTypeNode.name.value;1393 let interfaceType = this._types.get(interfaceName);1394 if (!interfaceType) {1395 interfaceType = new InterfaceType(interfaceName, isClient);1396 this._types.set(interfaceName, interfaceType);1397 }1398 if (!(interfaceType instanceof InterfaceType)) {1399 throw createCompilerError(1400 '_parseObjectTypeNode: Expected interface type',1401 null,1402 [interfaceTypeNode],1403 );1404 }1405 const implementations =1406 this._interfaceImplementations.get(interfaceType) ?? new Set();1407 implementations.add(type);1408 this._interfaceImplementations.set(interfaceType, implementations);1409 typeInterfaces.push(interfaceType);1410 });1411 let fetchable = null;1412 node.directives &&1413 node.directives.forEach(directiveNode => {1414 if (directiveNode.name.value === 'fetchable') {1415 const field_name_arg =1416 directiveNode.arguments &&1417 directiveNode.arguments.find(1418 arg => arg.name.value === 'field_name',1419 );1420 if (1421 field_name_arg != null &&1422 field_name_arg.value.kind === 'StringValue'1423 ) {1424 fetchable = {field_name: field_name_arg.value.value};1425 }1426 }1427 });1428 this._typeInterfaces.set(type, typeInterfaces);1429 this._types.set(name, type);1430 if (fetchable != null) {1431 this._fetchable.set(type, fetchable);1432 }1433 node.fields && this._handleTypeFieldsStrict(type, node.fields, isClient);1434 }1435 _parseInputObjectTypeNode(1436 node: InputObjectTypeDefinitionNode,1437 isClient: boolean,1438 ) {1439 const name = node.name.value;1440 if (this._types.has(name)) {1441 throw createCompilerError(1442 '_parseInputObjectTypeNode: Unable to parse schema file. Duplicate definition for object type',1443 null,1444 [node],1445 );1446 }1447 const type = new InputObjectType(name, isClient);1448 this._types.set(name, type);1449 this._parseInputObjectFields(type, node);1450 }1451 _parseUnionNode(node: UnionTypeDefinitionNode, isClient: boolean) {1452 const name = node.name.value;1453 if (this._types.has(name)) {1454 throw createCompilerError(1455 '_parseUnionNode: Unable to parse schema file. Duplicate definition for object type',1456 null,1457 [node],1458 );1459 }1460 const union = new UnionType(name, isClient);1461 this._types.set(name, union);1462 this._unionTypes.set(1463 union,1464 new Set(1465 node.types1466 ? node.types.map(typeInUnion => {1467 const typeInUnionName = typeInUnion.name.value;1468 const object =1469 this._types.get(typeInUnionName) ??1470 new ObjectType(typeInUnionName, false);1471 if (!(object instanceof ObjectType)) {1472 throw createCompilerError(1473 '_parseUnionNode: Expected object type',1474 null,1475 [typeInUnion],1476 );1477 }1478 this._types.set(typeInUnionName, object);1479 return object;1480 })1481 : [],1482 ),1483 );1484 }1485 _parseInterfaceNode(node: InterfaceTypeDefinitionNode, isClient: boolean) {1486 const name = node.name.value;1487 let type = this._types.get(name);1488 if (!type) {1489 type = new InterfaceType(name, isClient);1490 this._types.set(name, type);1491 }1492 if (!(type instanceof InterfaceType)) {1493 throw createCompilerError(1494 `_parseInterfaceNode: Expected interface type. Got ${String(type)}`,1495 null,1496 [node],1497 );1498 }1499 if (type.isClient !== isClient) {1500 throw createCompilerError(1501 `_parseInterfaceNode: Cannot create interface '${name}' defined as a client interface`,1502 null,1503 [node],1504 );1505 }1506 node.fields && this._handleTypeFieldsStrict(type, node.fields, isClient);1507 }1508 _handleTypeFieldsStrict(1509 type: ObjectType | InterfaceType,1510 fields: $ReadOnlyArray<FieldDefinitionNode>,1511 isClient: boolean,1512 ) {1513 if (this._fields.has(type)) {1514 throw createCompilerError(1515 '_handleTypeFieldsStrict: Unable to parse schema file. Duplicate definition for object type',1516 );1517 }1518 this._handleTypeFields(type, fields, isClient);1519 }1520 _handleTypeFields(1521 type: ObjectType | InterfaceType,1522 fields: $ReadOnlyArray<FieldDefinitionNode>,1523 isClient: boolean,1524 ) {1525 const fieldsMap = this._fields.get(type) ?? new Map();1526 fields.forEach(fieldNode => {1527 const fieldName = fieldNode.name.value;1528 if (fieldsMap.has(fieldName)) {1529 throw createCompilerError(1530 `_handleTypeFields: Duplicate definition for field '${fieldName}'.`,1531 );1532 }1533 fieldsMap.set(fieldName, {1534 arguments: fieldNode.arguments1535 ? fieldNode.arguments.map(arg => {1536 return {1537 name: arg.name.value,1538 typeNode: arg.type,1539 defaultValue: arg.defaultValue,1540 };1541 })1542 : [],1543 directives: fieldNode.directives1544 ? fieldNode.directives.map(directive => {1545 return {1546 name: directive.name.value,1547 args: directive.arguments1548 ? directive.arguments.map(arg => {1549 return {1550 name: arg.name.value,1551 value: arg.value,1552 };1553 })1554 : [],1555 };1556 })1557 : null,1558 type: fieldNode.type,1559 isClient: isClient,1560 });1561 });1562 this._fields.set(type, fieldsMap);1563 }1564 _parseInputObjectFields(1565 type: InputObjectType,1566 node: InputObjectTypeDefinitionNode,1567 ) {1568 if (this._inputFields.has(type)) {1569 throw createCompilerError(1570 '_parseInputObjectFields: Unable to parse schema file. Duplicate definition for type',1571 null,1572 [node],1573 );1574 }1575 const fields = new Map();1576 if (node.fields) {1577 node.fields.forEach(fieldNode => {1578 fields.set(fieldNode.name.value, fieldNode.type);1579 });1580 }1581 this._inputFields.set(type, fields);1582 }1583 _parseDirective(node: DirectiveDefinitionNode, isClient: boolean) {1584 const name = node.name.value;1585 this._directives.set(name, {1586 name,1587 args: node.arguments1588 ? node.arguments.map(arg => {1589 return {1590 name: arg.name.value,1591 typeNode: arg.type,1592 defaultValue: arg.defaultValue,1593 };1594 })1595 : [],1596 locations: node.locations.map(location => {1597 switch (location.value) {1598 case 'QUERY':1599 case 'MUTATION':1600 case 'SUBSCRIPTION':1601 case 'FIELD':1602 case 'FRAGMENT_DEFINITION':1603 case 'FRAGMENT_SPREAD':1604 case 'INLINE_FRAGMENT':1605 case 'VARIABLE_DEFINITION':1606 case 'SCHEMA':1607 case 'SCALAR':1608 case 'OBJECT':1609 case 'FIELD_DEFINITION':1610 case 'ARGUMENT_DEFINITION':1611 case 'INTERFACE':1612 case 'UNION':1613 case 'ENUM':1614 case 'ENUM_VALUE':1615 case 'INPUT_OBJECT':1616 case 'INPUT_FIELD_DEFINITION':1617 return location.value;1618 default:1619 throw createCompilerError('Invalid directive location');1620 }1621 }),1622 isClient,1623 });1624 }1625 _parseObjectTypeExtension(node: ObjectTypeExtensionNode) {1626 const type = this._types.get(node.name.value);1627 if (!(type instanceof ObjectType)) {1628 throw createCompilerError(1629 `_parseObjectTypeExtension: Expected to find type with the name '${node.name.value}'`,1630 null,1631 [node],1632 );1633 }1634 node.fields &&1635 this._handleTypeFields(type, node.fields, true /** client fields */);1636 }1637 _parseInterfaceTypeExtension(node: InterfaceTypeExtensionNode) {1638 const type = this._types.get(node.name.value);1639 if (!(type instanceof InterfaceType)) {1640 throw createCompilerError(1641 '_parseInterfaceTypeExtension: Expected to have an interface type',1642 );1643 }1644 node.fields && this._handleTypeFields(type, node.fields, true);1645 }1646 _extend(extensions: $ReadOnlyArray<ExtensionNode>) {1647 extensions.forEach(definition => {1648 if (definition.kind === 'ObjectTypeDefinition') {1649 this._parseObjectTypeNode(definition, true);1650 } else if (definition.kind === 'InterfaceTypeDefinition') {1651 this._parseInterfaceNode(definition, true);1652 } else if (definition.kind === 'ScalarTypeDefinition') {1653 this._parseScalarNode(definition, true);1654 } else if (definition.kind === 'EnumTypeDefinition') {1655 this._parseEnumNode(definition, true);1656 } else if (definition.kind === 'InterfaceTypeExtension') {1657 this._parseInterfaceTypeExtension(definition);1658 } else if (definition.kind === 'ObjectTypeExtension') {1659 this._parseObjectTypeExtension(definition);1660 } else if (definition.kind === 'DirectiveDefinition') {1661 this._parseDirective(definition, true /* client directive */);1662 } else {1663 throw createCompilerError(1664 `Unexpected extension kind: '${definition.kind}'`,1665 null,1666 [definition],1667 );1668 }1669 });1670 }1671 getTypes(): $ReadOnlyArray<BaseType> {1672 return Array.from(this._types.values());1673 }1674 getTypeByName(typename: string): ?BaseType {1675 return this._types.get(typename);1676 }1677 getInterfaces(type: ObjectType): $ReadOnlyArray<InterfaceType> {1678 return this._typeInterfaces.get(type) ?? [];1679 }1680 getPossibleTypeSet(1681 type: UnionType | InterfaceType,1682 ): $ReadOnlySet<ObjectType> {1683 let set;1684 if (type instanceof InterfaceType) {1685 set = this._interfaceImplementations.get(type) ?? new Set();1686 } else if (type instanceof UnionType) {1687 set = this._unionTypes.get(type) ?? new Set();1688 } else {1689 throw createCompilerError(1690 'Invalid type supplied to "getPossibleTypeSet"',1691 );1692 }1693 if (!set) {1694 throw createCompilerError(1695 `Unable to find possible types for ${type.name}`,1696 );1697 }1698 return set;1699 }1700 getFetchableFieldName(type: ObjectTypeID): ?string {1701 return this._fetchable.get(type)?.field_name ?? null;1702 }1703 getQueryType(): ?BaseType {1704 return this._types.get(this._queryTypeName);1705 }1706 getMutationType(): ?BaseType {1707 return this._types.get(this._mutationTypeName);1708 }1709 getSubscriptionType(): ?BaseType {1710 return this._types.get(this._subscriptionTypeName);1711 }1712 getField(1713 type: InterfaceType | ObjectType,1714 fieldName: string,1715 ): ?FieldDefinition {1716 const fields = this._fields.get(type);1717 if (fields) {1718 return fields.get(fieldName);1719 }1720 }1721 getFieldMap(type: InterfaceType | ObjectType): ?Map<string, FieldDefinition> {1722 return this._fields.get(type);1723 }1724 getInputField(type: InputObjectType, fieldName: string): ?TypeNode {1725 const inputFields = this._inputFields.get(type);1726 if (inputFields) {1727 return inputFields.get(fieldName);1728 }1729 }1730 getInputFieldMap(type: InputObjectType): ?Map<string, TypeNode> {1731 return this._inputFields.get(type);1732 }1733 getDirectives(): $ReadOnlyArray<InternalDirectiveStruct> {1734 return Array.from(this._directives.values());1735 }1736 extend(extensions: $ReadOnlyArray<ExtensionNode>): TypeMap {1737 return new TypeMap(this._source, this._extensions.concat(extensions));1738 }1739}1740function create(1741 baseSchema: Source,1742 schemaExtensionDocuments?: $ReadOnlyArray<DocumentNode>,1743 schemaExtensions?: $ReadOnlyArray<string>,1744): Schema {1745 const extensions: Array<ExtensionNode> = [];1746 schemaExtensions &&1747 schemaExtensions.forEach(source => {1748 const doc = parse(source, {1749 noLocation: true,1750 });1751 doc.definitions.forEach(definition => {1752 if (isSchemaDefinitionAST(definition)) {1753 extensions.push(definition);1754 }1755 });1756 });1757 schemaExtensionDocuments &&1758 schemaExtensionDocuments.forEach(doc => {1759 doc.definitions.forEach(definition => {1760 if (isSchemaDefinitionAST(definition)) {1761 extensions.push(definition);1762 }1763 });1764 });1765 return new Schema(new TypeMap(baseSchema, extensions));1766}1767function parseInputArgumentDefinitions(1768 schema: Schema,1769 args: $ReadOnlyArray<InternalArgumentStruct>,1770): $ReadOnlyArray<Argument> {1771 return args.map(arg => {1772 const argType = schema.assertInputType(1773 schema.expectTypeFromAST(arg.typeNode),1774 );1775 let defaultValue;1776 const defaultValueNode = arg.defaultValue;1777 if (defaultValueNode != null) {1778 const nullableType = schema.getNullableType(argType);1779 const isNullable = schema.isNonNull(argType) === false;1780 if (isNullable && defaultValueNode.kind === 'NullValue') {1781 defaultValue = null;1782 } else {1783 if (1784 nullableType instanceof ScalarType ||1785 nullableType instanceof EnumType1786 ) {1787 defaultValue = schema.parseLiteral(nullableType, defaultValueNode);1788 } else if (1789 (nullableType instanceof List &&1790 defaultValueNode.kind === 'ListValue') ||1791 (nullableType instanceof InputObjectType &&1792 defaultValueNode.kind === 'ObjectValue')1793 ) {1794 defaultValue = valueFromASTUntyped(defaultValueNode);1795 }1796 }1797 if (defaultValue === undefined) {1798 throw createCompilerError(1799 `parseInputArgumentDefinitions: Unexpected default value: ${String(1800 defaultValueNode,1801 )}. Expected to have a value of type ${String(nullableType)}.`,1802 );1803 }1804 }1805 return {1806 name: arg.name,1807 type: argType,1808 defaultValue,1809 };1810 });1811}1812function parseInputArgumentDefinitionsMap(...
vue-var-module.js
Source:vue-var-module.js
...40 let ast = parser.parse(varDir.exp.content, {41 plugins: [...context.expressionPlugins, ...shared.babelParserDefaultPlugins]42 }).program.body43 if (!Array.isArray(ast) || ast.length !== 1) {44 context.onError(createCompilerError(10001, varDir.loc, null, 'ÐÑибка в v-var вÑÑажении: пÑÑÑо или много'))45 return false46 }47 ast = ast[0]48 if (ast.type !== "ExpressionStatement") {49 context.onError(createCompilerError(10001, varDir.loc, null, 'ÐÑибка в v-var вÑÑажении: не вÑÑажение'))50 return false51 }52 ast = ast.expression53 if (ast.type === "SequenceExpression") {54 ast = ast.expressions55 } else if (ast.type === "AssignmentExpression") {56 ast = [ast]57 } else {58 context.onError(createCompilerError(10001, varDir.loc, null, 'ÐÑибка в v-var вÑÑажении: непонÑÑнÑй Ñип ' + ast.type))59 return false60 }61 for (let ae of ast) {62 if (ae.left.type !== "Identifier") {63 // пÑиÑвоение не пеÑеменной64 continue65 }66 let varName = ae.left.name67 if (!varNamesOut.includes(varName)) {68 varNamesOut.push(varName)69 }70 }71 // patch only-var template72 if (node.tag === 'template' && node.props.length === 0) {73 node.tagType = 3 /* ElementTypes.TEMPLATE */74 node.props.push({75 type: 7,76 name: 'if',77 exp: createSimpleExpression('true', false, varDir.loc, false),78 arg: undefined,79 modifiers: [],80 loc: varDir.loc81 })82 }83 }84 }85 }86 if ((node.type === 0 || node.type === 1) && node.children) {87 let r = true88 for (let child of node.children) {89 r = r && prepareTree(child, context, varNamesOut)90 }91 return r92 }93 return true94}95function processTree(parentNode, node, context) {96 if (node.loc._varDirs || node.loc._varDirsPre) {97 if (node.type === 1) {98 if (node.loc._varDirs) {99 let codegenNodeItems = ['(']100 for (const varDir of node.loc._varDirs) {101 codegenNodeItems.push(varDir.exp, ', ')102 }103 codegenNodeItems.push(node.codegenNode, ')')104 node.codegenNode = createCompoundExpression(codegenNodeItems, node.codegenNode.loc)105 }106 if (node.loc._varDirsPre) {107 context.onError(createCompilerError(10001, node.loc, null, 'ÐевеÑное меÑÑо Ð´Ð»Ñ v-var.pre. ÐоÑÑÑпно ÑолÑко вмеÑÑе Ñ if или for'))108 }109 } else if (node.type === 10 /* IF_BRANCH */) {110 let codePenNode = parentNode.codegenNode111 let codePenNodeBranch = 0/*consequent*/112 for (let i = 0; i < parentNode.branches.length; i++) {113 if (parentNode.branches[i] === node) {114 break115 }116 if (parentNode.branches[i + 1].condition) {117 codePenNodeBranch = 0/*consequent*/118 codePenNode = codePenNode.alternate119 if (codePenNode.type !== 19) {120 assert(codePenNode.type === 19)121 }122 } else {123 codePenNodeBranch = 1/*alternate*/124 }125 }126 if (node.loc._varDirs) {127 let codegenNodeItems = ['(']128 for (const varDir of node.loc._varDirs) {129 codegenNodeItems.push(varDir.exp, ', ')130 }131 if (codePenNodeBranch === 0/*consequent*/) {132 codegenNodeItems.push(codePenNode.consequent, ')')133 codePenNode.consequent = createCompoundExpression(codegenNodeItems, codePenNode.loc)134 } else {135 codegenNodeItems.push(codePenNode.alternate, ')')136 codePenNode.alternate = createCompoundExpression(codegenNodeItems, codePenNode.loc)137 }138 }139 if (node.loc._varDirsPre) {140 if (codePenNodeBranch === 1/*alternate*/) {141 context.onError(createCompilerError(10001, node.loc, null, 'ÐевеÑное меÑÑо Ð´Ð»Ñ v-var.pre. ÐоÑÑÑпно ÑолÑко вмеÑÑе Ñ if или for'))142 } else {143 let codegenNodeItems = ['(']144 for (const varDir of node.loc._varDirsPre) {145 codegenNodeItems.push(varDir.exp, ', ')146 }147 codegenNodeItems.push(codePenNode.test, ')')148 codePenNode.test = createCompoundExpression(codegenNodeItems, codePenNode.loc)149 }150 }151 delete node.loc._varDirsPre152 } else if (node.type === 9 /* IF */) {153 // no op154 } else if (node.type === 11 /* FOR */) {155 assert(node.codegenNode.type === 13)156 assert(node.codegenNode.children.type === 14)157 assert(node.codegenNode.children.arguments.length === 2)158 assert(node.codegenNode.children.arguments[1].type === 18 /* JS_FUNCTION_EXPRESSION */)159 if (node.loc._varDirs) {160 let codegenNodeItems = ['(']161 for (const varDir of node.loc._varDirs) {162 codegenNodeItems.push(varDir.exp, ', ')163 }164 codegenNodeItems.push(node.codegenNode.children.arguments[1].returns, ')')165 node.codegenNode.children.arguments[1].returns = createCompoundExpression(codegenNodeItems, node.codegenNode.children.loc)166 }167 if (node.loc._varDirsPre) {168 let codegenNodeItems = ['(']169 for (const varDir of node.loc._varDirsPre) {170 codegenNodeItems.push(varDir.exp, ', ')171 }172 codegenNodeItems.push(node.codegenNode.children.arguments[0], ')')173 node.codegenNode.children.arguments[0] = createCompoundExpression(codegenNodeItems, node.codegenNode.children.loc)174 }175 } else {176 context.onError(createCompilerError(10001, node.loc, null, 'Ðело ÑÑмное!'))177 debugger178 }179 }180 switch (node.type) {181 case 9 /* IF */:182 for (let i = 0; i < node.branches.length; i++) {183 processTree(node, node.branches[i], context)184 }185 break186 case 10 /* IF_BRANCH */:187 case 11 /* FOR */:188 case 1 /* ELEMENT */:189 case 0 /* ROOT */:190 for (let i = 0; i < node.children.length; i++) {...
NormalizationCodeGenerator.js
Source:NormalizationCodeGenerator.js
...30 * used at runtime.31 */32function generate(node) {33 if (node.kind !== 'Root' && node.kind !== 'SplitOperation') {34 throw createCompilerError("NormalizationCodeGenerator: Unsupported AST kind '".concat(node.kind, "'."), [node.loc]);35 }36 return IRVisitor.visit(node, NormalizationCodeGenVisitor);37}38var NormalizationCodeGenVisitor = {39 leave: {40 Root: function Root(node) {41 return {42 kind: 'Operation',43 name: node.name,44 argumentDefinitions: node.argumentDefinitions,45 selections: flattenArray(node.selections)46 };47 },48 Request: function Request(node) {49 throw createCompilerError('NormalizationCodeGenerator: unexpected Request node.');50 },51 Fragment: function Fragment(node) {52 throw createCompilerError('NormalizationCodeGenerator: unexpected Fragment node.');53 },54 LocalArgumentDefinition: function LocalArgumentDefinition(node) {55 return {56 kind: 'LocalArgument',57 name: node.name,58 type: node.type.toString(),59 defaultValue: node.defaultValue60 };61 },62 RootArgumentDefinition: function RootArgumentDefinition(node) {63 return {64 kind: 'RootArgument',65 name: node.name,66 type: node.type ? node.type.toString() : null67 };68 },69 Condition: function Condition(node, key, parent, ancestors) {70 if (node.condition.kind !== 'Variable') {71 throw createCompilerError("NormalizationCodeGenerator: Expected 'Condition' with static " + 'value to be pruned or inlined', [node.condition.loc]);72 }73 return {74 kind: 'Condition',75 passingValue: node.passingValue,76 condition: node.condition.variableName,77 selections: flattenArray(node.selections)78 };79 },80 Defer: function Defer(node, key, parent, ancestors) {81 var _node$if2;82 if (!(node["if"] == null || node["if"].kind === 'Variable' || node["if"].kind === 'Literal' && node["if"].value === true)) {83 var _ref, _node$if;84 throw createCompilerError('NormalizationCodeGenerator: Expected @defer `if` condition to be ' + 'a variable, unspecified, or the literal `true`.', [(_ref = (_node$if = node["if"]) === null || _node$if === void 0 ? void 0 : _node$if.loc) !== null && _ref !== void 0 ? _ref : node.loc]);85 }86 return {87 "if": ((_node$if2 = node["if"]) === null || _node$if2 === void 0 ? void 0 : _node$if2.kind) === 'Variable' ? node["if"].variableName : null,88 kind: 'Defer',89 label: node.label,90 metadata: node.metadata,91 selections: flattenArray(node.selections)92 };93 },94 FragmentSpread: function FragmentSpread(node) {95 // TODO(T37646905) enable this invariant after splitting the96 // RelayCodeGenerator-test and running the InlineFragmentsTransform on97 // normalization ASTs.98 //99 // throw new Error(100 // 'NormalizationCodeGenerator: unexpected FragmentSpread node.',101 // );102 return [];103 },104 InlineFragment: function InlineFragment(node) {105 return {106 kind: 'InlineFragment',107 type: node.typeCondition.toString(),108 selections: flattenArray(node.selections)109 };110 },111 LinkedField: function LinkedField(node) {112 // Note: it is important that the arguments of this field be sorted to113 // ensure stable generation of storage keys for equivalent arguments114 // which may have originally appeared in different orders across an app.115 var handles = node.handles && node.handles.map(function (handle) {116 return {117 kind: 'LinkedHandle',118 alias: node.alias,119 name: node.name,120 args: valuesOrNull(sortByName(node.args)),121 handle: handle.name,122 key: handle.key,123 filters: handle.filters124 };125 }) || [];126 var type = getRawType(node.type);127 var field = {128 kind: 'LinkedField',129 alias: node.alias,130 name: node.name,131 storageKey: null,132 args: valuesOrNull(sortByName(node.args)),133 concreteType: !isAbstractType(type) ? type.toString() : null,134 plural: isPlural(node.type),135 selections: flattenArray(node.selections)136 }; // Precompute storageKey if possible137 var storageKey = getStaticStorageKey(field, node.metadata);138 if (storageKey) {139 field = (0, _objectSpread2["default"])({}, field, {140 storageKey: storageKey141 });142 }143 return [field].concat(handles);144 },145 MatchField: function MatchField(node, key, parent, ancestors) {146 var selections = flattenArray(node.selections);147 var matchesByType = {};148 selections.forEach(function (selection) {149 var _regExpMatch$;150 if (selection.kind === 'ScalarField' && selection.name === '__typename') {151 // The RelayGenerateTypename transform will add a __typename selection152 // to the selections of the match field.153 return;154 }155 if (selection.kind !== 'MatchBranch') {156 throw createCompilerError("NormalizationCodeGenerator: Expected selection for MatchField '".concat(node.name, "' to be a 'MatchBranch', got '").concat(selection.kind, "'."), [selection.loc]);157 }158 if (matchesByType.hasOwnProperty(selection.type)) {159 throw createCompilerError('NormalizationCodeGenerator: Each @match type can appear at-most ' + "once. Type '".concat(String(selection.type), "' was duplicated."), selection.type, [selection.loc]);160 }161 var fragmentName = selection.name;162 var regExpMatch = fragmentName.match(/^([a-zA-Z][a-zA-Z0-9]*)(?:_([a-zA-Z][_a-zA-Z0-9]*))?$/);163 if (!regExpMatch) {164 throw createCompilerError('NormalizationCodeGenerator: @match fragments should be named ' + "'FragmentName_propName', got '".concat(fragmentName, "'."), [selection.loc]);165 }166 var fragmentPropName = (_regExpMatch$ = regExpMatch[2]) !== null && _regExpMatch$ !== void 0 ? _regExpMatch$ : 'matchData';167 matchesByType[selection.type] = {168 fragmentPropName: fragmentPropName,169 fragmentName: fragmentName170 };171 });172 var field = {173 kind: 'MatchField',174 alias: node.alias,175 name: node.name,176 storageKey: null,177 args: valuesOrNull(sortByName(node.args)),178 matchesByType: matchesByType179 }; // Precompute storageKey if possible180 var storageKey = getStaticStorageKey(field, node.metadata);181 if (storageKey) {182 field = (0, _objectSpread2["default"])({}, field, {183 storageKey: storageKey184 });185 }186 return field;187 },188 ScalarField: function ScalarField(node) {189 // Note: it is important that the arguments of this field be sorted to190 // ensure stable generation of storage keys for equivalent arguments191 // which may have originally appeared in different orders across an app.192 var handles = node.handles && node.handles.map(function (handle) {193 return {194 kind: 'ScalarHandle',195 alias: node.alias,196 name: node.name,197 args: valuesOrNull(sortByName(node.args)),198 handle: handle.name,199 key: handle.key,200 filters: handle.filters201 };202 }) || [];203 var field = {204 kind: 'ScalarField',205 alias: node.alias,206 name: node.name,207 args: valuesOrNull(sortByName(node.args)),208 storageKey: null209 }; // Precompute storageKey if possible210 var storageKey = getStaticStorageKey(field, node.metadata);211 if (storageKey) {212 field = (0, _objectSpread2["default"])({}, field, {213 storageKey: storageKey214 });215 }216 return [field].concat(handles);217 },218 SplitOperation: function SplitOperation(node, key, parent) {219 return {220 kind: 'SplitOperation',221 name: node.name,222 metadata: node.metadata,223 selections: flattenArray(node.selections)224 };225 },226 Stream: function Stream(node, key, parent, ancestors) {227 var _node$if4;228 if (!(node["if"] == null || node["if"].kind === 'Variable' || node["if"].kind === 'Literal' && node["if"].value === true)) {229 var _ref2, _node$if3;230 throw createCompilerError('NormalizationCodeGenerator: Expected @stream `if` condition to be ' + 'a variable, unspecified, or the literal `true`.', [(_ref2 = (_node$if3 = node["if"]) === null || _node$if3 === void 0 ? void 0 : _node$if3.loc) !== null && _ref2 !== void 0 ? _ref2 : node.loc]);231 }232 return {233 "if": ((_node$if4 = node["if"]) === null || _node$if4 === void 0 ? void 0 : _node$if4.kind) === 'Variable' ? node["if"].variableName : null,234 kind: 'Stream',235 label: node.label,236 metadata: node.metadata,237 selections: flattenArray(node.selections)238 };239 },240 Variable: function Variable(node, key, parent) {241 return {242 kind: 'Variable',243 name: parent.name,244 variableName: node.variableName,...
ReaderCodeGenerator.js
Source:ReaderCodeGenerator.js
...35}36var ReaderCodeGenVisitor = {37 leave: {38 Request: function Request(node) {39 throw createCompilerError('ReaderCodeGenerator: unexpeted Request node.');40 },41 Fragment: function Fragment(node) {42 var metadata = null;43 if (node.metadata != null) {44 var _node$metadata = node.metadata,45 mask = _node$metadata.mask,46 plural = _node$metadata.plural,47 connection = _node$metadata.connection,48 refetch = _node$metadata.refetch;49 if (Array.isArray(connection)) {50 var _metadata;51 metadata = (_metadata = metadata) !== null && _metadata !== void 0 ? _metadata : {};52 metadata.connection = connection;53 }54 if (typeof mask === 'boolean') {55 var _metadata2;56 metadata = (_metadata2 = metadata) !== null && _metadata2 !== void 0 ? _metadata2 : {};57 metadata.mask = mask;58 }59 if (typeof plural === 'boolean') {60 var _metadata3;61 metadata = (_metadata3 = metadata) !== null && _metadata3 !== void 0 ? _metadata3 : {};62 metadata.plural = plural;63 }64 if (typeof refetch === 'object') {65 var _metadata4;66 metadata = (_metadata4 = metadata) !== null && _metadata4 !== void 0 ? _metadata4 : {};67 metadata.refetch = {68 connection: refetch.connection,69 operation: CodeMarker.moduleDependency(refetch.operation + '.graphql'),70 fragmentPathInResult: refetch.fragmentPathInResult71 };72 }73 }74 return {75 kind: 'Fragment',76 name: node.name,77 type: node.type.toString(),78 metadata: metadata,79 argumentDefinitions: node.argumentDefinitions,80 selections: node.selections81 };82 },83 LocalArgumentDefinition: function LocalArgumentDefinition(node) {84 return {85 kind: 'LocalArgument',86 name: node.name,87 type: node.type.toString(),88 defaultValue: node.defaultValue89 };90 },91 RootArgumentDefinition: function RootArgumentDefinition(node) {92 return {93 kind: 'RootArgument',94 name: node.name,95 type: node.type ? node.type.toString() : null96 };97 },98 Condition: function Condition(node, key, parent, ancestors) {99 if (node.condition.kind !== 'Variable') {100 throw createCompilerError("ReaderCodeGenerator: Expected 'Condition' with static value to be " + 'pruned or inlined', [node.condition.loc]);101 }102 return {103 kind: 'Condition',104 passingValue: node.passingValue,105 condition: node.condition.variableName,106 selections: node.selections107 };108 },109 FragmentSpread: function FragmentSpread(node) {110 return {111 kind: 'FragmentSpread',112 name: node.name,113 args: valuesOrNull(sortByName(node.args))114 };115 },116 InlineFragment: function InlineFragment(node) {117 return {118 kind: 'InlineFragment',119 type: node.typeCondition.toString(),120 selections: node.selections121 };122 },123 LinkedField: function LinkedField(node) {124 // Note: it is important that the arguments of this field be sorted to125 // ensure stable generation of storage keys for equivalent arguments126 // which may have originally appeared in different orders across an app.127 // TODO(T37646905) enable this invariant after splitting the128 // RelayCodeGenerator-test and running the RelayFieldHandleTransform on129 // Reader ASTs.130 //131 // invariant(132 // node.handles == null,133 // 'ReaderCodeGenerator: unexpected handles',134 // );135 var type = getRawType(node.type);136 var field = {137 kind: 'LinkedField',138 alias: node.alias,139 name: node.name,140 storageKey: null,141 args: valuesOrNull(sortByName(node.args)),142 concreteType: !isAbstractType(type) ? type.toString() : null,143 plural: isPlural(node.type),144 selections: node.selections145 }; // Precompute storageKey if possible146 var storageKey = getStaticStorageKey(field, node.metadata);147 if (storageKey) {148 field = (0, _objectSpread2["default"])({}, field, {149 storageKey: storageKey150 });151 }152 return field;153 },154 MatchField: function MatchField(node, key, parent, ancestors) {155 var matchesByType = {};156 node.selections.forEach(function (selection) {157 var _regExpMatch$;158 if (selection.kind === 'ScalarField' && selection.name === '__typename') {159 // The RelayGenerateTypename transform will add a __typename selection160 // to the selections of the match field.161 return;162 }163 if (selection.kind !== 'MatchBranch') {164 throw createCompilerError("ReaderCodeGenerator: Expected selection for MatchField '".concat(node.name, "' to be a 'MatchBranch', got '").concat(selection.kind, "'."), [selection.loc]);165 }166 if (matchesByType.hasOwnProperty(selection.type)) {167 throw createCompilerError('ReaderCodeGenerator: Each @match type can appear at-most once. ' + "Type '".concat(String(selection.type), "' was duplicated."), selection.type, [selection.loc]);168 }169 var fragmentName = selection.name;170 var regExpMatch = fragmentName.match(/^([a-zA-Z][a-zA-Z0-9]*)(?:_([a-zA-Z][_a-zA-Z0-9]*))?$/);171 if (!regExpMatch) {172 throw createCompilerError('ReaderCodeGenerator: @match fragments should be named ' + "'FragmentName_propName', got '".concat(fragmentName, "'."), [selection.loc]);173 }174 var fragmentPropName = (_regExpMatch$ = regExpMatch[2]) !== null && _regExpMatch$ !== void 0 ? _regExpMatch$ : 'matchData';175 matchesByType[selection.type] = {176 fragmentPropName: fragmentPropName,177 fragmentName: fragmentName178 };179 });180 var field = {181 kind: 'MatchField',182 alias: node.alias,183 name: node.name,184 storageKey: null,185 args: valuesOrNull(sortByName(node.args)),186 matchesByType: matchesByType...
vue-forms-module.js
Source:vue-forms-module.js
...20 */21module.exports = function (node, context) {22 if (node.type === 1 && node.tag === 'FForm') {23 if (node.props.some(x=>x.type===7 && x.name === 'slot')) {24 context.onError(createCompilerError(10001, nameProp.loc, null, 'FForm не должен ÑодеÑжаÑÑ Ñвного ÑÐºÐ°Ð·Ð°Ð½Ð¸Ñ ÑлоÑов #=...'))25 }26 let slotProp = {27 type: 7 /*NodeTypes.DIRECTIVE*/,28 name: 'slot',29 exp: processExpression(createSimpleExpression("{$value, $cont}"), context, true),// createCompoundExpression(["{$value, $cont}"]),30 arg: undefined,31 modifiers: [''],32 loc: node.loc33 }34 node.props.push(slotProp)35 if (context.prefixIdentifiers) {36 context.addIdentifiers(slotProp.exp)37 }38 context.scopes.vSlot++39 context.scopes.f_inCont = context.scopes.f_inCont ? context.scopes.f_inCont + 1 : 140 return () => {41 if (context.prefixIdentifiers) {42 context.removeIdentifiers(slotProp.exp);43 }44 context.scopes.vSlot--;45 context.scopes.f_inCont--;46 };47 }48 if (node.type === 1 && node.tag === 'FCont') {49 if (node.props.some(x=>x.type===7 && x.name === 'slot')) {50 context.onError(createCompilerError(10001, nameProp.loc, null, 'FCont не должен ÑодеÑжаÑÑ Ñвного ÑÐºÐ°Ð·Ð°Ð½Ð¸Ñ ÑлоÑов #=...'))51 }52 let slotProp = {53 type: 7 /*NodeTypes.DIRECTIVE*/,54 name: 'slot',55 exp: processExpression(createSimpleExpression("{$value, $cont}"), context, true),56 arg: undefined,57 modifiers: [''],58 loc: node.loc59 }60 node.props.push(slotProp)61 if (context.prefixIdentifiers) {62 context.addIdentifiers(slotProp.exp)63 }64 context.scopes.vSlot++65 context.scopes.f_inCont = context.scopes.f_inCont ? context.scopes.f_inCont + 1 : 166 return () => {67 if (context.prefixIdentifiers) {68 context.removeIdentifiers(slotProp.exp);69 }70 context.scopes.vSlot--;71 context.scopes.f_inCont--;72 };73 }74 if (node.type === 1 && (node.tag === 'FArray' || node.tag === 'FObject')) {75 let nameProp = findProp(node, 'name')76 if (node.props.some(x=>x.type===7 && x.name === 'slot')) {77 context.onError(createCompilerError(10001, nameProp.loc, null, 'FArray и FObject не Ð´Ð¾Ð»Ð¶ÐµÐ½Ñ ÑодеÑжаÑÑ Ñвного ÑÐºÐ°Ð·Ð°Ð½Ð¸Ñ ÑлоÑов #=...'))78 }79 if (!nameProp) {80 context.onError(createCompilerError(10001, nameProp.loc, null, 'FArray и FObject Ð´Ð¾Ð»Ð¶ÐµÐ½Ñ ÑодеÑжаÑÑ ÑвойÑÑво name'))81 }82 let nameExpr83 if (nameProp.type === 6 /*ATTRIBUTE*/) {84 nameExpr = JSON.stringify(nameProp.value.content)85 } else if (nameProp.type === 7 /*DIRECTIVE*/ && nameProp.name === 'bind') {86 nameExpr = nameProp.exp.content87 } else {88 context.onError(createCompilerError(10001, nameProp.loc, null, 'ÐеизвеÑÑнÑй Ñип Ñзла имени'))89 }90 node.props.push({91 type: 7 /*NodeTypes.DIRECTIVE*/,92 name: 'bind',93 exp: `$value[${nameExpr}]`,94 arg: createSimpleExpression('value', true, locStub, true),95 modifiers: [],96 loc: node.loc97 })98 if (findProp(node, 'default')) {99 node.props.push({100 type: 7 /*NodeTypes.DIRECTIVE*/,101 name: 'on',102 exp: createSimpleExpression(`$value[${nameExpr}]=$event`),103 arg: createSimpleExpression('setDefault', true, locStub, true),104 modifiers: [],105 loc: node.loc106 })107 }108 let slotProp = {109 type: 7 /*NodeTypes.DIRECTIVE*/,110 name: 'slot',111 exp: processExpression(createSimpleExpression(node.tag === 'FArray' ? "{$parentCont, $cont, $value, $index}" : "{$parentCont, $cont, $value}"), context, true),// createCompoundExpression(["{$value, $cont}"]),112 arg: undefined,113 modifiers: [''],114 loc: node.loc115 }116 node.props.push(slotProp)117 if (context.prefixIdentifiers) {118 context.addIdentifiers(slotProp.exp)119 }120 context.scopes.vSlot++121 context.scopes.f_inCont = context.scopes.f_inCont ? context.scopes.f_inCont + 1 : 1122 return () => {123 if (context.prefixIdentifiers) {124 context.removeIdentifiers(slotProp.exp);125 }126 context.scopes.vSlot--;127 context.scopes.f_inCont--;128 };129 }130 if (node.type === 1 && context.scopes.f_inCont) {131 let nameProp = findProp(node, 'name')132 if (nameProp) {133 let isComponent = /^([A-Z]{2}|[a-z]-)/.test(node.tag)134 let nameExpr135 if (nameProp.type === 6 /*ATTRIBUTE*/) {136 nameExpr = JSON.stringify(nameProp.value.content)137 } else if (nameProp.type === 7 /*DIRECTIVE*/ && nameProp.name === 'bind') {138 nameExpr = nameProp.exp.content139 } else {140 context.onError(createCompilerError(10001, nameProp.loc, null, 'ÐеизвеÑÑнÑй Ñип Ñзла имени'))141 }142 if (!isComponent) {143 node.props.push({144 type: 7 /*NodeTypes.DIRECTIVE*/,145 name: 'fname',146 exp: processExpression(createSimpleExpression(`{name: ${nameExpr}, cont: $cont}`), context),147 arg: undefined,148 modifiers: [],149 loc: nameProp.loc150 })151 }152 let vModelExpr = `$value[${nameExpr}]`153 node.props.push({154 type: 7 /*NodeTypes.DIRECTIVE*/,...
FlattenTransform.js
Source:FlattenTransform.js
...53 // Determine the current type.54 var parentType = state.parentType;55 var type = node.kind === 'Condition' || node.kind === 'Defer' || node.kind === 'Stream' ? parentType : node.kind === 'InlineFragment' ? node.typeCondition : node.type;56 if (type == null) {57 throw createCompilerError('FlattenTransform: Expected a parent type.', [node.loc]);58 } // Flatten the selections in this node, creating a new node with flattened59 // selections if possible, then deeply traverse the flattened node, while60 // keeping track of the parent type.61 var nextSelections = new Map();62 var hasFlattened = flattenSelectionsInto(nextSelections, node, state, type);63 var flattenedNode = hasFlattened ? (0, _objectSpread2["default"])({}, node, {64 selections: Array.from(nextSelections.values())65 }) : node;66 state.parentType = type;67 var deeplyFlattenedNode = this.traverse(flattenedNode, state);68 state.parentType = parentType;69 return deeplyFlattenedNode;70}71/**72 * @private73 */74function flattenSelectionsInto(flattenedSelections, node, state, type) {75 var hasFlattened = false;76 node.selections.forEach(function (selection) {77 if (selection.kind === 'InlineFragment' && shouldFlattenInlineFragment(selection, state, type)) {78 hasFlattened = true;79 flattenSelectionsInto(flattenedSelections, selection, state, type);80 return;81 }82 var nodeIdentifier = getIdentifierForSelection(selection);83 var flattenedSelection = flattenedSelections.get(nodeIdentifier); // If this selection hasn't been seen before, keep track of it.84 if (!flattenedSelection) {85 flattenedSelections.set(nodeIdentifier, selection);86 return;87 } // Otherwise a similar selection exists which should be merged.88 hasFlattened = true;89 if (flattenedSelection.kind === 'InlineFragment') {90 if (selection.kind !== 'InlineFragment') {91 throw createCompilerError("FlattenTransform: Expected an InlineFragment, got a '".concat(selection.kind, "'"), [selection.loc]);92 }93 flattenedSelections.set(nodeIdentifier, (0, _objectSpread2["default"])({}, flattenedSelection, {94 selections: mergeSelections(flattenedSelection, selection, state, selection.typeCondition)95 }));96 } else if (flattenedSelection.kind === 'Condition') {97 if (selection.kind !== 'Condition') {98 throw createCompilerError("FlattenTransform: Expected a Condition, got a '".concat(selection.kind, "'"), [selection.loc]);99 }100 flattenedSelections.set(nodeIdentifier, (0, _objectSpread2["default"])({}, flattenedSelection, {101 selections: mergeSelections(flattenedSelection, selection, state, type)102 }));103 } else if (flattenedSelection.kind === 'FragmentSpread') {// Ignore duplicate fragment spreads.104 } else if (flattenedSelection.kind === 'MatchField' || flattenedSelection.kind === 'MatchBranch') {// Ignore duplicate matches that select the same fragments and105 // modules (encoded in the identifier)106 // Also ignore incremental data placeholders107 } else if (flattenedSelection.kind === 'Defer') {108 if (selection.kind !== 'Defer') {109 throw createCompilerError("FlattenTransform: Expected a Defer, got a '".concat(selection.kind, "'"), [selection.loc]);110 }111 flattenedSelections.set(nodeIdentifier, (0, _objectSpread2["default"])({112 kind: 'Defer'113 }, flattenedSelection, {114 selections: mergeSelections(flattenedSelection, selection, state, type)115 }));116 } else if (flattenedSelection.kind === 'Stream') {117 if (selection.kind !== 'Stream') {118 throw createCompilerError("FlattenTransform: Expected a Stream, got a '".concat(selection.kind, "'"), [selection.loc]);119 }120 flattenedSelections.set(nodeIdentifier, (0, _objectSpread2["default"])({121 kind: 'Stream'122 }, flattenedSelection, {123 selections: mergeSelections(flattenedSelection, selection, state, type)124 }));125 } else if (flattenedSelection.kind === 'LinkedField') {126 if (selection.kind !== 'LinkedField') {127 throw createCompilerError("FlattenTransform: Expected a LinkedField, got a '".concat(selection.kind, "'"), [selection.loc]);128 } // Note: arguments are intentionally reversed to avoid rebuilds129 assertUniqueArgsForAlias(selection, flattenedSelection);130 flattenedSelections.set(nodeIdentifier, (0, _objectSpread2["default"])({131 kind: 'LinkedField'132 }, flattenedSelection, {133 handles: mergeHandles(flattenedSelection, selection),134 selections: mergeSelections(flattenedSelection, selection, state, selection.type)135 }));136 } else if (flattenedSelection.kind === 'ScalarField') {137 if (selection.kind !== 'ScalarField') {138 throw createCompilerError("FlattenTransform: Expected a ScalarField, got a '".concat(selection.kind, "'"), [selection.loc]);139 } // Note: arguments are intentionally reversed to avoid rebuilds140 assertUniqueArgsForAlias(selection, flattenedSelection);141 flattenedSelections.set(nodeIdentifier, (0, _objectSpread2["default"])({142 kind: 'ScalarField'143 }, flattenedSelection, {144 // Note: arguments are intentionally reversed to avoid rebuilds145 handles: mergeHandles(selection, flattenedSelection)146 }));147 } else {148 flattenedSelection.kind;149 throw createCompilerError("FlattenTransform: Unknown kind '".concat(flattenedSelection.kind, "'"));150 }151 });152 return hasFlattened;153}154/**155 * @private156 */157function mergeSelections(nodeA, nodeB, state, type) {158 var flattenedSelections = new Map();159 flattenSelectionsInto(flattenedSelections, nodeA, state, type);160 flattenSelectionsInto(flattenedSelections, nodeB, state, type);161 return Array.from(flattenedSelections.values());162}163/**...
checkTemplate.js
Source:checkTemplate.js
...12 let ast;13 try {14 ast = parseVue($options.template);15 } catch (e) {16 throw createCompilerError(e.code);17 }18 if (!checkVariableAvailability) {19 return;20 }21 const propNamesArray = $options.props22 ? Array.isArray($options.props)23 ? $options.props24 : Object.keys($options.props)25 : [];26 const dataArray =27 typeof $options.data === "function" ? Object.keys($options.data()) : [];28 const computedArray = $options.computed ? Object.keys($options.computed) : [];29 const methodsArray =30 $options && $options.methods ? Object.keys($options.methods) : [];...
RelayCodeGenerator.js
Source:RelayCodeGenerator.js
...31 };32 case 'SplitOperation':33 return NormalizationCodeGenerator.generate(node);34 }35 throw createCompilerError("RelayCodeGenerator: Unknown AST kind '".concat(node.kind, "'."), [node.loc]);36}37module.exports = {38 generate: generate...
Using AI Code Generation
1const { createCompilerError } = require('@playwright/test/lib/server/traceModel');2const { createCompilerError } = require('@playwright/test/lib/server/traceModel');3const error = createCompilerError('error message');4console.log(error);5{ Error: error message6 at Object.<anonymous> (/Users/username/test.js:5:15)7 at Module._compile (internal/modules/cjs/loader.js:1063:30)8 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)9 at Module.load (internal/modules/cjs/loader.js:928:32)10 at Function.Module._load (internal/modules/cjs/loader.js:769:14)11 at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)12 [ { file: '/Users/username/test.js',13 functionName: 'Object.<anonymous>' } ] }14console.log(error.message);15console.log(error.stack);16 at Object.<anonymous> (/Users/username/test.js:5:15)17 at Module._compile (internal/modules/cjs/loader.js:1063:30)18 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)19 at Module.load (internal/modules/cjs/loader.js:928:32)20 at Function.Module._load (internal/modules/cjs/loader.js:769:14)21 at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)22console.log(error.frames);23[ { file: '/Users/username/test.js',24 functionName: 'Object.<anonymous>' } ]25console.log(error.frames);26[ { file
Using AI Code Generation
1const { createCompilerError } = require('playwright/lib/server/supplements/utils/compilerError');2const error = createCompilerError('Error message');3console.log(error.message);4console.log(error.stack);5 at Object.<anonymous> (/Users/xxx/Documents/xxx/test.js:4:23)6 at Module._compile (internal/modules/cjs/loader.js:1158:30)7 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)8 at Module.load (internal/modules/cjs/loader.js:1002:32)9 at Function.Module._load (internal/modules/cjs/loader.js:901:14)10 at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
Using AI Code Generation
1const { createCompilerError } = require('playwright/lib/server/errors');2const error = createCompilerError('This is a test error');3console.log(error);4const { createCompilerError } = require('playwright/lib/server/errors');5const error = createCompilerError('This is a test error');6console.log(error);7const { createCompilerError } = require('playwright/lib/server/errors');8const error = createCompilerError('This is a test error');9console.log(error);10const { createCompilerError } = require('playwright/lib/server/errors');11const error = createCompilerError('This is a test error');12console.log(error);13const { createCompilerError } = require('playwright/lib/server/errors');14const error = createCompilerError('This is a test error');15console.log(error);16const { createCompilerError } = require('playwright/lib/server/errors');17const error = createCompilerError('This is a test error');18console.log(error);19const { createCompilerError } = require('playwright/lib/server/errors');20const error = createCompilerError('This is a test error');21console.log(error);22const { createCompilerError } = require('playwright/lib/server/errors');23const error = createCompilerError('This is a test error');24console.log(error);25const { createCompilerError } = require('playwright/lib/server/errors');26const error = createCompilerError('This is a test error');27console.log(error);28const { createCompilerError } = require('playwright/lib/server/errors');29const error = createCompilerError('This is a test error');30console.log(error);31const { createCompilerError } = require('playwright/lib/server/errors');32const error = createCompilerError('This is a test error');33console.log(error);34const { createCompilerError } = require('playwright/lib/server/errors');35const error = createCompilerError('This is a test error');36console.log(error);37const { createCompilerError } = require('playwright/lib/server/errors');38const error = createCompilerError('This is a
Using AI Code Generation
1const { createCompilerError } = require('playwright-core/lib/server/inspector/inspector.js');2const error = createCompilerError({3 location: {4 },5});6console.log(error);7{ message: 'test error',8 { url: 'test url',9 column: 1 } }10const error = createCompilerError({ /* ... */ });11throw new Error(error.message);
Using AI Code Generation
1const { createCompilerError } = require('playwright/lib/utils/stackTrace');2const err = new Error('some error');3const internalError = createCompilerError(err);4console.log(internalError.stack);5const { createCompilerError } = require('playwright/lib/utils/stackTrace');6const err = new Error('some error');7const internalError = createCompilerError(err);8console.log(internalError.stack);9const { createCompilerError } = require('playwright/lib/utils/stackTrace');10const err = new Error('some error');11const internalError = createCompilerError(err);12console.log(internalError.stack);13const { createCompilerError } = require('playwright/lib/utils/stackTrace');14const err = new Error('some error');15const internalError = createCompilerError(err);16console.log(internalError.stack);17const { createCompilerError } = require('playwright/lib/utils/stackTrace');18const err = new Error('some error');19const internalError = createCompilerError(err);20console.log(internalError.stack);21const { createCompilerError } = require('playwright/lib/utils/stackTrace');22const err = new Error('some error');23const internalError = createCompilerError(err);24console.log(internalError.stack);25const { createCompilerError } = require('playwright/lib/utils/stackTrace');26const err = new Error('some error');27const internalError = createCompilerError(err);28console.log(internalError.stack);29const { createCompilerError } = require('playwright/lib/utils/stackTrace');30const err = new Error('some error');31const internalError = createCompilerError(err);32console.log(internalError.stack);
Using AI Code Generation
1import { createCompilerError } from "playwright-core/lib/server/utils/stackTrace";2const error = createCompilerError('Error Message');3console.log(error);4import { formatError } from "playwright-core/lib/server/utils/stackTrace";5const error = formatError('Error Message');6console.log(error);7import { formatError } from "playwright-core/lib/server/utils/stackTrace";8const error = formatError('Error Message');9console.log(error);10import { formatError } from "playwright-core/lib/server/utils/stackTrace";11const error = formatError('Error Message');12console.log(error);13import { formatError } from "playwright-core/lib/server/utils/stackTrace";14const error = formatError('Error Message');15console.log(error);16import { formatError } from "playwright-core/lib/server/utils/stackTrace";17const error = formatError('Error Message');18console.log(error);19import { formatError } from "playwright-core/lib/server/utils/stackTrace";20const error = formatError('Error Message');21console.log(error);22import { formatError } from "playwright-core/lib/server/utils/stackTrace";23const error = formatError('Error Message');24console.log(error);25import { formatError } from "playwright-core/lib/server/utils/stackTrace";26const error = formatError('Error Message');27console.log(error);28import { formatError } from "playwright-core/lib/server/utils/stackTrace";29const error = formatError('Error Message');30console.log(error);31import { formatError } from "playwright-core/lib/server/utils/stackTrace";32const error = formatError('Error Message');33console.log(error);34import { formatError } from "playwright-core/lib/server/utils/stackTrace";
Using AI Code Generation
1const { createCompilerError } = require('playwright/lib/server/supplements/compiler/compileScript');2const error = createCompilerError('Error message', 'Error stack');3console.log(error);4const { createCompilerError } = require('playwright/lib/server/supplements/compiler/compileScript');5const error = createCompilerError('Error message', 'Error stack');6console.log(error);7const { createCompilerError } = require('playwright/lib/server/supplements/compiler/compileScript');8const error = createCompilerError('Error message', 'Error stack');9console.log(error);10const { createCompilerError } = require('playwright/lib/server/supplements/compiler/compileScript');11const error = createCompilerError('Error message', 'Error stack');12console.log(error);13const { createCompilerError } = require('playwright/lib/server/supplements/compiler/compileScript');14const error = createCompilerError('Error message', 'Error stack');15console.log(error);16const { createCompilerError } = require('playwright/lib/server/supplements/compiler/compileScript');17const error = createCompilerError('Error message', 'Error stack');18console.log(error);19const { createCompilerError
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!