@trackunit/react-graphql-tools 1.16.4-alpha-3e7014314a8.0 → 1.17.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,96 @@
1
+ ## 1.17.5 (2026-08-27)
2
+
3
+ ### 🧱 Updated Dependencies
4
+
5
+ - Updated iris-app-build-utilities to 2.4.25
6
+
7
+ ## 1.17.4 (2026-08-27)
8
+
9
+ ### 🧱 Updated Dependencies
10
+
11
+ - Updated iris-app-build-utilities to 2.4.24
12
+
13
+ ## 1.17.3 (2026-08-27)
14
+
15
+ ### 🧱 Updated Dependencies
16
+
17
+ - Updated iris-app-build-utilities to 2.4.23
18
+
19
+ ## 1.17.2 (2026-08-27)
20
+
21
+ ### 🧱 Updated Dependencies
22
+
23
+ - Updated iris-app-build-utilities to 2.4.22
24
+
25
+ ## 1.17.1 (2026-08-27)
26
+
27
+ ### 🧱 Updated Dependencies
28
+
29
+ - Updated iris-app-build-utilities to 2.4.21
30
+
31
+ ## 1.17.0 (2026-08-27)
32
+
33
+ ### 🚀 Features
34
+
35
+ - **react-graphql-tools:** derive the authorization scopes a project requires ([7c5c1db1258](https://github.com/Trackunit/manager/commit/7c5c1db1258))
36
+
37
+ ### 🧱 Updated Dependencies
38
+
39
+ - Updated iris-app-build-utilities to 2.4.20
40
+
41
+ ### ❤️ Thank You
42
+
43
+ - Cursor @cursoragent
44
+ - Mikkel Thorbjørn Andersen
45
+
46
+ ## 1.16.3 (2026-08-27)
47
+
48
+ ### 🧱 Updated Dependencies
49
+
50
+ - Updated iris-app-build-utilities to 2.4.19
51
+
52
+ ## 1.16.2 (2026-08-25)
53
+
54
+ ### 🩹 Fixes
55
+
56
+ - **react-graphql-tools:** repair scope collection after applied review suggestions ([3890f3a9706](https://github.com/Trackunit/manager/commit/3890f3a9706))
57
+
58
+ ### 🧱 Updated Dependencies
59
+
60
+ - Updated iris-app-build-utilities to 2.4.18
61
+ - Updated react-vite-test-setup to 0.0.114
62
+
63
+ ### ❤️ Thank You
64
+
65
+ - Cursor @cursoragent
66
+ - Mikkel Thorbjørn Andersen
67
+
68
+ ## 1.16.1 (2026-08-25)
69
+
70
+ ### 🧱 Updated Dependencies
71
+
72
+ - Updated iris-app-build-utilities to 2.4.17
73
+ - Updated react-vite-test-setup to 0.0.113
74
+
75
+ ## 1.16.0 (2026-08-24)
76
+
77
+ ### 🚀 Features
78
+
79
+ - **react-graphql-tools:** document required authorization scopes in generated mocks ([8b500687a87](https://github.com/Trackunit/manager/commit/8b500687a87))
80
+
81
+ ### 🩹 Fixes
82
+
83
+ - **react-graphql-tools:** repair scope collection after applied review suggestions ([e0fe4fad522](https://github.com/Trackunit/manager/commit/e0fe4fad522))
84
+
85
+ ### 🧱 Updated Dependencies
86
+
87
+ - Updated iris-app-build-utilities to 2.4.16
88
+
89
+ ### ❤️ Thank You
90
+
91
+ - Cursor @cursoragent
92
+ - Mikkel Thorbjørn Andersen
93
+
1
94
  ## 1.15.17 (2026-08-20)
2
95
 
3
96
  ### 🧱 Updated Dependencies
@@ -0,0 +1 @@
1
+ {"version":3,"file":"entry.js","sourceRoot":"","sources":["../../../../../libs/react/graphql-tools/migrations/entry.ts"],"names":[],"mappings":"","sourcesContent":["export {};\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trackunit/react-graphql-tools",
3
- "version": "1.16.4-alpha-3e7014314a8.0",
3
+ "version": "1.17.5",
4
4
  "main": "src/index.js",
5
5
  "executors": "./executors.json",
6
6
  "generators": "./generators.json",
@@ -18,7 +18,9 @@
18
18
  "win-ca": "^3.5.1",
19
19
  "tslib": "^2.6.2",
20
20
  "@nx/devkit": "23.1.0",
21
- "@nx/js": "23.1.0"
21
+ "@nx/js": "23.1.0",
22
+ "@trackunit/iris-app-build-utilities": "2.4.25",
23
+ "graphql": "^16.10.0"
22
24
  },
23
25
  "migrations": "./migrations.json",
24
26
  "types": "./src/index.d.ts",
@@ -0,0 +1,25 @@
1
+ import { GraphQLSchema } from "graphql";
2
+ /**
3
+ * Loads the authorization-annotated schema, reusing codegen's own schema resolution
4
+ * (`resolveSchema`) so scopes are read from the exact schema operations are generated against - the
5
+ * internal superset (which carries every `@authorization` directive) when checked out, otherwise
6
+ * the public schema. Returns null when only the remote endpoint is available (nothing to read from
7
+ * disk) or the schema file is missing (e.g. isolated test workspaces).
8
+ */
9
+ export declare const loadAuthSchema: (nxRoot: string) => GraphQLSchema | null;
10
+ /**
11
+ * Builds a map of operation name -> sorted, de-duplicated authorization scopes required by that
12
+ * operation, from raw GraphQL operation/fragment source documents.
13
+ *
14
+ * @param schema The authorization-annotated schema to resolve field directives against.
15
+ * @param documents Raw `.graphql` source strings (operations and any fragments they spread).
16
+ */
17
+ export declare const collectPermissionsFromDocuments: (schema: GraphQLSchema, documents: Array<string>) => Map<string, Array<string>>;
18
+ /**
19
+ * Builds a map of operation name -> sorted, de-duplicated authorization scopes required by that
20
+ * operation, based on the `@authorization` directives of every field the operation touches.
21
+ *
22
+ * @param schema The authorization-annotated schema to resolve field directives against.
23
+ * @param generatedFilePath Path to the generated `graphql.ts`; its lib `src` root holds the operations.
24
+ */
25
+ export declare const collectOperationPermissions: (schema: GraphQLSchema, generatedFilePath: string) => Map<string, Array<string>>;
@@ -0,0 +1,200 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.collectOperationPermissions = exports.collectPermissionsFromDocuments = exports.loadAuthSchema = void 0;
4
+ const iris_app_build_utilities_1 = require("@trackunit/iris-app-build-utilities");
5
+ const fs_1 = require("fs");
6
+ const graphql_1 = require("graphql");
7
+ const path_1 = require("path");
8
+ const AUTH_DIRECTIVE = "authorization";
9
+ const ALLOW_ARGUMENT = "allow";
10
+ /**
11
+ * Schemas are large (tens of thousands of lines) and every generated lib triggers a scrub, so cache
12
+ * the built schema per absolute path for the lifetime of the process.
13
+ */
14
+ const schemaCache = new Map();
15
+ /**
16
+ * Loads the authorization-annotated schema, reusing codegen's own schema resolution
17
+ * (`resolveSchema`) so scopes are read from the exact schema operations are generated against - the
18
+ * internal superset (which carries every `@authorization` directive) when checked out, otherwise
19
+ * the public schema. Returns null when only the remote endpoint is available (nothing to read from
20
+ * disk) or the schema file is missing (e.g. isolated test workspaces).
21
+ */
22
+ const loadAuthSchema = (nxRoot) => {
23
+ const schemaPointer = (0, iris_app_build_utilities_1.resolveSchema)("auto");
24
+ // `resolveSchema` returns the public endpoint URL when no schema file is checked out; we can only
25
+ // inspect directives from a schema we can read off disk, so skip in that case.
26
+ if (/^https?:\/\//.test(schemaPointer))
27
+ return null;
28
+ const schemaPath = (0, path_1.isAbsolute)(schemaPointer) ? schemaPointer : (0, path_1.join)(nxRoot, schemaPointer);
29
+ if (!(0, fs_1.existsSync)(schemaPath))
30
+ return null;
31
+ const cached = schemaCache.get(schemaPath);
32
+ if (cached !== undefined)
33
+ return cached;
34
+ try {
35
+ const schema = (0, graphql_1.buildSchema)((0, fs_1.readFileSync)(schemaPath, { encoding: "utf-8" }), { assumeValidSDL: true });
36
+ schemaCache.set(schemaPath, schema);
37
+ return schema;
38
+ }
39
+ catch {
40
+ schemaCache.set(schemaPath, null);
41
+ return null;
42
+ }
43
+ };
44
+ exports.loadAuthSchema = loadAuthSchema;
45
+ /**
46
+ * Flattens a GraphQL value node into the string scopes it contains.
47
+ * `allow` accepts both a single string (`allow: "asset.view"`) and a list (`allow: ["asset.view"]`).
48
+ */
49
+ const valueToScopes = (value) => {
50
+ if (value.kind === "StringValue")
51
+ return [value.value];
52
+ if (value.kind === "ListValue")
53
+ return value.values.flatMap(valueToScopes);
54
+ return [];
55
+ };
56
+ /**
57
+ * Reads the scopes declared by any `@authorization(allow: ...)` directive in the given list.
58
+ */
59
+ const scopesFromDirectives = (directives) => {
60
+ if (!directives)
61
+ return [];
62
+ return directives
63
+ .filter(directive => directive.name.value === AUTH_DIRECTIVE)
64
+ .flatMap(directive => {
65
+ const allowArgument = directive.arguments?.find(argument => argument.name.value === ALLOW_ARGUMENT);
66
+ return allowArgument ? valueToScopes(allowArgument.value) : [];
67
+ });
68
+ };
69
+ /**
70
+ * Collects the object-level `@authorization` scopes declared directly on a type definition
71
+ * (the directive is valid on both FIELD_DEFINITION and OBJECT).
72
+ */
73
+ const scopesFromType = (type) => {
74
+ const definitionDirectives = scopesFromDirectives(type.astNode?.directives);
75
+ const extensionDirectives = type.extensionASTNodes.flatMap(extension => scopesFromDirectives(extension.directives));
76
+ return [...definitionDirectives, ...extensionDirectives];
77
+ };
78
+ /**
79
+ * Walks a selection set against the schema, following inline fragments and fragment spreads, and
80
+ * accumulates every authorization scope referenced by the accessed fields and their return types.
81
+ */
82
+ const collectSelectionScopes = (schema, parentType, selectionSet, fragments, scopes, visitedFragments) => {
83
+ if (!parentType)
84
+ return;
85
+ for (const selection of selectionSet.selections) {
86
+ if (selection.kind === "Field") {
87
+ if (selection.name.value === "__typename")
88
+ continue;
89
+ if (!(0, graphql_1.isObjectType)(parentType) && !(0, graphql_1.isInterfaceType)(parentType))
90
+ continue;
91
+ const fieldDefinition = parentType.getFields()[selection.name.value];
92
+ if (!fieldDefinition)
93
+ continue;
94
+ scopesFromDirectives(fieldDefinition.astNode?.directives).forEach(scope => scopes.add(scope));
95
+ const fieldType = (0, graphql_1.getNamedType)(fieldDefinition.type);
96
+ scopesFromType(fieldType).forEach(scope => scopes.add(scope));
97
+ if (selection.selectionSet) {
98
+ collectSelectionScopes(schema, fieldType, selection.selectionSet, fragments, scopes, visitedFragments);
99
+ }
100
+ }
101
+ else if (selection.kind === "InlineFragment") {
102
+ const targetType = selection.typeCondition ? schema.getType(selection.typeCondition.name.value) : parentType;
103
+ if (targetType)
104
+ scopesFromType(targetType).forEach(scope => scopes.add(scope));
105
+ collectSelectionScopes(schema, targetType ?? undefined, selection.selectionSet, fragments, scopes, visitedFragments);
106
+ }
107
+ else {
108
+ const fragmentName = selection.name.value;
109
+ if (visitedFragments.has(fragmentName))
110
+ continue;
111
+ visitedFragments.add(fragmentName);
112
+ const fragment = fragments.get(fragmentName);
113
+ if (!fragment)
114
+ continue;
115
+ const targetType = schema.getType(fragment.typeCondition.name.value);
116
+ if (targetType)
117
+ scopesFromType(targetType).forEach(scope => scopes.add(scope));
118
+ collectSelectionScopes(schema, targetType ?? undefined, fragment.selectionSet, fragments, scopes, visitedFragments);
119
+ }
120
+ }
121
+ };
122
+ /**
123
+ * Recursively reads every `.graphql` source document under a directory, skipping generated output.
124
+ * `*-manager.graphql` is excluded to match codegen's default document globs, so an operation that was
125
+ * never generated can't shadow a generated one of the same name.
126
+ */
127
+ const readGraphqlDocuments = (directory) => {
128
+ if (!(0, fs_1.existsSync)(directory))
129
+ return [];
130
+ const documents = [];
131
+ for (const entry of (0, fs_1.readdirSync)(directory, { withFileTypes: true })) {
132
+ const fullPath = (0, path_1.join)(directory, entry.name);
133
+ if (entry.isDirectory()) {
134
+ if (entry.name === "generated" || entry.name === "node_modules")
135
+ continue;
136
+ documents.push(...readGraphqlDocuments(fullPath));
137
+ }
138
+ else if (entry.name.endsWith(".graphql") && !entry.name.endsWith("-manager.graphql")) {
139
+ documents.push((0, fs_1.readFileSync)(fullPath, { encoding: "utf-8" }));
140
+ }
141
+ }
142
+ return documents;
143
+ };
144
+ /**
145
+ * Builds a map of operation name -> sorted, de-duplicated authorization scopes required by that
146
+ * operation, from raw GraphQL operation/fragment source documents.
147
+ *
148
+ * @param schema The authorization-annotated schema to resolve field directives against.
149
+ * @param documents Raw `.graphql` source strings (operations and any fragments they spread).
150
+ */
151
+ const collectPermissionsFromDocuments = (schema, documents) => {
152
+ const result = new Map();
153
+ if (documents.length === 0)
154
+ return result;
155
+ const definitions = [];
156
+ for (const document of documents) {
157
+ try {
158
+ definitions.push(...(0, graphql_1.parse)(document).definitions);
159
+ }
160
+ catch (error) {
161
+ // A single unparseable document must not silently strip scope docs from every other operation.
162
+ // eslint-disable-next-line no-console
163
+ console.warn(`[graphql-mock] Skipping unparseable GraphQL document: ${error.message}`);
164
+ }
165
+ }
166
+ const fragments = new Map();
167
+ for (const definition of definitions) {
168
+ if (definition.kind === "FragmentDefinition") {
169
+ fragments.set(definition.name.value, definition);
170
+ }
171
+ }
172
+ for (const definition of definitions) {
173
+ if (definition.kind !== "OperationDefinition" || !definition.name)
174
+ continue;
175
+ const rootType = definition.operation === "query"
176
+ ? schema.getQueryType()
177
+ : definition.operation === "mutation"
178
+ ? schema.getMutationType()
179
+ : schema.getSubscriptionType();
180
+ const scopes = new Set();
181
+ collectSelectionScopes(schema, rootType ?? undefined, definition.selectionSet, fragments, scopes, new Set());
182
+ result.set(definition.name.value, [...scopes].sort());
183
+ }
184
+ return result;
185
+ };
186
+ exports.collectPermissionsFromDocuments = collectPermissionsFromDocuments;
187
+ /**
188
+ * Builds a map of operation name -> sorted, de-duplicated authorization scopes required by that
189
+ * operation, based on the `@authorization` directives of every field the operation touches.
190
+ *
191
+ * @param schema The authorization-annotated schema to resolve field directives against.
192
+ * @param generatedFilePath Path to the generated `graphql.ts`; its lib `src` root holds the operations.
193
+ */
194
+ const collectOperationPermissions = (schema, generatedFilePath) => {
195
+ // <lib>/src/generated/graphql-api/graphql.ts -> <lib>/src
196
+ const documentsDirectory = (0, path_1.join)((0, path_1.dirname)(generatedFilePath), "..", "..");
197
+ return (0, exports.collectPermissionsFromDocuments)(schema, readGraphqlDocuments(documentsDirectory));
198
+ };
199
+ exports.collectOperationPermissions = collectOperationPermissions;
200
+ //# sourceMappingURL=collectPermissions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collectPermissions.js","sourceRoot":"","sources":["../../../../../../../libs/react/graphql-tools/src/executors/createHooks/collectPermissions.ts"],"names":[],"mappings":";;;AAAA,kFAAoE;AACpE,2BAA2D;AAC3D,qCAaiB;AACjB,+BAAiD;AAEjD,MAAM,cAAc,GAAG,eAAe,CAAC;AACvC,MAAM,cAAc,GAAG,OAAO,CAAC;AAE/B;;;GAGG;AACH,MAAM,WAAW,GAAG,IAAI,GAAG,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2BAA2B,+BAOtC","sourcesContent":["import { resolveSchema } from \"@trackunit/iris-app-build-utilities\";\nimport { existsSync, readdirSync, readFileSync } from \"fs\";\nimport {\n buildSchema,\n DefinitionNode,\n DirectiveNode,\n FragmentDefinitionNode,\n getNamedType,\n GraphQLNamedType,\n GraphQLSchema,\n isInterfaceType,\n isObjectType,\n parse,\n SelectionSetNode,\n ValueNode,\n} from \"graphql\";\nimport { dirname, isAbsolute, join } from \"path\";\n\nconst AUTH_DIRECTIVE = \"authorization\";\nconst ALLOW_ARGUMENT = \"allow\";\n\n/**\n * Schemas are large (tens of thousands of lines) and every generated lib triggers a scrub, so cache\n * the built schema per absolute path for the lifetime of the process.\n */\nconst schemaCache = new Map<string, GraphQLSchema | null>();\n\n/**\n * Loads the authorization-annotated schema, reusing codegen's own schema resolution\n * (`resolveSchema`) so scopes are read from the exact schema operations are generated against - the\n * internal superset (which carries every `@authorization` directive) when checked out, otherwise\n * the public schema. Returns null when only the remote endpoint is available (nothing to read from\n * disk) or the schema file is missing (e.g. isolated test workspaces).\n */\nexport const loadAuthSchema = (nxRoot: string): GraphQLSchema | null => {\n const schemaPointer = resolveSchema(\"auto\");\n\n // `resolveSchema` returns the public endpoint URL when no schema file is checked out; we can only\n // inspect directives from a schema we can read off disk, so skip in that case.\n if (/^https?:\\/\\//.test(schemaPointer)) return null;\n\n const schemaPath = isAbsolute(schemaPointer) ? schemaPointer : join(nxRoot, schemaPointer);\n if (!existsSync(schemaPath)) return null;\n\n const cached = schemaCache.get(schemaPath);\n if (cached !== undefined) return cached;\n\n try {\n const schema = buildSchema(readFileSync(schemaPath, { encoding: \"utf-8\" }), { assumeValidSDL: true });\n schemaCache.set(schemaPath, schema);\n return schema;\n } catch {\n schemaCache.set(schemaPath, null);\n return null;\n }\n};\n\n/**\n * Flattens a GraphQL value node into the string scopes it contains.\n * `allow` accepts both a single string (`allow: \"asset.view\"`) and a list (`allow: [\"asset.view\"]`).\n */\nconst valueToScopes = (value: ValueNode): Array<string> => {\n if (value.kind === \"StringValue\") return [value.value];\n if (value.kind === \"ListValue\") return value.values.flatMap(valueToScopes);\n return [];\n};\n\n/**\n * Reads the scopes declared by any `@authorization(allow: ...)` directive in the given list.\n */\nconst scopesFromDirectives = (directives: ReadonlyArray<DirectiveNode> | undefined): Array<string> => {\n if (!directives) return [];\n return directives\n .filter(directive => directive.name.value === AUTH_DIRECTIVE)\n .flatMap(directive => {\n const allowArgument = directive.arguments?.find(argument => argument.name.value === ALLOW_ARGUMENT);\n return allowArgument ? valueToScopes(allowArgument.value) : [];\n });\n};\n\n/**\n * Collects the object-level `@authorization` scopes declared directly on a type definition\n * (the directive is valid on both FIELD_DEFINITION and OBJECT).\n */\nconst scopesFromType = (type: GraphQLNamedType): Array<string> => {\n const definitionDirectives = scopesFromDirectives(type.astNode?.directives);\n const extensionDirectives = type.extensionASTNodes.flatMap(extension => scopesFromDirectives(extension.directives));\n return [...definitionDirectives, ...extensionDirectives];\n};\n\n/**\n * Walks a selection set against the schema, following inline fragments and fragment spreads, and\n * accumulates every authorization scope referenced by the accessed fields and their return types.\n */\nconst collectSelectionScopes = (\n schema: GraphQLSchema,\n parentType: GraphQLNamedType | undefined,\n selectionSet: SelectionSetNode,\n fragments: Map<string, FragmentDefinitionNode>,\n scopes: Set<string>,\n visitedFragments: Set<string>\n): void => {\n if (!parentType) return;\n\n for (const selection of selectionSet.selections) {\n if (selection.kind === \"Field\") {\n if (selection.name.value === \"__typename\") continue;\n if (!isObjectType(parentType) && !isInterfaceType(parentType)) continue;\n\n const fieldDefinition = parentType.getFields()[selection.name.value];\n if (!fieldDefinition) continue;\n\n scopesFromDirectives(fieldDefinition.astNode?.directives).forEach(scope => scopes.add(scope));\n\n const fieldType = getNamedType(fieldDefinition.type);\n scopesFromType(fieldType).forEach(scope => scopes.add(scope));\n\n if (selection.selectionSet) {\n collectSelectionScopes(schema, fieldType, selection.selectionSet, fragments, scopes, visitedFragments);\n }\n } else if (selection.kind === \"InlineFragment\") {\n const targetType = selection.typeCondition ? schema.getType(selection.typeCondition.name.value) : parentType;\n if (targetType) scopesFromType(targetType).forEach(scope => scopes.add(scope));\n collectSelectionScopes(\n schema,\n targetType ?? undefined,\n selection.selectionSet,\n fragments,\n scopes,\n visitedFragments\n );\n } else {\n const fragmentName = selection.name.value;\n if (visitedFragments.has(fragmentName)) continue;\n visitedFragments.add(fragmentName);\n\n const fragment = fragments.get(fragmentName);\n if (!fragment) continue;\n\n const targetType = schema.getType(fragment.typeCondition.name.value);\n if (targetType) scopesFromType(targetType).forEach(scope => scopes.add(scope));\n collectSelectionScopes(\n schema,\n targetType ?? undefined,\n fragment.selectionSet,\n fragments,\n scopes,\n visitedFragments\n );\n }\n }\n};\n\n/**\n * Recursively reads every `.graphql` source document under a directory, skipping generated output.\n * `*-manager.graphql` is excluded to match codegen's default document globs, so an operation that was\n * never generated can't shadow a generated one of the same name.\n */\nconst readGraphqlDocuments = (directory: string): Array<string> => {\n if (!existsSync(directory)) return [];\n\n const documents: Array<string> = [];\n for (const entry of readdirSync(directory, { withFileTypes: true })) {\n const fullPath = join(directory, entry.name);\n if (entry.isDirectory()) {\n if (entry.name === \"generated\" || entry.name === \"node_modules\") continue;\n documents.push(...readGraphqlDocuments(fullPath));\n } else if (entry.name.endsWith(\".graphql\") && !entry.name.endsWith(\"-manager.graphql\")) {\n documents.push(readFileSync(fullPath, { encoding: \"utf-8\" }));\n }\n }\n return documents;\n};\n\n/**\n * Builds a map of operation name -> sorted, de-duplicated authorization scopes required by that\n * operation, from raw GraphQL operation/fragment source documents.\n *\n * @param schema The authorization-annotated schema to resolve field directives against.\n * @param documents Raw `.graphql` source strings (operations and any fragments they spread).\n */\nexport const collectPermissionsFromDocuments = (\n schema: GraphQLSchema,\n documents: Array<string>\n): Map<string, Array<string>> => {\n const result = new Map<string, Array<string>>();\n if (documents.length === 0) return result;\n\n const definitions: Array<DefinitionNode> = [];\n for (const document of documents) {\n try {\n definitions.push(...parse(document).definitions);\n } catch (error) {\n // A single unparseable document must not silently strip scope docs from every other operation.\n // eslint-disable-next-line no-console\n console.warn(`[graphql-mock] Skipping unparseable GraphQL document: ${(error as Error).message}`);\n }\n }\n\n const fragments = new Map<string, FragmentDefinitionNode>();\n for (const definition of definitions) {\n if (definition.kind === \"FragmentDefinition\") {\n fragments.set(definition.name.value, definition);\n }\n }\n\n for (const definition of definitions) {\n if (definition.kind !== \"OperationDefinition\" || !definition.name) continue;\n\n const rootType =\n definition.operation === \"query\"\n ? schema.getQueryType()\n : definition.operation === \"mutation\"\n ? schema.getMutationType()\n : schema.getSubscriptionType();\n\n const scopes = new Set<string>();\n collectSelectionScopes(schema, rootType ?? undefined, definition.selectionSet, fragments, scopes, new Set());\n result.set(definition.name.value, [...scopes].sort());\n }\n\n return result;\n};\n\n/**\n * Builds a map of operation name -> sorted, de-duplicated authorization scopes required by that\n * operation, based on the `@authorization` directives of every field the operation touches.\n *\n * @param schema The authorization-annotated schema to resolve field directives against.\n * @param generatedFilePath Path to the generated `graphql.ts`; its lib `src` root holds the operations.\n */\nexport const collectOperationPermissions = (\n schema: GraphQLSchema,\n generatedFilePath: string\n): Map<string, Array<string>> => {\n // <lib>/src/generated/graphql-api/graphql.ts -> <lib>/src\n const documentsDirectory = join(dirname(generatedFilePath), \"..\", \"..\");\n return collectPermissionsFromDocuments(schema, readGraphqlDocuments(documentsDirectory));\n};\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"executor.js","sourceRoot":"","sources":["../../../../../../../libs/react/graphql-tools/src/executors/createHooks/executor.ts"],"names":[],"mappings":";;;AACA,2BAAgC;AAChC,+BAA4B;AAC5B,kBAAgB;AAChB,mDAAgD;AAEhD,2CAAwC;AAExC;;;;;;GAMG;AACI,MAAM,kBAAkB,GAAG,KAAK,EACrC,OAAyC,EACzC,OAAwB,EACgB,EAAE;IAC1C,MAAM,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,EAAE,CAAC;IACjC,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC;Q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,eAAU,EAAC,kBAAkB,CAAC,EAAE,CAAC;YACnC,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;gBACtB,sCAAsC;gBACtC,OAAO,CAAC,GAAG,CAAC,kBAAkB,EAAE,kBAAkB,CAAC,CAAC;YACtD,CAAC;YACD,MAAM,IAAA,qBAAS,EAAC,kBAAkB,EAAE,MAAM,EAAE,OAAO,CAAC,SAAS,EAAE,OAAO,CAAC,aAAa,CAAC,CAAC;QACxF,CAAC;IACH,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,MAAM,CAAC,EAAE,CAAC;AACtC,CAAC,CAAC;AAvDW,QAAA,kBAAkB,sBAuD7B","sourcesContent":["import { ExecutorContext } from \"@nx/devkit\";\nimport { existsSync } from \"fs\";\nimport { join } from \"path\";\nimport \"win-ca\";\nimport { generateHooks } from \"./generateHooks\";\nimport type { CreateGraphqlHooksExecutorSchema } from \"./schema\";\nimport { scrubFile } from \"./scrubFile\";\n\n/**\n * This executor generates react hooks for all graphql files.\n *\n * @param options GraphQL generation options\n * @param context The execution context for this executor\n * @returns {Promise<{ success: boolean; }>} success when finished\n */\nexport const CreateGraphqlHooks = async (\n options: CreateGraphqlHooksExecutorSchema,\n context: ExecutorContext\n): Promise<{ readonly success: boolean }> => {\n const nxRoot = `${context.root}`;\n if (!context.projectName) {\n throw new Error(\"context projectName is required\");\n }\n\n const libRoot = context.projectsConfigurations.projects[context.projectName]?.root;\n\n if (!libRoot) {\n throw new Error(\"Missing library root\");\n }\n\n const fullLibRoot = join(nxRoot, libRoot);\n const tsConfigPath = existsSync(join(fullLibRoot, \"tsconfig.lib.json\"))\n ? join(fullLibRoot, \"tsconfig.lib.json\")\n : join(fullLibRoot, \"tsconfig.app.json\");\n\n if (!tsConfigPath) {\n throw new Error(\"context projectsConfigurations is required\");\n }\n\n const codeGenFilePath = join(fullLibRoot, \"codegen.ts\");\n if (!existsSync(codeGenFilePath)) {\n throw new Error(`codegen.ts file not found in ${fullLibRoot} please add this file and run again to generate hooks. The content should be\nimport { type CodegenConfig } from \"@graphql-codegen/cli\";\nimport { getGraphqlCodegenConfig } from \"@trackunit/iris-app-build-utilities\";\n\nconst config: CodegenConfig = {\n ...getGraphqlCodegenConfig(__dirname),\n // You can override codegen default config here\n};\nexport default config;\n`);\n }\n\n const result = await generateHooks({\n nxRoot: context.root,\n codeGenFilePath,\n isVerbose: context.isVerbose,\n tsConfigPath,\n });\n if (process.env.SKIP_SCRUB !== \"true\") {\n const pathToGenerateFile = join(fullLibRoot, \"src\", \"generated\", \"graphql-api\", \"graphql.ts\");\n if (existsSync(pathToGenerateFile)) {\n if (context.isVerbose) {\n // eslint-disable-next-line no-console\n console.log(\"Scrubbing file: \", pathToGenerateFile);\n }\n await scrubFile(pathToGenerateFile, nxRoot, context.isVerbose, options.generateMocks);\n }\n }\n return { success: Boolean(result) };\n};\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generateHooks.js","sourceRoot":"","sources":["../../../../../../../libs/react/graphql-tools/src/executors/createHooks/generateHooks.ts"],"names":[],"mappings":";;;AAAA,8CAA+D;AAC/D,8CAAoD;AACpD,yCAAiC;AAEjC;;;;;;;;GAQG;AACI,MAAM,aAAa,GAAG,KAAK,EAAE,OAKnC,EAAE,EAAE;IACH,MAAM,aAAa,GAAG;QACpB,KAAK,EAAE,KAAK;QACZ,SAAS,EAAE,IAAI;QACf,MAAM,EAAE,CAAC,OAAO,CAAC,SAAS;QAC1B,UAAU,EAAE,KAAK;QACjB,OAAO,EAAE,KAAK;QACd,OAAO,EAAE,OAAO,CAAC,YAAY;QAC7B,MAAM,EAAE,OAAO,CAAC,eAAe;QAC/B,OAAO,EAAE,EAAE;QACX,OAAO,EAAE,OAAO,CAAC,SAAS;QAC1B,KAAK,EAAE,OAAO,CAAC,SAAS;KACzB,CAAC;IACF,IAAI,OAAO,CAAC,SAAS,EAAE,CAAC;QACtB,sCAAsC;QACtC,OAAO,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC;IAC7B,CAAC;IAED,6FAA6F;IAC7F,0FAA0F;IAC1F,2EAA2E;IAC3E,MAAM,mBAAmB,GAAG,IAAA,4BAAiB,EAAC,IAAA,gBAAI,EAAC,OAAO,CAAC,MAAM,EAAE,oBAAoB,CAAC,CAAC,CAAC;IAE1F,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,MAAM,IAAA,mBAAa,EAAC,aAAa,CAAC,CAAC;QAEnD,OAAO,MAAM,IAAA,cAAQ,EAAC,OAAO,CAAC,CAAC;IACjC,CAAC;YAAS,CAAC;QACT,mBAAmB,EAAE,CAAC;IACxB,CAAC;AACH,CAAC,CAAC;AAnCW,QAAA,aAAa,iBAmCxB","sourcesContent":["import { createContext, generate } from \"@graphql-codegen/cli\";\nimport { registerTsProject } from \"@nx/js/internal\";\nimport { join } from \"node:path\";\n\n/**\n * Generates React hooks from your graphql files.\n *\n * @param options - The generation options.\n * @param options.codeGenFilePath - The path to the codegen file.\n * @param options.nxRoot - The nx root.\n * @param options.tsConfigPath - The path to the tsconfig file.\n * @param options.isVerbose - If true, will log more information.\n */\nexport const generateHooks = async (options: {\n codeGenFilePath: string;\n nxRoot: string;\n isVerbose?: boolean;\n tsConfigPath: string;\n}) => {\n const contextConfig = {\n watch: false,\n overwrite: true,\n silent: !options.isVerbose,\n errorsOnly: false,\n profile: false,\n project: options.tsConfigPath,\n config: options.codeGenFilePath,\n require: [],\n verbose: options.isVerbose,\n debug: options.isVerbose,\n };\n if (options.isVerbose) {\n // eslint-disable-next-line no-console\n console.log(contextConfig);\n }\n\n // graphql-codegen loads codegen.ts through its own loader. Nx 23 leaves TypeScript to Node's\n // native type stripping and no longer registers tsconfig-paths up front, so the workspace\n // aliases codegen.ts imports only resolve once we register them ourselves.\n const unregisterTsProject = registerTsProject(join(options.nxRoot, \"tsconfig.base.json\"));\n\n try {\n const context = await createContext(contextConfig);\n\n return await generate(context);\n } finally {\n unregisterTsProject();\n }\n};\n"]}
@@ -93,7 +93,7 @@ const scrubFile = async (file, nxRoot, isVerbose, generateMocks = true) => {
93
93
  // mutates the shared source file via insertStatements().
94
94
  const scrubbedFileContent = await (0, exports.scrubFileContent)(fileContent, nxRoot, isVerbose, sharedSourceFile);
95
95
  const scrubbedMockFileContent = generateMocks
96
- ? await (0, scrubMockFile_1.scrubMockFileContent)(fileContent, nxRoot, isVerbose, sharedSourceFile)
96
+ ? await (0, scrubMockFile_1.scrubMockFileContent)(fileContent, nxRoot, isVerbose, sharedSourceFile, file)
97
97
  : undefined;
98
98
  const prettierOptions = await getPrettierOptions(nxRoot);
99
99
  let prettySrc = scrubbedFileContent;
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scrubFile.js","sourceRoot":"","sources":["../../../../../../../libs/react/graphql-tools/src/executors/createHooks/scrubFile.ts"],"names":[],"mappings":";;;;AAAA,+BAA+B;AAC/B,2BAAyD;AACzD,+BAAqC;AACrC,2DAAqC;AACrC,uCAA+C;AAC/C,mDAAuD;AACvD,mCAAoG;AAEpG;;;;;;;GAOG;AACH,MAAM,kBAAkB,GAAG,KAAK,EAAE,MAAc,EAAoC,EAAE;IACpF,MAAM,kBAAkB,GAAG,IAAA,WAAI,EAAC,MAAM,EAAE,qBAAqB,CAAC,CAAC;IAC/D,OAAO,MAAM,QAAQ;SAClB,aAAa,CAAC,kBAAkB,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,YAAY,EAAE,KAAK,EAAE,CAAC;SAC3E,KAAK,CAAC,CAAC,KAAY,EAAQ,EAAE;QAC5B,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QACnB,OAAO,IAAI,CAAC;IACd,CAAC,CAAC,CAAC;AACP,CAAC,CAAC;AAEF;;GAEG;AACI,MAAM,gBAAgB,GAAG,KAAK,EACnC,WAAmB,EACnB,OAAe,EACf,SAAmB,EACnB,kBAA+B,EAC/B,EAAE;IACF,MAAM,KAAK,GAAG,IAAI,IAAI,EAAE,CAAC,OAAO,EAAE,CAAC;IAEnC,MAAM,UAAU,GAA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;gBACH,aAAa,GAAG,MAAM,QAAQ,CAAC,MAAM,CAAC,uBAAuB,EAAE,aAAa,CAAC,CAAC;YAChF,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,OAAO,CAAC,KAAK,CAAC,2BAA2B,EAAE,KAAK,CAAC,CAAC;YACpD,CAAC;QACH,CAAC;IACH,CAAC;IACD,IAAA,kBAAa,EAAC,IAAI,EAAE,SAAS,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC;IAEtD,MAAM,YAAY,GAAG,IAAA,WAAI,EAAC,IAAA,cAAO,EAAC,IAAI,CAAC,EAAE,SAAS,CAAC,CAAC;IAEpD,4FAA4F;IAC5F,gFAAgF;IAChF,IAAI,aAAa,KAAK,SAAS,EAAE,CAAC;QAChC,IAAA,WAAM,EAAC,YAAY,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QACtC,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,IAAI,aAAa,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC7B,IAAA,kBAAa,EAAC,YAAY,EAAE,aAAa,EAAE,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC,CAAC;IACpE,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC,CAAC;AA3DW,QAAA,SAAS,aA2DpB","sourcesContent":["/* eslint-disable no-console */\nimport { readFileSync, rmSync, writeFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\nimport * as prettier from \"prettier\";\nimport { Project, SourceFile } from \"ts-morph\";\nimport { scrubMockFileContent } from \"./scrubMockFile\";\nimport { convertEnumToConstObject, createSourceFile, getPreservedTypes, isFragment } from \"./utils\";\n\n/**\n * Resolves the repo's Prettier config by searching upward from `nxRoot` (the same\n * lookup Prettier's CLI/editor integrations use), rather than requiring an exact\n * `prettier.config.mjs` at that path. This lets generated code be formatted with the\n * repo's real config when it exists, while degrading gracefully (no formatting, no\n * throw) for workspaces without one - e.g. the ad-hoc workspaces `nx-tools-e2e`\n * scaffolds via `create-iris-app-workspace` to exercise this executor in isolation.\n */\nconst getPrettierOptions = async (nxRoot: string): Promise<prettier.Options | null> => {\n const prettierConfigPath = join(nxRoot, \"prettier.config.mjs\");\n return await prettier\n .resolveConfig(prettierConfigPath, { useCache: false, editorconfig: false })\n .catch((error: Error): null => {\n console.log(error);\n return null;\n });\n};\n\n/**\n * Generates React hooks from your graphql files.\n */\nexport const scrubFileContent = async (\n fileContent: string,\n _nxRoot: string,\n isVerbose?: boolean,\n providedSourceFile?: SourceFile\n) => {\n const start = new Date().getTime();\n\n const sourceFile = providedSourceFile ?? createSourceFile(fileContent);\n\n let resultFileContent = \"\";\n const scalarsType = sourceFile.getTypeAliasOrThrow(\"Scalars\");\n scalarsType.getEndLineNumber();\n resultFileContent += `${fileContent.split(\"\\n\").slice(0, scalarsType.getEndLineNumber()).join(\"\\n\")}\\n`;\n const alreadyAdded = sourceFile\n .getTypeAliases()\n .filter(typeAlias => typeAlias.getStartLineNumber() < scalarsType.getEndLineNumber())\n .map(typeAlias => typeAlias.getName());\n\n resultFileContent = resultFileContent.replace(\n \"export type InputMaybe<T> = Maybe<T>;\",\n \"export type InputMaybe<T> = Maybe<T> | undefined;\"\n );\n\n const { preservedTypes, queryAndMutations } = getPreservedTypes(sourceFile, isVerbose);\n if (isVerbose) {\n console.log(\"PreservedTypes:\", preservedTypes);\n }\n\n sourceFile.getEnums().forEach(enumType => {\n const typeName = enumType.getName();\n if (preservedTypes.has(typeName) && !alreadyAdded.includes(typeName) && !isFragment(typeName)) {\n alreadyAdded.push(typeName);\n resultFileContent += `\\n${convertEnumToConstObject(enumType)}\\n`;\n }\n });\n sourceFile.getTypeAliases().forEach(typeAlias => {\n const typeName = typeAlias.getName();\n if (preservedTypes.has(typeName) && !alreadyAdded.includes(typeName) && !isFragment(typeName)) {\n alreadyAdded.push(typeName);\n resultFileContent += `\\n${typeAlias.getText()}\\n`;\n }\n });\n\n const resultQueryAndMutations = queryAndMutations.map(queryOrMutation => queryOrMutation.getFullText()).join(\"\\n\");\n\n const result = `${resultFileContent}\\n${resultQueryAndMutations}`;\n if (isVerbose) {\n const end = new Date().getTime();\n const time = end - start;\n console.log(`Execution time: ${time}`);\n }\n\n return result;\n};\n\n/**\n * Scrubs the file content.\n *\n * @param file The file to scrub.\n */\nexport const scrubFile = async (file: string, nxRoot: string, isVerbose?: boolean, generateMocks = true) => {\n const fileContent = readFileSync(file, { encoding: \"utf-8\" });\n if (fileContent.length === 0) {\n console.warn(`File ${file} is empty`);\n }\n\n // Parse the (large) generated file into ts-morph once and share it between the main and mock scrub\n // instead of parsing it twice. Use the mock's stricter compiler options (the main scrub doesn't use\n // the TypeChecker, so they don't affect its output).\n const sharedSourceFile = new Project({\n compilerOptions: {\n noUnusedLocals: true,\n noUnusedParameters: true,\n strictNullChecks: true,\n },\n }).createSourceFile(\"tmp.ts\", fileContent);\n\n // The main scrub reads line numbers from the pristine AST, so it must run before the mock scrub\n // mutates the shared source file via insertStatements().\n const scrubbedFileContent = await scrubFileContent(fileContent, nxRoot, isVerbose, sharedSourceFile);\n\n const scrubbedMockFileContent = generateMocks\n ? await scrubMockFileContent(fileContent, nxRoot, isVerbose, sharedSourceFile, file)\n : undefined;\n\n const prettierOptions = await getPrettierOptions(nxRoot);\n\n let prettySrc = scrubbedFileContent;\n let prettyMockSrc = scrubbedMockFileContent;\n if (prettierOptions) {\n const formatOptions: prettier.Options = { ...prettierOptions, parser: \"typescript\" };\n try {\n prettySrc = await prettier.format(scrubbedFileContent, formatOptions);\n } catch (error) {\n console.error(\"Error in prettier.format:\", error);\n }\n if (scrubbedMockFileContent !== undefined) {\n try {\n prettyMockSrc = await prettier.format(scrubbedMockFileContent, formatOptions);\n } catch (error) {\n console.error(\"Error in prettier.format:\", error);\n }\n }\n }\n writeFileSync(file, prettySrc, { encoding: \"utf-8\" });\n\n const mockFilePath = join(dirname(file), \"mock.ts\");\n\n // A project that turns mock generation off may still carry a mock file from an earlier run,\n // so remove it instead of leaving stale helpers behind in the generated output.\n if (prettyMockSrc === undefined) {\n rmSync(mockFilePath, { force: true });\n return prettySrc;\n }\n\n if (prettyMockSrc.length > 0) {\n writeFileSync(mockFilePath, prettyMockSrc, { encoding: \"utf-8\" });\n }\n return prettySrc;\n};\n"]}
@@ -2,4 +2,4 @@ import { SourceFile } from "ts-morph";
2
2
  /**
3
3
  * Generates React hooks from your graphql files.
4
4
  */
5
- export declare const scrubMockFileContent: (fileContent: string, _nxRoot: string, isVerbose?: boolean, providedSourceFile?: SourceFile) => Promise<string>;
5
+ export declare const scrubMockFileContent: (fileContent: string, nxRoot: string, isVerbose?: boolean, providedSourceFile?: SourceFile, generatedFilePath?: string) => Promise<string>;
@@ -4,6 +4,7 @@ exports.scrubMockFileContent = void 0;
4
4
  /* eslint-disable no-console */
5
5
  const faker_1 = require("@faker-js/faker");
6
6
  const ts_morph_1 = require("ts-morph");
7
+ const collectPermissions_1 = require("./collectPermissions");
7
8
  const UNDEFINED_SENTINEL = "__UNDEFINED__";
8
9
  /**
9
10
  * Strips surrounding double-quotes from a ts-morph property name.
@@ -281,7 +282,7 @@ const generateMockFromType = (type, text) => {
281
282
  /**
282
283
  * Generates React hooks from your graphql files.
283
284
  */
284
- const scrubMockFileContent = async (fileContent, _nxRoot, isVerbose, providedSourceFile) => {
285
+ const scrubMockFileContent = async (fileContent, nxRoot, isVerbose, providedSourceFile, generatedFilePath) => {
285
286
  const start = new Date().getTime();
286
287
  const generatedFile = providedSourceFile ??
287
288
  new ts_morph_1.Project({
@@ -307,6 +308,10 @@ const scrubMockFileContent = async (fileContent, _nxRoot, isVerbose, providedSou
307
308
  const time = end - start;
308
309
  console.log(`Mock Execution time: ${time}`);
309
310
  }
311
+ // Resolve which authorization scopes each mocked operation requires. `@authorization(allow: [...])`
312
+ // directives only live in the schema, so we walk each operation's selection set against it.
313
+ const schema = generatedFilePath ? (0, collectPermissions_1.loadAuthSchema)(nxRoot) : null;
314
+ const permissionsByOperation = schema && generatedFilePath ? (0, collectPermissions_1.collectOperationPermissions)(schema, generatedFilePath) : new Map();
310
315
  const mock = mockThese.map(mocker => {
311
316
  const postFix = (mocker.getName().includes("Query") ? "Query" : "Mutation").length;
312
317
  const variablesTypeName = `${mocker.getName()}Variables`;
@@ -346,7 +351,15 @@ const scrubMockFileContent = async (fileContent, _nxRoot, isVerbose, providedSou
346
351
  : `
347
352
  const default${mocker.getName()}Variables: gql.${variablesTypeName} = ${defaultVarsSource};
348
353
  `;
349
- return `${constBlock}
354
+ const permissions = permissionsByOperation.get(docName) ?? [];
355
+ const permissionsComment = permissions.length > 0
356
+ ? `
357
+ /**
358
+ * Required authorization scopes (the token needs at least one allowed scope per accessed field):
359
+ ${permissions.map(scope => ` * - ${scope}`).join("\n")}
360
+ */`
361
+ : "";
362
+ return `${constBlock}${permissionsComment}
350
363
  export const mockFor${mocker.getName()} = (${variablesParam}, data?: DeepPartialNullable<gql.${mocker.getName()}> ) => {
351
364
  return queryFor(gql.${docName}Document, mergeDeepVars(${defaultVarsRef}, variables),
352
365
  mergeDeep(
@@ -355,6 +368,11 @@ const scrubMockFileContent = async (fileContent, _nxRoot, isVerbose, providedSou
355
368
  );
356
369
  }`;
357
370
  });
371
+ const mockedOperationNames = mockThese.map(mocker => {
372
+ const postFix = (mocker.getName().includes("Query") ? "Query" : "Mutation").length;
373
+ return mocker.getName().substring(0, mocker.getName().length - postFix);
374
+ });
375
+ logRequiredPermissions(mockedOperationNames, permissionsByOperation, generatedFilePath, isVerbose);
358
376
  return `
359
377
  import { mergeDeep } from "@apollo/client/utilities";
360
378
  import { mergeDeepVars, queryFor, DeepPartialNullable, PickDeepPartialNullable } from "@trackunit/react-core-contexts-test";
@@ -364,4 +382,21 @@ const scrubMockFileContent = async (fileContent, _nxRoot, isVerbose, providedSou
364
382
  `;
365
383
  };
366
384
  exports.scrubMockFileContent = scrubMockFileContent;
385
+ /**
386
+ * Prints a summary of the authorization scopes required by the mocked operations, plus the full
387
+ * de-duplicated list of scopes a token must be granted to satisfy every mock in the file.
388
+ */
389
+ const logRequiredPermissions = (operationNames, permissionsByOperation, generatedFilePath, isVerbose) => {
390
+ if (!isVerbose || permissionsByOperation.size === 0)
391
+ return;
392
+ const allScopes = new Set();
393
+ console.log(`[graphql-mock] Required authorization scopes${generatedFilePath ? ` for ${generatedFilePath}` : ""}:`);
394
+ operationNames.forEach(operationName => {
395
+ const scopes = permissionsByOperation.get(operationName) ?? [];
396
+ scopes.forEach(scope => allScopes.add(scope));
397
+ console.log(` ${operationName}: ${scopes.length > 0 ? scopes.join(", ") : "(none)"}`);
398
+ });
399
+ const sortedScopes = [...allScopes].sort();
400
+ console.log(`[graphql-mock] All scopes referenced (${sortedScopes.length}): ${sortedScopes.length > 0 ? sortedScopes.join(", ") : "(none)"}`);
401
+ };
367
402
  //# sourceMappingURL=scrubMockFile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"scrubMockFile.js","sourceRoot":"","sources":["../../../../../../../libs/react/graphql-tools/src/executors/createHooks/scrubMockFile.ts"],"names":[],"mappings":";;;AAAA,+BAA+B;AAC/B,2CAAwC;AACxC,uCASkB;AAClB,6DAAmF;AAEnF,MAAM,kBAAkB,GAAG,eAAe,CAAC;AAE3C;;;GAGG;AACH,MAAM,WAAW,GAAG,CAAC,IAAY,EAAU,EAAE,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;AAEtH;;GAEG;AACH,MAAM,YAAY,GAAG,CAAC,GAA4B,EAAE,IAAY,EAAE,EAAE,CAClE,GAAG,CAAC,WAAW,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,WAAW,CAAC,IAAI,IAAI,GAAG,CAAC,CAAC;AAExD;;;GAGG;AACH,MAAM,eAAe,GAAG,CAAC,IAAm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sourcesContent":["/* eslint-disable no-console */\nimport { faker } from \"@faker-js/faker\";\nimport {\n ObjectLiteralExpression,\n Project,\n SourceFile,\n SyntaxKind,\n Node as TsMorphNode,\n Symbol as TsMorphSymbol,\n Type,\n TypeAliasDeclaration,\n} from \"ts-morph\";\nimport { collectOperationPermissions, loadAuthSchema } from \"./collectPermissions\";\n\nconst UNDEFINED_SENTINEL = \"__UNDEFINED__\";\n\n/**\n * Strips surrounding double-quotes from a ts-morph property name.\n * Codegen may emit JSON-style keys (`\"kind\"`) whose getName() includes the quotes.\n */\nconst stripQuotes = (name: string): string => (name.startsWith('\"') && name.endsWith('\"') ? name.slice(1, -1) : name);\n\n/**\n * Finds a property in an object literal by name, handling both quoted and unquoted keys.\n */\nconst findProperty = (obj: ObjectLiteralExpression, name: string) =>\n obj.getProperty(name) ?? obj.getProperty(`\"${name}\"`);\n\n/**\n * Resolves the type of a property symbol in the context of a source file.\n * Uses the TypeChecker to correctly handle mapped types like Exact<{...}>.\n */\nconst getPropertyType = (prop: TsMorphSymbol, sourceFile: SourceFile): Type => {\n return sourceFile.getProject().getTypeChecker().getTypeOfSymbolAtLocation(prop, sourceFile);\n};\n\n/**\n * Checks whether a type is an InputMaybe union (contains null or undefined members).\n * Required unions like `string | string[]` or enums do NOT match.\n */\nconst isInputMaybe = (type: Type): boolean =>\n type.isUnion() && type.getUnionTypes().some(m => m.isNull() || m.isUndefined());\n\n/**\n * Returns the names of required variable fields (those whose type is NOT\n * wrapped in InputMaybe, i.e. not a union containing null/undefined).\n */\nconst getRequiredVariableKeys = (variablesType: Type, sourceFile: SourceFile): Array<string> => {\n return variablesType\n .getProperties()\n .filter(prop => !isInputMaybe(getPropertyType(prop, sourceFile)))\n .map(prop => prop.getName());\n};\n\n/**\n * Generates default variable values for GraphQL query/mutation variables.\n *\n * - InputMaybe<T> (union with null/undefined) -> UNDEFINED_SENTINEL\n * - Required union (e.g. string | string[], enums) -> faker value from first concrete member\n * - Required scalar -> faker value\n * - Required object -> recursively expanded\n */\nconst generateDefaultFromInputType = (type: Type, sourceFile: SourceFile, depth = 0): unknown => {\n if (depth > 10) return UNDEFINED_SENTINEL;\n\n if (isInputMaybe(type)) {\n return UNDEFINED_SENTINEL;\n }\n\n if (type.isUnion()) {\n const firstMember = type.getUnionTypes()[0];\n if (!firstMember) return UNDEFINED_SENTINEL;\n return generateDefaultFromInputType(firstMember, sourceFile, depth);\n }\n\n if (type.isArray()) {\n const elementType = type.getArrayElementType();\n if (!elementType) return UNDEFINED_SENTINEL;\n const elementDefault = generateDefaultFromInputType(elementType, sourceFile, depth + 1);\n if (elementDefault === UNDEFINED_SENTINEL) return [];\n return [elementDefault];\n }\n\n if (type.isObject()) {\n const properties = type.getProperties();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const obj: Record<string, any> = {};\n for (const prop of properties) {\n const propType = getPropertyType(prop, sourceFile);\n obj[prop.getName()] = generateDefaultFromInputType(propType, sourceFile, depth + 1);\n }\n return obj;\n }\n\n if (type.isStringLiteral()) return type.getLiteralValue();\n if (type.isNumberLiteral()) return type.getLiteralValue();\n if (type.isBooleanLiteral()) return type.getText() === \"true\";\n\n const typeText = type.getText();\n if (typeText === \"string\" || typeText === \"number\" || typeText === \"boolean\") {\n faker.seed(123);\n if (typeText === \"string\") return faker.lorem.word();\n if (typeText === \"number\") return faker.number.int();\n return false;\n }\n\n return UNDEFINED_SENTINEL;\n};\n\nconst parseGraphqlDefaultValue = (kind: string | undefined, rawValue: string | undefined): unknown => {\n switch (kind) {\n case \"BooleanValue\":\n return rawValue === \"true\";\n case \"IntValue\":\n return rawValue ? parseInt(rawValue.replace(/\"/g, \"\"), 10) : 0;\n case \"FloatValue\":\n return rawValue ? parseFloat(rawValue.replace(/\"/g, \"\")) : 0;\n case \"StringValue\":\n return rawValue ? rawValue.replace(/^\"|\"$/g, \"\") : \"\";\n case \"EnumValue\":\n return rawValue ? rawValue.replace(/^\"|\"$/g, \"\") : undefined;\n case \"NullValue\":\n return null;\n default:\n return undefined;\n }\n};\n\n/**\n * Navigates variable -> name -> value inside a VariableDefinition object literal\n * to extract the GraphQL variable name.\n */\nconst extractVarDefName = (obj: ReturnType<SourceFile[\"getDescendantsOfKind\"]>[number]): string | undefined => {\n const varProp = obj\n .getChildrenOfKind(SyntaxKind.PropertyAssignment)\n .find(p => stripQuotes(p.getName()) === \"variable\");\n if (!varProp) return undefined;\n const varInit = varProp.getInitializer();\n if (!varInit || !TsMorphNode.isObjectLiteralExpression(varInit)) return undefined;\n const namePropInner = varInit\n .getChildrenOfKind(SyntaxKind.PropertyAssignment)\n .find(p => stripQuotes(p.getName()) === \"name\");\n if (!namePropInner) return undefined;\n const nameInit = namePropInner.getInitializer();\n if (!nameInit || !TsMorphNode.isObjectLiteralExpression(nameInit)) return undefined;\n const valuePropInner = nameInit\n .getChildrenOfKind(SyntaxKind.PropertyAssignment)\n .find(p => stripQuotes(p.getName()) === \"value\");\n if (!valuePropInner) return undefined;\n return valuePropInner.getInitializer()?.getText().replace(/\"/g, \"\");\n};\n\n/**\n * Extracts GraphQL-level default values from the DocumentNode AST constant.\n * e.g. `$withValues: Boolean = true` produces\n * `defaultValue: { kind: \"BooleanValue\", value: true }` in the generated TypeScript.\n */\nconst extractGraphqlDefaultValues = (sourceFile: SourceFile, documentName: string): Record<string, unknown> => {\n const defaults: Record<string, unknown> = {};\n\n const decl = sourceFile.getVariableDeclaration(documentName);\n\n if (!decl) return defaults;\n\n const objectLiterals = decl.getDescendantsOfKind(SyntaxKind.ObjectLiteralExpression);\n\n for (const obj of objectLiterals) {\n const kindProp = findProperty(obj, \"kind\");\n\n if (!kindProp || !TsMorphNode.isPropertyAssignment(kindProp)) continue;\n if (kindProp.getInitializer()?.getText() !== '\"VariableDefinition\"') continue;\n\n const dvProp = findProperty(obj, \"defaultValue\");\n if (!dvProp || !TsMorphNode.isPropertyAssignment(dvProp)) continue;\n const dvInit = dvProp.getInitializer();\n if (!dvInit || !TsMorphNode.isObjectLiteralExpression(dvInit)) continue;\n\n const varName = extractVarDefName(obj);\n if (!varName) continue;\n\n const dvKindProp = findProperty(dvInit, \"kind\");\n if (!dvKindProp || !TsMorphNode.isPropertyAssignment(dvKindProp)) continue;\n const dvKind = dvKindProp.getInitializer()?.getText().replace(/\"/g, \"\");\n\n let dvValue: string | undefined;\n const dvValueProp = findProperty(dvInit, \"value\");\n if (dvValueProp && TsMorphNode.isPropertyAssignment(dvValueProp)) {\n dvValue = dvValueProp.getInitializer()?.getText();\n }\n\n const parsed = parseGraphqlDefaultValue(dvKind, dvValue);\n if (parsed !== undefined) {\n defaults[varName] = parsed;\n }\n }\n\n return defaults;\n};\n\n/**\n * Serializes a value to JavaScript source code, emitting `undefined` for sentinel values.\n * JSON.stringify drops undefined, so we need a custom serializer.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst serializeToSource = (value: any, indent = 0): string => {\n const pad = \" \".repeat(indent);\n const innerPad = \" \".repeat(indent + 4);\n\n if (value === UNDEFINED_SENTINEL) return \"undefined\";\n if (value === null) return \"null\";\n if (typeof value === \"string\") return JSON.stringify(value);\n if (typeof value === \"number\" || typeof value === \"boolean\") return String(value);\n\n if (Array.isArray(value)) {\n if (value.length === 0) return \"[]\";\n const items = value.map(v => `${innerPad}${serializeToSource(v, indent + 4)}`).join(\",\\n\");\n return `[\\n${items}\\n${pad}]`;\n }\n\n if (typeof value === \"object\") {\n const entries = Object.entries(value);\n if (entries.length === 0) return \"{}\";\n const props = entries\n .map(([k, v]) => `${innerPad}${JSON.stringify(k)}: ${serializeToSource(v, indent + 4)}`)\n .join(\",\\n\");\n return `{\\n${props}\\n${pad}}`;\n }\n\n return \"undefined\";\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst generateMockFromType = (type: any, text: string): any => {\n faker.seed(123);\n // type aliases are not working well so using text here.\n const rightSideText = text.substring(text.indexOf(\":\") + 1).trim();\n if (rightSideText.startsWith(\"DateTimeISOString\")) {\n return \"2023-01-22T15:08:12.527Z\";\n }\n //GeoJSONCoordinates\n if (rightSideText.startsWith(\"[number, number] | [number, number][] | [number, number][][]\")) {\n return \"[[1, 2], [3, 4]]\";\n }\n if (Boolean(type.isStringLiteral())) {\n return type.compilerType.value; // Get the value of the string literal\n }\n if (Boolean(type.isNumberLiteral())) {\n return parseFloat(type.compilerType.value);\n }\n if (Boolean(type.isBooleanLiteral())) {\n return type.compilerType.value === \"true\";\n }\n\n if (type.getText() === \"string\") {\n return faker.lorem.word();\n }\n if (type.getText() === \"number\") {\n return faker.number.int();\n }\n if (type.getText() === \"Date\" || type.getText() === \"DateTime\") {\n return \"2023-01-22T15:08:12.527Z\";\n }\n\n if (Boolean(type.isUnion())) {\n const nonNullish = type.getUnionTypes().filter((m: Type) => !m.isNull() && !m.isUndefined());\n return generateMockFromType(nonNullish[0] ?? type.getUnionTypes()[0], \"\");\n }\n if (Boolean(type.isArray())) {\n return [generateMockFromType(type.getArrayElementTypeOrThrow(), \"\")];\n }\n if (Boolean(type.isObject())) {\n const properties = type.getProperties();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const obj: any = {};\n for (const prop of properties) {\n const declaration = prop.getValueDeclarationOrThrow();\n const propType = declaration.getType();\n if (prop.getName() === \"__typename\") {\n let typenameType = propType;\n if (Boolean(typenameType.isUnion())) {\n const real = typenameType.getUnionTypes().filter((m: Type) => !m.isNull() && !m.isUndefined());\n typenameType = real[0] ?? typenameType;\n }\n obj[prop.getName()] = Boolean(typenameType.isStringLiteral())\n ? typenameType.compilerType.value\n : typenameType\n .getText()\n .replace(/\"/g, \"\")\n .replace(/ \\| undefined/g, \"\");\n } else {\n obj[prop.getName()] = generateMockFromType(propType, declaration.getText());\n }\n }\n return obj;\n }\n return null; // Default\n};\n\n/**\n * Generates React hooks from your graphql files.\n */\nexport const scrubMockFileContent = async (\n fileContent: string,\n nxRoot: string,\n isVerbose?: boolean,\n providedSourceFile?: SourceFile,\n generatedFilePath?: string\n) => {\n const start = new Date().getTime();\n const generatedFile =\n providedSourceFile ??\n new Project({\n compilerOptions: {\n noUnusedLocals: true,\n noUnusedParameters: true,\n strictNullChecks: true,\n },\n }).createSourceFile(\"tmpMock.ts\", fileContent);\n const mockThese: Array<TypeAliasDeclaration> = [];\n\n generatedFile.insertStatements(0, \"/* eslint-disable @typescript-eslint/no-explicit-any */\");\n generatedFile.insertStatements(1, \"/* eslint-disable @typescript-eslint/array-type */\");\n\n generatedFile.getTypeAliases().forEach(node => {\n if (node.getName().endsWith(\"Query\") && node.getName().length > \"Query\".length) {\n mockThese.push(node);\n }\n if (node.getName().endsWith(\"Mutation\") && node.getName().length > \"Mutation\".length) {\n mockThese.push(node);\n }\n });\n\n if (isVerbose) {\n const end = new Date().getTime();\n const time = end - start;\n console.log(`Mock Execution time: ${time}`);\n }\n\n // Resolve which authorization scopes each mocked operation requires. `@authorization(allow: [...])`\n // directives only live in the schema, so we walk each operation's selection set against it.\n const schema = generatedFilePath ? loadAuthSchema(nxRoot) : null;\n const permissionsByOperation =\n schema && generatedFilePath ? collectOperationPermissions(schema, generatedFilePath) : new Map<string, Array<string>>();\n\n const mock = mockThese.map(mocker => {\n const postFix = (mocker.getName().includes(\"Query\") ? \"Query\" : \"Mutation\").length;\n const variablesTypeName = `${mocker.getName()}Variables`;\n const variablesTypeAlias = generatedFile.getTypeAlias(variablesTypeName);\n const docName = mocker.getName().substring(0, mocker.getName().length - postFix);\n const typeDefaults = variablesTypeAlias\n ? generateDefaultFromInputType(variablesTypeAlias.getType(), generatedFile)\n : {};\n const graphqlDefaults = extractGraphqlDefaultValues(generatedFile, `${docName}Document`);\n const defaultVars =\n Object.keys(graphqlDefaults).length > 0 &&\n typeDefaults &&\n typeof typeDefaults === \"object\" &&\n !Array.isArray(typeDefaults)\n ? Object.assign({}, typeDefaults, graphqlDefaults)\n : typeDefaults;\n\n const requiredKeys = variablesTypeAlias ? getRequiredVariableKeys(variablesTypeAlias.getType(), generatedFile) : [];\n\n let variablesParam: string;\n if (requiredKeys.length === 0) {\n variablesParam = `variables?: DeepPartialNullable<gql.${variablesTypeName}>`;\n } else {\n const keysUnion = requiredKeys.map(k => `\"${k}\"`).join(\" | \");\n const requiredDeepPartial = `PickDeepPartialNullable<gql.${variablesTypeName}, ${keysUnion}>`;\n const hasOptionalKeys = variablesTypeAlias\n ? variablesTypeAlias.getType().getProperties().length > requiredKeys.length\n : false;\n const varType = hasOptionalKeys\n ? `${requiredDeepPartial} & DeepPartialNullable<Omit<gql.${variablesTypeName}, ${keysUnion}>>`\n : requiredDeepPartial;\n variablesParam = `variables: ${varType}`;\n }\n\n const defaultVarsSource = serializeToSource(defaultVars, 4);\n const isEmptyDefault = defaultVarsSource === \"{}\";\n const defaultVarsRef = isEmptyDefault ? \"{}\" : `default${mocker.getName()}Variables`;\n const constBlock = isEmptyDefault\n ? \"\"\n : `\n const default${mocker.getName()}Variables: gql.${variablesTypeName} = ${defaultVarsSource};\n`;\n\n const permissions = permissionsByOperation.get(docName) ?? [];\n const permissionsComment =\n permissions.length > 0\n ? `\n /**\n * Required authorization scopes (the token needs at least one allowed scope per accessed field):\n${permissions.map(scope => ` * - ${scope}`).join(\"\\n\")}\n */`\n : \"\";\n\n return `${constBlock}${permissionsComment}\n export const mockFor${mocker.getName()} = (${variablesParam}, data?: DeepPartialNullable<gql.${mocker.getName()}> ) => {\n return queryFor(gql.${docName}Document, mergeDeepVars(${defaultVarsRef}, variables),\n mergeDeep(\n ${JSON.stringify(generateMockFromType(mocker.getType(), \"\"), null, 4)}\n , data || {}) as gql.${mocker.getName()}\n );\n }`;\n });\n\n const mockedOperationNames = mockThese.map(mocker => {\n const postFix = (mocker.getName().includes(\"Query\") ? \"Query\" : \"Mutation\").length;\n return mocker.getName().substring(0, mocker.getName().length - postFix);\n });\n logRequiredPermissions(mockedOperationNames, permissionsByOperation, generatedFilePath, isVerbose);\n\n return `\n import { mergeDeep } from \"@apollo/client/utilities\";\n import { mergeDeepVars, queryFor, DeepPartialNullable, PickDeepPartialNullable } from \"@trackunit/react-core-contexts-test\";\n import * as gql from \"./graphql\";\n\n ${mock.join(\"\\n\")}\n `;\n};\n\n/**\n * Prints a summary of the authorization scopes required by the mocked operations, plus the full\n * de-duplicated list of scopes a token must be granted to satisfy every mock in the file.\n */\nconst logRequiredPermissions = (\n operationNames: Array<string>,\n permissionsByOperation: Map<string, Array<string>>,\n generatedFilePath: string | undefined,\n isVerbose?: boolean\n): void => {\n if (!isVerbose || permissionsByOperation.size === 0) return;\n\n const allScopes = new Set<string>();\n\n console.log(`[graphql-mock] Required authorization scopes${generatedFilePath ? ` for ${generatedFilePath}` : \"\"}:`);\n operationNames.forEach(operationName => {\n const scopes = permissionsByOperation.get(operationName) ?? [];\n scopes.forEach(scope => allScopes.add(scope));\n console.log(` ${operationName}: ${scopes.length > 0 ? scopes.join(\", \") : \"(none)\"}`);\n });\n\n const sortedScopes = [...allScopes].sort();\n console.log(\n `[graphql-mock] All scopes referenced (${sortedScopes.length}): ${\n sortedScopes.length > 0 ? sortedScopes.join(\", \") : \"(none)\"\n }`\n );\n};\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../../../../../libs/react/graphql-tools/src/executors/createHooks/utils.ts"],"names":[],"mappings":";;;AAAA,uCAAwG;AAExG;;GAEG;AACH,MAAM,OAAO,GAAG,CAAC,EAAE,eAAe,EAAE,IAAI,EAAoD,EAAE,EAAE;IAC9F,OAAO,eAAe,KAAK,OAAO,IAAI,IAAI,KAAK,OAAO,CAAC;AACzD,CAAC,CAAC;AACF;;GAEG;AACH,MAAM,gBAAgB,GAAG,CAAC,IAAY,EAAE,EAAE;IACxC,OAAO,IAAI,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC;AACzC,CAAC,CAAC;AAEF;;GAEG;AACH,MAAM,UAAU,GAAG,CAAC,EAAE,eAAe,EAAE,IAAI,EAAoD,EAAE,EAAE;IACjG,OAAO,eAAe,KAAK,UAAU,IAAI,IAAI,KAAK,UAAU,CAAC;AAC/D,CAAC,CAAC;AA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esContent":["import { EnumDeclaration, Node, Project, SourceFile, SyntaxKind, TypeAliasDeclaration } from \"ts-morph\";\n\n/**\n * Check if the name is a *Query\n */\nconst isQuery = ({ typeLiteralText, name }: { typeLiteralText: string | null; name: string }) => {\n return typeLiteralText === \"Query\" && name !== \"Query\";\n};\n/**\n * Check if the name is a *QueryVariables\n */\nconst isQueryVariables = (name: string) => {\n return name.endsWith(\"QueryVariables\");\n};\n\n/**\n * Check if the name is a Mutation\n */\nconst isMutation = ({ typeLiteralText, name }: { typeLiteralText: string | null; name: string }) => {\n return typeLiteralText === \"Mutation\" && name !== \"Mutation\";\n};\n\n/**\n * Check if the name is a *QueryVariables\n */\nconst isMutationVariables = (name: string) => {\n return name.endsWith(\"MutationVariables\");\n};\n\n/**\n * Check if the name is a Subscription\n */\nconst isSubscription = ({ typeLiteralText, name }: { typeLiteralText: string | null; name: string }) => {\n return typeLiteralText === \"Subscription\" && name !== \"Subscription\";\n};\n/**\n * Check if the name is a *SubscriptionVariables\n */\nconst isSubscriptionVariables = (name: string) => {\n return name.endsWith(\"SubscriptionVariables\");\n};\n\n/**\n * Check if the name is a *Fragment and not *_Fragment\n */\nexport const isFragment = (name: string) => {\n return name.endsWith(\"Fragment\") && !name.endsWith(\"_Fragment\");\n};\n\n/**\n * Debug where you are in the tree\n */\nconst getFullPathUpOfNode = (node: Node) => {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let currentNode: any | undefined = node;\n const paths = [];\n\n while (currentNode !== undefined) {\n // You can customize what details to include for each node (e.g., kind, text)\n let name = currentNode.getName !== undefined ? currentNode.getName() : currentNode.getKindName();\n if (node.getKind() === SyntaxKind.TypeLiteral) {\n const typeLiteral = node.asKindOrThrow(SyntaxKind.TypeLiteral);\n name = typeLiteral.getText();\n }\n\n paths.unshift(`${name}`);\n currentNode = currentNode.getParent();\n }\n\n return paths.join(\">>\");\n};\n\n/**\n * Get the types that should be preserved\n */\nexport const getPreservedTypes = (\n sourceFile: SourceFile,\n isVerbose?: boolean\n): {\n preservedTypes: Set<string>;\n queryAndMutations: Array<Node>;\n} => {\n const typeAliases = sourceFile.getTypeAliases();\n const queryAndMutations: Array<Node> = [];\n\n const preservedTypes = new Set<string>();\n\n const variablesListToProcess: Array<TypeAliasDeclaration> = [];\n const queryMutationListToProcess: Array<TypeAliasDeclaration> = [];\n\n typeAliases.forEach(typeAlias => {\n const name = typeAlias.getName();\n\n // Name-based classification needs no type info, so handle it first and skip resolving the\n // `__typename` literal for the (many) *Variables / *Fragment aliases.\n if (isQueryVariables(name) || isMutationVariables(name) || isSubscriptionVariables(name) || isFragment(name)) {\n variablesListToProcess.push(typeAlias);\n queryAndMutations.push(typeAlias);\n return;\n }\n\n // Get the type literal node that contains the properties\n const typeLiteral = typeAlias.getTypeNode()?.asKind(SyntaxKind.TypeLiteral);\n if (!typeLiteral) {\n return;\n }\n // Find the __typename property\n const typenameProperty = typeLiteral.getProperties().find(prop => prop.getName() === \"__typename\");\n if (!typenameProperty) {\n return;\n }\n // Read the literal straight from the AST type node (`__typename?: 'Query'`) instead of asking the\n // TypeChecker via `getType()`, which is dramatically faster on large generated files. The AST text\n // keeps the source quote style (codegen emits single quotes), so strip both quote characters.\n const typeLiteralText = (typenameProperty.getTypeNode()?.getText() ?? typenameProperty.getType().getText()).replace(\n /['\"]/g,\n \"\"\n );\n\n if (\n isQuery({ typeLiteralText, name }) ||\n isMutation({ typeLiteralText, name }) ||\n isSubscription({ typeLiteralText, name })\n ) {\n queryMutationListToProcess.push(typeAlias);\n queryAndMutations.push(typeAlias);\n }\n });\n\n sourceFile.getVariableStatements().forEach(variableStatement => {\n const variable = variableStatement\n .getFirstChildByKind(SyntaxKind.VariableDeclarationList)\n ?.getFirstChildByKind(SyntaxKind.VariableDeclaration);\n if (variable?.getName().endsWith(\"Document\") || variable?.getName().endsWith(\"FragmentDoc\")) {\n queryAndMutations.push(variableStatement);\n }\n });\n\n // RUN VARAIABLES FIRST since it will force full props if nessasary\n\n // VARIABLES are input so force include all props\n variablesListToProcess.forEach(typeAlias => {\n preserveTypes(typeAlias, preservedTypes, sourceFile, isVerbose);\n });\n\n // QUERY and MUTATION are dynamic so dont force props\n queryMutationListToProcess.forEach(typeAlias => {\n preserveTypes(typeAlias, preservedTypes, sourceFile, isVerbose);\n });\n\n return { preservedTypes, queryAndMutations };\n};\n\nconst preserveTypes = (node: Node, preservedTypes: Set<string>, sourceFile: SourceFile, isVerbose?: boolean): void => {\n node.forEachDescendant(descendant => {\n if (descendant.getKind() !== SyntaxKind.TypeReference) {\n return;\n }\n\n // `getText()` serialises the node's subtree, so compute it once instead of up to nine times.\n const text = descendant.getText();\n if (\n text.startsWith(\"Scalars\") ||\n text.startsWith(\"Maybe<\") ||\n text.startsWith(\"InputMaybe<\") ||\n text.startsWith(\"Array<\") ||\n text.startsWith(\"Exact<\") ||\n text.includes(\"__typename\")\n ) {\n return;\n }\n\n if (isVerbose) {\n // eslint-disable-next-line no-console\n console.log(\"ADDING\", getFullPathUpOfNode(descendant), \":\", text, descendant.getKindName());\n }\n if (!preservedTypes.has(text)) {\n const foundTypeAlias = sourceFile.getTypeAlias(text);\n preservedTypes.add(text);\n if (foundTypeAlias) {\n preserveTypes(foundTypeAlias, preservedTypes, sourceFile, isVerbose);\n }\n }\n });\n};\n\n/**\n * Convert an enum to a const object and string literal type\n */\nexport const convertEnumToConstObject = (enumDeclaration: EnumDeclaration) => {\n const enumName = enumDeclaration.getName();\n const members = enumDeclaration.getMembers();\n\n const properties = members.map(member => {\n const name = member.getName();\n const value = member.getValue();\n return `${name}: '${value}'`;\n });\n\n const lowerCaseFirstLetter = enumName[0]?.toLowerCase() + enumName.slice(1);\n const constObjectText = `export const ${lowerCaseFirstLetter} = {\\n ${properties.join(\n \",\\n \"\n )},\\n} as const;\\nexport type ${enumName} = typeof ${lowerCaseFirstLetter}[keyof typeof ${lowerCaseFirstLetter}];`;\n\n return constObjectText;\n};\n\n/**\n * Create a source file from a string\n */\nexport const createSourceFile = (fileContent: string) => {\n const project = new Project({\n compilerOptions: {\n noUnusedLocals: true,\n noUnusedParameters: true,\n },\n });\n\n return project.createSourceFile(\"tmp.ts\", fileContent);\n};\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generator.js","sourceRoot":"","sources":["../../../../../../../libs/react/graphql-tools/src/generators/add-graphql/generator.ts"],"names":[],"mappings":";;AAQA,kDAqDC;;AA7DD,+BAA+B;AAC/B,uCAAuH;AACvH,mDAA6B;AAG7B;;GAEG;AACI,KAAK,UAAU,mBAAmB,CAAC,IAAU,EAAE,OAAkC;IACtF,MAAM,aAAa,GAAG,EAAE,CAAC;IACzB,MAAM,aAAa,GAAG,IAAA,iCAAwB,EAAC,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;IACtE,MAAM,WAAW,GAAG,aAAa,CAAC,IAAI,CAAC;IACvC,MAAM,eAAe,GAAG;QACtB,GAAG,OAAO;QACV,YAAY,EAAE,OAAO,CAAC,YAAY,IAAI,MAAM;KAC7C,CAAC;IACF,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,qBAAqB,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,mBAAmB,CAAC,EAAE,CAAC;QAC7E,IAAA,sBAAa,EAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,aAAa,EAAE,eAAe,CAAC,CAAC;IAC7F,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,GAAG,CACT,2KAA2K,CAC5K,CAAC;IACJ,CAAC;IAED,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,GAAG,WAAW,aAAa,CAAC,EAAE,CAAC;QAC9C,IAAA,sBAAa,EAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,OAAO,EAAE,cAAc,CAAC,EAAE,WAAW,EAAE,eAAe,CAAC,CAAC;IACnG,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,GAAG,CAAC,gCAAgC,WAAW,EAAE,CAAC,CAAC;IAC7D,CAAC;IAED,IAAA,mBAAU,EAAC,IAAI,EAAE,IAAA,0BAAiB,EAAC,WAAW,EAAE,cAAc,CAAC,EAAE,WAAW,CAAC,EAAE;QAC7E,MAAM,qBAAqB,GAAG,WAAW,CAAC,OAAO,EAAE,CAAC,eAAe,CAAC,CAAC;QACrE,WAAW,CAAC,OAAO,GAAG;YACpB,GAAG,WAAW,CAAC,OAAO;YACtB,eAAe,EAAE;gBACf,GAAG,qBAAqB;gBACxB,QAAQ,EAAE,4CAA4C;gBACtD,OAAO,EAAE,CAAC,yCAAyC,CAAC;gBACpD,GAAG,CAAC,OAAO,CAAC,aAAa,KAAK,SAAS;oBACrC,CAAC,CAAC,EAAE;oBACJ,CAAC,CAAC;wBACE,OAAO,EAAE;4BACP,GAAG,qBAAqB,EAAE,OAAO;4BACjC,aAAa,EAAE,OAAO,CAAC,aAAa;yBACrC;qBACF,CAAC;aACP;SACF,CAAC;QACF,OAAO,WAAW,CAAC;IACrB,CAAC,CAAC,CAAC;IAEH,IAAI,IAAI,CAAC,MAAM,CAAC,GAAG,WAAW,qBAAqB,CAAC,EAAE,CAAC;QACrD,IAAA,mBAAU,EAAC,IAAI,EAAE,IAAA,0BAAiB,EAAC,WAAW,EAAE,oBAAoB,CAAC,EAAE,IAAI,CAAC,EAAE;YAC5E,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE,CAAC;gBACzC,IAAI,CAAC,OAAO,GAAG,CAAC,GAAG,IAAI,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;YACjD,CAAC;YACD,OAAO,IAAI,CAAC;QACd,CAAC,CAAC,CAAC;IACL,CAAC;IAED,MAAM,IAAA,oBAAW,EAAC,IAAI,CAAC,CAAC;AAC1B,CAAC","sourcesContent":["/* eslint-disable no-console */\nimport { formatFiles, generateFiles, joinPathFragments, readProjectConfiguration, Tree, updateJson } from \"@nx/devkit\";\nimport * as path from \"path\";\nimport { AddGraphqlGeneratorSchema } from \"./schema\";\n\n/**\n * Setting up Graphql tools for Iris App development\n */\nexport async function addGraphqlGenerator(tree: Tree, options: AddGraphqlGeneratorSchema) {\n const workspaceRoot = \"\";\n const projectConfig = readProjectConfiguration(tree, options.project);\n const libraryRoot = projectConfig.root;\n const templateOptions = {\n ...options,\n schemaSource: options.schemaSource ?? \"auto\",\n };\n if (!tree.exists(\"graphql.config.json\") && !tree.exists(\"graphql.config.ts\")) {\n generateFiles(tree, path.join(__dirname, \"files\", \"root\"), workspaceRoot, templateOptions);\n } else {\n console.log(\n `\"graphql.config.json\" already exist in your workspace root. \\nPlease ensure that your \"graphql.config.json\" contains \"schema\": \"https://iris.trackunit.com/api/graphql/\".`\n );\n }\n\n if (!tree.exists(`${libraryRoot}/codegen.ts`)) {\n generateFiles(tree, path.join(__dirname, \"files\", \"subDirectory\"), libraryRoot, templateOptions);\n } else {\n console.log(`codegen.ts already exists in ${libraryRoot}`);\n }\n\n updateJson(tree, joinPathFragments(libraryRoot, \"project.json\"), projectJSON => {\n const existingGraphqlTarget = projectJSON.targets?.[\"graphql-hooks\"];\n projectJSON.targets = {\n ...projectJSON.targets,\n \"graphql-hooks\": {\n ...existingGraphqlTarget,\n executor: \"@trackunit/react-graphql-tools:createHooks\",\n outputs: [\"{projectRoot}/src/generated/graphql-api\"],\n ...(options.generateMocks === undefined\n ? {}\n : {\n options: {\n ...existingGraphqlTarget?.options,\n generateMocks: options.generateMocks,\n },\n }),\n },\n };\n return projectJSON;\n });\n\n if (tree.exists(`${libraryRoot}/tsconfig.spec.json`)) {\n updateJson(tree, joinPathFragments(libraryRoot, \"tsconfig.spec.json\"), json => {\n if (!json.include.includes(\"codegen.ts\")) {\n json.include = [...json.include, \"codegen.ts\"];\n }\n return json;\n });\n }\n\n await formatFiles(tree);\n}\n"]}
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../libs/react/graphql-tools/src/index.ts"],"names":[],"mappings":";;;AAGA,6DAAsE;AAA7D,8GAAA,kBAAkB,OAAA;AAC3B,gEAAyE;AAAhE,gHAAA,mBAAmB,OAAA","sourcesContent":["export type { CreateGraphqlHooksExecutorSchema } from \"./executors/createHooks/schema\";\nexport type { AddGraphqlGeneratorSchema } from \"./generators/add-graphql/schema\";\n\nexport { CreateGraphqlHooks } from \"./executors/createHooks/executor\";\nexport { addGraphqlGenerator } from \"./generators/add-graphql/generator\";\n"]}