@aligent/nx-openapi 1.0.0 → 2.0.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aligent/nx-openapi",
3
- "version": "1.0.0",
3
+ "version": "2.0.1",
4
4
  "type": "commonjs",
5
5
  "main": "./src/index.js",
6
6
  "typings": "./src/index.d.ts",
@@ -10,7 +10,7 @@
10
10
  "directory": "packages/nx-openapi"
11
11
  },
12
12
  "dependencies": {
13
- "@nx/devkit": "20.8.1",
13
+ "@nx/devkit": "22.4.1",
14
14
  "@redocly/openapi-core": "^1.34.2",
15
15
  "openapi-typescript": "7.7.3",
16
16
  "typescript": "^5.9.3"
@@ -8,7 +8,7 @@ This folder contains TypeScript API clients generated from OpenAPI specification
8
8
 
9
9
  ## Example
10
10
  ```typescript
11
- import { MyApiClient } from '@clients'; // Adjust the import name as necessary
11
+ import { MyApiClient } from 'clients'; // Adjust the import name as necessary
12
12
 
13
13
  const client = new MyApiClient(
14
14
  { baseUrl: 'https://my-api-client.base-url', signal: AbortSignal.timeout(30000) },
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "clients",
3
+ "type": "module",
4
+ "main": "./src/index.ts",
5
+ "types": "./src/index.ts",
6
+ "exports": {
7
+ ".": {
8
+ "types": "./src/index.ts",
9
+ "import": "./src/index.ts",
10
+ "default": "./src/index.ts"
11
+ },
12
+ "./package.json": "./package.json"
13
+ },
14
+ "nx": {
15
+ "tags": [
16
+ "scope:libs"
17
+ ]
18
+ }
19
+ }
@@ -1,19 +1,6 @@
1
1
  {
2
- "extends": "../tsconfig.base.json",
3
- "compilerOptions": {
4
- "forceConsistentCasingInFileNames": true,
5
- "strict": true,
6
- "importHelpers": true,
7
- "noImplicitOverride": true,
8
- "noImplicitReturns": true,
9
- "noFallthroughCasesInSwitch": true,
10
- "noPropertyAccessFromIndexSignature": true
11
- },
2
+ "extends": "@aligent/ts-code-standards/tsconfigs-extend",
12
3
  "files": [],
13
4
  "include": [],
14
- "references": [
15
- {
16
- "path": "./tsconfig.lib.json"
17
- }
18
- ]
5
+ "references": []
19
6
  }
@@ -5,38 +5,51 @@ const devkit_1 = require("@nx/devkit");
5
5
  const generate_openapi_types_1 = require("../../helpers/generate-openapi-types");
6
6
  const utilities_1 = require("../../helpers/utilities");
7
7
  const VALID_EXTENSIONS = ['yaml', 'yml', 'json'];
8
+ // We also use this as the project root for all generated clients
9
+ const PROJECT_NAME = 'clients';
8
10
  async function clientGenerator(tree, options) {
9
11
  const { name, schemaPath, importPath = `@clients`, skipValidate, override } = options;
10
12
  const ext = schemaPath.split('.').pop() || '';
11
13
  if (!VALID_EXTENSIONS.includes(ext)) {
12
14
  throw new Error(`Invalid schema file extension: ${ext}`);
13
15
  }
14
- if (!skipValidate) {
15
- const hasError = await (0, generate_openapi_types_1.validateSchema)(schemaPath);
16
- if (hasError) {
17
- throw new Error('Schema validation failed!');
18
- }
16
+ const hasError = await (0, generate_openapi_types_1.validateSchema)(schemaPath);
17
+ if (!skipValidate && hasError) {
18
+ throw new Error('Schema validation failed!');
19
19
  }
20
- const projectRoot = `clients`;
20
+ const projectRoot = PROJECT_NAME;
21
21
  const apiClientDest = `${projectRoot}/src/${name}`;
22
22
  const schemaDest = `${apiClientDest}/schema.${ext}`;
23
23
  const typesDest = `${apiClientDest}/generated-types.ts`;
24
24
  if (!override && tree.exists(apiClientDest)) {
25
25
  throw new Error(`Directory "${name}" already exists. If you want to override the current api client in this directory use "--override"`);
26
26
  }
27
- const isNewProject = (0, utilities_1.attemptToAddProjectConfiguration)(tree, projectRoot);
28
- await (0, generate_openapi_types_1.copySchema)(tree, schemaDest, schemaPath);
29
- await (0, generate_openapi_types_1.generateOpenApiTypes)(tree, schemaDest, typesDest);
30
- if (isNewProject) {
31
- devkit_1.logger.info(`Creating new project at ${projectRoot}`);
27
+ const existingProject = (0, utilities_1.getExistingProject)(tree, PROJECT_NAME);
28
+ if (!existingProject) {
29
+ devkit_1.logger.warn(`Creating new project ${PROJECT_NAME} at ${projectRoot}`);
32
30
  (0, devkit_1.generateFiles)(tree, (0, devkit_1.joinPathFragments)(__dirname, './files'), projectRoot, options);
33
- (0, utilities_1.addTsConfigPath)(tree, importPath, [(0, devkit_1.joinPathFragments)(projectRoot, './src', 'index.ts')]);
31
+ const tsConfigFile = (0, utilities_1.getRootTsConfigPathInTree)(tree);
32
+ if (tsConfigFile === 'tsconfig.json') {
33
+ (0, utilities_1.addTsConfigReference)(tree, tsConfigFile, `./${projectRoot}`);
34
+ }
35
+ else {
36
+ const lookupPath = (0, devkit_1.joinPathFragments)(projectRoot, './src', 'index.ts');
37
+ (0, utilities_1.addTsConfigPath)(tree, tsConfigFile, importPath, [lookupPath]);
38
+ }
34
39
  }
35
- // Generate the files for the specific new client
40
+ await (0, generate_openapi_types_1.copySchema)(tree, schemaDest, schemaPath);
41
+ await (0, generate_openapi_types_1.generateOpenApiTypes)(tree, schemaDest, typesDest);
42
+ /**
43
+ * Each time we add new API client, we actually add a new class into `clients` project (if it exists).
44
+ * This add a new example client class to `apiClientDest` folder
45
+ */
36
46
  (0, devkit_1.generateFiles)(tree, (0, devkit_1.joinPathFragments)(__dirname, './client-specific-files'), apiClientDest, {
37
47
  className: (0, utilities_1.toClassName)(name),
38
48
  });
39
- // Append to index file for imports
49
+ /**
50
+ * The `clients` project expose all the API clients via `src/index.ts` file.
51
+ * As a result, we need to append new client to the list of exporting;
52
+ */
40
53
  (0, utilities_1.appendToIndexFile)(tree, projectRoot, name);
41
54
  await (0, devkit_1.formatFiles)(tree);
42
55
  devkit_1.logger.info(`Successfully generated ${name} API client`);
@@ -1,29 +1,40 @@
1
1
  import { Tree } from '@nx/devkit';
2
2
  /**
3
- * Attempts to add a new project configuration to the workspace.
3
+ * Get existing project by name.
4
+ * If the project exists, it returns project configuration or undefined otherwise.
4
5
  *
5
- * This function adds a new project configuration to the workspace. If a project with the same name
6
- * already exists, it returns `false`. If an error occurs for any other reason, the error is re-thrown.
7
- *
8
- * @param {Tree} tree - The file system tree representing the current project.
9
- * @param {string} name - The name of the project to add.
10
- * @param {string} projectRoot - The root directory of the project.
11
- * @returns - Whether project configuration was added successfully, or it already exists.
12
- * @throws {Error} If an error occurs that is not related to the project already existing.
6
+ * @param tree - The file system tree representing the current project.
7
+ * @param projectName - The name of the project to add.
8
+ * @returns - The project configuration.
9
+ */
10
+ export declare function getExistingProject(tree: Tree, projectName: string): import("@nx/devkit").ProjectConfiguration | undefined;
11
+ /**
12
+ * The utility functions below are only exported by '@nx/js', not '@nx/devkit'
13
+ * They're simple so we recreate them here instead of adding '@nx/js' as a dependency
14
+ * Source: {@link https://github.com/nrwl/nx/blob/master/packages/js/src/utils/typescript/ts-config.ts}
13
15
  */
14
- export declare function attemptToAddProjectConfiguration(tree: Tree, projectRoot: string): boolean;
16
+ export declare function getRootTsConfigPathInTree(tree: Tree): string;
15
17
  /**
16
- * Adds a new path mapping to the `paths` property in the root TypeScript configuration file.
18
+ * Adds a new path mapping to the `compilerOptions.paths` property in the root TypeScript configuration file.
19
+ * If the import path already exists, an error is thrown.
17
20
  *
18
- * This function updates the `tsconfig.base.json` or `tsconfig.json` file to include a new path mapping
19
- * for the specified import path. If the import path already exists, an error is thrown.
21
+ * @param tree - The file system tree representing the current project.
22
+ * @param tsConfigFile - The root TypeScript configuration file path.
23
+ * @param importPath - The import path to add to the `paths` property.
24
+ * @param lookupPaths - The array of paths to associate with the import path.
25
+ * @throws - If the import path already exists in the `paths` property.
26
+ */
27
+ export declare function addTsConfigPath(tree: Tree, tsConfigFile: string, importPath: string, lookupPaths: string[]): void;
28
+ /**
29
+ * Adds a new referencing path to the `references` property in the root TypeScript configuration file.
30
+ * If the referencing path already exists, an error is thrown.
20
31
  *
21
- * @param {Tree} tree - The file system tree representing the current project.
22
- * @param {string} importPath - The import path to add to the `paths` property.
23
- * @param {string[]} lookupPaths - The array of paths to associate with the import path.
24
- * @throws {Error} If the import path already exists in the `paths` property.
32
+ * @param tree - The file system tree representing the current project.
33
+ * @param tsConfigFile - The root TypeScript configuration file path.
34
+ * @param referencePath - The referencing path.
35
+ * @throws - If the import path already exists in the `paths` property.
25
36
  */
26
- export declare function addTsConfigPath(tree: Tree, importPath: string, lookupPaths: string[]): void;
37
+ export declare function addTsConfigReference(tree: Tree, tsConfigFile: string, referencePath: string): void;
27
38
  /**
28
39
  * Appends a new export statement to the index file.
29
40
  *
@@ -1,38 +1,27 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.attemptToAddProjectConfiguration = attemptToAddProjectConfiguration;
3
+ exports.getExistingProject = getExistingProject;
4
+ exports.getRootTsConfigPathInTree = getRootTsConfigPathInTree;
4
5
  exports.addTsConfigPath = addTsConfigPath;
6
+ exports.addTsConfigReference = addTsConfigReference;
5
7
  exports.appendToIndexFile = appendToIndexFile;
6
8
  exports.toClassName = toClassName;
7
9
  const devkit_1 = require("@nx/devkit");
8
10
  /**
9
- * Attempts to add a new project configuration to the workspace.
11
+ * Get existing project by name.
12
+ * If the project exists, it returns project configuration or undefined otherwise.
10
13
  *
11
- * This function adds a new project configuration to the workspace. If a project with the same name
12
- * already exists, it returns `false`. If an error occurs for any other reason, the error is re-thrown.
13
- *
14
- * @param {Tree} tree - The file system tree representing the current project.
15
- * @param {string} name - The name of the project to add.
16
- * @param {string} projectRoot - The root directory of the project.
17
- * @returns - Whether project configuration was added successfully, or it already exists.
18
- * @throws {Error} If an error occurs that is not related to the project already existing.
14
+ * @param tree - The file system tree representing the current project.
15
+ * @param projectName - The name of the project to add.
16
+ * @returns - The project configuration.
19
17
  */
20
- function attemptToAddProjectConfiguration(tree, projectRoot) {
18
+ function getExistingProject(tree, projectName) {
21
19
  try {
22
- (0, devkit_1.addProjectConfiguration)(tree, 'clients', {
23
- root: projectRoot,
24
- projectType: 'library',
25
- sourceRoot: `${projectRoot}/src`,
26
- targets: {},
27
- tags: ['clients'],
28
- });
29
- return true;
20
+ return (0, devkit_1.readProjectConfiguration)(tree, projectName);
30
21
  }
31
- catch (err) {
32
- if (err instanceof Error && err.message.includes('already exists')) {
33
- return false;
34
- }
35
- throw err;
22
+ catch (error) {
23
+ devkit_1.logger.debug(`Project ${projectName} doesn't exist`, String(error));
24
+ return undefined;
36
25
  }
