Skip to content

feat: Proposal of an approach to support readOnly / writeOnly properties #1863

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
2 changes: 1 addition & 1 deletion packages/openapi-fetch/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
"build:cjs": "esbuild --bundle src/index.js --format=cjs --outfile=dist/cjs/index.cjs && cp dist/index.d.ts dist/cjs/index.d.cts",
"format": "biome format . --write",
"lint": "biome check .",
"generate-types": "openapi-typescript -c test/redocly.yaml",
"generate-types": "openapi-typescript -c test/redocly.yaml --experimental-visibility",
"pretest": "pnpm run generate-types",
"test": "pnpm run \"/^test:/\"",
"test:js": "vitest run",
Expand Down
7 changes: 4 additions & 3 deletions packages/openapi-fetch/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
ResponseObjectMap,
RequiredKeysOf,
SuccessResponse,
Writable,
} from "openapi-typescript-helpers";

/** Options for each client instance */
Expand All @@ -29,7 +30,7 @@ export type HeadersOptions =
| Record<string, string | number | boolean | (string | number | boolean)[] | null | undefined>;

export type QuerySerializer<T> = (
query: T extends { parameters: any } ? NonNullable<T["parameters"]["query"]> : Record<string, unknown>,
query: T extends { parameters: any } ? Writable<NonNullable<T["parameters"]["query"]>> : Record<string, unknown>,
) => string;

/** @see https://swagger.io/docs/specification/serialization/#query */
Expand Down Expand Up @@ -84,8 +85,8 @@ export type ParamsOption<T> = T extends {
parameters: any;
}
? RequiredKeysOf<T["parameters"]> extends never
? { params?: T["parameters"] }
: { params: T["parameters"] }
? { params?: Writable<T["parameters"]> }
: { params: Writable<T["parameters"]> }
: DefaultParamsOption;

