Skip to content
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

Generate types for new MFD design #2455

Merged
merged 22 commits into from
Apr 26, 2024
Merged
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
19 changes: 17 additions & 2 deletions common/config/rush/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

26 changes: 0 additions & 26 deletions packages/rlc-common/src/buildIndexFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { Project, SourceFile } from "ts-morph";
import { NameType, normalizeName } from "./helpers/nameUtils.js";
import {
hasCsvCollection,
needsFilePolyfil,
hasInputModels,
hasMultiCollection,
hasOutputModels,
Expand All @@ -19,7 +18,6 @@ import {
import { RLCModel } from "./interfaces.js";
import * as path from "path";
import { getImportModuleName } from "./helpers/nameConstructors.js";
import { getImportSpecifier } from "./helpers/importsUtil.js";

export function buildIndexFile(model: RLCModel) {
const multiClient = Boolean(model.options?.multiClient),
Expand Down Expand Up @@ -167,8 +165,6 @@ function generateRLCIndexForMultiClient(file: SourceFile, model: RLCModel) {
exports.push("SerializeHelper");
}

reExportFileHelperFromCore(file, model);

file.addExportDeclarations([
{
moduleSpecifier: getImportModuleName(
Expand Down Expand Up @@ -331,30 +327,8 @@ function generateRLCIndex(file: SourceFile, model: RLCModel) {
]);
}

reExportFileHelperFromCore(file, model);

file.addExportAssignment({
expression: createClientFuncName,
isExportEquals: false
});
}

// re-export file helpers from core
function reExportFileHelperFromCore(file: SourceFile, model: RLCModel) {
if (needsFilePolyfil(model)) {
file.addExportDeclarations([
{
moduleSpecifier: getImportSpecifier(
"restPipeline",
model.importInfo.runtimeImports
),
namedExports: [
"createFile",
"createFileFromStream",
"type CreateFileOptions",
"type CreateFileFromStreamOptions"
]
}
]);
}
}
191 changes: 160 additions & 31 deletions packages/rlc-common/src/buildObjectTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,27 @@

import {
InterfaceDeclarationStructure,
OptionalKind,
PropertySignatureStructure,
StructureKind,
TypeAliasDeclarationStructure
} from "ts-morph";
import { NameType, normalizeName } from "./helpers/nameUtils.js";
import { isDictionarySchema, isObjectSchema } from "./helpers/schemaHelpers.js";
import {
isArraySchema,
isDictionarySchema,
isObjectSchema
} from "./helpers/schemaHelpers.js";
import {
ArraySchema,
ObjectSchema,
Parameter,
Property,
RLCModel,
Schema,
SchemaContext
} from "./interfaces.js";
import { getMultipartPartTypeName } from "./helpers/nameConstructors.js";

/**
* Generates interfaces for ObjectSchemas
Expand All @@ -40,6 +48,19 @@ export function buildObjectInterfaces(
) {
continue;
}

// FIXME: disabling new multipart generation for modular while we figure out the story
if (objectSchema.isMultipartBody && !model.options?.isModularLibrary) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: what RLC version will be generated in modular SDK? I image that new design would align with v2, old design would align with v1.

Copy link
Member Author

@timovv timovv Apr 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We just generate a normal RLC model in the modular SDK (as if it was a plain old JSON operation) because of this check. This shape is more in line with v1 of the Core package. We can't generate the v2 models here yet as that results in a compile error, since the serializers don't serialize into the array shape.

objectInterfaces.push(
...buildMultipartPartDefinitions(
objectSchema,
importedModels,
schemaUsage
)
);
continue;
}

const baseName = getObjectBaseName(objectSchema, schemaUsage);
const interfaceDeclaration = getObjectInterfaceDeclaration(
model,
Expand All @@ -54,6 +75,66 @@ export function buildObjectInterfaces(
return objectInterfaces;
}

const MULTIPART_FILE_METADATA_PROPERTIES: OptionalKind<PropertySignatureStructure>[] =
[
{
name: "filename",
hasQuestionToken: true,
type: "string"
},
{
name: "contentType",
hasQuestionToken: true,
type: "string"
}
];

function buildMultipartPartDefinitions(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we consider the case for A extends B?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not currently but we can revisit if this becomes a requirement

schema: ObjectSchema,
importedModels: Set<string>,
schemaUsage: SchemaContext[]
): InterfaceDeclarationStructure[] {
if (!schema.isMultipartBody) {
return [];
}

// Transform property signatures into individual models
const propertySignatures = getPropertySignatures(
schema.properties ?? {},
schemaUsage,
importedModels,
{ flattenBinaryArrays: true }
);

const structures: InterfaceDeclarationStructure[] = [];

for (const signature of propertySignatures) {
const name = signature.name;
const typeName = getMultipartPartTypeName(schema.name, name);

const isFileUpload = signature.type?.toString().includes("File") ?? false;

structures.push({
kind: StructureKind.Interface,
isExported: true,
name: typeName,
properties: [
{
name: "name",
type: name
},
{
name: "body",
type: signature.type
},
...(isFileUpload ? MULTIPART_FILE_METADATA_PROPERTIES : [])
]
});
}

return structures;
}

export function buildObjectAliases(
model: RLCModel,
importedModels: Set<string>,
Expand All @@ -67,6 +148,30 @@ export function buildObjectAliases(
const objectAliases: TypeAliasDeclarationStructure[] = [];

for (const objectSchema of objectSchemas) {
// FIXME: disabling new multipart generation for modular while we figure out the story
if (objectSchema.isMultipartBody && !model.options?.isModularLibrary) {
const propertySignatures = getPropertySignatures(
objectSchema.properties ?? {},
schemaUsage,
importedModels,
{ flattenBinaryArrays: true }
);

const objectTypeNames = propertySignatures.map((sig) =>
getMultipartPartTypeName(objectSchema.name, sig.name)
);

objectAliases.push({
kind: StructureKind.TypeAlias,
...(objectSchema.description && {
docs: [{ description: objectSchema.description }]
}),
name: objectSchema.typeName!,
type: `FormData | Array<${objectTypeNames.join("|") || "unknown"}>`,
isExported: true
});
}

if (objectSchema.alias || objectSchema.outputAlias) {
const description = objectSchema.description;
const modelName = schemaUsage.includes(SchemaContext.Input)
Expand Down Expand Up @@ -424,10 +529,15 @@ export function getImmediateParentsNames(
return [...parents, ...extendFrom];
}

interface GetPropertySignatureOptions {
flattenBinaryArrays?: boolean;
}

function getPropertySignatures(
properties: { [key: string]: Property },
schemaUsage: SchemaContext[],
importedModels: Set<string>
importedModels: Set<string>,
options: GetPropertySignatureOptions = {}
) {
let validProperties = Object.keys(properties);
const readOnlyFilter = (name: string) =>
Expand All @@ -438,63 +548,82 @@ function getPropertySignatures(
getPropertySignature(
{ ...properties[p], name: p },
schemaUsage,
importedModels
importedModels,
options
)
);
}

function isBinaryArray(schema: Schema): boolean {
return Boolean(
isArraySchema(schema) &&
(schema.items?.typeName?.includes("NodeJS.ReadableStream") ||
schema.items?.outputTypeName?.includes("NodeJS.ReadableStream"))
);
}

/**
* Builds a Typescript property or parameter signature
* @param property - Property or parameter to get the Typescript signature for
* @param schema - Property or parameter to get the Typescript signature for
* @param importedModels - Set to track the models that need to be imported
* @returns a PropertySignatureStructure for the property.
*/
export function getPropertySignature(
property: Property | Parameter,
schemaUsage: SchemaContext[],
importedModels: Set<string>
importedModels: Set<string>,
options: GetPropertySignatureOptions = {}
): PropertySignatureStructure {
const propertyName = property.name;
const description = property.description;
let schema: Schema;
if (options.flattenBinaryArrays && isBinaryArray(property)) {
schema = {
...((property as ArraySchema).items ?? property),
name: property.name
};
} else {
schema = property;
}

const propertyName = schema.name;
const description = schema.description;
let type;
const hasCoreInArray =
property.type === "array" &&
(property as any).items &&
(property as any).items.fromCore;
schema.type === "array" &&
(schema as any).items &&
(schema as any).items.fromCore;
const hasCoreInRecord =
property.type === "dictionary" &&
(property as any).additionalProperties &&
(property as any).additionalProperties.fromCore;
if (hasCoreInArray && property.typeName) {
type = property.typeName;
schema.type === "dictionary" &&
(schema as any).additionalProperties &&
(schema as any).additionalProperties.fromCore;
if (hasCoreInArray && schema.typeName) {
type = schema.typeName;
importedModels.add(
(property as any).items.typeName ?? (property as any).items.name
(schema as any).items.typeName ?? (schema as any).items.name
);
} else if (hasCoreInRecord && property.typeName) {
type = property.typeName;
} else if (hasCoreInRecord && schema.typeName) {
type = schema.typeName;
importedModels.add(
(property as any).additionalProperties.typeName ??
(property as any).additionalProperties.name
(schema as any).additionalProperties.typeName ??
(schema as any).additionalProperties.name
);
} else {
type =
generateForOutput(schemaUsage, property.usage) && property.outputTypeName
? property.outputTypeName
: property.typeName
? property.typeName
: property.type;
if (property.typeName && property.fromCore) {
importedModels.add(property.typeName);
type = property.typeName;
generateForOutput(schemaUsage, schema.usage) && schema.outputTypeName
? schema.outputTypeName
: schema.typeName
? schema.typeName
: schema.type;
if (schema.typeName && schema.fromCore) {
importedModels.add(schema.typeName);
type = schema.typeName;
}
}

return {
name: propertyName,
...(description && { docs: [{ description }] }),
hasQuestionToken: !property.required,
isReadonly:
generateForOutput(schemaUsage, property.usage) && property.readOnly,
hasQuestionToken: !schema.required,
isReadonly: generateForOutput(schemaUsage, schema.usage) && schema.readOnly,
type,
kind: StructureKind.PropertySignature
};
Expand Down
2 changes: 1 addition & 1 deletion packages/rlc-common/src/helpers/importsUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export function buildRuntimeImports(flavor?: PackageFlavor): Imports {
restClient: {
type: "restClient",
specifier: "@azure-rest/core-client",
version: "^1.4.0"
version: "^2.0.0"
},
coreAuth: {
type: "coreAuth",
Expand Down
10 changes: 10 additions & 0 deletions packages/rlc-common/src/helpers/nameConstructors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,13 @@ export function getClientName(model: RLCModel) {

return clientInterfaceName;
}

export function getMultipartPartTypeName(schemaName: string, partName: string) {
const name = normalizeName(partName, NameType.Interface);
const bodyParamName = normalizeName(schemaName, NameType.Interface);

return normalizeName(
`${bodyParamName}_${name}_PartDescriptor`,
NameType.Interface
);
}
Loading
Loading