37
26
  }
38
27
  /**
@@ -49,18 +38,17 @@ function getRootTsConfigPathInTree(tree) {
49
38
  return 'tsconfig.base.json';
50
39
  }
51
40
  /**
52
- * Adds a new path mapping to the `paths` property in the root TypeScript configuration file.
41
+ * Adds a new path mapping to the `compilerOptions.paths` property in the root TypeScript configuration file.
42
+ * If the import path already exists, an error is thrown.
53
43
  *
54
- * This function updates the `tsconfig.base.json` or `tsconfig.json` file to include a new path mapping
55
- * for the specified import path. If the import path already exists, an error is thrown.
56
- *
57
- * @param {Tree} tree - The file system tree representing the current project.
58
- * @param {string} importPath - The import path to add to the `paths` property.
59
- * @param {string[]} lookupPaths - The array of paths to associate with the import path.
60
- * @throws {Error} If the import path already exists in the `paths` property.
44
+ * @param tree - The file system tree representing the current project.
45
+ * @param tsConfigFile - The root TypeScript configuration file path.
46
+ * @param importPath - The import path to add to the `paths` property.
47
+ * @param lookupPaths - The array of paths to associate with the import path.
48
+ * @throws - If the import path already exists in the `paths` property.
61
49
  */
62
- function addTsConfigPath(tree, importPath, lookupPaths) {
63
- (0, devkit_1.updateJson)(tree, getRootTsConfigPathInTree(tree), json => {
50
+ function addTsConfigPath(tree, tsConfigFile, importPath, lookupPaths) {
51
+ (0, devkit_1.updateJson)(tree, tsConfigFile, json => {
64
52
  json.compilerOptions ??= {};
65
53
  const c = json.compilerOptions;
66
54
  c.paths ??= {};
@@ -71,6 +59,27 @@ function addTsConfigPath(tree, importPath, lookupPaths) {
71
59
  return json;
72
60
  });
73
61
  }
62
+ /**
63
+ * Adds a new referencing path to the `references` property in the root TypeScript configuration file.
64
+ * If the referencing path already exists, an error is thrown.
65
+ *
66
+ * @param tree - The file system tree representing the current project.
67
+ * @param tsConfigFile - The root TypeScript configuration file path.
68
+ * @param referencePath - The referencing path.
69
+ * @throws - If the import path already exists in the `paths` property.
70
+ */
71
+ function addTsConfigReference(tree, tsConfigFile, referencePath) {
72
+ (0, devkit_1.updateJson)(tree, tsConfigFile, json => {
73
+ json.references ??= [];
74
+ if (json.references.some((r) => r.path === referencePath)) {
75
+ throw new Error(`You already have a library using the import path "${referencePath}". Make sure to specify a unique one.`);
76
+ }
77
+ json.references.push({
78
+ path: referencePath,
79
+ });
80
+ return json;
81
+ });
82
+ }
74
83
  /**
75
84
  * Appends a new export statement to the index file.
76
85
  *
@@ -1,9 +0,0 @@
1
- {
2
- "extends": "./tsconfig.json",
3
- "compilerOptions": {
4
- "outDir": "../../dist/out-tsc",
5
- "declaration": true,
6
- "types": ["node"]
7
- },
8
- "include": ["src/**/*.ts"]
9
- }