export type RequestBodyOption<T> = OperationRequestBodyContent<T> extends never
Expand Down
6 changes: 6 additions & 0 deletions packages/openapi-fetch/test/fixtures/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -859,9 +859,15 @@ export type webhooks = Record<string, never>;
export interface components {
schemas: {
Post: {
id: {
$read: string;
};
title: string;
body: string;
publish_date?: number;
password: {
$write: string;
};
};
StringArray: string[];
User: {
Expand Down
8 changes: 8 additions & 0 deletions packages/openapi-fetch/test/fixtures/api.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -495,15 +495,23 @@ components:
Post:
type: object
properties:
id:
type: string
readOnly: true
title:
type: string
body:
type: string
publish_date:
type: number
password:
type: string
writeOnly: true
required:
- id
- title
- body
- password
StringArray:
type: array
items:
Expand Down
2 changes: 2 additions & 0 deletions packages/openapi-fetch/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ describe("client", () => {
updated_at: number;
}
| {
id: string;
title: string;
body: string;
publish_date?: number;
Expand Down Expand Up @@ -721,6 +722,7 @@ describe("client", () => {
title: "",
publish_date: 3,
body: "",
password: "",
},
});
});
Expand Down
2 changes: 1 addition & 1 deletion packages/openapi-react-query/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
"dev": "tsc -p tsconfig.build.json --watch",
"format": "biome format . --write",
"lint": "biome check .",
"generate-types": "openapi-typescript test/fixtures/api.yaml -o test/fixtures/api.d.ts",
"generate-types": "openapi-typescript test/fixtures/api.yaml -o test/fixtures/api.d.ts --experimental-visibility",
"pretest": "pnpm run generate-types",
"test": "pnpm run \"/^test:/\"",
"test:js": "vitest run",
Expand Down
6 changes: 6 additions & 0 deletions packages/openapi-react-query/test/fixtures/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -819,9 +819,15 @@ export type webhooks = Record<string, never>;
export interface components {
schemas: {
Post: {
id: {
$read: string;
};
title: string;
body: string;
publish_date?: number;
password: {
$write: string;
};
};
StringArray: string[];
User: {
Expand Down
8 changes: 8 additions & 0 deletions packages/openapi-react-query/test/fixtures/api.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -475,15 +475,23 @@ components:
Post:
type: object
properties:
id:
type: string
readOnly: true
title:
type: string
body:
type: string
publish_date:
type: number
password:
type: string
writeOnly: true
required:
- id
- title
- body
- password
StringArray:
type: array
items:
Expand Down
36 changes: 33 additions & 3 deletions packages/openapi-typescript-helpers/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,17 @@ export type PathItemObject = {
[M in HttpMethod]: OperationObject;
} & { parameters?: any };

/** Return `content` for a RequestBody or Response Object */
type MediaContent<T> = T extends { content: any } ? T["content"] : unknown;

/** Return `responses` for an Operation Object */
export type ResponseObjectMap<T> = T extends { responses: any } ? T["responses"] : unknown;

/** Return `content` for a Response Object */
export type ResponseContent<T> = T extends { content: any } ? T["content"] : unknown;
export type ResponseContent<T> = Readable<MediaContent<T>>;

/** Return `content` for a RequestBody Object */
export type RequestBodyContent<T> = Writable<MediaContent<T>>;

/** Return type of `requestBody` for an Operation Object */
export type OperationRequestBody<T> = "requestBody" extends keyof T ? T["requestBody"] : never;
Expand All @@ -108,8 +114,8 @@ export type IsOperationRequestBodyOptional<T> = RequiredKeysOf<PickRequestBody<T

/** Internal helper used in OperationRequestBodyContent */
export type OperationRequestBodyMediaContent<T> = IsOperationRequestBodyOptional<T> extends true
? ResponseContent<NonNullable<OperationRequestBody<T>>> | undefined
: ResponseContent<OperationRequestBody<T>>;
? RequestBodyContent<NonNullable<OperationRequestBody<T>>> | undefined
: RequestBodyContent<OperationRequestBody<T>>;

/** Return first `content` from a Request Object Mapping, allowing any media type */
export type OperationRequestBodyContent<T> = FilterKeys<OperationRequestBodyMediaContent<T>, MediaType> extends never
Expand Down Expand Up @@ -139,6 +145,30 @@ export type ErrorResponseJSON<PathMethod> = JSONLike<ErrorResponse<ResponseObjec
/** Return JSON-like request body from a path + HTTP method */
export type RequestBodyJSON<PathMethod> = JSONLike<FilterKeys<OperationRequestBody<PathMethod>, "content">>;

/** Read-only property type */
export type ReadOnly<T> = { $read: T };

/** Write-only property type */
export type WriteOnly<T> = { $write: T };

type ReadOnlyKey<T> = { [K in keyof T]: T[K] extends ReadOnly<unknown> ? K : never }[keyof T];

type WriteOnlyKey<T> = { [K in keyof T]: T[K] extends WriteOnly<unknown> ? K : never }[keyof T];

/** Recursively remove write-only properties */
export type Readable<T> = Omit<
{ [K in keyof T]: T[K] extends ReadOnly<infer R> ? R : T[K] extends Record<string, unknown> ? Readable<T[K]> : T[K] },
WriteOnlyKey<T>
>;

/** Recursively remove read-only properties */
export type Writable<T> = Omit<
{
[K in keyof T]: T[K] extends WriteOnly<infer W> ? W : T[K] extends Record<string, unknown> ? Writable<T[K]> : T[K];
},
ReadOnlyKey<T>
>;

// Generic TS utils

/** Find first match of multiple keys */
Expand Down
2 changes: 2 additions & 0 deletions packages/openapi-typescript/bin/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ Options
--default-non-nullable Set to \`false\` to ignore default values when generating non-nullable types
--properties-required-by-default
Treat schema objects as if \`required\` is set to all properties by default
--experimental-visibility Enable experimental visibility support (readOnly, writeOnly)
--array-length Generate tuples using array minItems / maxItems
--path-params-as-types Convert paths to template literal types
--alphabetize Sort object keys alphabetically
Expand Down Expand Up @@ -133,6 +134,7 @@ async function generateSchema(schema, { redocly, silent = false }) {
exportType: flags.exportType,
immutable: flags.immutable,
pathParamsAsTypes: flags.pathParamsAsTypes,
experimentalVisibility: flags.experimentalVisibility,
redocly,
silent,
}),
Expand Down
1 change: 1 addition & 0 deletions packages/openapi-typescript/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ export default async function openapiTS(
pathParamsAsTypes: options.pathParamsAsTypes ?? false,
postTransform: typeof options.postTransform === "function" ? options.postTransform : undefined,
propertiesRequiredByDefault: options.propertiesRequiredByDefault ?? false,
experimentalVisibility: options.experimentalVisibility ?? false,
redoc,
silent: options.silent ?? false,
inject: options.inject ?? undefined,
Expand Down
8 changes: 8 additions & 0 deletions packages/openapi-typescript/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -389,3 +389,11 @@ export function warn(msg: string, silent = false) {
console.warn(c.yellow(` ⚠ ${msg}`));
}
}

export function createReadOnly(type: ts.TypeNode): ts.TypeNode {
return ts.factory.createTypeLiteralNode([ts.factory.createPropertySignature(undefined, "$read", undefined, type)]);
}

export function createWriteOnly(type: ts.TypeNode): ts.TypeNode {
return ts.factory.createTypeLiteralNode([ts.factory.createPropertySignature(undefined, "$write", undefined, type)]);
}
31 changes: 21 additions & 10 deletions packages/openapi-typescript/src/transform/schema-object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import {
tsUnion,
tsWithRequired,
} from "../lib/ts.js";
import { createDiscriminatorProperty, createRef, getEntries } from "../lib/utils.js";
import { createDiscriminatorProperty, createReadOnly, createRef, createWriteOnly, getEntries } from "../lib/utils.js";
import type { ReferenceObject, SchemaObject, TransformNodeOptions } from "../types.js";

/**
Expand Down Expand Up @@ -464,13 +464,24 @@ function transformSchemaObjectCore(schemaObject: SchemaObject, options: Transfor
!options.path?.includes("requestBodies")) // can’t be required, even with defaults
? undefined
: QUESTION_TOKEN;
let type =
"$ref" in v
? oapiRef(v.$ref)
: transformSchemaObject(v, {
...options,
path: createRef([options.path, k]),
});

let type: ts.TypeNode;
if ("$ref" in v) {
type = oapiRef(v.$ref);
} else {
type = transformSchemaObject(v, {
...options,
path: createRef([options.path, k]),
});

if (options.ctx.experimentalVisibility) {
if (v.readOnly && !v.writeOnly) {
type = createReadOnly(type);
} else if (v.writeOnly && !v.readOnly) {
type = createWriteOnly(type);
}
}
}

if (typeof options.ctx.transform === "function") {
const result = options.ctx.transform(v as SchemaObject, options);
Expand All @@ -486,7 +497,7 @@ function transformSchemaObjectCore(schemaObject: SchemaObject, options: Transfor

const property = ts.factory.createPropertySignature(
/* modifiers */ tsModifiers({
readonly: options.ctx.immutable || ("readOnly" in v && !!v.readOnly),
readonly: options.ctx.immutable || (!options.ctx.experimentalVisibility && "readOnly" in v && !!v.readOnly),
}),
/* name */ tsPropertyIndex(k),
/* questionToken */ optional,
Expand All @@ -503,7 +514,7 @@ function transformSchemaObjectCore(schemaObject: SchemaObject, options: Transfor
for (const [k, v] of Object.entries(schemaObject.$defs)) {
const property = ts.factory.createPropertySignature(
/* modifiers */ tsModifiers({
readonly: options.ctx.immutable || ("readonly" in v && !!v.readOnly),
readonly: options.ctx.immutable || (!options.ctx.experimentalVisibility && "readonly" in v && !!v.readOnly),
}),
/* name */ tsPropertyIndex(k),
/* questionToken */ undefined,
Expand Down
3 changes: 3 additions & 0 deletions packages/openapi-typescript/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,8 @@ export interface OpenAPITSOptions {
pathParamsAsTypes?: boolean;
/** Treat all objects as if they have \`required\` set to all properties by default (default: false) */
propertiesRequiredByDefault?: boolean;
/** Enable experimental visibility support (readOnly, writeOnly) */
experimentalVisibility?: boolean;
/**
* Configure Redocly for validation, schema fetching, and bundling
* @see https://redocly.com/docs/cli/configuration/
Expand Down Expand Up @@ -688,6 +690,7 @@ export interface GlobalContext {
pathParamsAsTypes: boolean;
postTransform: OpenAPITSOptions["postTransform"];
propertiesRequiredByDefault: boolean;
experimentalVisibility: boolean;
redoc: RedoclyConfig;
silent: boolean;
transform: OpenAPITSOptions["transform"];
Expand Down
1 change: 1 addition & 0 deletions packages/openapi-typescript/test/test-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ export const DEFAULT_CTX: GlobalContext = {
pathParamsAsTypes: false,
postTransform: undefined,
propertiesRequiredByDefault: false,
experimentalVisibility: false,
redoc: await createConfig({}, { extends: ["minimal"] }),
resolve($ref) {
return resolveRef({}, $ref, { silent: false });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,45 @@ describe("transformSchemaObject > object", () => {
},
},
],
[
"options > experimentalVisibility",
{
given: {
type: "object",
required: ["id", "name", "password"],
properties: {
id: {
type: "string",
format: "uuid",
readOnly: true,
},
name: {
type: "string",
},
password: {
type: "string",
format: "password",
writeOnly: true,
},
},
},
want: `{
/** Format: uuid */
id: {
$read: string;
};
name: string;
/** Format: password */
password: {
$write: string;
};
}`,
options: {
...DEFAULT_OPTIONS,
ctx: { ...DEFAULT_OPTIONS.ctx, experimentalVisibility: true },
},
},
],
];

for (const [testName, { given, want, options = DEFAULT_OPTIONS, ci }] of tests) {
Expand Down