Fix generated spec lint warnings (#12553)

* Fix generated spec lint warnings

* (fix): infer item types from JSON-string examples and wrap oneOf in allOf
This commit is contained in:
Chirag Aggarwal authored and GitHub committed 2026-06-10 12:04:46 +05:30
1 parent cb6ab80218
commit f63a1d53b6
4 files changed
+373 -16

No files matched your search

+54
View File
@@ -101,6 +101,60 @@ abstract class Format
return $this->params[$key] ?? $default;
}
/**
* @return array<string, mixed>
*/
protected function getArrayItemsSchema(mixed $example): array
{
if (\is_string($example)) {
$decoded = \json_decode($example, true);
if (\is_array($decoded)) {
$example = $decoded;
}
}
if (!\is_array($example) || empty($example)) {
return ['type' => 'object'];
}
foreach ($example as $item) {
if ($item === null) {
continue;
}
if (\is_array($item)) {
if (!\array_is_list($item)) {
return [
'type' => 'object',
'additionalProperties' => true,
];
}
return [
'type' => 'array',
'items' => $this->getArrayItemsSchema($item),
];
}
if (\is_int($item) || \is_float($item)) {
return [
'type' => 'number',
'format' => 'double',
];
}
return [
'type' => match (\gettype($item)) {
'boolean' => 'boolean',
'string' => 'string',
default => 'object',
},
];
}
return ['type' => 'object'];
}
/**
* Set Services.
*
@@ -497,11 +497,36 @@ class OpenAPI3 extends Format
case \Utopia\Database\Validator\Spatial::class:
/** @var Spatial $validator */
$node['schema']['type'] = 'array';
$node['schema']['items'] = [
'oneOf' => [
['type' => 'array']
]
];
$node['schema']['items'] = match ($validator->getSpatialType()) {
Database::VAR_POINT => [
'type' => 'number',
'format' => 'double',
],
Database::VAR_LINESTRING => [
'type' => 'array',
'items' => [
'type' => 'number',
'format' => 'double',
],
],
Database::VAR_POLYGON => [
'type' => 'array',
'items' => [
'type' => 'array',
'items' => [
'type' => 'number',
'format' => 'double',
],
],
],
default => [
'type' => 'array',
'items' => [
'type' => 'number',
'format' => 'double',
],
],
};
$node['schema']['x-example'] = ($param['example'] ?? '') ?: match ($validator->getSpatialType()) {
Database::VAR_POINT => '[1, 2]',
Database::VAR_LINESTRING => '[[1, 2], [3, 4], [5, 6]]',
@@ -777,7 +802,7 @@ class OpenAPI3 extends Format
if ($isPathParam) { // Param is in URL path (directly or through alias)
$node['in'] = 'path';
$temp['parameters'][] = $node;
} elseif ($route->getMethod() == 'GET') { // Param is in query
} elseif (\in_array($route->getMethod(), ['GET', 'DELETE'], true)) { // Param is in query
$node['in'] = 'query';
$temp['parameters'][] = $node;
} else { // Param is in payload
@@ -852,7 +877,7 @@ class OpenAPI3 extends Format
}
foreach ($this->models as $model) {
if (!in_array($model->getType(), $usedModels) && $model->getType() !== 'error') {
if (!in_array($model->getType(), $usedModels)) {
continue;
}
@@ -910,6 +935,7 @@ class OpenAPI3 extends Format
case 'array':
$type = 'array';
$items = $this->getArrayItemsSchema($rule['example'] ?? []);
break;
case 'integer':
@@ -1001,7 +1027,19 @@ class OpenAPI3 extends Format
}
}
if ($items) {
$output['components']['schemas'][$model->getType()]['properties'][$name]['items'] = $items;
if ($rule['array'] || $rule['type'] === 'array') {
$output['components']['schemas'][$model->getType()]['properties'][$name]['items'] = $items;
} else {
if (isset($items['$ref']) || isset($items['oneOf'])) {
$items = ['allOf' => [$items]];
}
/** @var array<string, mixed> $property */
$property = $output['components']['schemas'][$model->getType()]['properties'][$name];
$output['components']['schemas'][$model->getType()]['properties'][$name] = [
...$property,
...$items,
];
}
}
if ($rule['type'] === 'enum' && !empty($rule['enum'])) {
if ($rule['array']) {
@@ -479,11 +479,36 @@ class Swagger2 extends Format
case \Utopia\Database\Validator\Spatial::class:
/** @var Spatial $validator */
$node['type'] = 'array';
$node['schema']['items'] = [
'oneOf' => [
['type' => 'array']
]
];
$node['items'] = match ($validator->getSpatialType()) {
Database::VAR_POINT => [
'type' => 'number',
'format' => 'double',
],
Database::VAR_LINESTRING => [
'type' => 'array',
'items' => [
'type' => 'number',
'format' => 'double',
],
],
Database::VAR_POLYGON => [
'type' => 'array',
'items' => [
'type' => 'array',
'items' => [
'type' => 'number',
'format' => 'double',
],
],
],
default => [
'type' => 'array',
'items' => [
'type' => 'number',
'format' => 'double',
],
],
};
$node['x-example'] = ($param['example'] ?? '') ?: match ($validator->getSpatialType()) {
Database::VAR_POINT => '[1, 2]',
Database::VAR_LINESTRING => '[[1, 2], [3, 4], [5, 6]]',
@@ -737,7 +762,7 @@ class Swagger2 extends Format
if ($isPathParam) { // Param is in URL path (directly or through alias)
$node['in'] = 'path';
$temp['parameters'][] = $node;
} elseif ($route->getMethod() == 'GET') { // Param is in query
} elseif (\in_array($route->getMethod(), ['GET', 'DELETE'], true)) { // Param is in query
$node['in'] = 'query';
$temp['parameters'][] = $node;
} else { // Param is in payload
@@ -871,6 +896,7 @@ class Swagger2 extends Format
case 'array':
$type = 'array';
$items = $this->getArrayItemsSchema($rule['example'] ?? []);
break;
case 'integer':
@@ -925,7 +951,6 @@ class Swagger2 extends Format
}
} else {
$items = [
'type' => $type,
'$ref' => '#/definitions/' . $rule['type'],
];
}
@@ -978,7 +1003,19 @@ class Swagger2 extends Format
}
}
if ($items) {
$output['definitions'][$model->getType()]['properties'][$name]['items'] = $items;
if ($rule['array'] || $rule['type'] === 'array') {
$output['definitions'][$model->getType()]['properties'][$name]['items'] = $items;
} else {
if (isset($items['$ref'])) {
$items = ['allOf' => [$items]];
}
/** @var array<string, mixed> $property */
$property = $output['definitions'][$model->getType()]['properties'][$name];
$output['definitions'][$model->getType()]['properties'][$name] = [
...$property,
...$items,
];
}
}
if ($rule['type'] === 'enum' && !empty($rule['enum'])) {
if ($rule['array']) {
+228
View File
@@ -10,6 +10,15 @@ use Appwrite\SDK\Specification\Format\Swagger2;
use Appwrite\SDK\Specification\Validator\PasswordFormat;
use Appwrite\Utopia\Database\Validator\CustomId;
use Appwrite\Utopia\Response;
use Appwrite\Utopia\Response\Model\AlgoArgon2;
use Appwrite\Utopia\Response\Model\AlgoBcrypt;
use Appwrite\Utopia\Response\Model\AlgoMd5;
use Appwrite\Utopia\Response\Model\AlgoPhpass;
use Appwrite\Utopia\Response\Model\AlgoScrypt;
use Appwrite\Utopia\Response\Model\AlgoScryptModified;
use Appwrite\Utopia\Response\Model\AlgoSha;
use Appwrite\Utopia\Response\Model\AttributeLine;
use Appwrite\Utopia\Response\Model\Error as ErrorModel;
use Appwrite\Utopia\Response\Model\HealthStatus;
use Appwrite\Utopia\Response\Model\PlatformAndroid;
use Appwrite\Utopia\Response\Model\PlatformApple;
@@ -17,8 +26,13 @@ use Appwrite\Utopia\Response\Model\PlatformLinux;
use Appwrite\Utopia\Response\Model\PlatformList;
use Appwrite\Utopia\Response\Model\PlatformWeb;
use Appwrite\Utopia\Response\Model\PlatformWindows;
use Appwrite\Utopia\Response\Model\Preferences;
use Appwrite\Utopia\Response\Model\Team;
use Appwrite\Utopia\Response\Model\User;
use Appwrite\Utopia\Response\Model\Webhook;
use PHPUnit\Framework\TestCase;
use Utopia\Database\Database;
use Utopia\Database\Validator\Spatial;
use Utopia\DI\Container;
use Utopia\Http\Route;
use Utopia\Validator\Nullable;
@@ -40,6 +54,11 @@ class TestFormat extends Format
{
return $this->getRequestParameterConfig($optional, $nullable, $default, $methodName, $paramName);
}
public function arrayItemsSchema(mixed $example): array
{
return $this->getArrayItemsSchema($example);
}
}
final class FormatTest extends TestCase
@@ -113,6 +132,215 @@ final class FormatTest extends TestCase
);
}
public function testDeleteRouteOptionalParamsAreQueryParams(): void
{
Method::$processed = [];
Method::$errors = [];
$route = (new Route('DELETE', '/v1/tests/:testId'))
->desc('Delete test')
->label('sdk', new Method(
namespace: 'test',
group: null,
name: 'deleteTest',
description: 'Delete test.',
auth: [],
responses: [],
))
->param('testId', '', new Text(256), 'Test ID.')
->param('transactionId', null, new Nullable(new Text(256)), 'Transaction ID.', true);
$openApi = (new OpenAPI3(new Container(), [], [$route], [], [], 0, 'console'))->parse();
$swagger = (new Swagger2(new Container(), [], [$route], [], [], 0, 'console'))->parse();
$this->assertArrayNotHasKey('requestBody', $openApi['paths']['/tests/{testId}']['delete']);
$this->assertCount(2, $openApi['paths']['/tests/{testId}']['delete']['parameters']);
$this->assertSame('path', $openApi['paths']['/tests/{testId}']['delete']['parameters'][0]['in']);
$this->assertSame('transactionId', $openApi['paths']['/tests/{testId}']['delete']['parameters'][1]['name']);
$this->assertSame('query', $openApi['paths']['/tests/{testId}']['delete']['parameters'][1]['in']);
$this->assertCount(2, $swagger['paths']['/tests/{testId}']['delete']['parameters']);
$this->assertSame('path', $swagger['paths']['/tests/{testId}']['delete']['parameters'][0]['in']);
$this->assertSame('transactionId', $swagger['paths']['/tests/{testId}']['delete']['parameters'][1]['name']);
$this->assertSame('query', $swagger['paths']['/tests/{testId}']['delete']['parameters'][1]['in']);
}
public function testModelReferencesDoNotEmitItemsOnObjectProperties(): void
{
Method::$processed = [];
Method::$errors = [];
$route = (new Route('GET', '/v1/tests/team'))
->desc('Get test')
->label('sdk', new Method(
namespace: 'test',
group: null,
name: 'getTeamTest',
description: 'Get test.',
auth: [],
responses: [
new SDKResponse(
code: 200,
model: Response::MODEL_TEAM,
),
],
));
$models = [
new Team(),
new Preferences(),
new ErrorModel(),
];
$openApi = (new OpenAPI3(new Container(), [], [$route], $models, [], 0, 'console'))->parse();
$swagger = (new Swagger2(new Container(), [], [$route], $models, [], 0, 'console'))->parse();
$openApiPrefs = $openApi['components']['schemas']['team']['properties']['prefs'];
$swaggerPrefs = $swagger['definitions']['team']['properties']['prefs'];
$this->assertArrayNotHasKey('items', $openApiPrefs);
$this->assertArrayNotHasKey('error', $openApi['components']['schemas']);
$this->assertSame('object', $openApiPrefs['type']);
$this->assertSame([['$ref' => '#/components/schemas/preferences']], $openApiPrefs['allOf']);
$this->assertArrayNotHasKey('items', $swaggerPrefs);
$this->assertArrayNotHasKey('error', $swagger['definitions']);
$this->assertSame('object', $swaggerPrefs['type']);
$this->assertSame([['$ref' => '#/definitions/preferences']], $swaggerPrefs['allOf']);
}
public function testArrayItemsSchemaInfersTypesFromJsonStringExamples(): void
{
$this->assertSame(
[
'type' => 'array',
'items' => [
'type' => 'number',
'format' => 'double',
],
],
$this->format->arrayItemsSchema('[[1,2],[3,4]]')
);
$this->assertSame(
[
'type' => 'object',
'additionalProperties' => true,
],
$this->format->arrayItemsSchema('[{"resource":"Database","id":"public"}]')
);
$this->assertSame(
['type' => 'string'],
$this->format->arrayItemsSchema('["topt", "email"]')
);
$this->assertSame(
['type' => 'object'],
$this->format->arrayItemsSchema('[SHARED_SECRET]')
);
}
public function testMultiTypePropertiesWrapOneOfInAllOf(): void
{
Method::$processed = [];
Method::$errors = [];
$route = (new Route('GET', '/v1/tests/user'))
->desc('Get test')
->label('sdk', new Method(
namespace: 'test',
group: null,
name: 'getUserTest',
description: 'Get test.',
auth: [],
responses: [
new SDKResponse(
code: 200,
model: Response::MODEL_USER,
),
],
));
$models = [
new User(),
new AlgoArgon2(),
new AlgoScrypt(),
new AlgoScryptModified(),
new AlgoBcrypt(),
new AlgoPhpass(),
new AlgoSha(),
new AlgoMd5(),
];
$openApi = (new OpenAPI3(new Container(), [], [$route], $models, [], 0, 'console'))->parse();
$swagger = (new Swagger2(new Container(), [], [$route], $models, [], 0, 'console'))->parse();
$openApiHashOptions = $openApi['components']['schemas']['user']['properties']['hashOptions'];
$swaggerHashOptions = $swagger['definitions']['user']['properties']['hashOptions'];
$this->assertSame('object', $openApiHashOptions['type']);
$this->assertArrayNotHasKey('items', $openApiHashOptions);
$this->assertArrayNotHasKey('oneOf', $openApiHashOptions);
$this->assertCount(1, $openApiHashOptions['allOf']);
$this->assertCount(7, $openApiHashOptions['allOf'][0]['oneOf']);
$this->assertSame(['$ref' => '#/components/schemas/algoArgon2'], $openApiHashOptions['allOf'][0]['oneOf'][0]);
$this->assertSame('object', $swaggerHashOptions['type']);
$this->assertArrayNotHasKey('items', $swaggerHashOptions);
$this->assertCount(7, $swaggerHashOptions['x-oneOf']);
$this->assertSame(['$ref' => '#/definitions/algoArgon2'], $swaggerHashOptions['x-oneOf'][0]);
}
public function testArraySchemasEmitItems(): void
{
Method::$processed = [];
Method::$errors = [];
$requestRoute = (new Route('POST', '/v1/tests/spatial'))
->desc('Create spatial test')
->label('sdk', new Method(
namespace: 'test',
group: null,
name: 'createSpatialTest',
description: 'Create spatial test.',
auth: [],
responses: [],
))
->param('default', null, new Nullable(new Spatial(Database::VAR_LINESTRING)), 'Default value.', true);
$modelRoute = (new Route('GET', '/v1/tests/spatial-model'))
->desc('Get spatial test')
->label('sdk', new Method(
namespace: 'test',
group: null,
name: 'getSpatialTest',
description: 'Get spatial test.',
auth: [],
responses: [
new SDKResponse(
code: 200,
model: Response::MODEL_ATTRIBUTE_LINE,
),
],
));
$openApi = (new OpenAPI3(new Container(), [], [$requestRoute, $modelRoute], [new AttributeLine()], [], 0, 'console'))->parse();
$swagger = (new Swagger2(new Container(), [], [$requestRoute, $modelRoute], [new AttributeLine()], [], 0, 'console'))->parse();
$openApiRequestDefault = $openApi['paths']['/tests/spatial']['post']['requestBody']['content']['application/json']['schema']['properties']['default'];
$swaggerRequestDefault = $swagger['paths']['/tests/spatial']['post']['parameters'][0]['schema']['properties']['default'];
$openApiModelDefault = $openApi['components']['schemas']['attributeLine']['properties']['default'];
$swaggerModelDefault = $swagger['definitions']['attributeLine']['properties']['default'];
foreach ([$openApiRequestDefault, $swaggerRequestDefault, $openApiModelDefault, $swaggerModelDefault] as $default) {
$this->assertSame('array', $default['type']);
$this->assertSame('array', $default['items']['type']);
$this->assertSame('number', $default['items']['items']['type']);
$this->assertSame('double', $default['items']['items']['format']);
}
}
public function testPasswordFormatMarksOnlyExplicitPasswordFields(): void
{
Method::$processed = [];