diff --git a/packages/openapi/lib/object.dart b/packages/openapi/lib/object.dart new file mode 100644 index 0000000..0a7b93e --- /dev/null +++ b/packages/openapi/lib/object.dart @@ -0,0 +1,15 @@ +/* + * This file is part of the Protevus Platform. + * + * (C) Protevus + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/// This library exports the 'object' module from the Protevus OpenAPI package. +/// It provides access to the object-related functionality defined in the +/// 'src/object.dart' file of the 'protevus_openapi' package. +library object; + +export 'package:protevus_openapi/src/object.dart'; diff --git a/packages/openapi/lib/src/object.dart b/packages/openapi/lib/src/object.dart index 651786d..1cde693 100644 --- a/packages/openapi/lib/src/object.dart +++ b/packages/openapi/lib/src/object.dart @@ -5,4 +5,40 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:meta/meta.dart'; + +class APIObject extends Coding { + Map extensions = {}; + + @mustCallSuper + @override + void decode(KeyedArchive object) { + super.decode(object); + + final extensionKeys = object.keys.where((k) => k.startsWith("x-")); + for (final key in extensionKeys) { + extensions[key] = object.decode(key); + } + } + + @override + @mustCallSuper + void encode(KeyedArchive object) { + final invalidKeys = extensions.keys + .where((key) => !key.startsWith("x-")) + .map((key) => "'$key'") + .toList(); + if (invalidKeys.isNotEmpty) { + throw ArgumentError( + "extension keys must start with 'x-'. The following keys are invalid: ${invalidKeys.join(", ")}", + ); + } + + extensions.forEach((key, value) { + object.encode(key, value); + }); + } +} diff --git a/packages/openapi/lib/src/v2/document.dart b/packages/openapi/lib/src/v2/document.dart index 651786d..3c9d0f8 100644 --- a/packages/openapi/lib/src/v2/document.dart +++ b/packages/openapi/lib/src/v2/document.dart @@ -5,4 +5,98 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/cast.dart' as cast; +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/util.dart'; +import 'package:protevus_openapi/v2.dart'; + +/// Represents an OpenAPI 2.0 specification. +class APIDocument extends APIObject { + /// Creates an empty specification. + APIDocument(); + + /// Creates a specification from decoded JSON or YAML document object. + APIDocument.fromMap(Map map) { + decode(KeyedArchive.unarchive(map, allowReferences: true)); + } + + String version = "2.0"; + APIInfo? info = APIInfo(); + String? host; + String? basePath; + + List? tags = []; + List? schemes = []; + List? consumes = []; + List? produces = []; + List>?>? security = []; + + Map? paths = {}; + Map? responses = {}; + Map? parameters = {}; + Map? definitions = {}; + Map? securityDefinitions = {}; + + Map asMap() { + return KeyedArchive.archive(this, allowReferences: true); + } + + @override + Map get castMap => { + "schemes": const cast.List(cast.string), + "consumes": const cast.List(cast.string), + "produces": const cast.List(cast.string), + "security": + const cast.List(cast.Map(cast.string, cast.List(cast.string))) + }; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + version = object["swagger"] as String; + host = object["host"] as String?; + basePath = object["basePath"] as String?; + schemes = removeNullsFromList(object["schemes"] as List?); + + /// remove + consumes = removeNullsFromList(object["consumes"] as List?); + produces = removeNullsFromList(object["produces"] as List?); + security = object["security"] as List>?>; + + info = object.decodeObject("info", () => APIInfo()); + tags = object.decodeObjects("tags", () => APITag()); + paths = object.decodeObjectMap("paths", () => APIPath()); + responses = object.decodeObjectMap("responses", () => APIResponse()); + parameters = object.decodeObjectMap("parameters", () => APIParameter()); + definitions = + object.decodeObjectMap("definitions", () => APISchemaObject()); + securityDefinitions = object.decodeObjectMap( + "securityDefinitions", + () => APISecurityScheme(), + ); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encode("swagger", version); + object.encode("host", host); + object.encode("basePath", basePath); + object.encode("schemes", schemes); + object.encode("consumes", consumes); + object.encode("produces", produces); + object.encodeObjectMap("paths", paths); + object.encodeObject("info", info); + object.encodeObjectMap("parameters", parameters); + object.encodeObjectMap("responses", responses); + object.encodeObjectMap("securityDefinitions", securityDefinitions); + object.encode("security", security); + object.encodeObjects("tags", tags); + object.encodeObjectMap("definitions", definitions); + } +} diff --git a/packages/openapi/lib/src/v2/header.dart b/packages/openapi/lib/src/v2/header.dart index 651786d..71917ea 100644 --- a/packages/openapi/lib/src/v2/header.dart +++ b/packages/openapi/lib/src/v2/header.dart @@ -5,4 +5,33 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/v2.dart'; + +/// Represents a header in the OpenAPI specification. +class APIHeader extends APIProperty { + APIHeader(); + + String? description; + APIProperty? items; + + @override + void decode(KeyedArchive object) { + super.decode(object); + description = object.decode("description"); + if (type == APIType.array) { + items = object.decodeObject("items", () => APIProperty()); + } + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + object.encode("description", description); + if (type == APIType.array) { + object.encodeObject("items", items); + } + } +} diff --git a/packages/openapi/lib/src/v2/metadata.dart b/packages/openapi/lib/src/v2/metadata.dart index 651786d..ae5d29f 100644 --- a/packages/openapi/lib/src/v2/metadata.dart +++ b/packages/openapi/lib/src/v2/metadata.dart @@ -5,4 +5,118 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; + +/// Represents a metadata for an API in the OpenAPI specification. +class APIInfo extends APIObject { + /// Creates empty metadata for specification. + APIInfo(); + + String title = "API"; + String? description = "Description"; + String? version = "1.0"; + String? termsOfServiceURL = ""; + APIContact? contact = APIContact(); + APILicense? license = APILicense(); + + @override + void decode(KeyedArchive object) { + super.decode(object); + + title = object.decode("title") ?? ''; + description = object.decode("description"); + termsOfServiceURL = object.decode("termsOfService"); + contact = object.decodeObject("contact", () => APIContact()); + license = object.decodeObject("license", () => APILicense()); + version = object.decode("version"); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encode("title", title); + object.encode("description", description); + object.encode("version", version); + object.encode("termsOfService", termsOfServiceURL); + object.encodeObject("contact", contact); + object.encodeObject("license", license); + } +} + +/// Represents contact information in the OpenAPI specification. +class APIContact extends APIObject { + APIContact(); + + @override + void decode(KeyedArchive object) { + super.decode(object); + + name = object.decode("name") ?? "default"; + url = object.decode("url") ?? "http://localhost"; + email = object.decode("email") ?? "default"; + } + + String name = "default"; + String url = "http://localhost"; + String email = "default"; + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encode("name", name); + object.encode("url", url); + object.encode("email", email); + } +} + +/// Represents a copyright/open source license in the OpenAPI specification. +class APILicense extends APIObject { + APILicense(); + + @override + void decode(KeyedArchive object) { + super.decode(object); + + name = object.decode("name") ?? "default"; + url = object.decode("url") ?? "http://localhost"; + } + + String name = "default"; + String url = "http://localhost"; + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encode("name", name); + object.encode("url", url); + } +} + +class APITag extends APIObject { + APITag(); + + @override + void decode(KeyedArchive object) { + super.decode(object); + + name = object.decode("name"); + description = object.decode("description"); + } + + String? name; + String? description; + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encode("name", name); + object.encode("description", description); + } +} diff --git a/packages/openapi/lib/src/v2/operation.dart b/packages/openapi/lib/src/v2/operation.dart index 651786d..085a853 100644 --- a/packages/openapi/lib/src/v2/operation.dart +++ b/packages/openapi/lib/src/v2/operation.dart @@ -5,4 +5,71 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/cast.dart' as cast; +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v2.dart'; + +/// Represents a HTTP operation (a path/method pair) in the OpenAPI specification. +class APIOperation extends APIObject { + APIOperation(); + + @override + Map get castMap => { + "tags": const cast.List(cast.string), + "consumes": const cast.List(cast.string), + "produces": const cast.List(cast.string), + "schemes": const cast.List(cast.string), + "security": + const cast.List(cast.Map(cast.string, cast.List(cast.string))), + }; + + String? summary = ""; + String? description = ""; + String? id; + bool? deprecated; + + List? tags = []; + List? schemes = []; + List? consumes = []; + List? produces = []; + List? parameters = []; + List>?>? security = []; + Map? responses = {}; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + tags = object.decode("tags"); + summary = object.decode("summary"); + description = object.decode("description"); + id = object.decode("operationId"); + consumes = object.decode("consumes"); + produces = object.decode("produces"); + deprecated = object.decode("deprecated"); + parameters = object.decodeObjects("parameters", () => APIParameter()); + responses = object.decodeObjectMap("responses", () => APIResponse()); + schemes = object.decode("schemes"); + security = object.decode("security"); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encode("tags", tags); + object.encode("summary", summary); + object.encode("description", description); + object.encode("operationId", id); + object.encode("consumes", consumes); + object.encode("produces", produces); + object.encode("deprecated", deprecated); + + object.encodeObjects("parameters", parameters); + object.encodeObjectMap("responses", responses); + object.encode("security", security); + } +} diff --git a/packages/openapi/lib/src/v2/parameter.dart b/packages/openapi/lib/src/v2/parameter.dart index 651786d..dc82462 100644 --- a/packages/openapi/lib/src/v2/parameter.dart +++ b/packages/openapi/lib/src/v2/parameter.dart @@ -5,4 +5,105 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/v2.dart'; + +/// Represents a parameter location in the OpenAPI specification. +enum APIParameterLocation { query, header, path, formData, body } + +class APIParameterLocationCodec { + static APIParameterLocation? decode(String? location) { + switch (location) { + case "query": + return APIParameterLocation.query; + case "header": + return APIParameterLocation.header; + case "path": + return APIParameterLocation.path; + case "formData": + return APIParameterLocation.formData; + case "body": + return APIParameterLocation.body; + default: + return null; + } + } + + static String? encode(APIParameterLocation? location) { + switch (location) { + case APIParameterLocation.query: + return "query"; + case APIParameterLocation.header: + return "header"; + case APIParameterLocation.path: + return "path"; + case APIParameterLocation.formData: + return "formData"; + case APIParameterLocation.body: + return "body"; + default: + return null; + } + } +} + +/// Represents a parameter in the OpenAPI specification. +class APIParameter extends APIProperty { + APIParameter(); + + String? name; + String? description; + bool isRequired = false; + APIParameterLocation? location; + + // Valid if location is body. + APISchemaObject? schema; + + // Valid if location is not body. + bool allowEmptyValue = false; + APIProperty? items; + + @override + void decode(KeyedArchive object) { + name = object.decode("name"); + description = object.decode("description"); + location = APIParameterLocationCodec.decode(object.decode("in")); + if (location == APIParameterLocation.path) { + isRequired = true; + } else { + isRequired = object.decode("required") ?? false; + } + + if (location == APIParameterLocation.body) { + schema = object.decodeObject("schema", () => APISchemaObject()); + } else { + super.decode(object); + allowEmptyValue = object.decode("allowEmptyValue") ?? false; + if (type == APIType.array) { + items = object.decodeObject("items", () => APIProperty()); + } + } + } + + @override + void encode(KeyedArchive object) { + object.encode("name", name); + object.encode("description", description); + object.encode("in", APIParameterLocationCodec.encode(location)); + object.encode("required", isRequired); + + if (location == APIParameterLocation.body) { + object.encodeObject("schema", schema); + } else { + super.encode(object); + if (allowEmptyValue) { + object.encode("allowEmptyValue", allowEmptyValue); + } + if (type == APIType.array) { + object.encodeObject("items", items); + } + } + } +} diff --git a/packages/openapi/lib/src/v2/path.dart b/packages/openapi/lib/src/v2/path.dart index 651786d..b663179 100644 --- a/packages/openapi/lib/src/v2/path.dart +++ b/packages/openapi/lib/src/v2/path.dart @@ -5,4 +5,41 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v2.dart'; + +/// Represents a path (also known as a route) in the OpenAPI specification. +class APIPath extends APIObject { + APIPath(); + + List parameters = []; + Map operations = {}; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + for (final k in object.keys) { + if (k == r"$ref") { + // todo: reference + } else if (k == "parameters") { + parameters = object.decodeObjects(k, () => APIParameter())!; + } else { + operations[k] = object.decodeObject(k, () => APIOperation()); + } + } + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encodeObjects("parameters", parameters); + operations.forEach((opName, op) { + object.encodeObject(opName, op); + }); + } +} diff --git a/packages/openapi/lib/src/v2/property.dart b/packages/openapi/lib/src/v2/property.dart index 651786d..ff4fc32 100644 --- a/packages/openapi/lib/src/v2/property.dart +++ b/packages/openapi/lib/src/v2/property.dart @@ -5,4 +5,128 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v2.dart'; + +enum APISchemaRepresentation { + primitive, + array, + object, + structure, + unknownOrInvalid +} + +enum APICollectionFormat { csv, ssv, tsv, pipes } + +class APICollectionFormatCodec { + static APICollectionFormat? decode(String? location) { + switch (location) { + case "csv": + return APICollectionFormat.csv; + case "ssv": + return APICollectionFormat.ssv; + case "tsv": + return APICollectionFormat.tsv; + case "pipes": + return APICollectionFormat.pipes; + default: + return null; + } + } + + static String? encode(APICollectionFormat? location) { + switch (location) { + case APICollectionFormat.csv: + return "csv"; + case APICollectionFormat.ssv: + return "ssv"; + case APICollectionFormat.tsv: + return "tsv"; + case APICollectionFormat.pipes: + return "pipes"; + default: + return null; + } + } +} + +class APIProperty extends APIObject { + APIType? type; + String? format; + + APICollectionFormat? collectionFormat; + dynamic defaultValue; + num? maximum; + bool? exclusiveMaximum; + num? minimum; + bool? exclusiveMinimum; + int? maxLength; + int? minLength; + String? pattern; + int? maxItems; + int? minItems; + bool? uniqueItems; + num? multipleOf; + List? enumerated; + + APISchemaRepresentation get representation { + if (type == APIType.array) { + return APISchemaRepresentation.array; + } else if (type == APIType.object) { + return APISchemaRepresentation.object; + } + + return APISchemaRepresentation.primitive; + } + + @override + void decode(KeyedArchive object) { + super.decode(object); + + type = APITypeCodec.decode(object.decode("type")); + format = object.decode("format"); + collectionFormat = + APICollectionFormatCodec.decode(object.decode("collectionFormat")); + defaultValue = object.decode("default"); + maximum = object.decode("maximum"); + exclusiveMaximum = object.decode("exclusiveMaximum"); + minimum = object.decode("minimum"); + exclusiveMinimum = object.decode("exclusiveMinimum"); + maxLength = object.decode("maxLength"); + minLength = object.decode("minLength"); + pattern = object.decode("pattern"); + maxItems = object.decode("maxItems"); + minItems = object.decode("minItems"); + uniqueItems = object.decode("uniqueItems"); + multipleOf = object.decode("multipleOf"); + enumerated = object.decode("enum"); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encode("type", APITypeCodec.encode(type)); + object.encode("format", format); + object.encode( + "collectionFormat", + APICollectionFormatCodec.encode(collectionFormat), + ); + object.encode("default", defaultValue); + object.encode("maximum", maximum); + object.encode("exclusiveMaximum", exclusiveMaximum); + object.encode("minimum", minimum); + object.encode("exclusiveMinimum", exclusiveMinimum); + object.encode("maxLength", maxLength); + object.encode("minLength", minLength); + object.encode("pattern", pattern); + object.encode("maxItems", maxItems); + object.encode("minItems", minItems); + object.encode("uniqueItems", uniqueItems); + object.encode("multipleOf", multipleOf); + object.encode("enum", enumerated); + } +} diff --git a/packages/openapi/lib/src/v2/response.dart b/packages/openapi/lib/src/v2/response.dart index 651786d..ea0505b 100644 --- a/packages/openapi/lib/src/v2/response.dart +++ b/packages/openapi/lib/src/v2/response.dart @@ -5,4 +5,35 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v2.dart'; + +/// Represents an HTTP response in the OpenAPI specification. +class APIResponse extends APIObject { + APIResponse(); + + String? description = ""; + APISchemaObject? schema; + Map? headers = {}; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + description = object.decode("description"); + schema = object.decodeObject("schema", () => APISchemaObject()); + headers = object.decodeObjectMap("headers", () => APIHeader()); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encodeObjectMap("headers", headers); + object.encodeObject("schema", schema); + object.encode("description", description); + } +} diff --git a/packages/openapi/lib/src/v2/schema.dart b/packages/openapi/lib/src/v2/schema.dart index 651786d..66e363d 100644 --- a/packages/openapi/lib/src/v2/schema.dart +++ b/packages/openapi/lib/src/v2/schema.dart @@ -5,4 +5,72 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/cast.dart' as cast; +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/v2.dart'; + +/// Represents a schema object in the OpenAPI specification. +class APISchemaObject extends APIProperty { + APISchemaObject(); + + String? title; + String? description; + String? example; + List? isRequired = []; + bool readOnly = false; + + /// Valid when type == array + APISchemaObject? items; + + /// Valid when type == null + Map? properties; + + /// Valid when type == object + APISchemaObject? additionalProperties; + + @override + APISchemaRepresentation get representation { + if (properties != null) { + return APISchemaRepresentation.structure; + } + + return super.representation; + } + + @override + Map get castMap => + {"required": const cast.List(cast.string)}; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + title = object.decode("title"); + description = object.decode("description"); + isRequired = object.decode("required"); + example = object.decode("example"); + readOnly = object.decode("readOnly") ?? false; + + items = object.decodeObject("items", () => APISchemaObject()); + additionalProperties = + object.decodeObject("additionalProperties", () => APISchemaObject()); + properties = object.decodeObjectMap("properties", () => APISchemaObject()); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encode("title", title); + object.encode("description", description); + object.encode("required", isRequired); + object.encode("example", example); + object.encode("readOnly", readOnly); + + object.encodeObject("items", items); + object.encodeObject("additionalProperties", additionalProperties); + object.encodeObjectMap("properties", properties); + } +} diff --git a/packages/openapi/lib/src/v2/security.dart b/packages/openapi/lib/src/v2/security.dart index 651786d..e644459 100644 --- a/packages/openapi/lib/src/v2/security.dart +++ b/packages/openapi/lib/src/v2/security.dart @@ -5,4 +5,133 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/cast.dart' as cast; +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v2.dart'; + +/// Represents a OAuth 2.0 security scheme flow in the OpenAPI specification. +enum APISecuritySchemeFlow { + implicit, + password, + application, + authorizationCode +} + +class APISecuritySchemeFlowCodec { + static APISecuritySchemeFlow? decode(String? flow) { + switch (flow) { + case "accessCode": + return APISecuritySchemeFlow.authorizationCode; + case "password": + return APISecuritySchemeFlow.password; + case "implicit": + return APISecuritySchemeFlow.implicit; + case "application": + return APISecuritySchemeFlow.application; + default: + return null; + } + } + + static String? encode(APISecuritySchemeFlow? flow) { + switch (flow) { + case APISecuritySchemeFlow.authorizationCode: + return "accessCode"; + case APISecuritySchemeFlow.password: + return "password"; + case APISecuritySchemeFlow.implicit: + return "implicit"; + case APISecuritySchemeFlow.application: + return "application"; + default: + return null; + } + } +} + +/// Represents a security scheme in the OpenAPI specification. +class APISecurityScheme extends APIObject { + APISecurityScheme(); + + APISecurityScheme.basic() { + type = "basic"; + } + + APISecurityScheme.apiKey(this.apiKeyName, this.apiKeyLocation) { + type = "apiKey"; + } + + APISecurityScheme.oauth2( + this.oauthFlow, { + this.authorizationURL, + this.tokenURL, + this.scopes = const {}, + }) { + type = "oauth2"; + } + + late String type; + String? description; + + // API Key + String? apiKeyName; + APIParameterLocation? apiKeyLocation; + + // Oauth2 + APISecuritySchemeFlow? oauthFlow; + String? authorizationURL; + String? tokenURL; + Map? scopes; + + bool get isOAuth2 { + return type == "oauth2"; + } + + @override + Map get castMap => + {"scopes": const cast.Map(cast.string, cast.string)}; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + type = object.decode("type") ?? "oauth2"; + description = object.decode("description"); + + if (type == "basic") { + } else if (type == "oauth2") { + oauthFlow = APISecuritySchemeFlowCodec.decode(object.decode("flow")); + authorizationURL = object.decode("authorizationUrl"); + tokenURL = object.decode("tokenUrl"); + final scopeMap = object.decode>("scopes")!; + scopes = Map.from(scopeMap); + } else if (type == "apiKey") { + apiKeyName = object.decode("name"); + apiKeyLocation = APIParameterLocationCodec.decode(object.decode("in")); + } + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encode("type", type); + object.encode("description", description); + + if (type == "basic") { + /* nothing to do */ + } else if (type == "apiKey") { + object.encode("name", apiKeyName); + object.encode("in", APIParameterLocationCodec.encode(apiKeyLocation)); + } else if (type == "oauth2") { + object.encode("flow", APISecuritySchemeFlowCodec.encode(oauthFlow)); + + object.encode("authorizationUrl", authorizationURL); + object.encode("tokenUrl", tokenURL); + object.encode("scopes", scopes); + } + } +} diff --git a/packages/openapi/lib/src/v2/types.dart b/packages/openapi/lib/src/v2/types.dart index 651786d..c190d58 100644 --- a/packages/openapi/lib/src/v2/types.dart +++ b/packages/openapi/lib/src/v2/types.dart @@ -5,4 +5,49 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +enum APIType { string, number, integer, boolean, array, file, object } + +class APITypeCodec { + static APIType? decode(String? type) { + switch (type) { + case "string": + return APIType.string; + case "number": + return APIType.number; + case "integer": + return APIType.integer; + case "boolean": + return APIType.boolean; + case "array": + return APIType.array; + case "file": + return APIType.file; + case "object": + return APIType.object; + } + return null; + } + + static String? encode(APIType? type) { + switch (type) { + case APIType.string: + return "string"; + case APIType.number: + return "number"; + case APIType.integer: + return "integer"; + case APIType.boolean: + return "boolean"; + case APIType.array: + return "array"; + case APIType.file: + return "file"; + case APIType.object: + return "object"; + default: + return null; + } + } +} diff --git a/packages/openapi/lib/src/v3/callback.dart b/packages/openapi/lib/src/v3/callback.dart index 651786d..f0c3355 100644 --- a/packages/openapi/lib/src/v3/callback.dart +++ b/packages/openapi/lib/src/v3/callback.dart @@ -5,4 +5,42 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v3.dart'; + +/// A map of possible out-of band callbacks related to the parent operation. +/// +/// Each value in the map is a [APIPath] that describes a set of requests that may be initiated by the API provider and the expected responses. The key value used to identify the callback object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation. +class APICallback extends APIObject { + APICallback({this.paths}); + APICallback.empty(); + + /// Callback paths. + /// + /// The key that identifies the [APIPath] is a runtime expression that can be evaluated in the context of a runtime HTTP request/response to identify the URL to be used for the callback request. A simple example might be $request.body#/url. + Map? paths; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + paths = {}; + object.forEach((key, dynamic value) { + if (value is! KeyedArchive) { + throw ArgumentError( + "Invalid specification. Callback contains non-object value.", + ); + } + paths![key] = value.decodeObject(key, () => APIPath())!; + }); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + throw StateError("APICallback.encode: not yet implemented."); + } +} diff --git a/packages/openapi/lib/src/v3/componenets.dart b/packages/openapi/lib/src/v3/componenets.dart deleted file mode 100644 index 651786d..0000000 --- a/packages/openapi/lib/src/v3/componenets.dart +++ /dev/null @@ -1,8 +0,0 @@ -/* - * This file is part of the Protevus Platform. - * - * (C) Protevus - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ \ No newline at end of file diff --git a/packages/openapi/lib/src/v3/components.dart b/packages/openapi/lib/src/v3/components.dart new file mode 100644 index 0000000..a3e2ea5 --- /dev/null +++ b/packages/openapi/lib/src/v3/components.dart @@ -0,0 +1,158 @@ +/* + * This file is part of the Protevus Platform. + * + * (C) Protevus + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/util.dart'; +import 'package:protevus_openapi/v3.dart'; + +/// Holds a set of reusable objects for different aspects of the OAS. +/// +/// All objects defined within the components object will have no effect on the API unless they are explicitly referenced from properties outside the components object. +class APIComponents extends APIObject { + APIComponents(); + + APIComponents.empty(); + + /// An object to hold reusable [APISchemaObject?]. + Map schemas = {}; + + /// An object to hold reusable [APIResponse?]. + Map responses = {}; + + /// An object to hold reusable [APIParameter?]. + Map parameters = {}; + + //Map examples = {}; + + /// An object to hold reusable [APIRequestBody?]. + Map requestBodies = {}; + + /// An object to hold reusable [APIHeader]. + Map headers = {}; + + /// An object to hold reusable [APISecurityScheme?]. + Map securitySchemes = {}; + + //Map links = {}; + + /// An object to hold reusable [APICallback?]. + Map callbacks = {}; + + /// Returns a component definition for [uri]. + /// + /// Construct [uri] as a path, e.g. `Uri(path: /components/schemas/name)`. + APIObject? resolveUri(Uri uri) { + final segments = uri.pathSegments; + if (segments.length != 3) { + throw ArgumentError( + "Invalid reference URI. Must be a path URI of the form: '/components//'", + ); + } + + if (segments.first != "components") { + throw ArgumentError( + "Invalid reference URI: does not begin with /components/", + ); + } + + Map? namedMap; + switch (segments[1]) { + case "schemas": + namedMap = schemas; + break; + case "responses": + namedMap = responses; + break; + case "parameters": + namedMap = parameters; + break; + case "requestBodies": + namedMap = requestBodies; + break; + case "headers": + namedMap = headers; + break; + case "securitySchemes": + namedMap = securitySchemes; + break; + case "callbacks": + namedMap = callbacks; + break; + } + + if (namedMap == null) { + throw ArgumentError( + "Invalid reference URI: component type '${segments[1]}' does not exist.", + ); + } + + final result = namedMap[segments.last]; + + return result; + } + + T? resolve(T refObject) { + if (refObject.referenceURI == null) { + throw ArgumentError("APIObject is not a reference to a component."); + } + + return resolveUri(refObject.referenceURI!) as T?; + } + + @override + void decode(KeyedArchive object) { + super.decode(object); + + schemas = removeNullsFromMap( + object.decodeObjectMap("schemas", () => APISchemaObject()), + ); + responses = removeNullsFromMap( + object.decodeObjectMap("responses", () => APIResponse.empty()), + ); + parameters = removeNullsFromMap( + object.decodeObjectMap("parameters", () => APIParameter.empty()), + ); +// examples = object.decodeObjectMap("examples", () => APIExample()); + requestBodies = removeNullsFromMap( + object.decodeObjectMap("requestBodies", () => APIRequestBody.empty()), + ); + headers = removeNullsFromMap( + object.decodeObjectMap("headers", () => APIHeader()), + ); + + securitySchemes = removeNullsFromMap( + object.decodeObjectMap("securitySchemes", () => APISecurityScheme()), + ); +// links = object.decodeObjectMap("links", () => APILink()); + callbacks = removeNullsFromMap( + object.decodeObjectMap("callbacks", () => APICallback()), + ); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + if (schemas.isNotEmpty) object.encodeObjectMap("schemas", schemas); + if (responses.isNotEmpty) object.encodeObjectMap("responses", responses); + if (parameters.isNotEmpty) object.encodeObjectMap("parameters", parameters); +// object.encodeObjectMap("examples", examples); + if (requestBodies.isNotEmpty) { + object.encodeObjectMap("requestBodies", requestBodies); + } + if (headers.isNotEmpty) object.encodeObjectMap("headers", headers); + if (securitySchemes.isNotEmpty) { + object.encodeObjectMap("securitySchemes", securitySchemes); + } + +// object.encodeObjectMap("links", links); + if (callbacks.isNotEmpty) object.encodeObjectMap("callbacks", callbacks); + } +} diff --git a/packages/openapi/lib/src/v3/document.dart b/packages/openapi/lib/src/v3/document.dart index 651786d..9508367 100644 --- a/packages/openapi/lib/src/v3/document.dart +++ b/packages/openapi/lib/src/v3/document.dart @@ -5,4 +5,91 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v3.dart'; + +/// This is the root document object of the OpenAPI document. +class APIDocument extends APIObject { + /// Creates an empty specification. + APIDocument(); + + /// Creates a specification from decoded JSON or YAML document object. + APIDocument.fromMap(Map map) { + decode(KeyedArchive.unarchive(map, allowReferences: true)); + } + + /// This string MUST be the semantic version number of the OpenAPI Specification version that the OpenAPI document uses. + /// + /// REQUIRED. The openapi field SHOULD be used by tooling specifications and clients to interpret the OpenAPI document. This is not related to the API info.version string. + String version = "3.0.0"; + + /// Provides metadata about the API. + /// + /// REQUIRED. The metadata MAY be used by tooling as required. + APIInfo info = APIInfo.empty(); + + /// An array of [APIServerDescription], 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 [APIServerDescription] with a url value of /. + List? servers; + + /// The available paths and operations for the API. + /// + /// REQUIRED. + Map? paths; + + /// An element to hold various schemas for the specification. + APIComponents? components; + + /// 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. + List? security; + + /// 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. + List? tags; + + Map asMap() { + return KeyedArchive.archive(this, allowReferences: true); + } + + @override + void decode(KeyedArchive object) { + super.decode(object); + + version = object.decode("openapi") ?? "3.0.0"; + info = + object.decodeObject("info", () => APIInfo.empty()) ?? APIInfo.empty(); + servers = + object.decodeObjects("servers", () => APIServerDescription.empty()); + paths = object.decodeObjectMap("paths", () => APIPath()); + components = object.decodeObject("components", () => APIComponents()); + security = + object.decodeObjects("security", () => APISecurityRequirement.empty()); + tags = object.decodeObjects("tags", () => APITag.empty()); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + if (!info.isValid || paths == null) { + throw ArgumentError( + "APIDocument must have values for: 'version', 'info' and 'paths'.", + ); + } + + object.encode("openapi", version); + object.encodeObject("info", info); + object.encodeObjects("servers", servers); + object.encodeObjectMap("paths", paths); + object.encodeObject("components", components); + object.encodeObjects("security", security); + object.encodeObjects("tags", tags); + } +} diff --git a/packages/openapi/lib/src/v3/encoding.dart b/packages/openapi/lib/src/v3/encoding.dart index 651786d..cfa40a2 100644 --- a/packages/openapi/lib/src/v3/encoding.dart +++ b/packages/openapi/lib/src/v3/encoding.dart @@ -5,4 +5,70 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v3.dart'; + +/// A single encoding definition applied to a single schema property. +class APIEncoding extends APIObject { + APIEncoding({ + this.contentType, + this.headers, + this.style, + this.allowReserved = false, + this.explode = false, + }); + + APIEncoding.empty() + : allowReserved = false, + explode = false; + + /// The Content-Type for encoding a specific property. + /// + /// Default value depends on the property type: for string with format being binary – application/octet-stream; for other primitive types – text/plain; for object - application/json; for array – the default is defined based on the inner type. The value can be a specific media type (e.g. application/json), a wildcard media type (e.g. image/*), or a comma-separated list of the two types. + String? contentType; + + /// A map allowing additional information to be provided as headers, for example Content-Disposition. + /// + /// Content-Type is described separately and SHALL be ignored in this section. This property SHALL be ignored if the request body media type is not a multipart. + Map? headers; + + /// Determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986 :/?#[]@!$&'()*+,;= to be included without percent-encoding. + /// + /// The default value is false. This property SHALL be ignored if the request body media type is not application/x-www-form-urlencoded. + bool? allowReserved; + + /// When this is true, property values of type array or object generate separate parameters for each value of the array, or key-value-pair of the map. + /// + /// For other types of properties this property has no effect. When style is form, the default value is true. For all other styles, the default value is false. This property SHALL be ignored if the request body media type is not application/x-www-form-urlencoded. + bool? explode; + + /// Describes how a specific property value will be serialized depending on its type. + /// + /// See [APIParameter] for details on the style property. The behavior follows the same values as query parameters, including default values. This property SHALL be ignored if the request body media type is not application/x-www-form-urlencoded. + String? style; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + contentType = object.decode("contentType"); + headers = object.decodeObjectMap("headers", () => APIHeader()); + allowReserved = object.decode("allowReserved"); + explode = object.decode("explode"); + style = object.decode("style"); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encode("contentType", contentType); + object.encodeObjectMap("headers", headers); + object.encode("allowReserved", allowReserved); + object.encode("explode", explode); + object.encode("style", style); + } +} diff --git a/packages/openapi/lib/src/v3/header.dart b/packages/openapi/lib/src/v3/header.dart index 651786d..e837553 100644 --- a/packages/openapi/lib/src/v3/header.dart +++ b/packages/openapi/lib/src/v3/header.dart @@ -5,4 +5,26 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/v3.dart'; + +/// [APIHeader] follows the structure of the [APIParameter] with the following changes: +/// +/// name MUST NOT be specified, it is given in the corresponding headers map. +/// in MUST NOT be specified, it is implicitly in header. +/// All traits that are affected by the location MUST be applicable to a location of header (for example, style). +class APIHeader extends APIParameter { + APIHeader({APISchemaObject? schema}) : super.header(null, schema: schema); + APIHeader.empty() : super.header(null); + + @override + void encode(KeyedArchive object) { + name = "temporary"; + super.encode(object); + object.remove("name"); + object.remove("in"); + name = null; + } +} diff --git a/packages/openapi/lib/src/v3/media_type.dart b/packages/openapi/lib/src/v3/media_type.dart index 651786d..5b7826f 100644 --- a/packages/openapi/lib/src/v3/media_type.dart +++ b/packages/openapi/lib/src/v3/media_type.dart @@ -5,4 +5,38 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v3.dart'; + +/// Each [APIMediaType] provides schema and examples for the media type identified by its key. +class APIMediaType extends APIObject { + APIMediaType({this.schema, this.encoding}); + APIMediaType.empty(); + + /// The schema defining the type used for the request body. + APISchemaObject? schema; + + /// A map between a property name and its encoding information. + /// + /// The key, being the property name, MUST exist in the schema as a property. The encoding object SHALL only apply to requestBody objects when the media type is multipart or application/x-www-form-urlencoded. + Map? encoding; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + schema = object.decodeObject("schema", () => APISchemaObject()); + encoding = object.decodeObjectMap("encoding", () => APIEncoding()); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encodeObject("schema", schema); + object.encodeObjectMap("encoding", encoding); + } +} diff --git a/packages/openapi/lib/src/v3/metadata.dart b/packages/openapi/lib/src/v3/metadata.dart index 651786d..eb6df2c 100644 --- a/packages/openapi/lib/src/v3/metadata.dart +++ b/packages/openapi/lib/src/v3/metadata.dart @@ -5,4 +5,194 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v3.dart'; + +/// The object provides metadata about the API. +/// +/// The metadata MAY be used by the clients if needed, and MAY be presented in editing or documentation generation tools for convenience. +class APIInfo extends APIObject { + /// Creates empty metadata for specification. + APIInfo( + this.title, + this.version, { + this.description, + this.termsOfServiceURL, + this.license, + this.contact, + }); + + APIInfo.empty(); + + /// The title of the application. + /// + /// REQUIRED. + String? title; + + /// A short description of the application. + /// + /// CommonMark syntax MAY be used for rich text representation. + String? description; + + /// The version of the OpenAPI document (which is distinct from the OpenAPI Specification version or the API implementation version). + /// + /// REQUIRED. + String? version; + + /// A URL to the Terms of Service for the API. + /// + /// MUST be in the format of a URL. + Uri? termsOfServiceURL; + + /// The contact information for the exposed API. + APIContact? contact; + + /// The license information for the exposed API. + APILicense? license; + + bool get isValid => title != null && version != null; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + title = object.decode("title"); + description = object.decode("description"); + termsOfServiceURL = object.decode("termsOfService"); + contact = object.decodeObject("contact", () => APIContact()); + license = object.decodeObject("license", () => APILicense.empty()); + version = object.decode("version"); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + if (title == null || version == null) { + throw ArgumentError( + "APIInfo must have non-null values for: 'title', 'version'.", + ); + } + + object.encode("title", title); + object.encode("description", description); + object.encode("version", version); + object.encode("termsOfService", termsOfServiceURL); + object.encodeObject("contact", contact); + object.encodeObject("license", license); + } +} + +/// Contact information for the exposed API. +class APIContact extends APIObject { + APIContact({this.name, this.url, this.email}); + APIContact.empty(); + + /// The identifying name of the contact person/organization. + String? name; + + /// The URL pointing to the contact information. + /// + /// MUST be in the format of a URL. + Uri? url; + + /// The email address of the contact person/organization. + /// + /// MUST be in the format of an email address. + String? email; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + name = object.decode("name"); + url = object.decode("url"); + email = object.decode("email"); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encode("name", name); + object.encode("url", url); + object.encode("email", email); + } +} + +/// License information for the exposed API. +class APILicense extends APIObject { + APILicense(this.name, {this.url}); + APILicense.empty(); + + /// The license name used for the API. + /// + /// REQUIRED. + String? name; + + /// A URL to the license used for the API. + /// + /// MUST be in the format of a URL. + Uri? url; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + name = object.decode("name"); + url = object.decode("url"); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + if (name == null) { + throw ArgumentError("APILicense must have non-null values for: 'name'."); + } + + object.encode("name", name); + object.encode("url", url); + } +} + +/// Adds metadata to a single tag that is used by the [APIOperation]. +/// +/// It is not mandatory to have a [APITag] per tag defined in the [APIOperation] instances. +class APITag extends APIObject { + APITag(this.name, {this.description}); + + APITag.empty(); + + /// The name of the tag. + /// + /// REQUIRED. + String? name; + + /// A short description for the tag. + /// + /// CommonMark syntax MAY be used for rich text representation. + String? description; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + name = object.decode("name"); + description = object.decode("description"); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + if (name == null) { + throw ArgumentError("APITag must have non-null values for: 'name'."); + } + object.encode("name", name); + object.encode("description", description); + } +} diff --git a/packages/openapi/lib/src/v3/operation.dart b/packages/openapi/lib/src/v3/operation.dart index 651786d..f52204d 100644 --- a/packages/openapi/lib/src/v3/operation.dart +++ b/packages/openapi/lib/src/v3/operation.dart @@ -5,4 +5,182 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/cast.dart' as cast; +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v3.dart'; + +/// Describes a single API operation on a path. +class APIOperation extends APIObject { + APIOperation( + this.id, + this.responses, { + this.tags, + this.summary, + this.description, + this.parameters, + this.security, + this.requestBody, + this.callbacks, + this.deprecated, + }); + + APIOperation.empty(); + + /// A list of tags for API documentation control. + /// + /// Tags can be used for logical grouping of operations by resources or any other qualifier. + List? tags; + + /// A short summary of what the operation does. + String? summary; + + /// A verbose explanation of the operation behavior. + /// + /// CommonMark syntax MAY be used for rich text representation. + String? description; + + /// Unique string used to identify the operation. + /// + /// The id MUST be unique among all operations described in the API. Tools and libraries MAY use the operationId to uniquely identify an operation, therefore, it is RECOMMENDED to follow common programming naming conventions. + String? id; + + /// A list of parameters that are applicable for this operation. + /// + /// If a parameter is already defined at the Path Item, the definition will override it but can never remove it. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters. + List? parameters; + + /// A declaration of which security mechanisms can be used for this operation. + /// + /// 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. This definition overrides any declared top-level security. To remove a top-level security declaration, an empty array can be used. + List? security; + + /// The request body applicable for this operation. + /// + /// The requestBody is only supported in HTTP methods where the HTTP 1.1 specification RFC7231 has explicitly defined semantics for request bodies. In other cases where the HTTP spec is vague, requestBody SHALL be ignored by consumers. + APIRequestBody? requestBody; + + /// The list of possible responses as they are returned from executing this operation. + /// + /// REQUIRED. + Map? responses; + + /// A map of possible out-of band callbacks related to the parent operation. + /// + /// The key is a unique identifier for the [APICallback]. Each value in the map is a [APICallback] that describes a request that may be initiated by the API provider and the expected responses. The key value used to identify the callback object is an expression, evaluated at runtime, that identifies a URL to use for the callback operation. + Map? callbacks; + + /// An alternative server array to service this operation. + /// + /// If an alternative server object is specified at the [APIPath] or [APIDocument] level, it will be overridden by this value. + List? servers; + + /// Declares this operation to be deprecated. + /// + /// Consumers SHOULD refrain from usage of the declared operation. Default value is false. + bool? deprecated; + + /// Returns the parameter named [name] or null if it doesn't exist. + APIParameter? parameterNamed(String name) => + parameters?.firstWhere((p) => p.name == name); + + /// Adds [parameter] to [parameters]. + /// + /// If [parameters] is null, invoking this method will set it to a list containing [parameter]. + /// Otherwise, [parameter] is added to [parameters]. + void addParameter(APIParameter parameter) { + parameters ??= []; + parameters!.add(parameter); + } + + /// Adds [requirement] to [security]. + /// + /// If [security] is null, invoking this method will set it to a list containing [requirement]. + /// Otherwise, [requirement] is added to [security]. + void addSecurityRequirement(APISecurityRequirement requirement) { + security ??= []; + + security!.add(requirement); + } + + /// Adds [response] to [responses], merging schemas if necessary. + /// + /// [response] will be added to [responses] for the key [statusCode]. + /// + /// If a response already exists for this [statusCode], [response]'s content + /// and headers are added to the list of possible content and headers for the existing response. Descriptions + /// of each response are joined together. All headers are marked as optional.. + void addResponse(int statusCode, APIResponse? response) { + responses ??= {}; + + final key = "$statusCode"; + + final existingResponse = responses![key]; + if (existingResponse == null) { + responses![key] = response; + return; + } + + existingResponse.description = + "${existingResponse.description ?? ""}\n${response!.description}"; + response.headers?.forEach((name, header) { + existingResponse.addHeader(name, header); + }); + response.content?.forEach((contentType, mediaType) { + existingResponse.addContent(contentType, mediaType?.schema); + }); + } + + @override + Map get castMap => {"tags": const cast.List(cast.string)}; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + tags = object.decode("tags"); + summary = object.decode("summary"); + description = object.decode("description"); + id = object.decode("operationId"); + parameters = object + .decodeObjects("parameters", () => APIParameter.empty()) + ?.nonNulls + .toList(); + requestBody = + object.decodeObject("requestBody", () => APIRequestBody.empty()); + responses = object.decodeObjectMap("responses", () => APIResponse.empty()); + callbacks = object.decodeObjectMap("callbacks", () => APICallback()); + deprecated = object.decode("deprecated"); + security = object + .decodeObjects("security", () => APISecurityRequirement.empty()) + ?.nonNulls + .toList(); + servers = + object.decodeObjects("servers", () => APIServerDescription.empty()); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + if (responses == null) { + throw ArgumentError( + "Invalid specification. APIOperation must have non-null values for: 'responses'.", + ); + } + + object.encode("tags", tags); + object.encode("summary", summary); + object.encode("description", description); + object.encode("operationId", id); + object.encodeObjects("parameters", parameters); + object.encodeObject("requestBody", requestBody); + object.encodeObjectMap("responses", responses); + object.encodeObjectMap("callbacks", callbacks); + object.encode("deprecated", deprecated); + object.encodeObjects("security", security); + object.encodeObjects("servers", servers); + } +} diff --git a/packages/openapi/lib/src/v3/parameter.dart b/packages/openapi/lib/src/v3/parameter.dart index 651786d..fee19c9 100644 --- a/packages/openapi/lib/src/v3/parameter.dart +++ b/packages/openapi/lib/src/v3/parameter.dart @@ -5,4 +5,254 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v3.dart'; + +/// There are four possible parameter locations specified by the in field. +/// +/// - path: +/// - query: +/// - header: +/// - cookie: +enum APIParameterLocation { + /// Parameters that are appended to the URL. + /// + /// For example, in /items?id=###, the query parameter is id. + query, + + /// Custom headers that are expected as part of the request. + /// + /// Note that RFC7230 states header names are case insensitive. + header, + + /// Used together with Path Templating, where the parameter value is actually part of the operation's URL. + /// + /// This does not include the host or base path of the API. For example, in /items/{itemId}, the path parameter is itemId. + path, + + /// Used to pass a specific cookie value to the API. + cookie +} + +class APIParameterLocationCodec { + static APIParameterLocation? decode(String? location) { + switch (location) { + case "query": + return APIParameterLocation.query; + case "header": + return APIParameterLocation.header; + case "path": + return APIParameterLocation.path; + case "cookie": + return APIParameterLocation.cookie; + default: + return null; + } + } + + static String? encode(APIParameterLocation? location) { + switch (location) { + case APIParameterLocation.query: + return "query"; + case APIParameterLocation.header: + return "header"; + case APIParameterLocation.path: + return "path"; + case APIParameterLocation.cookie: + return "cookie"; + default: + return null; + } + } +} + +/// Describes a single operation parameter. +/// +/// A unique parameter is defined by a combination of a [name] and [location]. +class APIParameter extends APIObject { + APIParameter( + this.name, + this.location, { + this.description, + this.schema, + this.content, + this.style, + bool? isRequired, + this.deprecated, + this.allowEmptyValue, + this.explode, + this.allowReserved, + }) : _required = isRequired; + + APIParameter.empty(); + + APIParameter.header( + this.name, { + this.description, + this.schema, + this.content, + this.style, + bool? isRequired, + this.deprecated, + this.allowEmptyValue, + this.explode, + this.allowReserved, + }) : _required = isRequired { + location = APIParameterLocation.header; + } + + APIParameter.query( + this.name, { + this.description, + this.schema, + this.content, + this.style, + bool? isRequired, + this.deprecated, + this.allowEmptyValue, + this.explode, + this.allowReserved, + }) : _required = isRequired { + location = APIParameterLocation.query; + } + + APIParameter.path(this.name) + : location = APIParameterLocation.path, + schema = APISchemaObject.string(), + _required = true; + + APIParameter.cookie( + this.name, { + this.description, + this.schema, + this.content, + this.style, + bool? isRequired, + this.deprecated, + this.allowEmptyValue, + this.explode, + this.allowReserved, + }) : _required = isRequired { + location = APIParameterLocation.cookie; + } + + /// The name of the parameter. + /// + /// REQUIRED. Parameter names are case sensitive. + /// If in is "path", the name field MUST correspond to the associated path segment from the path field in [APIDocument.paths]. See Path Templating for further information. + /// If in is "header" and the name field is "Accept", "Content-Type" or "Authorization", the parameter definition SHALL be ignored. + /// For all other cases, the name corresponds to the parameter name used by the in property. + String? name; + + /// A brief description of the parameter. + /// + /// This could contain examples of use. CommonMark syntax MAY be used for rich text representation. + String? description; + + /// Determines whether this parameter is mandatory. + /// + /// If the parameter location is "path", this property is REQUIRED and its value MUST be true. Otherwise, the property MAY be included and its default value is false. + bool? get isRequired => + location == APIParameterLocation.path ? true : _required; + + set isRequired(bool? f) { + _required = f; + } + + bool? _required; + + /// Specifies that a parameter is deprecated and SHOULD be transitioned out of usage. + + bool? deprecated; + + /// The location of the parameter. + /// + /// REQUIRED. Possible values are "query", "header", "path" or "cookie". + APIParameterLocation? location; + + /// The schema defining the type used for the parameter. + APISchemaObject? schema; + + // Sets the ability to pass empty-valued parameters. + // + // This is valid only for query parameters and allows sending a parameter with an empty value. Default value is false. If style is used, and if behavior is n/a (cannot be serialized), the value of allowEmptyValue SHALL be ignored. + bool? allowEmptyValue = false; + + /// Describes how the parameter value will be serialized depending on the type of the parameter value. + /// + /// Default values (based on value of in): for query - form; for path - simple; for header - simple; for cookie - form. + String? style; + + /// When this is true, parameter values of type array or object generate separate parameters for each value of the array or key-value pair of the map. + /// + /// For other types of parameters this property has no effect. When style is form, the default value is true. For all other styles, the default value is false. + bool? explode = false; + + /// Determines whether the parameter value SHOULD allow reserved characters, as defined by RFC3986 :/?#[]@!$&'()*+,;= to be included without percent-encoding. + /// + /// This property only applies to parameters with an in value of query. The default value is false. + bool? allowReserved = false; + + /// A map containing the representations for the parameter. + /// + /// The key is the media type and the value describes it. The map MUST only contain one entry. + Map? content; + + // Currently missing: + // example, examples + + @override + void decode(KeyedArchive object) { + super.decode(object); + + name = object.decode("name"); + description = object.decode("description"); + location = APIParameterLocationCodec.decode(object.decode("in")); + _required = object.decode("required"); + + deprecated = object.decode("deprecated"); + allowEmptyValue = object.decode("allowEmptyValue"); + + schema = object.decodeObject("schema", () => APISchemaObject()); + style = object.decode("style"); + explode = object.decode("explode"); + allowReserved = object.decode("allowReserved"); + content = object.decodeObjectMap("content", () => APIMediaType()); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + if (name == null || location == null) { + throw ArgumentError( + "APIParameter must have non-null values for: 'name', 'location'.", + ); + } + + object.encode("name", name); + object.encode("description", description); + object.encode("in", APIParameterLocationCodec.encode(location)); + + if (location == APIParameterLocation.path) { + object.encode("required", true); + } else { + object.encode("required", _required); + } + + object.encode("deprecated", deprecated); + + if (location == APIParameterLocation.query) { + object.encode("allowEmptyValue", allowEmptyValue); + } + + object.encodeObject("schema", schema); + object.encode("style", style); + object.encode("explode", explode); + object.encode("allowReserved", allowReserved); + object.encodeObjectMap("content", content); + } +} diff --git a/packages/openapi/lib/src/v3/path.dart b/packages/openapi/lib/src/v3/path.dart index 651786d..5196226 100644 --- a/packages/openapi/lib/src/v3/path.dart +++ b/packages/openapi/lib/src/v3/path.dart @@ -5,4 +5,105 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v3.dart'; + +/// Describes the operations available on a single path. +/// +/// An [APIPath] MAY be empty, due to ACL constraints. The path itself is still exposed to the documentation viewer but they will not know which operations and parameters are available. +class APIPath extends APIObject { + APIPath({ + this.summary, + this.description, + List? parameters, + Map? operations, + }) { + this.parameters = parameters ?? []; + this.operations = operations ?? {}; + } + APIPath.empty() + : parameters = [], + operations = {}; + + /// An optional, string summary, intended to apply to all operations in this path. + String? summary; + + /// An optional, string description, intended to apply to all operations in this path. + /// + /// CommonMark syntax MAY be used for rich text representation. + String? description; + + /// A list of parameters that are applicable for all the operations described under this path. + /// + /// These parameters can be overridden at the operation level, but cannot be removed there. The list MUST NOT include duplicated parameters. A unique parameter is defined by a combination of a name and location. The list can use the Reference Object to link to parameters that are defined at the OpenAPI Object's components/parameters. + late List parameters; + + /// Definitions of operations on this path. + /// + /// Keys are lowercased HTTP methods, e.g. get, put, delete, post, etc. + late Map operations; + + /// Returns true if this path has path parameters [parameterNames]. + /// + /// Returns true if [parameters] contains path parameters with names that match [parameterNames] and + /// both lists have the same number of elements. + bool containsPathParameters(List parameterNames) { + final pathParams = parameters + .where((p) => p?.location == APIParameterLocation.path) + .map((p) => p?.name) + .toList(); + if (pathParams.length != parameterNames.length) { + return false; + } + + return parameterNames.every((check) => pathParams.contains(check)); + } + + // todo (joeconwaystk): alternative servers not yet implemented + + @override + void decode(KeyedArchive object) { + super.decode(object); + + summary = object.decode("summary"); + description = object.decode("description"); + parameters = + object.decodeObjects("parameters", () => APIParameter.empty()) ?? + []; + + final methodNames = [ + "get", + "put", + "post", + "delete", + "options", + "head", + "patch", + "trace" + ]; + for (final methodName in methodNames) { + if (object.containsKey(methodName)) { + operations[methodName] = + object.decodeObject(methodName, () => APIOperation.empty()); + } + } + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encode("summary", summary); + object.encode("description", description); + if (parameters.isNotEmpty) { + object.encodeObjects("parameters", parameters); + } + + operations.forEach((opName, op) { + object.encodeObject(opName.toLowerCase(), op); + }); + } +} diff --git a/packages/openapi/lib/src/v3/request_body.dart b/packages/openapi/lib/src/v3/request_body.dart index 651786d..a704b7e 100644 --- a/packages/openapi/lib/src/v3/request_body.dart +++ b/packages/openapi/lib/src/v3/request_body.dart @@ -5,4 +5,66 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v3.dart'; + +/// Describes a single request body. +class APIRequestBody extends APIObject { + APIRequestBody(this.content, {this.description, this.isRequired = false}); + + APIRequestBody.empty(); + + APIRequestBody.schema( + APISchemaObject schema, { + Iterable contentTypes = const ["application/json"], + this.description, + this.isRequired = false, + }) { + content = contentTypes.fold({}, (prev, elem) { + prev![elem] = APIMediaType(schema: schema); + return prev; + }); + } + + /// A brief description of the request body. + /// + /// This could contain examples of use. CommonMark syntax MAY be used for rich text representation. + String? description; + + /// The content of the request body. + /// + /// REQUIRED. The key is a media type or media type range and the value describes it. For requests that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* + Map? content; + + /// Determines if the request body is required in the request. + /// + /// Defaults to false. + bool isRequired = false; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + description = object.decode("description"); + isRequired = object.decode("required") ?? false; + content = object.decodeObjectMap("content", () => APIMediaType()); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + if (content == null) { + throw ArgumentError( + "APIRequestBody must have non-null values for: 'content'.", + ); + } + + object.encode("description", description); + object.encode("required", isRequired); + object.encodeObjectMap("content", content); + } +} diff --git a/packages/openapi/lib/src/v3/response.dart b/packages/openapi/lib/src/v3/response.dart index 651786d..4b80b60 100644 --- a/packages/openapi/lib/src/v3/response.dart +++ b/packages/openapi/lib/src/v3/response.dart @@ -5,4 +5,103 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v3.dart'; + +/// Describes a single response from an API Operation, including design-time, static links to operations based on the response. +class APIResponse extends APIObject { + APIResponse(this.description, {this.content, this.headers}); + APIResponse.empty(); + APIResponse.schema( + this.description, + APISchemaObject schema, { + Iterable contentTypes = const ["application/json"], + this.headers, + }) { + content = contentTypes.fold({}, (prev, elem) { + prev![elem] = APIMediaType(schema: schema); + return prev; + }); + } + + /// A short description of the response. + /// + /// REQUIRED. CommonMark syntax MAY be used for rich text representation. + String? description; + + /// Maps a header name to its definition. + /// + /// RFC7230 states header names are case insensitive. If a response header is defined with the name "Content-Type", it SHALL be ignored. + Map? headers; + + /// A map containing descriptions of potential response payloads. + /// + /// The key is a media type or media type range and the value describes it. For responses that match multiple keys, only the most specific key is applicable. e.g. text/plain overrides text/* + Map? content; + + // Currently missing: + // links + + /// Adds a [header] to [headers] for [name]. + /// + /// If [headers] is null, it is created. If the key does not exist in [headers], [header] is added for the key. + /// If the key exists, [header] is not added. (To replace a header, access [headers] directly.) + void addHeader(String name, APIHeader? header) { + headers ??= {}; + if (!headers!.containsKey(name)) { + headers![name] = header; + } + } + + /// Adds a [bodyObject] to [content] for a content-type. + /// + /// [contentType] must take the form 'primaryType/subType', e.g. 'application/json'. Do not include charsets. + /// + /// If [content] is null, it is created. If [contentType] does not exist in [content], [bodyObject] is added for [contentType]. + /// If [contentType] exists, the [bodyObject] is added the list of possible schemas that were previously added. + void addContent(String contentType, APISchemaObject? bodyObject) { + content ??= {}; + + final key = contentType; + final existingContent = content![key]; + if (existingContent == null) { + content![key] = APIMediaType(schema: bodyObject); + return; + } + + final schema = existingContent.schema; + if (schema?.oneOf != null) { + schema!.oneOf!.add(bodyObject); + } else { + final container = APISchemaObject()..oneOf = [schema, bodyObject]; + existingContent.schema = container; + } + } + + @override + void decode(KeyedArchive object) { + super.decode(object); + + description = object.decode("description"); + content = object.decodeObjectMap("content", () => APIMediaType()); + headers = object.decodeObjectMap("headers", () => APIHeader()); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + if (description == null) { + throw ArgumentError( + "APIResponse must have non-null values for: 'description'.", + ); + } + + object.encode("description", description); + object.encodeObjectMap("headers", headers); + object.encodeObjectMap("content", content); + } +} diff --git a/packages/openapi/lib/src/v3/schema.dart b/packages/openapi/lib/src/v3/schema.dart index 651786d..0810e26 100644 --- a/packages/openapi/lib/src/v3/schema.dart +++ b/packages/openapi/lib/src/v3/schema.dart @@ -5,4 +5,366 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/cast.dart' as cast; +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v3.dart'; + +enum APISchemaAdditionalPropertyPolicy { + /// When [APISchemaObject] prevents properties other than those defined by [APISchemaObject.properties] from being included + disallowed, + + /// When [APISchemaObject] allows any additional properties + freeForm, + + /// When [APISchemaObject.additionalPropertySchema] contains a schema object + restricted +} + +/// Represents a schema object in the OpenAPI specification. +class APISchemaObject extends APIObject { + APISchemaObject(); + APISchemaObject.empty(); + + APISchemaObject.string({this.format}) : type = APIType.string; + APISchemaObject.number() : type = APIType.number; + APISchemaObject.integer() : type = APIType.integer; + APISchemaObject.boolean() : type = APIType.boolean; + APISchemaObject.map({ + APIType? ofType, + APISchemaObject? ofSchema, + bool any = false, + }) : type = APIType.object { + if (ofType != null) { + additionalPropertySchema = APISchemaObject()..type = ofType; + } else if (ofSchema != null) { + additionalPropertySchema = ofSchema; + } else if (any) { + } else { + throw ArgumentError( + "Invalid 'APISchemaObject.map' with neither 'ofType', 'any' or 'ofSchema' specified.", + ); + } + } + APISchemaObject.array({APIType? ofType, APISchemaObject? ofSchema}) + : type = APIType.array { + if (ofType != null) { + items = APISchemaObject()..type = ofType; + } else if (ofSchema != null) { + items = ofSchema; + } else { + throw ArgumentError( + "Invalid 'APISchemaObject.array' with neither 'ofType' or 'ofSchema' specified.", + ); + } + } + APISchemaObject.object(this.properties) : type = APIType.object; + APISchemaObject.file({bool isBase64Encoded = false}) + : type = APIType.string, + format = isBase64Encoded ? "byte" : "binary"; + + APISchemaObject.freeForm() + : type = APIType.object, + additionalPropertyPolicy = APISchemaAdditionalPropertyPolicy.freeForm; + + /// A title for the object. + String? title; + + /// The value of "maximum" MUST be a number, representing an upper limit + /// for a numeric instance. + /// + /// If the instance is a number, then this keyword validates if + /// "exclusiveMaximum" is true and instance is less than the provided + /// value, or else if the instance is less than or exactly equal to the + /// provided value. + num? maximum; + + /// The value of "exclusiveMaximum" MUST be a boolean, representing + /// whether the limit in "maximum" is exclusive or not. + /// + /// An undefined value is the same as false. + /// + /// If "exclusiveMaximum" is true, then a numeric instance SHOULD NOT be + /// equal to the value specified in "maximum". If "exclusiveMaximum" is + /// false (or not specified), then a numeric instance MAY be equal to the + /// value of "maximum". + bool? exclusiveMaximum; + + /// The value of "minimum" MUST be a number, representing a lower limit + /// for a numeric instance. + + /// If the instance is a number, then this keyword validates if + /// "exclusiveMinimum" is true and instance is greater than the provided + /// value, or else if the instance is greater than or exactly equal to + /// the provided value. + num? minimum; + + /// The value of "exclusiveMinimum" MUST be a boolean, representing + /// whether the limit in "minimum" is exclusive or not. An undefined + /// value is the same as false. + + /// If "exclusiveMinimum" is true, then a numeric instance SHOULD NOT be + /// equal to the value specified in "minimum". If "exclusiveMinimum" is + /// false (or not specified), then a numeric instance MAY be equal to the + /// value of "minimum". + bool? exclusiveMinimum; + + /// The value of this keyword MUST be a non-negative integer. + /// + /// The value of this keyword MUST be an integer. This integer MUST be + /// greater than, or equal to, 0. + /// + /// A string instance is valid against this keyword if its length is less + /// than, or equal to, the value of this keyword. + /// + /// The length of a string instance is defined as the number of its + /// characters as defined by RFC 7159 [RFC7159]. + int? maxLength; + + /// A string instance is valid against this keyword if its length is + /// greater than, or equal to, the value of this keyword. + /// + /// The length of a string instance is defined as the number of its + /// characters as defined by RFC 7159 [RFC7159]. + /// + /// The value of this keyword MUST be an integer. This integer MUST be + /// greater than, or equal to, 0. + /// + /// "minLength", if absent, may be considered as being present with + /// integer value 0. + int? minLength; + + /// The value of this keyword MUST be a string. This string SHOULD be a + /// valid regular expression, according to the ECMA 262 regular + /// expression dialect. + /// + /// A string instance is considered valid if the regular expression + /// matches the instance successfully. Recall: regular expressions are + /// not implicitly anchored. + String? pattern; + + /// The value of this keyword MUST be an integer. This integer MUST be + /// greater than, or equal to, 0. + /// + /// An array instance is valid against "maxItems" if its size is less + /// than, or equal to, the value of this keyword. + int? maxItems; + + /// The value of this keyword MUST be an integer. This integer MUST be + /// greater than, or equal to, 0. + /// + /// An array instance is valid against "minItems" if its size is greater + /// than, or equal to, the value of this keyword. + /// + /// If this keyword is not present, it may be considered present with a + /// value of 0. + int? minItems; + + /// The value of this keyword MUST be a boolean. + /// + /// 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. + + /// If not present, this keyword may be considered present with boolean + /// value false. + bool? uniqueItems; + + /// The value of "multipleOf" MUST be a number, strictly greater than 0. + + /// A numeric instance is only valid if division by this keyword's value + /// results in an integer. + num? multipleOf; + + /// The value of this keyword MUST be an integer. This integer MUST be + /// greater than, or equal to, 0. + /// + /// An object instance is valid against "maxProperties" if its number of + /// properties is less than, or equal to, the value of this keyword. + int? maxProperties; + + /// The value of this keyword MUST be an integer. This integer MUST be + /// greater than, or equal to, 0. + /// + /// An object instance is valid against "minProperties" if its number of + /// properties is greater than, or equal to, the value of this keyword. + /// + /// If this keyword is not present, it may be considered present with a + /// value of 0. + int? minProperties; + + /// The value of this keyword MUST be an array. This array MUST have at + /// least one element. Elements of this array MUST be strings, and MUST + /// be unique. + /// + /// An object instance is valid against this keyword if its property set + /// contains all elements in this keyword's array value. + List? isRequired; + + /// The value of this keyword MUST be an array. This array SHOULD have + /// at least one element. Elements in the array SHOULD be unique. + /// + /// Elements in the array MAY be of any type, including null. + /// + /// An instance validates successfully against this keyword if its value + /// is equal to one of the elements in this keyword's array value. + List? enumerated; + + /* Modified JSON Schema for OpenAPI */ + + APIType? type; + List? allOf; + List? anyOf; + List? oneOf; + APISchemaObject? not; + + APISchemaObject? items; + Map? properties; + APISchemaObject? additionalPropertySchema; + APISchemaAdditionalPropertyPolicy? additionalPropertyPolicy; + + String? description; + String? format; + dynamic defaultValue; + + bool? get isNullable => _nullable ?? false; + + set isNullable(bool? n) { + _nullable = n; + } + + // APIDiscriminator discriminator; + + bool? get isReadOnly => _readOnly ?? false; + + set isReadOnly(bool? n) { + _readOnly = n; + } + + bool? get isWriteOnly => _writeOnly ?? false; + + set isWriteOnly(bool? n) { + _writeOnly = n; + } + + bool? _nullable; + bool? _readOnly; + bool? _writeOnly; + bool? deprecated; + + @override + Map get castMap => + {"required": const cast.List(cast.string)}; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + title = object.decode("title"); + maximum = object.decode("maximum"); + exclusiveMaximum = object.decode("exclusiveMaximum"); + minimum = object.decode("minimum"); + exclusiveMinimum = object.decode("exclusiveMinimum"); + maxLength = object.decode("maxLength"); + minLength = object.decode("minLength"); + pattern = object.decode("pattern"); + maxItems = object.decode("maxItems"); + minItems = object.decode("minItems"); + uniqueItems = object.decode("uniqueItems"); + multipleOf = object.decode("multipleOf"); + enumerated = object.decode("enum"); + minProperties = object.decode("minProperties"); + maxProperties = object.decode("maxProperties"); + isRequired = object.decode("required"); + + // + + type = APITypeCodec.decode(object.decode("type")); + allOf = object.decodeObjects("allOf", () => APISchemaObject()); + anyOf = object.decodeObjects("anyOf", () => APISchemaObject()); + oneOf = object.decodeObjects("oneOf", () => APISchemaObject()); + not = object.decodeObject("not", () => APISchemaObject()); + + items = object.decodeObject("items", () => APISchemaObject()); + properties = object.decodeObjectMap("properties", () => APISchemaObject()); + + final addlProps = object["additionalProperties"]; + if (addlProps is bool) { + if (addlProps) { + additionalPropertyPolicy = APISchemaAdditionalPropertyPolicy.freeForm; + } else { + additionalPropertyPolicy = APISchemaAdditionalPropertyPolicy.disallowed; + } + } else if (addlProps is KeyedArchive && addlProps.isEmpty) { + additionalPropertyPolicy = APISchemaAdditionalPropertyPolicy.freeForm; + } else { + additionalPropertyPolicy = APISchemaAdditionalPropertyPolicy.restricted; + additionalPropertySchema = + object.decodeObject("additionalProperties", () => APISchemaObject()); + } + + description = object.decode("description"); + format = object.decode("format"); + defaultValue = object.decode("default"); + + _nullable = object.decode("nullable"); + _readOnly = object.decode("readOnly"); + _writeOnly = object.decode("writeOnly"); + deprecated = object.decode("deprecated"); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encode("title", title); + object.encode("maximum", maximum); + object.encode("exclusiveMaximum", exclusiveMaximum); + object.encode("minimum", minimum); + object.encode("exclusiveMinimum", exclusiveMinimum); + object.encode("maxLength", maxLength); + object.encode("minLength", minLength); + object.encode("pattern", pattern); + object.encode("maxItems", maxItems); + object.encode("minItems", minItems); + object.encode("uniqueItems", uniqueItems); + object.encode("multipleOf", multipleOf); + object.encode("enum", enumerated); + object.encode("minProperties", minProperties); + object.encode("maxProperties", maxProperties); + object.encode("required", isRequired); + + // + + object.encode("type", APITypeCodec.encode(type)); + object.encodeObjects("allOf", allOf); + object.encodeObjects("anyOf", anyOf); + object.encodeObjects("oneOf", oneOf); + object.encodeObject("not", not); + + object.encodeObject("items", items); + if (additionalPropertyPolicy != null || additionalPropertySchema != null) { + if (additionalPropertyPolicy == + APISchemaAdditionalPropertyPolicy.disallowed) { + object.encode("additionalProperties", false); + } else if (additionalPropertyPolicy == + APISchemaAdditionalPropertyPolicy.freeForm) { + object.encode("additionalProperties", true); + } else { + object.encodeObject("additionalProperties", additionalPropertySchema); + } + } + object.encodeObjectMap("properties", properties); + + object.encode("description", description); + object.encode("format", format); + object.encode("default", defaultValue); + + object.encode("nullable", _nullable); + object.encode("readOnly", _readOnly); + object.encode("writeOnly", _writeOnly); + object.encode("deprecated", deprecated); + } +} diff --git a/packages/openapi/lib/src/v3/security.dart b/packages/openapi/lib/src/v3/security.dart index 651786d..f424c05 100644 --- a/packages/openapi/lib/src/v3/security.dart +++ b/packages/openapi/lib/src/v3/security.dart @@ -5,4 +5,322 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; +import 'package:protevus_openapi/v3.dart'; + +enum APISecuritySchemeType { apiKey, http, oauth2, openID } + +class APISecuritySchemeTypeCodec { + static APISecuritySchemeType? decode(String? type) { + switch (type) { + case "apiKey": + return APISecuritySchemeType.apiKey; + case "http": + return APISecuritySchemeType.http; + case "oauth2": + return APISecuritySchemeType.oauth2; + case "openID": + return APISecuritySchemeType.openID; + default: + return null; + } + } + + static String? encode(APISecuritySchemeType? type) { + switch (type) { + case APISecuritySchemeType.apiKey: + return "apiKey"; + case APISecuritySchemeType.http: + return "http"; + case APISecuritySchemeType.oauth2: + return "oauth2"; + case APISecuritySchemeType.openID: + return "openID"; + default: + return null; + } + } +} + +/// Defines a security scheme that can be used by the operations. +/// +/// Supported schemes are HTTP authentication, an API key (either as a header or as a query parameter), OAuth2's common flows (implicit, password, application and access code) as defined in RFC6749, and OpenID Connect Discovery. +class APISecurityScheme extends APIObject { + APISecurityScheme(); + APISecurityScheme.empty(); + + APISecurityScheme.http(this.scheme) : type = APISecuritySchemeType.http; + + APISecurityScheme.apiKey(this.name, this.location) + : type = APISecuritySchemeType.apiKey; + + APISecurityScheme.oauth2(this.flows) : type = APISecuritySchemeType.oauth2; + + APISecurityScheme.openID(this.connectURL) + : type = APISecuritySchemeType.openID; + + /// The type of the security scheme. + /// + /// REQUIRED. Valid values are "apiKey", "http", "oauth2", "openIdConnect". + APISecuritySchemeType? type; + + /// A short description for security scheme. + /// CommonMark syntax MAY be used for rich text representation. + String? description; + + /// The name of the header, query or cookie parameter to be used. + /// + /// For apiKey only. REQUIRED if so. + String? name; + + /// The location of the API key. + /// + /// Valid values are "query", "header" or "cookie". + /// + /// For apiKey only. REQUIRED if so. + APIParameterLocation? location; + + /// The name of the HTTP Authorization scheme to be used in the Authorization header as defined in RFC7235. + /// + /// For http only. REQUIRED if so. + String? scheme; + + /// A hint to the client to identify how the bearer token is formatted. + /// + /// Bearer tokens are usually generated by an authorization server, so this information is primarily for documentation purposes. + /// + /// For http only. + String? format; + + /// An object containing configuration information for the flow types supported. + /// + /// Fixed keys are implicit, password, clientCredentials and authorizationCode. + /// + /// For oauth2 only. REQUIRED if so. + Map? flows; + + /// OpenId Connect URL to discover OAuth2 configuration values. + /// + /// This MUST be in the form of a URL. + /// + /// For openID only. REQUIRED if so. + Uri? connectURL; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + type = APISecuritySchemeTypeCodec.decode(object.decode("type")); + description = object.decode("description"); + + switch (type) { + case APISecuritySchemeType.apiKey: + { + name = object.decode("name"); + location = APIParameterLocationCodec.decode(object.decode("in")); + } + break; + case APISecuritySchemeType.oauth2: + { + flows = object.decodeObjectMap( + "flows", + () => APISecuritySchemeOAuth2Flow.empty(), + ); + } + break; + case APISecuritySchemeType.http: + { + scheme = object.decode("scheme"); + format = object.decode("bearerFormat"); + } + break; + case APISecuritySchemeType.openID: + { + connectURL = object.decode("openIdConnectUrl"); + } + break; + default: + throw ArgumentError( + "APISecurityScheme must have non-null values for: 'type'.", + ); + } + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + if (type == null) { + throw ArgumentError( + "APISecurityScheme must have non-null values for: 'type'.", + ); + } + + object.encode("type", APISecuritySchemeTypeCodec.encode(type)); + object.encode("description", description); + + switch (type) { + case APISecuritySchemeType.apiKey: + { + if (name == null || location == null) { + throw ArgumentError( + "APISecurityScheme with 'apiKey' type must have non-null values for: 'name', 'location'.", + ); + } + + object.encode("name", name); + object.encode("in", APIParameterLocationCodec.encode(location)); + } + break; + case APISecuritySchemeType.oauth2: + { + if (flows == null) { + throw ArgumentError( + "APISecurityScheme with 'oauth2' type must have non-null values for: 'flows'.", + ); + } + + object.encodeObjectMap("flows", flows); + } + break; + case APISecuritySchemeType.http: + { + if (scheme == null) { + throw ArgumentError( + "APISecurityScheme with 'http' type must have non-null values for: 'scheme'.", + ); + } + + object.encode("scheme", scheme); + object.encode("bearerFormat", format); + } + break; + case APISecuritySchemeType.openID: + { + if (connectURL == null) { + throw ArgumentError( + "APISecurityScheme with 'openID' type must have non-null values for: 'connectURL'.", + ); + } + object.encode("openIdConnectUrl", connectURL); + } + break; + default: + throw ArgumentError( + "APISecurityScheme must have non-null values for: 'type'.", + ); + } + } +} + +/// Allows configuration of the supported OAuth Flows. +class APISecuritySchemeOAuth2Flow extends APIObject { + APISecuritySchemeOAuth2Flow.empty(); + APISecuritySchemeOAuth2Flow.code( + this.authorizationURL, + this.tokenURL, + this.refreshURL, + this.scopes, + ); + APISecuritySchemeOAuth2Flow.implicit( + this.authorizationURL, + this.refreshURL, + this.scopes, + ); + APISecuritySchemeOAuth2Flow.password( + this.tokenURL, + this.refreshURL, + this.scopes, + ); + APISecuritySchemeOAuth2Flow.client( + this.tokenURL, + this.refreshURL, + this.scopes, + ); + + /// The authorization URL to be used for this flow. + /// + /// REQUIRED. This MUST be in the form of a URL. + Uri? authorizationURL; + + /// The token URL to be used for this flow. + /// + /// REQUIRED. This MUST be in the form of a URL. + Uri? tokenURL; + + /// The URL to be used for obtaining refresh tokens. + /// + /// This MUST be in the form of a URL. + Uri? refreshURL; + + /// The available scopes for the OAuth2 security scheme. + /// + /// REQUIRED. A map between the scope name and a short description for it. + Map? scopes; + + @override + void encode(KeyedArchive object) { + super.encode(object); + + object.encode("authorizationUrl", authorizationURL); + object.encode("tokenUrl", tokenURL); + object.encode("refreshUrl", refreshURL); + object.encode("scopes", scopes); + } + + @override + void decode(KeyedArchive object) { + super.decode(object); + + authorizationURL = object.decode("authorizationUrl"); + + tokenURL = object.decode("tokenUrl"); + refreshURL = object.decode("refreshUrl"); + scopes = object.decode>("scopes"); + } +} + +/// Lists the required security schemes to execute an operation. +/// +/// The name used for each property MUST correspond to a security scheme declared in [APIComponents.securitySchemes]. + +/// [APISecurityRequirement] that contain multiple schemes require that all schemes MUST be satisfied for a request to be authorized. This enables support for scenarios where multiple query parameters or HTTP headers are required to convey security information. + +/// When a list of [APISecurityRequirement] is defined on the [APIDocument] or [APIOperation], only one of [APISecurityRequirement] in the list needs to be satisfied to authorize the request. +class APISecurityRequirement extends APIObject { + APISecurityRequirement(this.requirements); + APISecurityRequirement.empty(); + + /// Each name MUST correspond to a security scheme which is declared in [APIComponents.securitySchemes]. + /// + /// If the security scheme is of type [APISecuritySchemeType.oauth2] or [APISecuritySchemeType.openID], then the value is a list of scope names required for the execution. For other security scheme types, the array MUST be empty. + Map>? requirements; + + @override + void encode(KeyedArchive object) { + super.encode(object); + + if (requirements != null) { + requirements!.forEach((key, value) { + object.encode(key, value); + }); + } + } + + @override + void decode(KeyedArchive object) { + super.decode(object); + + for (final key in object.keys) { + final decoded = object.decode>(key); + if (decoded != null) { + final req = List.from(decoded); + requirements ??= >{}; + requirements![key] = req; + } + } + } +} diff --git a/packages/openapi/lib/src/v3/server.dart b/packages/openapi/lib/src/v3/server.dart index 651786d..9e65ae1 100644 --- a/packages/openapi/lib/src/v3/server.dart +++ b/packages/openapi/lib/src/v3/server.dart @@ -5,4 +5,103 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +import 'package:protevus_typeforge/codable.dart'; +import 'package:protevus_openapi/object.dart'; + +/// An object representing a Server. +class APIServerDescription extends APIObject { + APIServerDescription(this.url, {this.description, this.variables}); + + APIServerDescription.empty(); + + /// A URL to the target host. + /// + /// REQUIRED. This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where the OpenAPI document is being served. Variable substitutions will be made when a variable is named in {brackets}. + Uri? url; + + /// An optional string describing the host designated by the URL. + /// + /// CommonMark syntax MAY be used for rich text representation. + String? description; + + /// A map between a variable name and its value. + /// + /// The value is used for substitution in the server's URL template. + Map? variables; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + url = object.decode("url"); + description = object.decode("description"); + variables = + object.decodeObjectMap("variables", () => APIServerVariable.empty()); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + if (url == null) { + throw ArgumentError( + "APIServerDescription must have non-null values for: 'url'.", + ); + } + + object.encode("url", url); + object.encode("description", description); + object.encodeObjectMap("variables", variables); + } +} + +/// An object representing a Server Variable for server URL template substitution. +class APIServerVariable extends APIObject { + APIServerVariable( + this.defaultValue, { + this.availableValues, + this.description, + }); + + APIServerVariable.empty(); + + /// An enumeration of string values to be used if the substitution options are from a limited set. + List? availableValues; + + /// The default value to use for substitution, and to send, if an alternate value is not supplied. + /// + /// REQUIRED. Unlike the Schema Object's default, this value MUST be provided by the consumer. + String? defaultValue; + + /// An optional description for the server variable. + /// + /// CommonMark syntax MAY be used for rich text representation. + String? description; + + @override + void decode(KeyedArchive object) { + super.decode(object); + + final enumMap = object.decode("enum") as List; + availableValues = List.from(enumMap); + defaultValue = object.decode("default"); + description = object.decode("description"); + } + + @override + void encode(KeyedArchive object) { + super.encode(object); + + if (defaultValue == null) { + throw ArgumentError( + "APIServerVariable must have non-null values for: 'defaultValue'.", + ); + } + + object.encode("enum", availableValues); + object.encode("default", defaultValue); + object.encode("description", description); + } +} diff --git a/packages/openapi/lib/src/v3/types.dart b/packages/openapi/lib/src/v3/types.dart index 651786d..93bf8b6 100644 --- a/packages/openapi/lib/src/v3/types.dart +++ b/packages/openapi/lib/src/v3/types.dart @@ -5,4 +5,46 @@ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. - */ \ No newline at end of file + */ + +enum APIType { string, number, integer, boolean, array, object } + +class APITypeCodec { + static APIType? decode(String? type) { + switch (type) { + case "string": + return APIType.string; + case "number": + return APIType.number; + case "integer": + return APIType.integer; + case "boolean": + return APIType.boolean; + case "array": + return APIType.array; + case "object": + return APIType.object; + default: + return null; + } + } + + static String? encode(APIType? type) { + switch (type) { + case APIType.string: + return "string"; + case APIType.number: + return "number"; + case APIType.integer: + return "integer"; + case APIType.boolean: + return "boolean"; + case APIType.array: + return "array"; + case APIType.object: + return "object"; + default: + return null; + } + } +} diff --git a/packages/openapi/lib/util.dart b/packages/openapi/lib/util.dart new file mode 100644 index 0000000..52ba3a0 --- /dev/null +++ b/packages/openapi/lib/util.dart @@ -0,0 +1,22 @@ +/* + * This file is part of the Protevus Platform. + * + * (C) Protevus + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +/// Utility library for the Protevus OpenAPI package. +/// +/// This library exports helper functions for working with lists and maps +/// from the Protevus OpenAPI package. It provides convenient access to +/// utility functions that can be used across the application. +/// +/// Exports: +/// - list_helper.dart: Contains functions for list manipulation. +/// - map_helper.dart: Contains functions for map manipulation. +library util; + +export 'package:protevus_openapi/src/util/list_helper.dart'; +export 'package:protevus_openapi/src/util/map_helper.dart'; diff --git a/packages/openapi/lib/v2.dart b/packages/openapi/lib/v2.dart index 250f2fe..d357395 100644 --- a/packages/openapi/lib/v2.dart +++ b/packages/openapi/lib/v2.dart @@ -7,4 +7,20 @@ * file that was distributed with this source code. */ -library; +/// This library exports various components of the Protevus OpenAPI v2 specification. +/// It provides access to classes and utilities for working with OpenAPI v2 documents, +/// including document structure, headers, metadata, operations, parameters, paths, +/// responses, schemas, security definitions, and common types used throughout the API. +library v2; + +export 'package:protevus_openapi/src/v2/document.dart'; +export 'package:protevus_openapi/src/v2/header.dart'; +export 'package:protevus_openapi/src/v2/metadata.dart'; +export 'package:protevus_openapi/src/v2/operation.dart'; +export 'package:protevus_openapi/src/v2/parameter.dart'; +export 'package:protevus_openapi/src/v2/path.dart'; +export 'package:protevus_openapi/src/v2/property.dart'; +export 'package:protevus_openapi/src/v2/response.dart'; +export 'package:protevus_openapi/src/v2/schema.dart'; +export 'package:protevus_openapi/src/v2/security.dart'; +export 'package:protevus_openapi/src/v2/types.dart'; diff --git a/packages/openapi/lib/v3.dart b/packages/openapi/lib/v3.dart index 250f2fe..9619ee4 100644 --- a/packages/openapi/lib/v3.dart +++ b/packages/openapi/lib/v3.dart @@ -7,4 +7,30 @@ * file that was distributed with this source code. */ -library; +/// This library exports various components of the OpenAPI v3 specification. +/// It provides access to essential classes and structures used for defining +/// and working with OpenAPI v3 documents, including callbacks, components, +/// document structure, encodings, headers, media types, metadata, operations, +/// parameters, paths, request bodies, responses, schemas, security definitions, +/// servers, and other related types. +/// +/// By importing this library, users can access all the necessary elements +/// to create, parse, and manipulate OpenAPI v3 specifications in their Dart projects. +library v3; + +export 'package:protevus_openapi/src/v3/callback.dart'; +export 'package:protevus_openapi/src/v3/components.dart'; +export 'package:protevus_openapi/src/v3/document.dart'; +export 'package:protevus_openapi/src/v3/encoding.dart'; +export 'package:protevus_openapi/src/v3/header.dart'; +export 'package:protevus_openapi/src/v3/media_type.dart'; +export 'package:protevus_openapi/src/v3/metadata.dart'; +export 'package:protevus_openapi/src/v3/operation.dart'; +export 'package:protevus_openapi/src/v3/parameter.dart'; +export 'package:protevus_openapi/src/v3/path.dart'; +export 'package:protevus_openapi/src/v3/request_body.dart'; +export 'package:protevus_openapi/src/v3/response.dart'; +export 'package:protevus_openapi/src/v3/schema.dart'; +export 'package:protevus_openapi/src/v3/security.dart'; +export 'package:protevus_openapi/src/v3/server.dart'; +export 'package:protevus_openapi/src/v3/types.dart';