Skip to content

introducing OmitReadonly type to resolve required + readonly/writeonly properties #1145

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 1 addition & 30 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -1,31 +1,2 @@
# Contributing to Webpack Typings for JSON
# DURING RELEASE

Thanks for your interest in contributing to this project.

## Pull Request guidelines

Before working on a Pull Request, create an issue explaining what you want to contribute.
This ensures that your pull request won't go unnoticed, and that you are not contributing
something that is not suitable for the project.

If you are unfamiliar with GitHub Pull Requests, please read the following documentation:
https://help.github.com/articles/using-pull-requests

**Your Pull Request must:**

* Address a single issue or add a single item of functionality.
* Contain a clean history of small, incremental, logically separate commits, with no merge commits.
* Use clear commit messages.
* Be possible to merge automatically.

## Submitting a Pull Request

1. Make your changes in a new git branch: `git checkout -b my-fix-branch master`
2. Create your patch or feature
3. Ensure the builds work by running: `npm run build`
4. Ensure the tests will pass by running: `npm run test`
5. Ensure the code is formatted by running: `npm run eslint:fix`
6. Commit your changes using a descriptive commit message

After your Pull Request is created, it will automatically be build using Circle CI.
When the build is successful then the Pull Request is ready for review.
31,775 changes: 4,767 additions & 27,008 deletions package-lock.json

Large diffs are not rendered by default.

40 changes: 12 additions & 28 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
{
"name": "openapi-typescript-codegen",
"version": "0.23.0",
"name": "@docupilot/openapi-typescript-codegen",
"version": "0.23.7",
"description": "Library that generates Typescript clients based on the OpenAPI specification.",
"author": "Ferdi Koomen",
"homepage": "https://github.com/ferdikoomen/openapi-typescript-codegen",
"repository": {
"type": "git",
"url": "git+https://github.com/ferdikoomen/openapi-typescript-codegen.git"
},
"publishConfig": {
"registry": "https://npm.pkg.github.com"
},
"bugs": {
"url": "https://github.com/ferdikoomen/openapi-typescript-codegen/issues"
},
Expand Down Expand Up @@ -48,11 +51,6 @@
"release": "rollup --config --environment NODE_ENV:production",
"validate": "tsc --project tsconfig.json --noEmit",
"run": "node ./test/index.js",
"test": "jest --selectProjects UNIT",
"test:update": "jest --selectProjects UNIT --updateSnapshot",
"test:watch": "jest --selectProjects UNIT --watch",
"test:coverage": "jest --selectProjects UNIT --coverage",
"test:e2e": "jest --selectProjects E2E --runInBand --verbose",
"eslint": "eslint .",
"eslint:fix": "eslint . --fix",
"prepublishOnly": "npm run clean && npm run release",
Expand All @@ -66,19 +64,8 @@
"json-schema-ref-parser": "^9.0.9"
},
"devDependencies": {
"@angular-devkit/build-angular": "14.0.1",
"@angular/animations": "14.0.1",
"@angular/cli": "14.0.1",
"@angular/common": "14.0.1",
"@angular/compiler": "14.0.1",
"@angular/compiler-cli": "14.0.1",
"@angular/core": "14.0.1",
"@angular/forms": "14.0.1",
"@angular/platform-browser": "14.0.1",
"@angular/platform-browser-dynamic": "14.0.1",
"@angular/router": "14.0.1",
"@babel/cli": "7.18.6",
"@babel/core": "7.18.6",
"@babel/core": "^7.24.4",
"@babel/preset-env": "7.18.6",
"@babel/preset-typescript": "7.18.6",
"@rollup/plugin-commonjs": "22.0.1",
Expand All @@ -88,35 +75,32 @@
"@types/express": "4.17.13",
"@types/fs-extra": "^9.0.13",
"@types/glob": "7.2.0",
"@types/jest": "28.1.5",
"@types/node": "18.0.4",
"@types/node-fetch": "2.6.1",
"@types/qs": "6.9.7",
"@typescript-eslint/eslint-plugin": "5.30.6",
"@typescript-eslint/parser": "5.30.6",
"abort-controller": "3.0.0",
"axios": "0.27.2",
"axios": "^1.7.7",
"codecov": "3.8.3",
"cross-spawn": "7.0.3",
"cross-spawn": "^7.0.6",
"eslint": "8.19.0",
"eslint-config-prettier": "8.5.0",
"eslint-plugin-prettier": "4.2.1",
"eslint-plugin-simple-import-sort": "7.0.0",
"express": "4.18.1",
"express": "^4.21.0",
"form-data": "4.0.0",
"glob": "8.0.3",
"jest": "28.1.3",
"jest-cli": "28.1.3",
"prettier": "2.7.1",
"puppeteer": "15.4.0",
"puppeteer": "^23.4.0",
"qs": "6.11.0",
"rimraf": "3.0.2",
"rollup": "2.77.0",
"rollup": "^2.79.2",
"rollup-plugin-terser": "7.0.2",
"rxjs": "7.5.6",
"ts-node": "10.9.1",
"tslib": "2.4.0",
"typescript": "4.7.3",
"typescript": "5.6.3",
"zone.js": "0.11.6"
},
"resolutions": {
Expand Down
47 changes: 47 additions & 0 deletions src/templates/core/utils/OmitReadonly.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/**
* The contents of this file are inspired from https://github.com/ts-essentials/ts-essentials#ReadonlyKeys
*
* The MIT License
*
* Copyright (c) 2018-2019 Chris Kaczor (github.com/krzkaczor)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* */

type Writable<T> = { -readonly [P in keyof T]: T[P] };

type IsEqualConsideringWritability<X, Y> = (<T>() => T extends X ? 1 : 2) extends <T>() => T extends Y ? 1 : 2
? true
: false;

type IsFullyWritable<T extends object> = IsEqualConsideringWritability<
{ [Q in keyof T]: T[Q] },
Writable<{ [Q in keyof T]: T[Q] }>
>;

/** Gets keys of an object which are readonly */
type ReadonlyKeys<T extends object> = {
[P in keyof T]-?: IsFullyWritable<Pick<T, P>> extends true ? never : P;
}[keyof T];

/**
* Exclude keys of an object which are readonly
* In case of union types containing types not extending object, type is inferred as-is
* */
export declare type OmitReadonly<T> = T extends object ? Omit<T, ReadonlyKeys<T>> : T;
1 change: 1 addition & 0 deletions src/templates/exportService.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import type { BaseHttpRequest } from '../core/BaseHttpRequest';
import { OpenAPI } from '../core/OpenAPI';
import { request as __request } from '../core/request';
{{/if}}
import type { OmitReadonly } from '../core/utils/OmitReadonly';

{{#equals @root.httpClient 'angular'}}
@Injectable()
Expand Down
4 changes: 2 additions & 2 deletions src/templates/partials/parameters.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,13 @@
{{/if}}
*/
{{/ifdef}}
{{{name}}}{{>isRequired}}: {{>type}},
{{{name}}}{{>isRequired}}: {{>typeWithOmitReadOnly httpMethod=../method}},
{{/each}}
}
{{~else}}

{{#each parameters}}
{{{name}}}{{>isRequired}}: {{>type}}{{#if default}} = {{{default}}}{{/if}},
{{{name}}}{{>isRequired}}: {{>typeWithOmitReadOnly httpMethod=../method}}{{#if default}} = {{{default}}}{{/if}},
{{/each}}
{{/if}}
{{/if}}
13 changes: 13 additions & 0 deletions src/templates/partials/typeWithOmitReadOnly.hbs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{{#equals export "reference"}}
{{#equals httpMethod "POST"~}}
OmitReadonly<{{>type}}>
{{~else equals httpMethod "PUT"~}}
OmitReadonly<{{>type}}>
{{~else equals httpMethod "PATCH"~}}
OmitReadonly<{{>type}}>
{{else}}
{{~>type}}
{{~/equals}}
{{~else}}
{{~>type}}
{{~/equals}}
9 changes: 9 additions & 0 deletions src/utils/registerHandlebarTemplates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import nodeRequest from '../templates/core/node/request.hbs';
import nodeSendRequest from '../templates/core/node/sendRequest.hbs';
import templateCoreSettings from '../templates/core/OpenAPI.hbs';
import templateCoreRequest from '../templates/core/request.hbs';
import omitReadonly from '../templates/core/utils/OmitReadonly.hbs';
import xhrGetHeaders from '../templates/core/xhr/getHeaders.hbs';
import xhrGetRequestBody from '../templates/core/xhr/getRequestBody.hbs';
import xhrGetResponseBody from '../templates/core/xhr/getResponseBody.hbs';
Expand Down Expand Up @@ -83,6 +84,7 @@ import partialTypeInterface from '../templates/partials/typeInterface.hbs';
import partialTypeIntersection from '../templates/partials/typeIntersection.hbs';
import partialTypeReference from '../templates/partials/typeReference.hbs';
import partialTypeUnion from '../templates/partials/typeUnion.hbs';
import typeWithOmitReadOnly from '../templates/partials/typeWithOmitReadOnly.hbs';
import { registerHandlebarHelpers } from './registerHandlebarHelpers';

export interface Templates {
Expand All @@ -102,6 +104,9 @@ export interface Templates {
request: Handlebars.TemplateDelegate;
baseHttpRequest: Handlebars.TemplateDelegate;
httpRequest: Handlebars.TemplateDelegate;
utils: {
omitReadonly: Handlebars.TemplateDelegate;
};
};
}

Expand Down Expand Up @@ -134,6 +139,9 @@ export const registerHandlebarTemplates = (root: {
request: Handlebars.template(templateCoreRequest),
baseHttpRequest: Handlebars.template(templateCoreBaseHttpRequest),
httpRequest: Handlebars.template(templateCoreHttpRequest),
utils: {
omitReadonly: Handlebars.template(omitReadonly),
},
},
};

Expand Down Expand Up @@ -163,6 +171,7 @@ export const registerHandlebarTemplates = (root: {
Handlebars.registerPartial('typeInterface', Handlebars.template(partialTypeInterface));
Handlebars.registerPartial('typeReference', Handlebars.template(partialTypeReference));
Handlebars.registerPartial('typeUnion', Handlebars.template(partialTypeUnion));
Handlebars.registerPartial('typeWithOmitReadOnly', Handlebars.template(typeWithOmitReadOnly));
Handlebars.registerPartial('typeIntersection', Handlebars.template(partialTypeIntersection));
Handlebars.registerPartial('base', Handlebars.template(partialBase));

Expand Down
3 changes: 3 additions & 0 deletions src/utils/writeClient.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ describe('writeClient', () => {
request: () => 'request',
baseHttpRequest: () => 'baseHttpRequest',
httpRequest: () => 'httpRequest',
utils: {
omitReadonly: () => 'omitReadonly',
},
},
};

Expand Down
14 changes: 12 additions & 2 deletions src/utils/writeClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export const writeClient = async (
): Promise<void> => {
const outputPath = resolve(process.cwd(), output);
const outputPathCore = resolve(outputPath, 'core');
const outputPathCoreUtils = resolve(outputPath, 'core', 'utils');
const outputPathModels = resolve(outputPath, 'models');
const outputPathSchemas = resolve(outputPath, 'schemas');
const outputPathServices = resolve(outputPath, 'services');
Expand All @@ -60,8 +61,17 @@ export const writeClient = async (

if (exportCore) {
await rmdir(outputPathCore);
await mkdir(outputPathCore);
await writeClientCore(client, templates, outputPathCore, httpClient, indent, clientName, request);
await mkdir(outputPathCoreUtils);
await writeClientCore(
client,
templates,
outputPathCore,
outputPathCoreUtils,
httpClient,
indent,
clientName,
request
);
}

if (exportServices) {
Expand Down
3 changes: 3 additions & 0 deletions src/utils/writeClientClass.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ describe('writeClientClass', () => {
request: () => 'request',
baseHttpRequest: () => 'baseHttpRequest',
httpRequest: () => 'httpRequest',
utils: {
omitReadonly: () => 'omitReadonly',
},
},
};

Expand Down
6 changes: 5 additions & 1 deletion src/utils/writeClientCore.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,20 @@ describe('writeClientCore', () => {
request: () => 'request',
baseHttpRequest: () => 'baseHttpRequest',
httpRequest: () => 'httpRequest',
utils: {
omitReadonly: () => 'omitReadonly',
},
},
};

await writeClientCore(client, templates, '/', HttpClient.FETCH, Indent.SPACE_4);
await writeClientCore(client, templates, '/', '/utils', HttpClient.FETCH, Indent.SPACE_4);

expect(writeFile).toBeCalledWith('/OpenAPI.ts', `settings${EOL}`);
expect(writeFile).toBeCalledWith('/ApiError.ts', `apiError${EOL}`);
expect(writeFile).toBeCalledWith('/ApiRequestOptions.ts', `apiRequestOptions${EOL}`);
expect(writeFile).toBeCalledWith('/ApiResult.ts', `apiResult${EOL}`);
expect(writeFile).toBeCalledWith('/CancelablePromise.ts', `cancelablePromise${EOL}`);
expect(writeFile).toBeCalledWith('/request.ts', `request${EOL}`);
expect(writeFile).toBeCalledWith('/utils/OmitReadonly.ts', `omitReadonly${EOL}`);
});
});
3 changes: 3 additions & 0 deletions src/utils/writeClientCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type { Templates } from './registerHandlebarTemplates';
* @param client Client object, containing, models, schemas and services
* @param templates The loaded handlebar templates
* @param outputPath Directory to write the generated files to
* @param outputUtilsPath Directory to write the generated util files to
* @param httpClient The selected httpClient (fetch, xhr, node or axios)
* @param indent Indentation options (4, 2 or tab)
* @param clientName Custom client class name
Expand All @@ -23,6 +24,7 @@ export const writeClientCore = async (
client: Client,
templates: Templates,
outputPath: string,
outputUtilsPath: string,
httpClient: HttpClient,
indent: Indent,
clientName?: string,
Expand All @@ -43,6 +45,7 @@ export const writeClientCore = async (
await writeFile(resolve(outputPath, 'ApiResult.ts'), i(templates.core.apiResult(context), indent));
await writeFile(resolve(outputPath, 'CancelablePromise.ts'), i(templates.core.cancelablePromise(context), indent));
await writeFile(resolve(outputPath, 'request.ts'), i(templates.core.request(context), indent));
await writeFile(resolve(outputUtilsPath, 'OmitReadonly.ts'), i(templates.core.utils.omitReadonly(context), indent));

if (isDefined(clientName)) {
await writeFile(resolve(outputPath, 'BaseHttpRequest.ts'), i(templates.core.baseHttpRequest(context), indent));
Expand Down
3 changes: 3 additions & 0 deletions src/utils/writeClientIndex.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ describe('writeClientIndex', () => {
request: () => 'request',
baseHttpRequest: () => 'baseHttpRequest',
httpRequest: () => 'httpRequest',
utils: {
omitReadonly: () => 'omitReadonly',
},
},
};

Expand Down
3 changes: 3 additions & 0 deletions src/utils/writeClientModels.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ describe('writeClientModels', () => {
request: () => 'request',
baseHttpRequest: () => 'baseHttpRequest',
httpRequest: () => 'httpRequest',
utils: {
omitReadonly: () => 'omitReadonly',
},
},
};

Expand Down
3 changes: 3 additions & 0 deletions src/utils/writeClientSchemas.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ describe('writeClientSchemas', () => {
request: () => 'request',
baseHttpRequest: () => 'baseHttpRequest',
httpRequest: () => 'httpRequest',
utils: {
omitReadonly: () => 'omitReadonly',
},
},
};

Expand Down
3 changes: 3 additions & 0 deletions src/utils/writeClientServices.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ describe('writeClientServices', () => {
request: () => 'request',
baseHttpRequest: () => 'baseHttpRequest',
httpRequest: () => 'httpRequest',
utils: {
omitReadonly: () => 'omitReadonly',
},
},
};

Expand Down
Loading