@mo36924/babel-plugin-graphql-tagged-template 1.6.11 → 5.0.56

Sign up to get free protection for your applications and to get access to all the features.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2021 mo36924
3
+ Copyright (c) 2023 mo36924
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/dist/index.cjs CHANGED
@@ -1,110 +1,116 @@
1
1
  'use strict';
2
2
 
3
- const fs = require('fs');
4
- const graphqlBuild = require('@mo36924/graphql-build');
5
- const graphqlConfig = require('@mo36924/graphql-config');
6
- const graphqlModel = require('@mo36924/graphql-model');
7
- const graphql = require('graphql');
3
+ var node_crypto = require('node:crypto');
4
+ var node_path = require('node:path');
5
+ var node_url = require('node:url');
6
+ var core = require('@babel/core');
7
+ var helperPluginUtils = require('@babel/helper-plugin-utils');
8
+ var basex = require('base-x');
9
+ var graphql = require('graphql');
8
10
 
9
- const index = ({ types: t }, options) => {
10
- let schema;
11
- if (typeof options.schema === "string") {
12
- schema = graphqlBuild.buildASTSchema(graphql.parse(fs.readFileSync(options.schema, "utf-8")));
13
- }
14
- else if (options.schema && typeof options.schema === "object") {
15
- schema = options.schema;
16
- }
17
- else if (typeof options.model === "string") {
18
- schema = graphqlModel.buildModel(fs.readFileSync(options.model, "utf-8")).schema;
19
- }
20
- else if (options.model && typeof options.model === "object") {
21
- schema = graphqlBuild.buildASTSchema(options.model);
22
- }
23
- else {
24
- schema = graphqlConfig.config().schema;
25
- }
11
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
12
+ const queriesCache = [];
13
+ const queriesDir = node_path.dirname(node_url.fileURLToPath((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('packages/babel-plugin-graphql-tagged-template/dist/index.cjs', document.baseURI).href))));
14
+ const queriesPaths = [
15
+ "js",
16
+ "cjs",
17
+ "ts"
18
+ ].map((extname)=>node_path.join(queriesDir, `queries.${extname}`));
19
+ const base52 = basex("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
20
+ const hash = (data)=>base52.encode(node_crypto.createHash("sha256").update(data).digest());
21
+ var index = helperPluginUtils.declare((_, { schema, development, queries = queriesCache })=>{
26
22
  return {
27
- name: "graphql-tagged-template",
23
+ name: "babel-plugin-graphql-tagged-template",
28
24
  visitor: {
29
- TaggedTemplateExpression(path) {
30
- const { tag, quasi: { quasis, expressions }, } = path.node;
31
- if (!t.isIdentifier(tag)) {
25
+ VariableDeclarator (path, { filename = "" }) {
26
+ if (!(queriesPaths.includes(filename) && path.get("id").isIdentifier({
27
+ name: "queries"
28
+ }) && path.get("init").isObjectExpression())) {
29
+ return;
30
+ }
31
+ path.get("init").replaceWith(core.types.objectExpression([
32
+ ...new Set(queries)
33
+ ].sort().map((query)=>core.types.objectProperty(core.types.identifier(hash(query)), core.types.callExpression(core.types.memberExpression(core.types.identifier("JSON"), core.types.identifier("parse")), [
34
+ core.types.stringLiteral(JSON.stringify(graphql.parse(query, {
35
+ noLocation: true
36
+ })))
37
+ ])))));
38
+ },
39
+ TaggedTemplateExpression (path) {
40
+ const { tag, quasi: { quasis, expressions } } = path.node;
41
+ if (!core.types.isIdentifier(tag)) {
32
42
  return;
33
43
  }
34
44
  const name = tag.name;
35
- let operation = "";
36
- switch (name) {
37
- case "gql":
38
- case "query":
39
- case "useQuery":
40
- break;
41
- case "mutation":
42
- case "useMutation":
43
- operation = "mutation";
44
- break;
45
- case "subscription":
46
- case "useSubscription":
47
- operation = "subscription";
48
- break;
49
- default:
50
- return;
45
+ if (name !== "gql") {
46
+ return;
51
47
  }
52
- let query = operation + (quasis[0].value.cooked ?? quasis[0].value.raw);
53
- for (let i = 0; i < expressions.length; i++) {
48
+ let query = quasis[0].value.cooked ?? quasis[0].value.raw;
49
+ if (query.trimStart()[0] !== "{") {
50
+ throw path.buildCodeFrameError("Named operation are not allowed");
51
+ }
52
+ for(let i = 0; i < expressions.length; i++){
54
53
  query += `$_${i}${quasis[i + 1].value.cooked ?? quasis[i + 1].value.raw}`;
55
54
  }
56
55
  let documentNode;
57
56
  try {
58
57
  documentNode = graphql.parse(query);
59
- }
60
- catch (err) {
58
+ } catch (err) {
61
59
  throw path.buildCodeFrameError(String(err));
62
60
  }
61
+ const definitions = documentNode.definitions;
62
+ const definition = definitions[0];
63
+ if (definitions.length !== 1 || definition.kind !== "OperationDefinition") {
64
+ throw path.buildCodeFrameError("Only a single operation is allowed");
65
+ }
66
+ if (definition.variableDefinitions?.length) {
67
+ throw path.buildCodeFrameError("Variables are not allowed");
68
+ }
69
+ const field = definition.selectionSet.selections[0];
70
+ if (field.kind !== "Field") {
71
+ throw path.buildCodeFrameError("Only a field is allowed");
72
+ }
73
+ const isMutation = !!schema.getMutationType()?.getFields()[field.name.value];
74
+ const operation = isMutation ? "mutation" : "query";
75
+ // @ts-expect-error ignore readonly
76
+ definition.operation = operation;
63
77
  const values = [];
64
78
  const typeInfo = new graphql.TypeInfo(schema);
65
- graphql.visit(documentNode, graphql.visitWithTypeInfo(typeInfo, {
66
- Variable() {
79
+ graphql.visit(definition, graphql.visitWithTypeInfo(typeInfo, {
80
+ Variable () {
67
81
  values.push(typeInfo.getInputType());
68
- },
82
+ }
69
83
  }));
70
84
  if (values.length) {
71
- const variables = `(${values.map((value, i) => `$_${i}:${value}`).join()})`;
72
- if (operation) {
73
- query = operation + variables + query.slice(operation.length);
74
- }
75
- else if (name !== "gql") {
76
- query = "query" + variables + query;
77
- }
85
+ const variables = `(${values.map((value, i)=>`$_${i}:${value}`).join()})`;
86
+ query = `${operation}${variables}${query}`;
87
+ } else if (operation === "mutation") {
88
+ query = `${operation}${query}`;
78
89
  }
79
90
  try {
80
- documentNode = graphql.parse(query, { noLocation: true });
81
- }
82
- catch (err) {
91
+ documentNode = graphql.parse(query, {
92
+ noLocation: true
93
+ });
94
+ } catch (err) {
83
95
  throw path.buildCodeFrameError(String(err));
84
96
  }
85
97
  const errors = graphql.validate(schema, documentNode);
86
98
  if (errors.length) {
87
99
  throw path.buildCodeFrameError(errors[0].message);
88
100
  }
89
- const properties = [];
90
- if (options.parse) {
91
- const id = path.scope.generateUid("gql");
92
- path.scope.getProgramParent().push({ kind: "let", id: t.identifier(id) });
93
- properties.push(t.objectProperty(t.identifier("document"), t.assignmentExpression("||=", t.identifier(id), t.callExpression(t.memberExpression(t.identifier("JSON"), t.identifier("parse")), [
94
- t.stringLiteral(JSON.stringify(documentNode)),
95
- ]))));
96
- }
97
- else {
98
- properties.push(t.objectProperty(t.identifier("query"), t.stringLiteral(graphql.stripIgnoredCharacters(query))));
99
- }
101
+ query = graphql.stripIgnoredCharacters(query);
102
+ queries.push(query);
103
+ const id = development ? query : hash(query);
104
+ const properties = [
105
+ core.types.objectProperty(core.types.identifier("query"), core.types.stringLiteral(id))
106
+ ];
100
107
  if (expressions.length) {
101
- properties.push(t.objectProperty(t.identifier("variables"), t.objectExpression(expressions.map((expression, i) => t.objectProperty(t.identifier("_" + i), expression)))));
108
+ properties.push(core.types.objectProperty(core.types.identifier("variables"), core.types.objectExpression(expressions.map((expression, i)=>core.types.objectProperty(core.types.identifier(`_${i}`), expression)))));
102
109
  }
103
- path.replaceWith(t.callExpression(t.identifier(name), [t.objectExpression(properties)]));
104
- },
105
- },
110
+ path.replaceWith(core.types.objectExpression(properties));
111
+ }
112
+ }
106
113
  };
107
- };
114
+ });
108
115
 
109
116
  module.exports = index;
110
- //# sourceMappingURL=index.cjs.map
package/dist/index.d.ts CHANGED
@@ -1,11 +1,12 @@
1
- import babel, { PluginObj } from '@babel/core';
2
- import { DocumentNode, GraphQLSchema } from 'graphql';
1
+ import * as _babel_core from '@babel/core';
2
+ import { PluginObj } from '@babel/core';
3
+ import { GraphQLSchema } from 'graphql';
3
4
 
4
- declare type Options = {
5
- parse?: boolean;
6
- model?: string | DocumentNode;
7
- schema?: string | GraphQLSchema;
5
+ type Options = {
6
+ schema: GraphQLSchema;
7
+ development?: boolean;
8
+ queries?: string[];
8
9
  };
9
- declare const _default: ({ types: t }: typeof babel, options: Options) => PluginObj;
10
+ declare const _default: (api: object, options: Options | null | undefined, dirname: string) => PluginObj<_babel_core.PluginPass>;
10
11
 
11
- export { Options, _default as default };
12
+ export { type Options, _default as default };
package/dist/index.js CHANGED
@@ -1,108 +1,113 @@
1
- import { readFileSync } from 'fs';
2
- import { buildASTSchema } from '@mo36924/graphql-build';
3
- import { config } from '@mo36924/graphql-config';
4
- import { buildModel } from '@mo36924/graphql-model';
1
+ import { createHash } from 'node:crypto';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { types } from '@babel/core';
5
+ import { declare } from '@babel/helper-plugin-utils';
6
+ import basex from 'base-x';
5
7
  import { parse, TypeInfo, visit, visitWithTypeInfo, validate, stripIgnoredCharacters } from 'graphql';
6
8
 
7
- const index = ({ types: t }, options) => {
8
- let schema;
9
- if (typeof options.schema === "string") {
10
- schema = buildASTSchema(parse(readFileSync(options.schema, "utf-8")));
11
- }
12
- else if (options.schema && typeof options.schema === "object") {
13
- schema = options.schema;
14
- }
15
- else if (typeof options.model === "string") {
16
- schema = buildModel(readFileSync(options.model, "utf-8")).schema;
17
- }
18
- else if (options.model && typeof options.model === "object") {
19
- schema = buildASTSchema(options.model);
20
- }
21
- else {
22
- schema = config().schema;
23
- }
9
+ const queriesCache = [];
10
+ const queriesDir = dirname(fileURLToPath(import.meta.url));
11
+ const queriesPaths = [
12
+ "js",
13
+ "cjs",
14
+ "ts"
15
+ ].map((extname)=>join(queriesDir, `queries.${extname}`));
16
+ const base52 = basex("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz");
17
+ const hash = (data)=>base52.encode(createHash("sha256").update(data).digest());
18
+ var index = declare((_, { schema, development, queries = queriesCache })=>{
24
19
  return {
25
- name: "graphql-tagged-template",
20
+ name: "babel-plugin-graphql-tagged-template",
26
21
  visitor: {
27
- TaggedTemplateExpression(path) {
28
- const { tag, quasi: { quasis, expressions }, } = path.node;
29
- if (!t.isIdentifier(tag)) {
22
+ VariableDeclarator (path, { filename = "" }) {
23
+ if (!(queriesPaths.includes(filename) && path.get("id").isIdentifier({
24
+ name: "queries"
25
+ }) && path.get("init").isObjectExpression())) {
26
+ return;
27
+ }
28
+ path.get("init").replaceWith(types.objectExpression([
29
+ ...new Set(queries)
30
+ ].sort().map((query)=>types.objectProperty(types.identifier(hash(query)), types.callExpression(types.memberExpression(types.identifier("JSON"), types.identifier("parse")), [
31
+ types.stringLiteral(JSON.stringify(parse(query, {
32
+ noLocation: true
33
+ })))
34
+ ])))));
35
+ },
36
+ TaggedTemplateExpression (path) {
37
+ const { tag, quasi: { quasis, expressions } } = path.node;
38
+ if (!types.isIdentifier(tag)) {
30
39
  return;
31
40
  }
32
41
  const name = tag.name;
33
- let operation = "";
34
- switch (name) {
35
- case "gql":
36
- case "query":
37
- case "useQuery":
38
- break;
39
- case "mutation":
40
- case "useMutation":
41
- operation = "mutation";
42
- break;
43
- case "subscription":
44
- case "useSubscription":
45
- operation = "subscription";
46
- break;
47
- default:
48
- return;
42
+ if (name !== "gql") {
43
+ return;
49
44
  }
50
- let query = operation + (quasis[0].value.cooked ?? quasis[0].value.raw);
51
- for (let i = 0; i < expressions.length; i++) {
45
+ let query = quasis[0].value.cooked ?? quasis[0].value.raw;
46
+ if (query.trimStart()[0] !== "{") {
47
+ throw path.buildCodeFrameError("Named operation are not allowed");
48
+ }
49
+ for(let i = 0; i < expressions.length; i++){
52
50
  query += `$_${i}${quasis[i + 1].value.cooked ?? quasis[i + 1].value.raw}`;
53
51
  }
54
52
  let documentNode;
55
53
  try {
56
54
  documentNode = parse(query);
57
- }
58
- catch (err) {
55
+ } catch (err) {
59
56
  throw path.buildCodeFrameError(String(err));
60
57
  }
58
+ const definitions = documentNode.definitions;
59
+ const definition = definitions[0];
60
+ if (definitions.length !== 1 || definition.kind !== "OperationDefinition") {
61
+ throw path.buildCodeFrameError("Only a single operation is allowed");
62
+ }
63
+ if (definition.variableDefinitions?.length) {
64
+ throw path.buildCodeFrameError("Variables are not allowed");
65
+ }
66
+ const field = definition.selectionSet.selections[0];
67
+ if (field.kind !== "Field") {
68
+ throw path.buildCodeFrameError("Only a field is allowed");
69
+ }
70
+ const isMutation = !!schema.getMutationType()?.getFields()[field.name.value];
71
+ const operation = isMutation ? "mutation" : "query";
72
+ // @ts-expect-error ignore readonly
73
+ definition.operation = operation;
61
74
  const values = [];
62
75
  const typeInfo = new TypeInfo(schema);
63
- visit(documentNode, visitWithTypeInfo(typeInfo, {
64
- Variable() {
76
+ visit(definition, visitWithTypeInfo(typeInfo, {
77
+ Variable () {
65
78
  values.push(typeInfo.getInputType());
66
- },
79
+ }
67
80
  }));
68
81
  if (values.length) {
69
- const variables = `(${values.map((value, i) => `$_${i}:${value}`).join()})`;
70
- if (operation) {
71
- query = operation + variables + query.slice(operation.length);
72
- }
73
- else if (name !== "gql") {
74
- query = "query" + variables + query;
75
- }
82
+ const variables = `(${values.map((value, i)=>`$_${i}:${value}`).join()})`;
83
+ query = `${operation}${variables}${query}`;
84
+ } else if (operation === "mutation") {
85
+ query = `${operation}${query}`;
76
86
  }
77
87
  try {
78
- documentNode = parse(query, { noLocation: true });
79
- }
80
- catch (err) {
88
+ documentNode = parse(query, {
89
+ noLocation: true
90
+ });
91
+ } catch (err) {
81
92
  throw path.buildCodeFrameError(String(err));
82
93
  }
83
94
  const errors = validate(schema, documentNode);
84
95
  if (errors.length) {
85
96
  throw path.buildCodeFrameError(errors[0].message);
86
97
  }
87
- const properties = [];
88
- if (options.parse) {
89
- const id = path.scope.generateUid("gql");
90
- path.scope.getProgramParent().push({ kind: "let", id: t.identifier(id) });
91
- properties.push(t.objectProperty(t.identifier("document"), t.assignmentExpression("||=", t.identifier(id), t.callExpression(t.memberExpression(t.identifier("JSON"), t.identifier("parse")), [
92
- t.stringLiteral(JSON.stringify(documentNode)),
93
- ]))));
94
- }
95
- else {
96
- properties.push(t.objectProperty(t.identifier("query"), t.stringLiteral(stripIgnoredCharacters(query))));
97
- }
98
+ query = stripIgnoredCharacters(query);
99
+ queries.push(query);
100
+ const id = development ? query : hash(query);
101
+ const properties = [
102
+ types.objectProperty(types.identifier("query"), types.stringLiteral(id))
103
+ ];
98
104
  if (expressions.length) {
99
- properties.push(t.objectProperty(t.identifier("variables"), t.objectExpression(expressions.map((expression, i) => t.objectProperty(t.identifier("_" + i), expression)))));
105
+ properties.push(types.objectProperty(types.identifier("variables"), types.objectExpression(expressions.map((expression, i)=>types.objectProperty(types.identifier(`_${i}`), expression)))));
100
106
  }
101
- path.replaceWith(t.callExpression(t.identifier(name), [t.objectExpression(properties)]));
102
- },
103
- },
107
+ path.replaceWith(types.objectExpression(properties));
108
+ }
109
+ }
104
110
  };
105
- };
111
+ });
106
112
 
107
113
  export { index as default };
108
- //# sourceMappingURL=index.js.map
@@ -0,0 +1,5 @@
1
+ 'use strict';
2
+
3
+ const queries = {};
4
+
5
+ exports.queries = queries;
@@ -0,0 +1,7 @@
1
+ import { DocumentNode } from 'graphql';
2
+
3
+ declare const queries: {
4
+ [key: string]: DocumentNode;
5
+ };
6
+
7
+ export { queries };
@@ -0,0 +1,3 @@
1
+ const queries = {};
2
+
3
+ export { queries };
package/package.json CHANGED
@@ -1,31 +1,40 @@
1
1
  {
2
2
  "name": "@mo36924/babel-plugin-graphql-tagged-template",
3
- "version": "1.6.11",
3
+ "type": "module",
4
+ "version": "5.0.56",
4
5
  "description": "babel-plugin-graphql-tagged-template",
5
- "keywords": [],
6
- "homepage": "https://github.com/mo36924/monorepo#readme",
7
- "bugs": {
8
- "url": "https://github.com/mo36924/monorepo/issues"
9
- },
6
+ "author": "mo36924",
7
+ "license": "MIT",
8
+ "homepage": "https://github.com/mo36924/packages#readme",
10
9
  "repository": {
11
10
  "type": "git",
12
- "url": "git+https://github.com/mo36924/monorepo.git",
11
+ "url": "git+https://github.com/mo36924/packages.git",
13
12
  "directory": "packages/babel-plugin-graphql-tagged-template"
14
13
  },
15
- "license": "MIT",
16
- "author": "mo36924 <mo36924@users.noreply.github.com>",
14
+ "bugs": {
15
+ "url": "https://github.com/mo36924/packages/issues"
16
+ },
17
+ "keywords": [],
17
18
  "exports": {
18
19
  ".": {
19
20
  "types": "./dist/index.d.ts",
20
- "browser": "./dist/index.js",
21
- "import": "./dist/index.mjs",
21
+ "import": "./dist/index.js",
22
22
  "require": "./dist/index.cjs",
23
- "default": "./dist/index.cjs"
23
+ "default": "./dist/index.js"
24
+ },
25
+ "./queries": {
26
+ "types": "./dist/queries.d.ts",
27
+ "import": "./dist/queries.js",
28
+ "require": "./dist/queries.cjs",
29
+ "default": "./dist/queries.js"
24
30
  }
25
31
  },
26
- "main": "./dist/index.cjs",
27
- "module": "./dist/index.mjs",
32
+ "main": "./dist/index.js",
33
+ "module": "./dist/index.js",
28
34
  "types": "./dist/index.d.ts",
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
29
38
  "typesVersions": {
30
39
  "*": {
31
40
  "*": [
@@ -38,15 +47,12 @@
38
47
  "dist"
39
48
  ],
40
49
  "dependencies": {
41
- "@babel/core": "^7.17.8",
42
- "@mo36924/graphql-build": "^1.6.11",
43
- "@mo36924/graphql-config": "^1.6.11",
44
- "@mo36924/graphql-model": "^1.6.11",
45
- "@types/babel__core": "^7.1.19",
46
- "graphql": "^16.3.0"
47
- },
48
- "publishConfig": {
49
- "access": "public"
50
+ "@babel/core": "^7.25.2",
51
+ "@babel/helper-plugin-utils": "^7.24.8",
52
+ "@types/babel__core": "^7.20.5",
53
+ "@types/babel__helper-plugin-utils": "^7.10.3",
54
+ "base-x": "^5.0.0",
55
+ "graphql": "^16.9.0"
50
56
  },
51
- "gitHead": "5272a63e6ed50e20346c253155e6c6f7041ea566"
57
+ "gitHead": "25d1f49663a624870a44bbc9ca3aa78bea0f06b6"
52
58
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.cjs","sources":["../src/index.ts"],"sourcesContent":["import { readFileSync } from \"fs\";\nimport babel, { PluginObj, types as t } from \"@babel/core\";\nimport { buildASTSchema } from \"@mo36924/graphql-build\";\nimport { config } from \"@mo36924/graphql-config\";\nimport { buildModel } from \"@mo36924/graphql-model\";\nimport {\n DocumentNode,\n GraphQLInputType,\n GraphQLSchema,\n TypeInfo,\n parse,\n stripIgnoredCharacters,\n validate,\n visit,\n visitWithTypeInfo,\n} from \"graphql\";\n\nexport type Options = {\n parse?: boolean;\n model?: string | DocumentNode;\n schema?: string | GraphQLSchema;\n};\n\nexport default ({ types: t }: typeof babel, options: Options): PluginObj => {\n let schema: GraphQLSchema;\n\n if (typeof options.schema === \"string\") {\n schema = buildASTSchema(parse(readFileSync(options.schema, \"utf-8\")));\n } else if (options.schema && typeof options.schema === \"object\") {\n schema = options.schema;\n } else if (typeof options.model === \"string\") {\n schema = buildModel(readFileSync(options.model, \"utf-8\")).schema;\n } else if (options.model && typeof options.model === \"object\") {\n schema = buildASTSchema(options.model);\n } else {\n schema = config().schema;\n }\n\n return {\n name: \"graphql-tagged-template\",\n visitor: {\n TaggedTemplateExpression(path) {\n const {\n tag,\n quasi: { quasis, expressions },\n } = path.node;\n\n if (!t.isIdentifier(tag)) {\n return;\n }\n\n const name = tag.name;\n let operation = \"\";\n\n switch (name) {\n case \"gql\":\n case \"query\":\n case \"useQuery\":\n break;\n case \"mutation\":\n case \"useMutation\":\n operation = \"mutation\";\n break;\n case \"subscription\":\n case \"useSubscription\":\n operation = \"subscription\";\n break;\n default:\n return;\n }\n\n let query = operation + (quasis[0].value.cooked ?? quasis[0].value.raw);\n\n for (let i = 0; i < expressions.length; i++) {\n query += `$_${i}${quasis[i + 1].value.cooked ?? quasis[i + 1].value.raw}`;\n }\n\n let documentNode: DocumentNode;\n\n try {\n documentNode = parse(query);\n } catch (err) {\n throw path.buildCodeFrameError(String(err));\n }\n\n const values: GraphQLInputType[] = [];\n const typeInfo = new TypeInfo(schema);\n\n visit(\n documentNode,\n visitWithTypeInfo(typeInfo, {\n Variable() {\n values.push(typeInfo.getInputType()!);\n },\n }),\n );\n\n if (values.length) {\n const variables = `(${values.map((value, i) => `$_${i}:${value}`).join()})`;\n\n if (operation) {\n query = operation + variables + query.slice(operation.length);\n } else if (name !== \"gql\") {\n query = \"query\" + variables + query;\n }\n }\n\n try {\n documentNode = parse(query, { noLocation: true });\n } catch (err) {\n throw path.buildCodeFrameError(String(err));\n }\n\n const errors = validate(schema, documentNode);\n\n if (errors.length) {\n throw path.buildCodeFrameError(errors[0].message);\n }\n\n const properties: t.ObjectProperty[] = [];\n\n if (options.parse) {\n const id = path.scope.generateUid(\"gql\");\n path.scope.getProgramParent().push({ kind: \"let\", id: t.identifier(id) });\n\n properties.push(\n t.objectProperty(\n t.identifier(\"document\"),\n t.assignmentExpression(\n \"||=\",\n t.identifier(id),\n t.callExpression(t.memberExpression(t.identifier(\"JSON\"), t.identifier(\"parse\")), [\n t.stringLiteral(JSON.stringify(documentNode)),\n ]),\n ),\n ),\n );\n } else {\n properties.push(t.objectProperty(t.identifier(\"query\"), t.stringLiteral(stripIgnoredCharacters(query))));\n }\n\n if (expressions.length) {\n properties.push(\n t.objectProperty(\n t.identifier(\"variables\"),\n t.objectExpression(\n expressions.map((expression, i) => t.objectProperty(t.identifier(\"_\" + i), expression as t.Expression)),\n ),\n ),\n );\n }\n\n path.replaceWith(t.callExpression(t.identifier(name), [t.objectExpression(properties)]));\n },\n },\n };\n};\n"],"names":["buildASTSchema","parse","readFileSync","buildModel","config","TypeInfo","visit","visitWithTypeInfo","validate","stripIgnoredCharacters"],"mappings":";;;;;;;;AAuBA,cAAe,CAAC,EAAE,KAAK,EAAE,CAAC,EAAgB,EAAE,OAAgB;IAC1D,IAAI,MAAqB,CAAC;IAE1B,IAAI,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,EAAE;QACtC,MAAM,GAAGA,2BAAc,CAACC,aAAK,CAACC,eAAY,CAAC,OAAO,CAA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,CACH,CACF,CACF,CAAC;iBACH;qBAAM;oBACL,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,UAAU,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC,aAAa,CAACC,8BAAsB,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC;iBAC1G;gBAED,IAAI,WAAW,CAAC,MAAM,EAAE;oBACtB,UAAU,CAAC,IAAI,CACb,CAAC,CAAC,cAAc,CACd,CAAC,CAAC,UAAU,CAAC,WAAW,CAAC,EACzB,CAAC,CAAC,gBAAgB,CAChB,WAAW,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,CAAC,KAAK,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,GAAG,CAAC,CAAC,EAAE,UAA0B,CAAC,CAAC,CACxG,CACF,CACF,CAAC;iBACH;gBAED,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,gBAAgB,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;aAC1F;SACF;KACF,CAAC;AACJ,CAAC;;;;"}
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import { readFileSync } from \"fs\";\nimport babel, { PluginObj, types as t } from \"@babel/core\";\nimport { buildASTSchema } from \"@mo36924/graphql-build\";\nimport { config } from \"@mo36924/graphql-config\";\nimport { buildModel } from \"@mo36924/graphql-model\";\nimport {\n DocumentNode,\n GraphQLInputType,\n GraphQLSchema,\n TypeInfo,\n parse,\n stripIgnoredCharacters,\n validate,\n visit,\n visitWithTypeInfo,\n} from \"graphql\";\n\nexport type Options = {\n parse?: boolean;\n model?: string | DocumentNode;\n schema?: string | GraphQLSchema;\n};\n\nexport default ({ types: t }: typeof babel, options: Options): PluginObj => {\n let schema: GraphQLSchema;\n\n if (typeof options.schema === \"string\") {\n schema = buildASTSchema(parse(readFileSync(options.schema, \"utf-8\")));\n } else if (options.schema && typeof options.schema === \"object\") {\n schema = options.schema;\n } else if (typeof options.model === \"string\") {\n schema = buildModel(readFileSync(options.model, \"utf-8\")).schema;\n } else if (options.model && typeof options.model === \"object\") {\n schema = buildASTSchema(options.model);\n } else {\n schema = config().schema;\n }\n\n return {\n name: \"graphql-tagged-template\",\n visitor: {\n TaggedTemplateExpression(path) {\n const {\n tag,\n quasi: { quasis, expressions },\n } = path.node;\n\n if (!t.isIdentifier(tag)) {\n return;\n }\n\n const name = tag.name;\n let operation = \"\";\n\n switch (name) {\n case \"gql\":\n case \"query\":\n case \"useQuery\":\n break;\n case \"mutation\":\n case \"useMutation\":\n operation = \"mutation\";\n break;\n case \"subscription\":\n case \"useSubscription\":\n operation = \"subscription\";\n break;\n default:\n return;\n }\n\n let query = operation + (quasis[0].value.cooked ?? quasis[0].value.raw);\n\n for (let i = 0; i < expressions.length; i++) {\n query += `$_${i}${quasis[i + 1].value.cooked ?? quasis[i + 1].value.raw}`;\n }\n\n let documentNode: DocumentNode;\n\n try {\n documentNode = parse(query);\n } catch (err) {\n throw path.buildCodeFrameError(String(err));\n }\n\n const values: GraphQLInputType[] = [];\n const typeInfo = new TypeInfo(schema);\n\n visit(\n documentNode,\n visitWithTypeInfo(typeInfo, {\n Variable() {\n values.push(typeInfo.getInputType()!);\n },\n }),\n );\n\n if (values.length) {\n const variables = `(${values.map((value, i) => `$_${i}:${value}`).join()})`;\n\n if (operation) {\n query = operation + variables + query.slice(operation.length);\n } else if (name !== \"gql\") {\n query = \"query\" + variables + query;\n }\n }\n\n try {\n documentNode = parse(query, { noLocation: true });\n } catch (err) {\n throw path.buildCodeFrameError(String(err));\n }\n\n const errors = validate(schema, documentNode);\n\n if (errors.length) {\n throw path.buildCodeFrameError(errors[0].message);\n }\n\n const properties: t.ObjectProperty[] = [];\n\n if (options.parse) {\n const id = path.scope.generateUid(\"gql\");\n path.scope.getProgramParent().push({ kind: \"let\", id: t.identifier(id) });\n\n properties.push(\n t.objectProperty(\n t.identifier(\"document\"),\n t.assignmentExpression(\n \"||=\",\n t.identifier(id),\n t.callExpression(t.memberExpression(t.identifier(\"JSON\"), t.identifier(\"parse\")), [\n t.stringLiteral(JSON.stringify(documentNode)),\n ]),\n ),\n ),\n );\n } else {\n properties.push(t.objectProperty(t.identifier(\"query\"), t.stringLiteral(stripIgnoredCharacters(query))));\n }\n\n if (expressions.length) {\n properties.push(\n t.objectProperty(\n t.identifier(\"variables\"),\n t.objectExpression(\n expressions.map((expression, i) => t.objectProperty(t.identifier(\"_\" + i), expression as t.Expression)),\n ),\n ),\n );\n }\n\n path.replaceWith(t.callExpression(t.identifier(name), [t.objectExpression(properties)]));\n },\n },\n };\n};\n"],"names":[],"mappings":";;;;;;AAuBA,cAAe,CAAC,EAAE,KAAK,EAAE,CAAC,EAAgB,EAAE,OAAgB;IAC1D,IAAI,MAAqB,CAAC;IAE1B,IAAI,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,EAAE;QACtC,MAAM,GAAG,cAAc,CAAC,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;KACvE;SAAM,IAAI,OAAO,CAAC,MAAM,IAAI,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,EAAE;QAC/D,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;KACzB;SAAM,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,QAAQ,EAAE;QAC5C,MAAM,GAAG,UAAU,CAAC,YAAY,CAAC,OAAO,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC;KAClE;SAAM,IAAI,OAAO,CAAC,KAAK,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,QAAQ,EAAE;QAC7D,MAAM,GAAG,cAAc,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;KACxC;SAAM;QACL,MAAM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C,CACxG,CACF,CACF,CAAC;iBACH;gBAED,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,gBAAgB,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC;aAC1F;SACF;KACF,CAAC;AACJ,CAAC;;;;"}
package/dist/index.mjs DELETED
@@ -1,108 +0,0 @@
1
- import { readFileSync } from 'fs';
2
- import { buildASTSchema } from '@mo36924/graphql-build';
3
- import { config } from '@mo36924/graphql-config';
4
- import { buildModel } from '@mo36924/graphql-model';
5
- import { parse, TypeInfo, visit, visitWithTypeInfo, validate, stripIgnoredCharacters } from 'graphql';
6
-
7
- const index = ({ types: t }, options) => {
8
- let schema;
9
- if (typeof options.schema === "string") {
10
- schema = buildASTSchema(parse(readFileSync(options.schema, "utf-8")));
11
- }
12
- else if (options.schema && typeof options.schema === "object") {
13
- schema = options.schema;
14
- }
15
- else if (typeof options.model === "string") {
16
- schema = buildModel(readFileSync(options.model, "utf-8")).schema;
17
- }
18
- else if (options.model && typeof options.model === "object") {
19
- schema = buildASTSchema(options.model);
20
- }
21
- else {
22
- schema = config().schema;
23
- }
24
- return {
25
- name: "graphql-tagged-template",
26
- visitor: {
27
- TaggedTemplateExpression(path) {
28
- const { tag, quasi: { quasis, expressions }, } = path.node;
29
- if (!t.isIdentifier(tag)) {
30
- return;
31
- }
32
- const name = tag.name;
33
- let operation = "";
34
- switch (name) {
35
- case "gql":
36
- case "query":
37
- case "useQuery":
38
- break;
39
- case "mutation":
40
- case "useMutation":
41
- operation = "mutation";
42
- break;
43
- case "subscription":
44
- case "useSubscription":
45
- operation = "subscription";
46
- break;
47
- default:
48
- return;
49
- }
50
- let query = operation + (quasis[0].value.cooked ?? quasis[0].value.raw);
51
- for (let i = 0; i < expressions.length; i++) {
52
- query += `$_${i}${quasis[i + 1].value.cooked ?? quasis[i + 1].value.raw}`;
53
- }
54
- let documentNode;
55
- try {
56
- documentNode = parse(query);
57
- }
58
- catch (err) {
59
- throw path.buildCodeFrameError(String(err));
60
- }
61
- const values = [];
62
- const typeInfo = new TypeInfo(schema);
63
- visit(documentNode, visitWithTypeInfo(typeInfo, {
64
- Variable() {
65
- values.push(typeInfo.getInputType());
66
- },
67
- }));
68
- if (values.length) {
69
- const variables = `(${values.map((value, i) => `$_${i}:${value}`).join()})`;
70
- if (operation) {
71
- query = operation + variables + query.slice(operation.length);
72
- }
73
- else if (name !== "gql") {
74
- query = "query" + variables + query;
75
- }
76
- }
77
- try {
78
- documentNode = parse(query, { noLocation: true });
79
- }
80
- catch (err) {
81
- throw path.buildCodeFrameError(String(err));
82
- }
83
- const errors = validate(schema, documentNode);
84
- if (errors.length) {
85
- throw path.buildCodeFrameError(errors[0].message);
86
- }
87
- const properties = [];
88
- if (options.parse) {
89
- const id = path.scope.generateUid("gql");
90
- path.scope.getProgramParent().push({ kind: "let", id: t.identifier(id) });
91
- properties.push(t.objectProperty(t.identifier("document"), t.assignmentExpression("||=", t.identifier(id), t.callExpression(t.memberExpression(t.identifier("JSON"), t.identifier("parse")), [
92
- t.stringLiteral(JSON.stringify(documentNode)),
93
- ]))));
94
- }
95
- else {
96
- properties.push(t.objectProperty(t.identifier("query"), t.stringLiteral(stripIgnoredCharacters(query))));
97
- }
98
- if (expressions.length) {
99
- properties.push(t.objectProperty(t.identifier("variables"), t.objectExpression(expressions.map((expression, i) => t.objectProperty(t.identifier("_" + i), expression)))));
100
- }
101
- path.replaceWith(t.callExpression(t.identifier(name), [t.objectExpression(properties)]));
102
- },
103
- },
104
- };
105
- };
106
-
107
- export { index as default };
108
- //# sourceMappingURL=index.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.mjs","sources":["../src/index.ts"],"sourcesContent":["import { readFileSync } from \"fs\";\nimport babel, { PluginObj, types as t } from \"@babel/core\";\nimport { buildASTSchema } from \"@mo36924/graphql-build\";\nimport { config } from \"@mo36924/graphql-config\";\nimport { buildModel } from \"@mo36924/graphql-model\";\nimport {\n DocumentNode,\n GraphQLInputType,\n GraphQLSchema,\n TypeInfo,\n parse,\n stripIgnoredCharacters,\n validate,\n visit,\n visitWithTypeInfo,\n} from \"graphql\";\n\nexport type Options = {\n parse?: boolean;\n model?: string | DocumentNode;\n schema?: string | GraphQLSchema;\n};\n\nexport default ({ types: t }: typeof babel, options: Options): PluginObj => {\n let schema: GraphQLSchema;\n\n if (typeof options.schema === \"string\") {\n schema = buildASTSchema(parse(readFileSync(options.schema, \"utf-8\")));\n } else if (options.schema && typeof options.schema === \"object\") {\n schema = options.schema;\n } else if (typeof options.model === \"string\") {\n schema = buildModel(readFileSync(options.model, \"utf-8\")).schema;\n } else if (options.model && typeof options.model === \"object\") {\n schema = buildASTSchema(options.model);\n } else {\n schema = config().schema;\n }\n\n return {\n name: \"graphql-tagged-template\",\n visitor: {\n TaggedTemplateExpression(path) {\n const {\n tag,\n quasi: { quasis, expressions },\n } = path.node;\n\n if (!t.isIdentifier(tag)) {\n return;\n }\n\n const name = tag.name;\n let operation = \"\";\n\n switch (name) {\n case \"gql\":\n case \"query\":\n case \"useQuery\":\n break;\n case \"mutation\":\n case \"useMutation\":\n operation = \"mutation\";\n break;\n case \"subscription\":\n case \"useSubscription\":\n operation = \"subscription\";\n break;\n default:\n return;\n }\n\n let query = operation + (quasis[0].value.cooked ?? quasis[0].value.raw);\n\n for (let i = 0; i < expressions.length; i++) {\n query += `$_${i}${quasis[i + 1].value.cooked ?? quasis[i + 1].value.raw}`;\n }\n\n let documentNode: DocumentNode;\n\n try {\n documentNode = parse(query);\n } catch (err) {\n throw path.buildCodeFrameError(String(err));\n }\n\n const values: GraphQLInputType[] = [];\n const typeInfo = new TypeInfo(schema);\n\n visit(\n documentNode,\n visitWithTypeInfo(typeInfo, {\n Variable() {\n values.push(typeInfo.getInputType()!);\n },\n }),\n );\n\n if (values.length) {\n const variables = `(${values.map((value, i) => `$_${i}:${value}`).join()})`;\n\n if (operation) {\n query = operation + variables + query.slice(operation.length);\n } else if (name !== \"gql\") {\n query = \"query\" + variables + query;\n }\n }\n\n try {\n documentNode = parse(query, { noLocation: true });\n } catch (err) {\n throw path.buildCodeFrameError(String(err));\n }\n\n const errors = validate(schema, documentNode);\n\n if (errors.length) {\n throw path.buildCodeFrameError(errors[0].message);\n }\n\n const properties: t.ObjectProperty[] = [];\n\n if (options.parse) {\n const id = path.scope.generateUid(\"gql\");\n path.scope.getProgramParent().push({ kind: \"let\", id: t.identifier(id) });\n\n properties.push(\n t.objectProperty(\n t.identifier(\"document\"),\n t.assignmentExpression(\n \"||=\",\n t.identifier(id),\n t.callExpression(t.memberExpression(t.identifier(\"JSON\"), t.identifier(\"parse\")), [\n t.stringLiteral(JSON.stringify(documentNode)),\n ]),\n ),\n ),\n );\n } else {\n properties.push(t.objectProperty(t.identifier(\"query\"), t.stringLiteral(stripIgnoredCharacters(query))));\n }\n\n if (expressions.length) {\n properties.push(\n t.objectProperty(\n t.identifier(\"variables\"),\n t.objectExpression(\n expressions.map((expression, i) => t.objectProperty(t.identifier(\"_\" + i), expression as t.Expression)),\n ),\n ),\n );\n }\n\n path.replaceWith(t.callExpression(t.identifier(name), [t.objectExpression(properties)]));\n },\n },\n };\n};\n"],"names":[],"mappings":";;;;;;AAuBA,cAAe,CAAC,EAAE,KAAK,EAAE,CAAC,EAAgB,EAAE,OAAgB;IAC1D,IAAI,MAAqB,CAAC;IAE1B,IAAI,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,EAAE;QACtC,MAAM,GAAG,cAAc,CAAC,KAAK,CAAC,YAAY,CAAC,OAAO,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC;KACvE;SAAM,IAAI,OAAO,CAAC,MAAM,IAAI,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ,EAAE;QAC/D,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;KACzB;SAAM,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,QAAQ,EAAE;QAC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