New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@typespec/openapi3

Package Overview
Dependencies
Maintainers
0
Versions
226
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@typespec/openapi3 - npm Package Compare versions

Comparing version 0.64.0-dev.2 to 0.64.0-dev.4

dist/src/attach-extensions.d.ts

4

dist/src/encoding.d.ts
import { type ModelProperty, Program, type Scalar } from "@typespec/compiler";
import type { ResolvedOpenAPI3EmitterOptions } from "./openapi.js";
import type { OpenAPI3Schema } from "./types.js";
export declare function applyEncoding(program: Program, typespecType: Scalar | ModelProperty, target: OpenAPI3Schema, options: ResolvedOpenAPI3EmitterOptions): OpenAPI3Schema;
import type { OpenAPI3Schema, OpenAPISchema3_1 } from "./types.js";
export declare function applyEncoding(program: Program, typespecType: Scalar | ModelProperty, target: OpenAPI3Schema | OpenAPISchema3_1, getEncodedFieldName: (typespecType: Scalar | ModelProperty) => string, options: ResolvedOpenAPI3EmitterOptions): OpenAPI3Schema & OpenAPISchema3_1;
//# sourceMappingURL=encoding.d.ts.map
import { getEncode } from "@typespec/compiler";
import { ObjectBuilder } from "@typespec/compiler/emitter-framework";
import { getSchemaForStdScalars } from "./std-scalar-schemas.js";
export function applyEncoding(program, typespecType, target, options) {
export function applyEncoding(program, typespecType, target, getEncodedFieldName, options) {
const encodeData = getEncode(program, typespecType);

@@ -11,3 +11,4 @@ if (encodeData) {

// If the target already has a format it takes priority. (e.g. int32)
newTarget.format = mergeFormatAndEncoding(newTarget.format, encodeData.encoding, newType.format);
const encodedFieldName = getEncodedFieldName(typespecType);
newTarget[encodedFieldName] = mergeFormatAndEncoding(newTarget[encodedFieldName], encodeData.encoding, newType.format);
return newTarget;

@@ -14,0 +15,0 @@ }

import { JSONSchemaType } from "@typespec/compiler";
export type FileType = "yaml" | "json";
export type OpenAPIVersion = "3.0.0" | "3.1.0";
export interface OpenAPI3EmitterOptions {

@@ -4,0 +5,0 @@ /**

@@ -41,2 +41,14 @@ import { createTypeSpecLibrary, paramMessage } from "@typespec/compiler";

},
"openapi-versions": {
type: "array",
items: {
type: "string",
enum: ["3.0.0", "3.1.0"],
nullable: true,
description: "The versions of OpenAPI to emit. Defaults to `[3.0.0]`",
},
nullable: true,
uniqueItems: true,
minItems: 1,
},
"new-line": {

@@ -43,0 +55,0 @@ type: "string",

import { EmitContext, NewLine, Program } from "@typespec/compiler";
import { FileType, OpenAPI3EmitterOptions } from "./lib.js";
import { FileType, OpenAPI3EmitterOptions, OpenAPIVersion } from "./lib.js";
import { OpenAPI3ServiceRecord } from "./types.js";

@@ -19,2 +19,3 @@ export declare function $onEmit(context: EmitContext<OpenAPI3EmitterOptions>): Promise<void>;

outputFile: string;
openapiVersions: OpenAPIVersion[];
newLine: NewLine;

@@ -21,0 +22,0 @@ omitUnreachableTypes: boolean;

import { compilerAssert, createDiagnosticCollector, emitFile, getAllTags, getAnyExtensionFromPath, getDoc, getFormat, getKnownValues, getMaxItems, getMaxLength, getMaxValue, getMaxValueExclusive, getMinItems, getMinLength, getMinValue, getMinValueExclusive, getNamespaceFullName, getPattern, getService, getSummary, ignoreDiagnostics, interpolatePath, isDeprecated, isGlobalNamespace, isNeverType, isSecret, isVoidType, listServices, navigateTypesInNamespace, projectProgram, resolvePath, } from "@typespec/compiler";
import { createAssetEmitter } from "@typespec/compiler/emitter-framework";
import { createMetadataInfo, getHttpService, getServers, getStatusCodeDescription, isContentTypeHeader, isOrExtendsHttpFile, isOverloadSameEndpoint, reportIfNoRoutes, resolveAuthentication, resolveRequestVisibility, Visibility, } from "@typespec/http";
import { getExtensions, getExternalDocs, getOpenAPITypeName, getParameterKey, getTagsMetadata, isReadonlyProperty, resolveInfo, resolveOperationId, shouldInline, } from "@typespec/openapi";
import { getExtensions, getExternalDocs, getOpenAPITypeName, getParameterKey, getTagsMetadata, isReadonlyProperty, resolveOperationId, shouldInline, } from "@typespec/openapi";
import { buildVersionProjections } from "@typespec/versioning";
import { stringify } from "yaml";
import { getRef } from "./decorators.js";
import { applyEncoding } from "./encoding.js";
import { getExampleOrExamples, resolveOperationExamples } from "./examples.js";
import { resolveJsonSchemaModule } from "./json-schema.js";
import { createDiagnostic } from "./lib.js";
import { getDefaultValue, isBytesKeptRaw, OpenAPI3SchemaEmitter } from "./schema-emitter.js";
import { getOpenApiSpecProps } from "./openapi-spec-mappings.js";
import { getOpenAPI3StatusCodes } from "./status-codes.js";
import { deepEquals, isSharedHttpOperation } from "./util.js";
import { deepEquals, getDefaultValue, isBytesKeptRaw, isSharedHttpOperation, } from "./util.js";
import { resolveVisibilityUsage } from "./visibility-usage.js";

@@ -25,4 +25,6 @@ import { resolveXmlModule } from "./xml-module.js";

const options = resolveOptions(context);
const emitter = createOAPIEmitter(context, options);
await emitter.emitOpenAPI();
for (const specVersion of options.openapiVersions) {
const emitter = createOAPIEmitter(context, options, specVersion);
await emitter.emitOpenAPI();
}
}

@@ -48,4 +50,8 @@ /**

const resolvedOptions = resolveOptions(context);
const emitter = createOAPIEmitter(context, resolvedOptions);
return emitter.getOpenAPI();
const serviceRecords = [];
for (const specVersion of resolvedOptions.openapiVersions) {
const emitter = createOAPIEmitter(context, resolvedOptions, specVersion);
serviceRecords.push(...(await emitter.getOpenAPI()));
}
return serviceRecords;
}

@@ -70,2 +76,4 @@ function findFileTypeFromFilename(filename) {

const outputFile = resolvedOptions["output-file"] ?? `openapi.{service-name}.{version}.${fileType}`;
const openapiVersions = resolvedOptions["openapi-versions"] ?? ["3.0.0"];
const specDir = openapiVersions.length > 1 ? "{openapi-version}" : "";
return {

@@ -77,6 +85,8 @@ fileType,

safeintStrategy: resolvedOptions["safeint-strategy"],
outputFile: resolvePath(context.emitterOutputDir, outputFile),
outputFile: resolvePath(context.emitterOutputDir, specDir, outputFile),
openapiVersions,
};
}
function createOAPIEmitter(context, options) {
function createOAPIEmitter(context, options, specVersion = "3.0.0") {
const { applyEncoding, createRootDoc, createSchemaEmitter, getRawBinarySchema, isRawBinarySchema, } = getOpenApiSpecProps(specVersion);
let program = context.program;

@@ -148,3 +158,3 @@ let schemaEmitter;

}
function initializeEmitter(service, allHttpAuthentications, defaultAuth, xmlModule, version) {
function initializeEmitter(service, allHttpAuthentications, defaultAuth, optionalDependencies, version) {
diagnostics = createDiagnosticCollector();

@@ -157,30 +167,17 @@ currentService = service;

visibilityUsage = resolveVisibilityUsage(program, metadataInfo, service.type, options.omitUnreachableTypes);
schemaEmitter = createAssetEmitter(program, class extends OpenAPI3SchemaEmitter {
constructor(emitter) {
super(emitter, metadataInfo, visibilityUsage, options, xmlModule);
}
}, context);
schemaEmitter = createSchemaEmitter({
program,
context,
metadataInfo,
visibilityUsage,
options,
optionalDependencies,
});
const securitySchemes = getOpenAPISecuritySchemes(allHttpAuthentications);
const security = getOpenAPISecurity(defaultAuth);
const info = resolveInfo(program, service.type);
root = {
openapi: "3.0.0",
info: {
title: "(title)",
...info,
version: version ?? info?.version ?? "0.0.0",
},
externalDocs: getExternalDocs(program, service.type),
tags: [],
paths: {},
security: security.length > 0 ? security : undefined,
components: {
parameters: {},
requestBodies: {},
responses: {},
schemas: {},
examples: {},
securitySchemes: securitySchemes,
},
};
root = createRootDoc(program, service.type, version);
if (security.length > 0) {
root.security = security;
}
root.components.securitySchemes = securitySchemes;
const servers = getServers(program, service.type);

@@ -332,2 +329,3 @@ if (servers) {

return interpolatePath(options.outputFile, {
"openapi-version": specVersion,
"service-name": multipleService ? getNamespaceFullName(service.type) : undefined,

@@ -438,3 +436,4 @@ version,

const xmlModule = await resolveXmlModule();
initializeEmitter(service, auth.schemes, auth.defaultAuth, xmlModule, version);
const jsonSchemaModule = await resolveJsonSchemaModule();
initializeEmitter(service, auth.schemes, auth.defaultAuth, { xmlModule, jsonSchemaModule }, version);
reportIfNoRoutes(program, httpService.operations);

@@ -766,3 +765,3 @@ for (const op of resolveOperations(httpService.operations)) {

if (isBinary) {
return { schema: { type: "string", format: "binary" } };
return { schema: getRawBinarySchema(contentType) };
}

@@ -794,3 +793,3 @@ const oai3Examples = examples && getExampleOrExamples(program, examples);

let schema = isBytesKeptRaw(program, part.body.type)
? { type: "string", format: "binary" }
? getRawBinarySchema()
: getSchemaForSingleBody(part.body.type, visibility, part.body.isExplicit && part.body.containsMetadataAnnotations, part.body.type.kind === "Union" ? contentType : undefined);

@@ -863,6 +862,4 @@ if (part.multi) {

case "application/octet-stream":
return ((schema.type === "string" && schema.format === "binary") ||
(schema.type === "array" &&
schema.items?.type === "string" &&
schema.items?.format === "binary"));
return (isRawBinarySchema(schema) ||
(schema.type === "array" && !!schema.items && isRawBinarySchema(schema.items)));
case "application/json":

@@ -869,0 +866,0 @@ return schema.type === "object";

@@ -1,15 +0,24 @@

import { BooleanLiteral, Enum, EnumMember, IntrinsicType, Model, ModelProperty, NumericLiteral, Program, Scalar, StringLiteral, StringTemplate, Tuple, Type, Union, UnionVariant, Value } from "@typespec/compiler";
import { AssetEmitter, Context, Declaration, EmitEntity, EmitterOutput, ReferenceCycle, Scope, TypeEmitter } from "@typespec/compiler/emitter-framework";
import { BooleanLiteral, DiscriminatedUnion, Enum, EnumMember, IntrinsicScalarName, Model, ModelProperty, NumericLiteral, Program, Scalar, StringLiteral, StringTemplate, Tuple, Type, Union, UnionVariant } from "@typespec/compiler";
import { ArrayBuilder, AssetEmitter, Context, Declaration, EmitEntity, EmitterOutput, ObjectBuilder, Placeholder, ReferenceCycle, Scope, TypeEmitter } from "@typespec/compiler/emitter-framework";
import { MetadataInfo } from "@typespec/http";
import { JsonSchemaModule } from "./json-schema.js";
import { OpenAPI3EmitterOptions } from "./lib.js";
import { ResolvedOpenAPI3EmitterOptions } from "./openapi.js";
import { OpenAPI3Schema, OpenAPI3SchemaProperty } from "./types.js";
import { OpenAPI3Schema, OpenAPI3SchemaProperty, OpenAPISchema3_1 } from "./types.js";
import { VisibilityUsageTracker } from "./visibility-usage.js";
import { XmlModule } from "./xml-module.js";
/**
* OpenAPI3 schema emitter. Deals with emitting content of `components/schemas` section.
* Base OpenAPI3 schema emitter. Deals with emitting content of `components/schemas` section.
*/
export declare class OpenAPI3SchemaEmitter extends TypeEmitter<Record<string, any>, OpenAPI3EmitterOptions> {
export declare class OpenAPI3SchemaEmitterBase<Schema extends OpenAPI3Schema | OpenAPISchema3_1> extends TypeEmitter<Record<string, any>, OpenAPI3EmitterOptions> {
#private;
constructor(emitter: AssetEmitter<Record<string, any>, OpenAPI3EmitterOptions>, metadataInfo: MetadataInfo, visibilityUsage: VisibilityUsageTracker, options: ResolvedOpenAPI3EmitterOptions, xmlModule: XmlModule | undefined);
protected _metadataInfo: MetadataInfo;
protected _visibilityUsage: VisibilityUsageTracker;
protected _options: ResolvedOpenAPI3EmitterOptions;
protected _jsonSchemaModule: JsonSchemaModule | undefined;
protected _xmlModule: XmlModule | undefined;
constructor(emitter: AssetEmitter<Record<string, any>, OpenAPI3EmitterOptions>, metadataInfo: MetadataInfo, visibilityUsage: VisibilityUsageTracker, options: ResolvedOpenAPI3EmitterOptions, optionalDependencies: {
jsonSchemaModule?: JsonSchemaModule;
xmlModule?: XmlModule;
});
modelDeclarationReferenceContext(model: Model, name: string): Context;

@@ -21,3 +30,5 @@ modelLiteralReferenceContext(model: Model): Context;

reduceContext(type: Type): Context;
applyDiscriminator(type: Model | Union, schema: Schema): void;
modelDeclaration(model: Model, _: string): EmitterOutput<object>;
getContentType(): string;
modelLiteral(model: Model): EmitterOutput<object>;

@@ -30,2 +41,3 @@ modelInstantiation(model: Model, name: string | undefined): EmitterOutput<Record<string, any>>;

modelProperties(model: Model): EmitterOutput<Record<string, OpenAPI3SchemaProperty>>;
getRawBinarySchema(): Schema;
modelPropertyLiteral(prop: ModelProperty): EmitterOutput<object>;

@@ -37,5 +49,8 @@ booleanLiteral(boolean: BooleanLiteral): EmitterOutput<object>;

enumDeclaration(en: Enum, name: string): EmitterOutput<object>;
enumSchema(en: Enum): Schema;
enumMember(member: EnumMember): EmitterOutput<Record<string, any>>;
enumMemberReference(member: EnumMember): EmitterOutput<Record<string, any>>;
unionDeclaration(union: Union, name: string): EmitterOutput<object>;
unionSchema(union: Union): ObjectBuilder<Schema>;
getDiscriminatorMapping(union: DiscriminatedUnion): Record<string, string>;
unionLiteral(union: Union): EmitterOutput<object>;

@@ -47,10 +62,18 @@ unionVariants(union: Union): EmitterOutput<object>;

circularReference(target: EmitEntity<Record<string, any>>, scope: Scope<Record<string, any>> | undefined, cycle: ReferenceCycle): Record<string, any> | EmitEntity<Record<string, any>>;
scalarDeclaration(scalar: Scalar, name: string): EmitterOutput<OpenAPI3Schema>;
scalarDeclaration(scalar: Scalar, name: string): EmitterOutput<Schema>;
scalarInstantiation(scalar: Scalar, name: string | undefined): EmitterOutput<Record<string, any>>;
tupleLiteral(tuple: Tuple): EmitterOutput<Record<string, any>>;
intrinsic(intrinsic: IntrinsicType, name: string): EmitterOutput<object>;
getSchemaForStdScalars(scalar: Scalar & {
name: IntrinsicScalarName;
}): Schema;
applyCustomConstraints(type: Scalar | Model | ModelProperty | Union | Enum, target: Schema, refSchema?: Schema): void;
applyConstraints(type: Scalar | Model | ModelProperty | Union | Enum, original: Schema, refSchema?: Schema): ObjectBuilder<Schema>;
applyXml(type: Scalar | Model | ModelProperty | Union | Enum, schema: Schema, refSchema?: Schema): void;
applyEncoding(typespecType: Scalar | ModelProperty, target: Schema | Placeholder<Schema>): Schema;
programContext(program: Program): Context;
}
export declare function getDefaultValue(program: Program, defaultType: Value, modelProperty: ModelProperty): any;
export declare function isBytesKeptRaw(program: Program, type: Type): boolean;
export declare const Builders: {
readonly array: <T>(items: T[]) => ArrayBuilder<T>;
readonly object: <T extends Record<string, unknown>>(obj: T) => ObjectBuilder<T[string]>;
};
//# sourceMappingURL=schema-emitter.d.ts.map

@@ -1,23 +0,26 @@

import { compilerAssert, explainStringTemplateNotSerializable, getDeprecated, getDiscriminatedUnion, getDiscriminator, getDoc, getEncode, getExamples, getFormat, getKnownValues, getMaxItems, getMaxLength, getMaxValue, getMaxValueExclusive, getMinItems, getMinLength, getMinValue, getMinValueExclusive, getNamespaceFullName, getPattern, getSummary, getTypeName, ignoreDiagnostics, isArrayModelType, isNeverType, isNullType, isSecret, isTemplateDeclaration, resolveEncodedName, serializeValueAsJson, } from "@typespec/compiler";
import { compilerAssert, explainStringTemplateNotSerializable, getDeprecated, getDiscriminatedUnion, getDiscriminator, getDoc, getEncode, getFormat, getKnownValues, getMaxItems, getMaxLength, getMaxValue, getMinItems, getMinLength, getMinValue, getNamespaceFullName, getPattern, getSummary, getTypeName, ignoreDiagnostics, isArrayModelType, isNeverType, isSecret, resolveEncodedName, } from "@typespec/compiler";
import { ArrayBuilder, ObjectBuilder, Placeholder, TypeEmitter, } from "@typespec/compiler/emitter-framework";
import { Visibility, getVisibilitySuffix } from "@typespec/http";
import { checkDuplicateTypeName, getExtensions, getExternalDocs, getOpenAPITypeName, isReadonlyProperty, shouldInline, } from "@typespec/openapi";
import { checkDuplicateTypeName, getExternalDocs, getOpenAPITypeName, isReadonlyProperty, shouldInline, } from "@typespec/openapi";
import { attachExtensions } from "./attach-extensions.js";
import { getOneOf, getRef } from "./decorators.js";
import { applyEncoding } from "./encoding.js";
import { reportDiagnostic } from "./lib.js";
import { getSchemaForStdScalars } from "./std-scalar-schemas.js";
import { getDefaultValue, includeDerivedModel, isBytesKeptRaw, isStdType } from "./util.js";
/**
* OpenAPI3 schema emitter. Deals with emitting content of `components/schemas` section.
* Base OpenAPI3 schema emitter. Deals with emitting content of `components/schemas` section.
*/
export class OpenAPI3SchemaEmitter extends TypeEmitter {
#metadataInfo;
#visibilityUsage;
#options;
#xmlModule;
constructor(emitter, metadataInfo, visibilityUsage, options, xmlModule) {
export class OpenAPI3SchemaEmitterBase extends TypeEmitter {
_metadataInfo;
_visibilityUsage;
_options;
_jsonSchemaModule;
_xmlModule;
constructor(emitter, metadataInfo, visibilityUsage, options, optionalDependencies) {
super(emitter);
this.#metadataInfo = metadataInfo;
this.#visibilityUsage = visibilityUsage;
this.#options = options;
this.#xmlModule = xmlModule;
this._metadataInfo = metadataInfo;
this._visibilityUsage = visibilityUsage;
this._options = options;
this._jsonSchemaModule = optionalDependencies.jsonSchemaModule;
this._xmlModule = optionalDependencies.xmlModule;
}

@@ -42,6 +45,6 @@ modelDeclarationReferenceContext(model, name) {

const patch = {};
if (visibility !== Visibility.Read && !this.#metadataInfo.isTransformed(type, visibility)) {
if (visibility !== Visibility.Read && !this._metadataInfo.isTransformed(type, visibility)) {
patch.visibility = Visibility.Read;
}
const contentType = this.#getContentType();
const contentType = this.getContentType();
if (contentType === "application/json") {

@@ -52,2 +55,15 @@ patch.contentType = undefined;

}
applyDiscriminator(type, schema) {
const program = this.emitter.getProgram();
const discriminator = getDiscriminator(program, type);
if (discriminator) {
// the decorator validates that all the variants will be a model type
// with the discriminator field present.
schema.discriminator = { ...discriminator };
const discriminatedUnion = ignoreDiagnostics(getDiscriminatedUnion(type, discriminator));
if (discriminatedUnion.variants.size > 0) {
schema.discriminator.mapping = this.getDiscriminatorMapping(discriminatedUnion);
}
}
}
modelDeclaration(model, _) {

@@ -69,19 +85,11 @@ const program = this.emitter.getProgram();

}
const discriminator = getDiscriminator(program, model);
if (discriminator) {
const [union] = getDiscriminatedUnion(model, discriminator);
const openApiDiscriminator = { ...discriminator };
if (union.variants.size > 0) {
openApiDiscriminator.mapping = this.#getDiscriminatorMapping(union);
}
schema.discriminator = openApiDiscriminator;
}
this.applyDiscriminator(model, schema);
this.#applyExternalDocs(model, schema);
if (model.baseModel) {
schema.set("allOf", B.array([this.emitter.emitTypeReference(model.baseModel)]));
schema.set("allOf", Builders.array([this.emitter.emitTypeReference(model.baseModel)]));
}
const baseName = getOpenAPITypeName(program, model, this.#typeNameOptions());
const isMultipart = this.#getContentType().startsWith("multipart/");
const isMultipart = this.getContentType().startsWith("multipart/");
const name = isMultipart ? baseName + "MultiPart" : baseName;
return this.#createDeclaration(model, name, this.#applyConstraints(model, schema));
return this.#createDeclaration(model, name, this.applyConstraints(model, schema));
}

@@ -110,3 +118,3 @@ #applyExternalDocs(typespecType, target) {

}
#getContentType() {
getContentType() {
return this.emitter.getContext().contentType ?? "application/json";

@@ -137,3 +145,3 @@ }

});
return this.#createDeclaration(array, name, this.#applyConstraints(array, schema));
return this.#createDeclaration(array, name, this.applyConstraints(array, schema));
}

@@ -163,7 +171,7 @@ arrayDeclarationReferenceContext(array, name, elementType) {

}
if (!this.#metadataInfo.isPayloadProperty(prop, visibility, this.#ignoreMetadataAnnotations())) {
if (!this._metadataInfo.isPayloadProperty(prop, visibility, this.#ignoreMetadataAnnotations())) {
continue;
}
if (!this.#metadataInfo.isOptional(prop, visibility)) {
const encodedName = resolveEncodedName(this.emitter.getProgram(), prop, this.#getContentType());
if (!this._metadataInfo.isOptional(prop, visibility)) {
const encodedName = resolveEncodedName(this.emitter.getProgram(), prop, this.getContentType());
requiredProps.push(encodedName);

@@ -184,3 +192,3 @@ }

const visibility = this.emitter.getContext().visibility;
const contentType = this.#getContentType();
const contentType = this.getContentType();
for (const prop of model.properties.values()) {

@@ -191,3 +199,3 @@ if (isNeverType(prop.type)) {

}
if (!this.#metadataInfo.isPayloadProperty(prop, visibility, this.#ignoreMetadataAnnotations())) {
if (!this._metadataInfo.isPayloadProperty(prop, visibility, this.#ignoreMetadataAnnotations())) {
continue;

@@ -211,8 +219,11 @@ }

}
getRawBinarySchema() {
throw new Error("Method not implemented.");
}
modelPropertyLiteral(prop) {
const program = this.emitter.getProgram();
const isMultipart = this.#getContentType().startsWith("multipart/");
const isMultipart = this.getContentType().startsWith("multipart/");
if (isMultipart) {
if (isBytesKeptRaw(program, prop.type) && getEncode(program, prop) === undefined) {
return { type: "string", format: "binary" };
return this.getRawBinarySchema();
}

@@ -222,3 +233,3 @@ if (prop.type.kind === "Model" &&

isBytesKeptRaw(program, prop.type.indexer.value)) {
return { type: "array", items: { type: "string", format: "binary" } };
return { type: "array", items: this.getRawBinarySchema() };
}

@@ -244,5 +255,5 @@ }

const isRef = refSchema.value instanceof Placeholder || "$ref" in refSchema.value;
const schema = this.#applyEncoding(prop, refSchema.value);
const schema = this.applyEncoding(prop, refSchema.value);
// Apply decorators on the property to the type's schema
const additionalProps = this.#applyConstraints(prop, {}, schema);
const additionalProps = this.applyConstraints(prop, {}, schema);
if (prop.defaultValue) {

@@ -255,3 +266,3 @@ additionalProps.default = getDefaultValue(program, prop.defaultValue, prop);

// Attach any additional OpenAPI extensions
this.#attachExtensions(program, prop, additionalProps);
attachExtensions(program, prop, additionalProps);
if (schema && isRef && !(prop.type.kind === "Model" && isArrayModelType(program, prop.type))) {

@@ -306,24 +317,7 @@ if (Object.keys(additionalProps).length === 0) {

const baseName = getOpenAPITypeName(this.emitter.getProgram(), en, this.#typeNameOptions());
return this.#createDeclaration(en, baseName, new ObjectBuilder(this.#enumSchema(en)));
return this.#createDeclaration(en, baseName, new ObjectBuilder(this.enumSchema(en)));
}
#enumSchema(en) {
const program = this.emitter.getProgram();
if (en.members.size === 0) {
reportDiagnostic(program, { code: "empty-enum", target: en });
return {};
}
const enumTypes = new Set();
const enumValues = new Set();
for (const member of en.members.values()) {
enumTypes.add(typeof member.value === "number" ? "number" : "string");
enumValues.add(member.value ?? member.name);
}
if (enumTypes.size > 1) {
reportDiagnostic(program, { code: "enum-unique-type", target: en });
}
const schema = {
type: enumTypes.values().next().value,
enum: [...enumValues],
};
return this.#applyConstraints(en, schema);
enumSchema(en) {
// Enums are handled differently between 3.x versions due to the differences in `type`
throw new Error("Method not implemented.");
}

@@ -345,130 +339,12 @@ enumMember(member) {

unionDeclaration(union, name) {
const schema = this.#unionSchema(union);
const schema = this.unionSchema(union);
const baseName = getOpenAPITypeName(this.emitter.getProgram(), union, this.#typeNameOptions());
return this.#createDeclaration(union, baseName, schema);
}
#unionSchema(union) {
const program = this.emitter.getProgram();
if (union.variants.size === 0) {
reportDiagnostic(program, { code: "empty-union", target: union });
return new ObjectBuilder({});
}
const variants = Array.from(union.variants.values());
const literalVariantEnumByType = {};
const ofType = getOneOf(program, union) ? "oneOf" : "anyOf";
const schemaMembers = [];
let nullable = false;
const discriminator = getDiscriminator(program, union);
const isMultipart = this.#getContentType().startsWith("multipart/");
for (const variant of variants) {
if (isNullType(variant.type)) {
nullable = true;
continue;
}
if (isMultipart && isBytesKeptRaw(program, variant.type)) {
schemaMembers.push({ schema: { type: "string", format: "binary" }, type: variant.type });
continue;
}
if (isLiteralType(variant.type)) {
if (!literalVariantEnumByType[variant.type.kind]) {
const enumValue = [variant.type.value];
literalVariantEnumByType[variant.type.kind] = enumValue;
schemaMembers.push({
schema: { type: literalType(variant.type), enum: enumValue },
type: null,
});
}
else {
literalVariantEnumByType[variant.type.kind].push(variant.type.value);
}
}
else {
const enumSchema = this.emitter.emitTypeReference(variant.type, {
referenceContext: isMultipart ? { contentType: "application/json" } : {},
});
compilerAssert(enumSchema.kind === "code", "Unexpected enum schema. Should be kind: code");
schemaMembers.push({ schema: enumSchema.value, type: variant.type });
}
}
const wrapWithObjectBuilder = (schemaMember, { mergeUnionWideConstraints }) => {
// we can just return the single schema member after applying nullable
const schema = schemaMember.schema;
const type = schemaMember.type;
const additionalProps = mergeUnionWideConstraints
? this.#applyConstraints(union, {})
: {};
if (mergeUnionWideConstraints && nullable) {
additionalProps.nullable = true;
}
if (Object.keys(additionalProps).length === 0) {
return new ObjectBuilder(schema);
}
else {
if ((schema instanceof Placeholder || "$ref" in schema) &&
!(type && shouldInline(program, type))) {
if (type && (type.kind === "Model" || type.kind === "Scalar")) {
return new ObjectBuilder({
type: "object",
allOf: B.array([schema]),
...additionalProps,
});
}
else {
return new ObjectBuilder({ allOf: B.array([schema]), ...additionalProps });
}
}
else {
const merged = new ObjectBuilder(schema);
for (const [key, value] of Object.entries(additionalProps)) {
merged.set(key, value);
}
return merged;
}
}
};
const checkMerge = (schemaMembers) => {
if (nullable) {
for (const m of schemaMembers) {
if (m.schema instanceof Placeholder || "$ref" in m.schema) {
return true;
}
}
}
return false;
};
if (schemaMembers.length === 0) {
if (nullable) {
// This union is equivalent to just `null` but OA3 has no way to specify
// null as a value, so we throw an error.
reportDiagnostic(program, { code: "union-null", target: union });
return new ObjectBuilder({});
}
else {
// completely empty union can maybe only happen with bugs?
compilerAssert(false, "Attempting to emit an empty union");
}
}
if (schemaMembers.length === 1) {
return wrapWithObjectBuilder(schemaMembers[0], { mergeUnionWideConstraints: true });
}
const isMerge = checkMerge(schemaMembers);
const schema = {
[ofType]: schemaMembers.map((m) => wrapWithObjectBuilder(m, { mergeUnionWideConstraints: isMerge })),
};
if (!isMerge && nullable) {
schema.nullable = true;
}
if (discriminator) {
// the decorator validates that all the variants will be a model type
// with the discriminator field present.
schema.discriminator = { ...discriminator };
// Diagnostic already reported in compiler for unions
const discriminatedUnion = ignoreDiagnostics(getDiscriminatedUnion(union, discriminator));
if (discriminatedUnion.variants.size > 0) {
schema.discriminator.mapping = this.#getDiscriminatorMapping(discriminatedUnion);
}
}
return this.#applyConstraints(union, schema);
unionSchema(union) {
// Unions are handled differently between 3.x versions
// mostly due to how nullable properties are handled.
throw new Error("Method not implemented.");
}
#getDiscriminatorMapping(union) {
getDiscriminatorMapping(union) {
const mapping = {};

@@ -483,3 +359,3 @@ for (const [key, model] of union.variants.entries()) {

unionLiteral(union) {
return this.#unionSchema(union);
return this.unionSchema(union);
}

@@ -499,11 +375,2 @@ unionVariants(union) {

}
#attachExtensions(program, type, emitObject) {
// Attach any OpenAPI extensions
const extensions = getExtensions(program, type);
if (extensions) {
for (const key of extensions.keys()) {
emitObject[key] = extensions.get(key);
}
}
}
reference(targetDeclaration, pathUp, pathDown, commonScope) {

@@ -536,7 +403,9 @@ if (targetDeclaration.value instanceof Placeholder) {

scalarDeclaration(scalar, name) {
const isStd = this.#isStdType(scalar);
const isStd = isStdType(this.emitter.getProgram(), scalar);
const schema = this.#getSchemaForScalar(scalar);
const baseName = getOpenAPITypeName(this.emitter.getProgram(), scalar, this.#typeNameOptions());
// Don't create a declaration for std types
return isStd ? schema : this.#createDeclaration(scalar, baseName, new ObjectBuilder(schema));
return isStd
? schema
: this.#createDeclaration(scalar, baseName, new ObjectBuilder(schema));
}

@@ -551,5 +420,5 @@ scalarInstantiation(scalar, name) {

let result = {};
const isStd = this.#isStdType(scalar);
const isStd = isStdType(this.emitter.getProgram(), scalar);
if (isStd) {
result = this.#getSchemaForStdScalars(scalar);
result = this.getSchemaForStdScalars(scalar);
}

@@ -559,3 +428,3 @@ else if (scalar.baseScalar) {

}
const withDecorators = this.#applyEncoding(scalar, this.#applyConstraints(scalar, result));
const withDecorators = this.applyEncoding(scalar, this.applyConstraints(scalar, result));
if (isStd) {

@@ -567,13 +436,8 @@ // Standard types are going to be inlined in the spec and we don't want the description of the scalar to show up

}
#getSchemaForStdScalars(scalar) {
return getSchemaForStdScalars(scalar, this.#options);
getSchemaForStdScalars(scalar) {
return getSchemaForStdScalars(scalar, this._options);
}
#applySchemaExamples(type, target) {
const program = this.emitter.getProgram();
const examples = getExamples(program, type);
if (examples.length > 0) {
target.set("example", serializeValueAsJson(program, examples[0].value, type));
}
}
#applyConstraints(type, original, refSchema) {
applyCustomConstraints(type, target, refSchema) { }
applyConstraints(type, original, refSchema) {
// Apply common constraints
const schema = new ObjectBuilder(original);

@@ -587,3 +451,2 @@ const program = this.emitter.getProgram();

};
this.#applySchemaExamples(type, schema);
applyConstraint(getMinLength, "minLength");

@@ -596,12 +459,10 @@ applyConstraint(getMaxLength, "maxLength");

applyConstraint(getMaxItems, "maxItems");
const minValueExclusive = getMinValueExclusive(program, type);
if (minValueExclusive !== undefined) {
schema.minimum = minValueExclusive;
schema.exclusiveMinimum = true;
// apply json schema decorators
const jsonSchemaModule = this._jsonSchemaModule;
if (jsonSchemaModule) {
applyConstraint(jsonSchemaModule.getMultipleOf, "multipleOf");
applyConstraint(jsonSchemaModule.getUniqueItems, "uniqueItems");
applyConstraint(jsonSchemaModule.getMinProperties, "minProperties");
applyConstraint(jsonSchemaModule.getMaxProperties, "maxProperties");
}
const maxValueExclusive = getMaxValueExclusive(program, type);
if (maxValueExclusive !== undefined) {
schema.maximum = maxValueExclusive;
schema.exclusiveMaximum = true;
}
if (isSecret(program, type)) {

@@ -612,3 +473,3 @@ schema.format = "password";

// so ignore this format if it's the built-in type.
if (!this.#isStdType(type) || type.name !== "url") {
if (!isStdType(program, type) || type.name !== "url") {
applyConstraint(getFormat, "format");

@@ -619,24 +480,29 @@ }

applyConstraint((p, t) => (getDeprecated(p, t) !== undefined ? true : undefined), "deprecated");
if (this.#xmlModule) {
this.applyCustomConstraints(type, schema, refSchema);
this.applyXml(type, schema, refSchema);
attachExtensions(program, type, schema);
const values = getKnownValues(program, type);
if (values) {
return new ObjectBuilder({
oneOf: [schema, this.enumSchema(values)],
});
}
return new ObjectBuilder(schema);
}
applyXml(type, schema, refSchema) {
const program = this.emitter.getProgram();
if (this._xmlModule) {
switch (type.kind) {
case "Scalar":
case "Model":
this.#xmlModule.attachXmlObjectForScalarOrModel(program, type, schema);
this._xmlModule.attachXmlObjectForScalarOrModel(program, type, schema);
break;
case "ModelProperty":
this.#xmlModule.attachXmlObjectForModelProperty(program, this.#options, type, schema, refSchema);
this._xmlModule.attachXmlObjectForModelProperty(program, this._options, type, schema, refSchema);
break;
}
}
this.#attachExtensions(program, type, schema);
const values = getKnownValues(program, type);
if (values) {
return new ObjectBuilder({
oneOf: [schema, this.#enumSchema(values)],
});
}
return new ObjectBuilder(schema);
}
#inlineType(type, schema) {
if (this.#options.includeXTypeSpecName !== "never") {
if (this._options.includeXTypeSpecName !== "never") {
schema.set("x-typespec-name", getTypeName(type, this.#typeNameOptions()));

@@ -660,3 +526,3 @@ }

}
const usage = this.#visibilityUsage.getUsage(type);
const usage = this._visibilityUsage.getUsage(type);
const shouldAddSuffix = usage !== undefined && usage.size > 1;

@@ -669,22 +535,5 @@ const visibility = this.#getVisibilityContext();

}
#isStdType(type) {
return this.emitter.getProgram().checker.isStdType(type);
applyEncoding(typespecType, target) {
throw new Error("Method not implemented.");
}
#applyEncoding(typespecType, target) {
return applyEncoding(this.emitter.getProgram(), typespecType, target, this.#options);
}
intrinsic(intrinsic, name) {
switch (name) {
case "unknown":
return {};
case "null":
return { nullable: true };
}
reportDiagnostic(this.emitter.getProgram(), {
code: "invalid-schema",
format: { type: name },
target: intrinsic,
});
return {};
}
programContext(program) {

@@ -695,22 +544,3 @@ const sourceFile = this.emitter.createSourceFile("openapi");

}
function isLiteralType(type) {
return type.kind === "Boolean" || type.kind === "String" || type.kind === "Number";
}
function literalType(type) {
switch (type.kind) {
case "String":
return "string";
case "Number":
return "number";
case "Boolean":
return "boolean";
}
}
function includeDerivedModel(model) {
return (!isTemplateDeclaration(model) &&
(model.templateMapper?.args === undefined ||
model.templateMapper.args?.length === 0 ||
model.derivedModels.length > 0));
}
const B = {
export const Builders = {
array: (items) => {

@@ -731,8 +561,2 @@ const builder = new ArrayBuilder();

};
export function getDefaultValue(program, defaultType, modelProperty) {
return serializeValueAsJson(program, defaultType, modelProperty);
}
export function isBytesKeptRaw(program, type) {
return type.kind === "Scalar" && type.name === "bytes" && getEncode(program, type) === undefined;
}
//# sourceMappingURL=schema-emitter.js.map
import type { IntrinsicScalarName, Scalar } from "@typespec/compiler";
import type { ResolvedOpenAPI3EmitterOptions } from "./openapi.js";
import type { OpenAPI3Schema } from "./types.js";
import type { OpenAPI3Schema, OpenAPISchema3_1 } from "./types.js";
export declare function getSchemaForStdScalars(scalar: Scalar & {
name: IntrinsicScalarName;
}, options: ResolvedOpenAPI3EmitterOptions): OpenAPI3Schema;
}, options: ResolvedOpenAPI3EmitterOptions): OpenAPI3Schema & OpenAPISchema3_1;
//# sourceMappingURL=std-scalar-schemas.d.ts.map
import { Diagnostic, Service } from "@typespec/compiler";
import { Contact, ExtensionKey, License } from "@typespec/openapi";
export type CommonOpenAPI3Schema = OpenAPI3Schema & OpenAPISchema3_1;
export type SupportedOpenAPIDocuments = OpenAPI3Document | OpenAPIDocument3_1;
export type Extensions = {

@@ -44,3 +46,3 @@ [key in ExtensionKey]?: any;

/** The OpenAPI 3 document */
readonly document: OpenAPI3Document;
readonly document: SupportedOpenAPIDocuments;
/** The diagnostics created for this document */

@@ -62,3 +64,3 @@ readonly diagnostics: readonly Diagnostic[];

/** The OpenAPI document*/
readonly document: OpenAPI3Document;
readonly document: SupportedOpenAPIDocuments;
/** The service that generated this OpenAPI document. */

@@ -569,2 +571,350 @@ readonly service: Service;

export type Refable<T> = Ref<T> | T;
export type JsonSchemaType = "array" | "boolean" | "integer" | "null" | "number" | "object" | "string";
export type JsonSchema<AdditionalVocabularies extends {} = {}> = AdditionalVocabularies & {
/**
* The JSON type for the schema.
* If the value is an array, then an instance validates successfully if its type
* matches any of the types indicated by the string in the array.
*
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-type
*/
type?: JsonSchemaType | JsonSchemaType[];
/**
* The extending format for the previously mentioned type.
*/
format?: string;
/**
* This provides an enumeration of all possible values that are valid
* for the instance property. This MUST be an array, and each item in
* the array represents a possible value for the instance value. If
* this attribute is defined, the instance value MUST be one of the
* values in the array in order for the schema to be valid.
*
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-enum
*/
enum?: (string | number | boolean | null)[];
/**
* Functionally equivalent to "enum" with a single value.
* An instance validates successfully if its value is equal to the value of this keyword.
*
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-const
*/
const?: unknown;
/**
* Must be strictly greater than 0.
* A numeric instance is valid only if division by this keyword's value results in an integer.
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-multipleof
*/
multipleOf?: number;
/**
* Representing an inclusive upper limit for a numeric instance.
* This keyword validates only if the instance is less than or exactly equal to "maximum".
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-maximum
*/
maximum?: number;
/**
* Representing an exclusive upper limit for a numeric instance.
* This keyword validates only if the instance is strictly less than (not equal to) to "exclusiveMaximum".
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-exclusivemaximum
*/
exclusiveMaximum?: number;
/**
* Representing an inclusive lower limit for a numeric instance.
* This keyword validates only if the instance is greater than or exactly equal to "minimum".
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-minimum
*/
minimum?: number;
/**
* Representing an exclusive lower limit for a numeric instance.
* This keyword validates only if the instance is strictly greater than (not equal to) to "exclusiveMinimum".
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-exclusiveminimum
*/
exclusiveMinimum?: number;
/**
* Must be a non-negative integer.
* A string instance is valid against this keyword if its length is less than, or equal to, the value of this keyword.
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-maxlength
*/
maxLength?: number;
/**
* Must be a non-negative integer.
* A string instance is valid against this keyword if its length is greater than, or equal to, the value of this keyword.
* Omitting this keyword has the same behavior as a value of 0.
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-minlength
*/
minLength?: number;
/**
* Should be a valid regular expression, according to the ECMA 262 regular expression dialect.
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-pattern
*/
pattern?: string;
/**
* Must be a non-negative integer.
* An array instance is valid against "maxItems" if its size is less than, or equal to, the value of this keyword.
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-maxitems
*/
maxItems?: number;
/**
* Must be a non-negative integer.
* An array instance is valid against "maxItems" if its size is greater than, or equal to, the value of this keyword.
* Omitting this keyword has the same behavior as a value of 0.
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-minitems
*/
minItems?: number;
/**
* If this keyword has boolean value false, the instance validates successfully.
* If it has boolean value true, the instance validates successfully if all of its elements are unique.
* Omitting this keyword has the same behavior as a value of false.
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-uniqueitems
*/
uniqueItems?: boolean;
/**
* Must be a non-negative integer.
* If "contains" is not present within the same schema object, then this has no effect.
* An array instance is valid against "maxContains" if the number of elements that are'
* valid against the schema defined by "contains" is less than, or equal to, the value of this keyword.
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-maxcontains
*/
maxContains?: number;
/**
* Must be a non-negative integer.
* If "contains" is not present within the same schema object, then this has no effect.
* An array instance is valid against "minContains" if the number of elements that are'
* valid against the schema defined by "contains" is greater than, or equal to, the value of this keyword.
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-maxcontains
*/
minContains?: number;
/**
* Must be a non-negative integer.
* An object instance is valid against "maxProperties" if its number of properties is less than, or equal to, the value of this keyword.
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-maxproperties
*/
maxProperties?: number;
/**
* Must be a non-negative integer.
* An object instance is valid against "maxProperties" if its number of properties is greater than,
* or equal to, the value of this keyword.
* Omitting this keyword has the same behavior as a value of 0.
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-minproperties
*/
minProperties?: number;
/**
* Elements of this array must be unique.
* An object instance is valid against this keyword if every item in the array is the name of a property in the instance.
* Omitting this keyword has the same behavior as an empty array.
*
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-required
*/
required?: Array<string>;
/**
* Must be a string.
* If the schema instance is a string, this property defines that the string SHOULD be
* interpreted as encoded binary data and decoded using the encoding named by this property.
*
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-contentencoding
*/
contentEncoding?: string;
/**
* If the schema instance is a string and "contentMediaType" is present, this property
* contains a schema which describes the structure of the string.
* This should be ignored if "contentMediaType" is not present.
*
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-contentschema
*/
contentSchema?: Refable<JsonSchema<AdditionalVocabularies>>;
/**
* Must be a string.
* If the schema instance is a string, this property indicates the media type of the contents of the string.
* If "contentEncoding" is present, this property describes the decoded string.
*
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-contentmediatype
*/
contentMediaType?: string;
/**
* This attribute is a string that provides a short description of the instance property.
*
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-title-and-description
*/
title?: string;
/**
* This attribute is a string that provides a full description of the schema
*
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-title-and-description
*/
description?: string;
/**
* Declares the value of the property that the server will use if none is provided,
* for example a "count" to control the number of results per page might default to 100 if not supplied by the client in the request.
*
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-default
*/
default?: string | boolean | number | null | Record<string, any>;
/**
* Specifies that a schema is deprecated and SHOULD be transitioned out of usage.
* Default value is false.
*
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-deprecated
*/
deprecated?: boolean;
/**
* An array of free-form properties to include examples of an instance for this schema.
* To represent examples that cannot be naturally represented in JSON or YAML, a string value can be used to contain the example with escaping where necessary.
*
* @see https://json-schema.org/draft/2020-12/json-schema-validation#name-examples
*/
examples?: any[];
/**
* A collection of schemas that this schema also must conform to.
*
* An instance validates successfully against this keyword if it validates successfully against all schemas defined by this keyword's value.
*
* @see https://json-schema.org/draft/2020-12/json-schema-core#name-allof
*/
allOf?: Refable<JsonSchema<AdditionalVocabularies>>[];
/**
* A collection of schemas that this schema may conform to one or more of.
*
* An instance validates successfully against this keyword if it validates successfully against at least one schema defined by this keyword's value.
*
* @see https://json-schema.org/draft/2020-12/json-schema-core#name-anyof
*/
anyOf?: Refable<JsonSchema<AdditionalVocabularies>>[];
/**
* A collection of schemas that this schema may conform to only one of.
*
* An instance validates successfully against this keyword if it validates successfully against exactly one schema defined by this keyword's value.
*
* @see https://json-schema.org/draft/2020-12/json-schema-core#name-oneof
*/
oneOf?: Refable<JsonSchema<AdditionalVocabularies>>[];
/**
* An instance is valid against this keyword if it fails to validate successfully against the schema defined by this keyword.
* @see https://json-schema.org/draft/2020-12/json-schema-core#name-not
*/
not?: Refable<JsonSchema<AdditionalVocabularies>>;
/**
* Validation succeeds if each element of the instance validates against the schema at the same position, if any.
* This keyword does not constrain the length of the array.
* If the array is longer than this keyword's value, this keyword validates only the prefix of matching length.
*
* @see https://json-schema.org/draft/2020-12/json-schema-core#name-prefixitems
*/
prefixItems?: Refable<JsonSchema<AdditionalVocabularies>>[];
/**
* This keyword applies its subschema to all instance elements at indexes greater than the lenfth of the "prefixItems" array.
*
* @see https://json-schema.org/draft/2020-12/json-schema-core#name-items
* */
items?: Refable<JsonSchema<AdditionalVocabularies>>;
/**
* An array instance validates successfully against this keyword if at least one of its elements is valid against the given schema,
* except when `minContains` is present and has a value of 0.
*
* @see https://json-schema.org/draft/2020-12/json-schema-core#name-contains
*/
contains?: Refable<JsonSchema<AdditionalVocabularies>>;
/**
* This attribute is an object with property definitions that define the
* valid values of instance object property values. When the instance
* value is an object, the property values of the instance object MUST
* conform to the property definitions in this object. In this object,
* each property definition's value MUST be a schema, and the property's
* name MUST be the name of the instance property that it defines. The
* instance property value MUST be valid according to the schema from
* the property definition. Properties are considered unordered, the
* order of the instance properties MAY be in any order.
*
* @see https://json-schema.org/draft/2020-12/json-schema-core#name-properties
*/
properties?: Record<string, Refable<JsonSchema<AdditionalVocabularies>> | JsonSchema<AdditionalVocabularies>>;
/**
* indicates that additional unlisted properties can exist in this schema
*
* @see https://json-schema.org/draft/2020-12/json-schema-core#name-additionalproperties
*/
additionalProperties?: boolean | Refable<JsonSchema<AdditionalVocabularies>>;
/**
* Property is readonly.
*/
readOnly?: boolean;
/** Adds support for polymorphism. The discriminator is an object name that is used to differentiate between other schemas which may satisfy the payload description */
discriminator?: OpenAPI3Discriminator;
/** Additional external documentation for this schema. */
externalDocs?: OpenAPI3ExternalDocs;
};
export type OpenAPISchema3_1 = JsonSchema<{
/**
* Adds support for polymorphism.
* The discriminator is an object name that is used to differentiate between other schemas which may satisfy the payload description
*
* @see https://spec.openapis.org/oas/v3.1.1.html#discriminator-object
*/
discriminator?: OpenAPI3Discriminator;
/**
* Additional external documentation for this schema.
*
* @see https://spec.openapis.org/oas/v3.1.1.html#external-documentation-object
*/
externalDocs?: OpenAPI3ExternalDocs;
/**
* This MAY be used only on properties schemas.
* It has no effect on root schemas.
* Adds additional metadata to describe the XML representation of this property.
*/
xml?: OpenAPI3XmlSchema;
} & Extensions>;
export interface OpenAPIDocument3_1 extends Extensions {
openapi: "3.1.0";
/**
* Provides metadata about the API. The metadata can be used by the clients if needed.
*/
info: OpenAPI3Info;
/**
* The default value for the $schema keyword within Schema Objects contained within this document.
* This MUST be in the form of a URI.
*/
jsonSchemaDialect?: string;
/** Additional external documentation. */
externalDocs?: OpenAPI3ExternalDocs;
/** The available paths and operations for the API */
paths: Record<string, OpenAPI3PathItem>;
/**
* The incoming webhooks that may be received as part of this API.
* The key name is a unique string to refer to each webhook.
*/
webhooks?: Record<string, OpenAPI3PathItem>;
/**
* An array of Server Objects, which provide connectivity information to a target server.
* If the servers property is not provided, or is an empty array, the default value would be a Server Object with a url value of /.
*/
servers?: OpenAPI3Server[];
/**
* A list of tags used by the specification with additional metadata.
* The order of the tags can be used to reflect on their order by the parsing tools.
* Not all tags that are used by the Operation Object must be declared.
* The tags that are not declared MAY be organized randomly or based on the tools' logic. Each tag name in the list MUST be unique.
*/
tags?: OpenAPI3Tag[];
/** An element to hold various schemas for the specification. */
components?: OpenAPIComponents3_1;
/**
* A declaration of which security mechanisms can be used across the API.
* The list of values includes alternative security requirement objects that can be used.
* Only one of the security requirement objects need to be satisfied to authorize a request.
* Individual operations can override this definition.
*/
security?: Record<string, string[]>[];
}
export interface OpenAPIComponents3_1 extends Extensions {
schemas?: Record<string, OpenAPISchema3_1>;
responses?: Record<string, Refable<OpenAPI3Response>>;
parameters?: Record<string, Refable<OpenAPI3Parameter>>;
examples?: Record<string, Refable<OpenAPI3Example>>;
requestBodies?: Record<string, Refable<OpenAPI3RequestBody>>;
headers?: Record<string, Refable<OpenAPI3Header>>;
securitySchemes?: Record<string, Refable<OpenAPI3SecurityScheme>>;
links?: Record<string, Refable<OpenAPI3Link>>;
callbacks?: Record<string, Record<string, OpenAPI3PathItem>>;
pathItems?: Record<string, OpenAPI3PathItem>;
}
//# sourceMappingURL=types.d.ts.map

@@ -0,1 +1,2 @@

import { BooleanLiteral, IntrinsicScalarName, Model, ModelProperty, NumericLiteral, Program, Scalar, StringLiteral, Type, Value } from "@typespec/compiler";
import { HttpOperation } from "@typespec/http";

@@ -33,2 +34,11 @@ /**

export declare function isSharedHttpOperation(operation: HttpOperation | SharedHttpOperation): operation is SharedHttpOperation;
export declare function isStdType(program: Program, type: Type): type is Scalar & {
name: IntrinsicScalarName;
};
export declare function isLiteralType(type: Type): type is StringLiteral | NumericLiteral | BooleanLiteral;
export declare function literalType(type: StringLiteral | NumericLiteral | BooleanLiteral): "string" | "number" | "boolean";
export declare function includeDerivedModel(model: Model): boolean;
export declare function isScalarExtendsBytes(type: Type): boolean;
export declare function getDefaultValue(program: Program, defaultType: Value, modelProperty: ModelProperty): any;
export declare function isBytesKeptRaw(program: Program, type: Type): boolean;
//# sourceMappingURL=util.d.ts.map

@@ -0,1 +1,2 @@

import { getEncode, isTemplateDeclaration, serializeValueAsJson, } from "@typespec/compiler";
/**

@@ -68,2 +69,43 @@ * Checks if two objects are deeply equal.

}
export function isStdType(program, type) {
return program.checker.isStdType(type);
}
export function isLiteralType(type) {
return type.kind === "Boolean" || type.kind === "String" || type.kind === "Number";
}
export function literalType(type) {
switch (type.kind) {
case "String":
return "string";
case "Number":
return "number";
case "Boolean":
return "boolean";
}
}
export function includeDerivedModel(model) {
return (!isTemplateDeclaration(model) &&
(model.templateMapper?.args === undefined ||
model.templateMapper.args?.length === 0 ||
model.derivedModels.length > 0));
}
export function isScalarExtendsBytes(type) {
if (type.kind !== "Scalar") {
return false;
}
let current = type;
while (current) {
if (current.name === "bytes") {
return true;
}
current = current.baseScalar;
}
return false;
}
export function getDefaultValue(program, defaultType, modelProperty) {
return serializeValueAsJson(program, defaultType, modelProperty);
}
export function isBytesKeptRaw(program, type) {
return type.kind === "Scalar" && type.name === "bytes" && getEncode(program, type) === undefined;
}
//# sourceMappingURL=util.js.map
import { Model, ModelProperty, Program, Scalar } from "@typespec/compiler";
import { ResolvedOpenAPI3EmitterOptions } from "./openapi.js";
import { OpenAPI3Schema } from "./types.js";
import { OpenAPI3Schema, OpenAPISchema3_1 } from "./types.js";
export interface XmlModule {
attachXmlObjectForScalarOrModel(program: Program, type: Scalar | Model, emitObject: OpenAPI3Schema): void;
attachXmlObjectForModelProperty(program: Program, options: ResolvedOpenAPI3EmitterOptions, prop: ModelProperty, emitObject: OpenAPI3Schema, ref?: Record<string, any>): void;
attachXmlObjectForScalarOrModel(program: Program, type: Scalar | Model, emitObject: OpenAPI3Schema | OpenAPISchema3_1): void;
attachXmlObjectForModelProperty(program: Program, options: ResolvedOpenAPI3EmitterOptions, prop: ModelProperty, emitObject: OpenAPI3Schema | OpenAPISchema3_1, ref?: Record<string, any>): void;
}
export declare function resolveXmlModule(): Promise<XmlModule | undefined>;
//# sourceMappingURL=xml-module.d.ts.map
{
"name": "@typespec/openapi3",
"version": "0.64.0-dev.2",
"version": "0.64.0-dev.4",
"author": "Microsoft Corporation",

@@ -52,2 +52,3 @@ "description": "TypeSpec library for emitting OpenAPI 3.0 from the TypeSpec REST protocol binding and converting OpenAPI3 to TypeSpec",

"@typespec/http": "~0.63.0 || >=0.64.0-dev <0.64.0",
"@typespec/json-schema": "~0.63.0 || >=0.64.0-dev <0.64.0",
"@typespec/openapi": "~0.63.0 || >=0.64.0-dev <0.64.0",

@@ -57,2 +58,5 @@ "@typespec/versioning": "~0.63.0 || >=0.64.0-dev <0.64.0"

"peerDependenciesMeta": {
"@typespec/json-schema": {
"optional": true
},
"@typespec/xml": {

@@ -67,2 +71,3 @@ "optional": true

"@typespec/http": "~0.63.0 || >=0.64.0-dev <0.64.0",
"@typespec/json-schema": "~0.63.0 || >=0.64.0-dev <0.64.0",
"@typespec/library-linter": "~0.63.0 || >=0.64.0-dev <0.64.0",

@@ -69,0 +74,0 @@ "@typespec/openapi": "~0.63.0 || >=0.64.0-dev <0.64.0",

@@ -77,2 +77,6 @@ # @typespec/openapi3

### `openapi-versions`
**Type:** `array`
### `new-line`

@@ -79,0 +83,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc