@povio/openapi-codegen-cli 3.2.0-rc.9 → 3.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{native-bindings-BTQGSGhU.mjs → generate.runner-BD9BbYIx.mjs} +184 -4
- package/dist/{generate.utils-CT-LA-gX.cjs → generate.utils-BqlgVd-i.cjs} +5 -5
- package/dist/{generateCodeFromOpenAPIDoc-iEa8YAUQ.cjs → generateCodeFromOpenAPIDoc-CkVgg5Zy.cjs} +64 -19
- package/dist/{generateCodeFromOpenAPIDoc--ufinTug.mjs → generateCodeFromOpenAPIDoc-idp1RVDa.mjs} +50 -10
- package/dist/generator.mjs +3 -4
- package/dist/{getDataFromOpenAPIDoc-D8w0QElH.mjs → getDataFromOpenAPIDoc-Cyrm3VKA.mjs} +16 -11
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/metro.cjs +2 -2
- package/dist/metro.mjs +2 -2
- package/dist/{native-rest-interceptor-CAWR8H5Y.mjs → native-rest-interceptor-Np4Ov54n.mjs} +15 -8
- package/dist/{native-rest-interceptor-Cz6saoq5.d.mts → native-rest-interceptor-PgziZt1f.d.mts} +4 -1
- package/dist/native.d.mts +1 -1
- package/dist/native.mjs +1 -1
- package/dist/openapi-codegen-native-darwin-arm64.node +0 -0
- package/dist/openapi-codegen-native-linux-x64.node +0 -0
- package/dist/openapi-codegen-native-win32-x64.node +0 -0
- package/dist/{openapi-codegen.runner-6Yth6QZC.mjs → openapi-codegen.runner-BZH4V6rq.mjs} +1 -2
- package/dist/{openapi-source.runner-BZ6ZLgRO.mjs → openapi-source.runner-DPUNTduQ.mjs} +7 -5
- package/dist/sh.mjs +9 -8
- package/dist/tiny.mjs +1 -1
- package/dist/vite.mjs +2 -2
- package/package.json +6 -6
- package/dist/generate.runner-D8AYuEFm.mjs +0 -184
|
@@ -1260,9 +1260,9 @@ function renderMediaUploadMutationBody({ resolver, endpointFunction, resolvedEnd
|
|
|
1260
1260
|
" let dataToSend: File | FormData = file;",
|
|
1261
1261
|
" if (method === \"post\") {",
|
|
1262
1262
|
" dataToSend = new FormData();",
|
|
1263
|
-
" if (uploadInstructions.fields) {",
|
|
1264
|
-
" for (const [key, value] of uploadInstructions.fields) {",
|
|
1265
|
-
" dataToSend.append(key, value);",
|
|
1263
|
+
" if (\"fields\" in uploadInstructions && uploadInstructions.fields) {",
|
|
1264
|
+
" for (const [key, value] of Object.entries(uploadInstructions.fields)) {",
|
|
1265
|
+
" dataToSend.append(key, String(value));",
|
|
1266
1266
|
" }",
|
|
1267
1267
|
" }",
|
|
1268
1268
|
" dataToSend.append(\"file\", file);",
|
|
@@ -1437,6 +1437,20 @@ function removeEmptyDirectories(root) {
|
|
|
1437
1437
|
removeIfEmpty(root);
|
|
1438
1438
|
}
|
|
1439
1439
|
//#endregion
|
|
1440
|
+
//#region src/generators/core/resolveConfig.ts
|
|
1441
|
+
function resolveConfig({ fileConfig = {}, params: { includeTags, excludeTags, inlineEndpointsExcludeModules, workspaceContext, ...options } }) {
|
|
1442
|
+
const resolvedConfig = deepMerge(DEFAULT_GENERATE_OPTIONS, fileConfig ?? {}, {
|
|
1443
|
+
...options,
|
|
1444
|
+
includeTags: includeTags?.split(","),
|
|
1445
|
+
excludeTags: excludeTags?.split(","),
|
|
1446
|
+
inlineEndpointsExcludeModules: inlineEndpointsExcludeModules?.split(","),
|
|
1447
|
+
workspaceContext: workspaceContext?.split(",")
|
|
1448
|
+
});
|
|
1449
|
+
resolvedConfig.checkAcl = resolvedConfig.acl && resolvedConfig.checkAcl;
|
|
1450
|
+
resolvedConfig.workspaceContext = Array.from(new Set((resolvedConfig.workspaceContext ?? []).map((value) => value.trim()).filter(Boolean)));
|
|
1451
|
+
return resolvedConfig;
|
|
1452
|
+
}
|
|
1453
|
+
//#endregion
|
|
1440
1454
|
//#region src/native/native-bindings.ts
|
|
1441
1455
|
let bindings;
|
|
1442
1456
|
let nativePath;
|
|
@@ -1477,4 +1491,170 @@ function compileNativeData(source, yaml, optionsJson) {
|
|
|
1477
1491
|
return getNativeBindings().compileData(source, yaml, optionsJson);
|
|
1478
1492
|
}
|
|
1479
1493
|
//#endregion
|
|
1480
|
-
|
|
1494
|
+
//#region src/native/generateFilesFromNativeOpenAPI.ts
|
|
1495
|
+
function generateFilesFromNativeOpenAPI(source, yaml, options) {
|
|
1496
|
+
if (!supportsCompleteNativeRender(options)) {
|
|
1497
|
+
if (process.env.OPENAPI_CODEGEN_REQUIRE_FULL_NATIVE === "1") throw new Error("The selected options are not supported by the full native renderer");
|
|
1498
|
+
return;
|
|
1499
|
+
}
|
|
1500
|
+
const nativeData = compileNativeData(source, yaml, JSON.stringify({
|
|
1501
|
+
...options,
|
|
1502
|
+
nativeCompact: true
|
|
1503
|
+
})).data;
|
|
1504
|
+
if (!nativeData.renderedComplete) {
|
|
1505
|
+
if (process.env.OPENAPI_CODEGEN_REQUIRE_FULL_NATIVE === "1") throw new Error("The selected options are not supported by the full native renderer");
|
|
1506
|
+
return;
|
|
1507
|
+
}
|
|
1508
|
+
const files = [];
|
|
1509
|
+
const taggedRenderers = options.modelsOnly ? [["models", nativeData.renderedModels]] : [
|
|
1510
|
+
["models", nativeData.renderedModels],
|
|
1511
|
+
["endpoints", nativeData.renderedEndpoints],
|
|
1512
|
+
["queries", nativeData.renderedQueries],
|
|
1513
|
+
...options.acl ? [["acl", nativeData.renderedAcl]] : []
|
|
1514
|
+
];
|
|
1515
|
+
for (const tag of nativeData.renderedTags) for (const [type, rendered] of taggedRenderers) {
|
|
1516
|
+
const content = rendered[tag];
|
|
1517
|
+
if (content) files.push(taggedFile(options, tag, type, content));
|
|
1518
|
+
}
|
|
1519
|
+
if (!options.modelsOnly) {
|
|
1520
|
+
if (options.acl && nativeData.renderedShared.appAcl) files.push(outputFile(options, "acl/app.ability.ts", nativeData.renderedShared.appAcl));
|
|
1521
|
+
if (options.mutationEffects && nativeData.renderedShared.queryModules) files.push(outputFile(options, "queryModules.ts", nativeData.renderedShared.queryModules));
|
|
1522
|
+
if (!options.restClientImportPath) files.push(outputFile(options, "app-rest-client.ts", `import { ${options.restClient === "native" ? "NativeRestClient" : "RestClient"} } from "@povio/openapi-codegen-cli${options.restClient === "native" ? "/native" : ""}";\n\nexport const AppRestClient = new ${options.restClient === "native" ? "NativeRestClient" : "RestClient"}({\n config: {\n baseURL: "${nativeData.baseUrl}"\n },\n});\n`));
|
|
1523
|
+
if (nativeData.renderedShared.domainErrors) files.push(outputFile(options, "domain-errors.ts", nativeData.renderedShared.domainErrors));
|
|
1524
|
+
}
|
|
1525
|
+
return files;
|
|
1526
|
+
}
|
|
1527
|
+
function supportsCompleteNativeRender(options) {
|
|
1528
|
+
return options.splitByTags && (options.modelsInCommon && options.tsNamespaces || !options.modelsInCommon && !options.tsNamespaces) && !options.inlineEndpoints && !options.builderConfigs && (options.workspaceContext?.length ?? 0) === 0;
|
|
1529
|
+
}
|
|
1530
|
+
function taggedFile(options, tag, type, content) {
|
|
1531
|
+
return outputFile(options, getTagFileName({
|
|
1532
|
+
tag,
|
|
1533
|
+
type,
|
|
1534
|
+
options
|
|
1535
|
+
}), content);
|
|
1536
|
+
}
|
|
1537
|
+
function outputFile(options, fileName, content) {
|
|
1538
|
+
return {
|
|
1539
|
+
fileName: getOutputFileName({
|
|
1540
|
+
output: options.output,
|
|
1541
|
+
fileName
|
|
1542
|
+
}),
|
|
1543
|
+
content
|
|
1544
|
+
};
|
|
1545
|
+
}
|
|
1546
|
+
//#endregion
|
|
1547
|
+
//#region src/generators/run/generate.runner.ts
|
|
1548
|
+
async function runGenerate({ fileConfig, params, formatGeneratedFile, profiler = new Profiler(process.env.OPENAPI_CODEGEN_PROFILE === "1") }) {
|
|
1549
|
+
const config = profiler.runSync("config.resolve", () => resolveConfig({
|
|
1550
|
+
fileConfig,
|
|
1551
|
+
params: params ?? {}
|
|
1552
|
+
}));
|
|
1553
|
+
const useNative = shouldUseNativeCodegen();
|
|
1554
|
+
const isJson = path.extname(new URL(config.input, "file://").pathname).toLowerCase() === ".json";
|
|
1555
|
+
const useRawNativeInput = useNative && (isJson || typeof Bun === "undefined");
|
|
1556
|
+
let nativeInput = useRawNativeInput ? await getRawOpenApiSource(config.input, profiler) : await getOpenApiSource(config.input, profiler);
|
|
1557
|
+
if (useNative && !useRawNativeInput) {
|
|
1558
|
+
const document = "document" in nativeInput ? nativeInput.document : void 0;
|
|
1559
|
+
nativeInput = {
|
|
1560
|
+
...nativeInput,
|
|
1561
|
+
source: profiler.runSync("openapi.serialize", () => JSON.stringify(document)),
|
|
1562
|
+
yaml: false
|
|
1563
|
+
};
|
|
1564
|
+
}
|
|
1565
|
+
const openApiDoc = "document" in nativeInput ? nativeInput.document : {};
|
|
1566
|
+
const outputExists = fs.existsSync(config.output);
|
|
1567
|
+
const filesData = await profiler.runAsync("generate.total", async () => {
|
|
1568
|
+
if (useNative) {
|
|
1569
|
+
const nativeFiles = generateFilesFromNativeOpenAPI(nativeInput.source, nativeInput.yaml, config);
|
|
1570
|
+
if (nativeFiles) return nativeFiles;
|
|
1571
|
+
}
|
|
1572
|
+
const { generateCodeFromOpenAPIDoc } = await import("./generateCodeFromOpenAPIDoc-idp1RVDa.mjs").then((n) => n.n);
|
|
1573
|
+
return generateCodeFromOpenAPIDoc(openApiDoc, config, profiler, {
|
|
1574
|
+
source: nativeInput.source,
|
|
1575
|
+
yaml: nativeInput.yaml
|
|
1576
|
+
});
|
|
1577
|
+
});
|
|
1578
|
+
if (config.clearOutput) profiler.runSync("files.removeStaleGenerated", () => {
|
|
1579
|
+
removeStaleGeneratedFiles({
|
|
1580
|
+
output: config.output,
|
|
1581
|
+
filesData,
|
|
1582
|
+
options: config
|
|
1583
|
+
});
|
|
1584
|
+
});
|
|
1585
|
+
await profiler.runAsync("files.write", async () => {
|
|
1586
|
+
await writeGenerateFileData(filesData, {
|
|
1587
|
+
formatGeneratedFile,
|
|
1588
|
+
skipExistingCheck: !outputExists
|
|
1589
|
+
});
|
|
1590
|
+
});
|
|
1591
|
+
return {
|
|
1592
|
+
skipped: false,
|
|
1593
|
+
config,
|
|
1594
|
+
stats: getGenerateStats(filesData, config)
|
|
1595
|
+
};
|
|
1596
|
+
}
|
|
1597
|
+
async function getOpenApiDoc(input, profiler = new Profiler(false)) {
|
|
1598
|
+
return (await getOpenApiSource(input, profiler)).document;
|
|
1599
|
+
}
|
|
1600
|
+
async function getOpenApiSource(input, profiler = new Profiler(false)) {
|
|
1601
|
+
const raw = await getRawOpenApiSource(input, profiler);
|
|
1602
|
+
const { source } = raw;
|
|
1603
|
+
const document = await profiler.runAsync("openapi.parse", () => parseOpenApiSource(input, source));
|
|
1604
|
+
return {
|
|
1605
|
+
...raw,
|
|
1606
|
+
document
|
|
1607
|
+
};
|
|
1608
|
+
}
|
|
1609
|
+
async function getRawOpenApiSource(input, profiler = new Profiler(false)) {
|
|
1610
|
+
return {
|
|
1611
|
+
source: await profiler.runAsync("openapi.read", () => readOpenApiSource(input)),
|
|
1612
|
+
yaml: path.extname(new URL(input, "file://").pathname).toLowerCase() !== ".json"
|
|
1613
|
+
};
|
|
1614
|
+
}
|
|
1615
|
+
async function readOpenApiSource(input) {
|
|
1616
|
+
if (/^https?:\/\//i.test(input)) {
|
|
1617
|
+
const response = await fetch(input);
|
|
1618
|
+
if (!response.ok) throw new Error(`Unable to load OpenAPI document: ${response.status} ${response.statusText}`);
|
|
1619
|
+
return response.text();
|
|
1620
|
+
}
|
|
1621
|
+
return fs.promises.readFile(input, "utf-8");
|
|
1622
|
+
}
|
|
1623
|
+
async function parseOpenApiSource(input, source) {
|
|
1624
|
+
try {
|
|
1625
|
+
return JSON.parse(source.charCodeAt(0) === 65279 ? source.slice(1) : source);
|
|
1626
|
+
} catch (error) {
|
|
1627
|
+
if (path.extname(new URL(input, "file://").pathname).toLowerCase() === ".json") throw error;
|
|
1628
|
+
if (typeof Bun !== "undefined") return Bun.YAML.parse(source);
|
|
1629
|
+
const { parse } = await import("yaml");
|
|
1630
|
+
return parse(source);
|
|
1631
|
+
}
|
|
1632
|
+
}
|
|
1633
|
+
function getGenerateStats(filesData, config) {
|
|
1634
|
+
const generatedFilesCount = filesData.length;
|
|
1635
|
+
if (generatedFilesCount === 0) return {
|
|
1636
|
+
generatedFilesCount,
|
|
1637
|
+
generatedModulesCount: 0
|
|
1638
|
+
};
|
|
1639
|
+
if (!config.splitByTags) return {
|
|
1640
|
+
generatedFilesCount,
|
|
1641
|
+
generatedModulesCount: 1
|
|
1642
|
+
};
|
|
1643
|
+
const moduleSuffixes = new Set(Object.values(config.configs).map((generateConfig) => generateConfig.outputFileNameSuffix).filter(Boolean));
|
|
1644
|
+
const modules = /* @__PURE__ */ new Set();
|
|
1645
|
+
for (const file of filesData) {
|
|
1646
|
+
const segments = path.relative(config.output, file.fileName).split(path.sep).filter(Boolean);
|
|
1647
|
+
if (segments.length < 2) continue;
|
|
1648
|
+
const moduleName = segments[0];
|
|
1649
|
+
const fileName = segments[segments.length - 1];
|
|
1650
|
+
if (!fileName.startsWith(`${moduleName}.`)) continue;
|
|
1651
|
+
const suffix = fileName.slice(moduleName.length + 1).replace(/\.tsx?$/, "");
|
|
1652
|
+
if (moduleSuffixes.has(suffix)) modules.add(moduleName);
|
|
1653
|
+
}
|
|
1654
|
+
return {
|
|
1655
|
+
generatedFilesCount,
|
|
1656
|
+
generatedModulesCount: modules.size
|
|
1657
|
+
};
|
|
1658
|
+
}
|
|
1659
|
+
//#endregion
|
|
1660
|
+
export { getImportedAbilityFunctionName as $, isPrimitiveType as $t, getEndpointsImports as A, NATIVE_RESPONSE_TYPE as An, APP_REST_CLIENT_NAME as At, getPrefetchInfiniteQueryName as B, getMostCommonAdjacentCombinationSplit as Bn, PACKAGE_IMPORT_PATH as Bt, getAppRestClientImportPath as C, ZOD_IMPORT as Cn, getParamZodSchemaName as Ct, getTagFileName as D, AXIOS_REQUEST_CONFIG_TYPE as Dn, isEnumZodSchema as Dt, getQueryTypesImportPath as E, AXIOS_REQUEST_CONFIG_NAME as En, getZodSchemaOperationName as Et, mergeImports as F, isTagIncluded as Fn, QUERY_MODULE_ENUM as Ft, getAbilityConditionType as G, getParameterEnumNames as Gt, getQueryName as H, removeWord as Hn, getNamespaceName as Ht, getImportedInfiniteQueryName as I, shouldInlineEndpointsForTag as In, QUERY_OPTIONS_TYPES as It, getAbilityFunctionName as J, isErrorStatus as Jt, getAbilityConditionsTypes as K, getSchemaNameByRef as Kt, getImportedQueryName as L, camelToSpaceSeparated as Ln, ZOD_EXTENDED as Lt, getInfiniteQueriesImports as M, formatTag as Mn, DOMAIN_ERRORS_FILE as Mt, getModelsImports as N, getEndpointTag as Nn, MUTATION_EFFECTS as Nt, getTagImportPath as O, BODY_PARAMETER_NAME as On, isNamedZodSchema as Ot, getQueriesImports as P, getOperationTag as Pn, QUERY_MODULES_FILE as Pt, getAppAbilitiesType as Q, isPathExcluded as Qt, getInfiniteQueryName as R, capitalize as Rn, CONFIG_PACKAGE_IMPORT_PATH as Rt, getTsTypeBase as S, VOID_SCHEMA as Sn, getEnumZodSchemaName as St, getQueryModulesImportPath as T, AXIOS_IMPORT as Tn, getZodSchemaName as Tt, getQueryOptionsName as U, snakeToCamel as Un, autocorrectRef as Ut, getPrefetchQueryName as V, kebabToCamel as Vn, REST_PACKAGE_IMPORT_PATH as Vt, getAbilityAction as W, Profiler as Wn, escapeControlCharacters as Wt, getAbilitySubjectTypes as X, isMediaTypeAllowed as Xt, getAbilitySubject as Y, isMainResponseStatus as Yt, getAclData as Z, isParamMediaTypeAllowed as Zt, hasEndpointConfig as _, INT_SCHEMA as _n, isReadAllEndpoint as _t, resolveConfig as a, wrapWithQuotesIfNeeded as an, getZodSchemaInferedTypeName as at, requiresBody as b, URL_SCHEMA as bn, invalidVariableNameCharactersToCamel as bt, getDestructuredVariables as c, isReferenceObject as cn, getSchemaDescriptions as ct, isQuery as d, ALLOWED_PATH_IN as dn, DEFAULT_GENERATE_OPTIONS as dt, isSortingParameterObject as en, hasAbilityConditions as et, getEndpointBody as f, ANY_SCHEMA as fn, getPathSegments as ft, getImportedEndpointName as g, ENUM_SCHEMA as gn, isPathSegmentParam as gt, getEndpointPath as h, EMAIL_SCHEMA as hn, isDeleteEndpoint as ht, shouldUseNativeCodegen as i, unwrapQuotesIfNeeded as in, getZodSchemaDescription as it, getImportPath as j, getRequestConfigTypeName as jn, BUILDERS_UTILS as jt, getAclImports as k, JSON_APPLICATION_FORMAT as kn, APP_REST_CLIENT_FILE as kt, isInfiniteQuery as l, isSchemaObject as ln, iterateSchema as lt, getEndpointName as m, DATETIME_SCHEMA as mn, isCreateEndpoint as mt, runGenerate as n, pathToVariableName as nn, getImportedZodSchemaInferedTypeName as nt, getOutputFileName as o, inferRequiredSchema as on, getZodSchemaPropertyDescriptions as ot, getEndpointConfig as p, BLOB_SCHEMA as pn, isBulkDeleteEndpoint as pt, getAbilityDescription as q, getSchemaRef as qt, compileNativeData as r, replaceHyphenatedPath as rn, getImportedZodSchemaName as rt, pick as s, isArraySchemaObject as sn, getZodSchemaType as st, getOpenApiDoc as t, pathParamToVariableName as tn, renderAclCheckCall as tt, isMutation as u, ALLOWED_METHODS as un, getUniqueArray as ut, mapEndpointParamsToFunctionParams as v, NUMBER_SCHEMA as vn, isReadEndpoint as vt, getFileNameWithExtension as w, AXIOS_DEFAULT_IMPORT_NAME as wn, getResponseZodSchemaName as wt, getSchemaTsMetaType as x, UUID_SCHEMA as xn, getBodyZodSchemaName as xt, renderMediaUploadMutationBody as y, STRING_SCHEMA as yn, isUpdateEndpoint as yt, getInfiniteQueryOptionsName as z, decapitalize as zn, NATIVE_PACKAGE_IMPORT_PATH as zt };
|
|
@@ -364,13 +364,13 @@ function shouldUseNativeCodegen() {
|
|
|
364
364
|
}
|
|
365
365
|
function getNativeBindings() {
|
|
366
366
|
if (!bindings) {
|
|
367
|
-
const require = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
|
|
367
|
+
const require$1 = (0, node_module.createRequire)(require("url").pathToFileURL(__filename).href);
|
|
368
368
|
const resolvedNativePath = getNativePath();
|
|
369
369
|
if (typeof process.dlopen === "function") {
|
|
370
370
|
const nativeModule = { exports: {} };
|
|
371
371
|
process.dlopen(nativeModule, resolvedNativePath);
|
|
372
372
|
bindings = nativeModule.exports;
|
|
373
|
-
} else bindings = require(resolvedNativePath);
|
|
373
|
+
} else bindings = require$1(resolvedNativePath);
|
|
374
374
|
}
|
|
375
375
|
return bindings;
|
|
376
376
|
}
|
|
@@ -1145,9 +1145,9 @@ function renderMediaUploadMutationBody({ resolver, endpointFunction, resolvedEnd
|
|
|
1145
1145
|
" let dataToSend: File | FormData = file;",
|
|
1146
1146
|
" if (method === \"post\") {",
|
|
1147
1147
|
" dataToSend = new FormData();",
|
|
1148
|
-
" if (uploadInstructions.fields) {",
|
|
1149
|
-
" for (const [key, value] of uploadInstructions.fields) {",
|
|
1150
|
-
" dataToSend.append(key, value);",
|
|
1148
|
+
" if (\"fields\" in uploadInstructions && uploadInstructions.fields) {",
|
|
1149
|
+
" for (const [key, value] of Object.entries(uploadInstructions.fields)) {",
|
|
1150
|
+
" dataToSend.append(key, String(value));",
|
|
1151
1151
|
" }",
|
|
1152
1152
|
" }",
|
|
1153
1153
|
" dataToSend.append(\"file\", file);",
|
package/dist/{generateCodeFromOpenAPIDoc-iEa8YAUQ.cjs → generateCodeFromOpenAPIDoc-CkVgg5Zy.cjs}
RENAMED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const require_generate_utils = require("./generate.utils-
|
|
1
|
+
const require_generate_utils = require("./generate.utils-BqlgVd-i.cjs");
|
|
2
2
|
//#region src/generators/const/acl.const.ts
|
|
3
3
|
const ACL_APP_ABILITY_FILE = {
|
|
4
4
|
fileName: "acl/app.ability",
|
|
@@ -81,12 +81,14 @@ function formatPatternIfNeeded(pattern) {
|
|
|
81
81
|
function getZodChainableNumberValidations(schema) {
|
|
82
82
|
const validations = [];
|
|
83
83
|
if (schema.enum) return "";
|
|
84
|
-
if (schema.minimum !== void 0)
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
84
|
+
if (schema.minimum !== void 0) {
|
|
85
|
+
if (schema.exclusiveMinimum === true) validations.push(`gt(${schema.minimum})`);
|
|
86
|
+
else validations.push(`gte(${schema.minimum})`);
|
|
87
|
+
} else if (typeof schema.exclusiveMinimum === "number") validations.push(`gt(${schema.exclusiveMinimum})`);
|
|
88
|
+
if (schema.maximum !== void 0) {
|
|
89
|
+
if (schema.exclusiveMaximum === true) validations.push(`lt(${schema.maximum})`);
|
|
90
|
+
else validations.push(`lte(${schema.maximum})`);
|
|
91
|
+
} else if (typeof schema.exclusiveMaximum === "number") validations.push(`lt(${schema.exclusiveMaximum})`);
|
|
90
92
|
if (schema.multipleOf) validations.push(`multipleOf(${schema.multipleOf})`);
|
|
91
93
|
return validations.join(".");
|
|
92
94
|
}
|
|
@@ -161,8 +163,10 @@ function getOpenAPISchemaComplexity(current, schema) {
|
|
|
161
163
|
const props = Object.values(schema.properties);
|
|
162
164
|
current += complexityByComposite("object") + sum(props.map((prop) => getOpenAPISchemaComplexity(0, prop)));
|
|
163
165
|
} else current += complexityByComposite("empty-object");
|
|
164
|
-
if (schema.additionalProperties)
|
|
165
|
-
|
|
166
|
+
if (schema.additionalProperties) {
|
|
167
|
+
if (typeof schema.additionalProperties === "object") current += getOpenAPISchemaComplexity(0, schema.additionalProperties);
|
|
168
|
+
else current += getOpenAPISchemaComplexity(1);
|
|
169
|
+
}
|
|
166
170
|
}
|
|
167
171
|
return current;
|
|
168
172
|
}
|
|
@@ -346,7 +350,7 @@ function getZodSchema({ schema, resolver, meta: inheritedMeta, tag }) {
|
|
|
346
350
|
propZodSchema,
|
|
347
351
|
isCircular
|
|
348
352
|
];
|
|
349
|
-
}).map(([prop, propSchema, isCircular]) => isCircular ?
|
|
353
|
+
}).map(([prop, propSchema, isCircular]) => isCircular ? `${require_generate_utils.wrapWithQuotesIfNeeded(prop)}: z.lazy(() => ${propSchema})` : `${require_generate_utils.wrapWithQuotesIfNeeded(prop)}: ${propSchema}`).join(", ")} }`;
|
|
350
354
|
let additionalPropsSchema = "";
|
|
351
355
|
if (schema.additionalProperties) additionalPropsSchema = `.catchall(${typeof schema.additionalProperties === "object" && Object.keys(schema.additionalProperties).length > 0 ? getZodSchema({
|
|
352
356
|
...params,
|
|
@@ -554,7 +558,8 @@ function getEnumZodSchema({ resolver, schema, zodSchema, meta, tag }) {
|
|
|
554
558
|
return zodSchema.assign(`${namespacePrefix}${extractedEnumZodSchema.zodSchemaName}`);
|
|
555
559
|
}
|
|
556
560
|
function getEnumZodSchemaCode(schema) {
|
|
557
|
-
|
|
561
|
+
const values = schema.enum?.filter((value) => value !== null) ?? [];
|
|
562
|
+
return `${require_generate_utils.ENUM_SCHEMA}([${values.map((value) => `"${value}"`).join(", ")}])`;
|
|
558
563
|
}
|
|
559
564
|
function getEnumZodSchemaCodeFromEnumNames(enumNames) {
|
|
560
565
|
return `${require_generate_utils.ENUM_SCHEMA}([${enumNames.map((value) => `"${value}"`).join(", ")}])`;
|
|
@@ -2185,8 +2190,10 @@ function getBuilderConfigs({ data, tag, resolver }) {
|
|
|
2185
2190
|
if (!columnsConfig) return;
|
|
2186
2191
|
importedEndpoints.push(readAllEndpoint);
|
|
2187
2192
|
importedInfiniteEndpoints.push(readAllEndpoint);
|
|
2188
|
-
if (columnsConfig.zodSchema)
|
|
2189
|
-
|
|
2193
|
+
if (columnsConfig.zodSchema) {
|
|
2194
|
+
if (require_generate_utils.isNamedZodSchema(columnsConfig.zodSchema)) importedZodSchemas.push(columnsConfig.zodSchema);
|
|
2195
|
+
else hasZodImport = true;
|
|
2196
|
+
}
|
|
2190
2197
|
if (columnsConfig.sortableEnumSchemaName) importedZodSchemas.push(columnsConfig.sortableEnumSchemaName);
|
|
2191
2198
|
const filter = readAllEndpoint.parameters.find((param) => param.name === resolver.options.filterParamName);
|
|
2192
2199
|
if (filter) importedZodSchemas.push(filter.zodSchema);
|
|
@@ -2802,8 +2809,8 @@ function generateModels({ resolver, data, tag }) {
|
|
|
2802
2809
|
for (const [key, code] of Object.entries(zodSchemas)) {
|
|
2803
2810
|
const schemaRef = resolver.getRefByZodSchemaName(key);
|
|
2804
2811
|
zodSchemasData[key] = {
|
|
2805
|
-
code,
|
|
2806
|
-
|
|
2812
|
+
code: resolver.options.modelsInModules ? code.replace(/\b[A-Z][A-Za-z0-9]*Models\./g, "") : code,
|
|
2813
|
+
isCircular: schemaRef ? resolver.isSchemaCircular(schemaRef) : false,
|
|
2807
2814
|
isEnum: require_generate_utils.isEnumZodSchema(code),
|
|
2808
2815
|
schemaObj: resolver.getZodSchemaObj(key)
|
|
2809
2816
|
};
|
|
@@ -2824,14 +2831,51 @@ function generateModels({ resolver, data, tag }) {
|
|
|
2824
2831
|
tag,
|
|
2825
2832
|
resolver
|
|
2826
2833
|
}));
|
|
2827
|
-
|
|
2828
|
-
lines.push(`export type ${
|
|
2834
|
+
const inferredTypeName = require_generate_utils.getZodSchemaInferedTypeName(name, resolver.options);
|
|
2835
|
+
if (zodSchema.isCircular && zodSchema.schemaObj) lines.push(`export type ${inferredTypeName} = ${renderSchemaType(zodSchema.schemaObj, resolver)};`);
|
|
2836
|
+
const typeAnnotation = zodSchema.isCircular ? `: z.ZodObject<z.ZodRawShape> & z.ZodType<${inferredTypeName}>` : "";
|
|
2837
|
+
const schemaCode = zodSchema.isCircular ? zodSchema.code : `z.compile(${zodSchema.code})`;
|
|
2838
|
+
lines.push(`export const ${name}${typeAnnotation} = ${schemaCode};`);
|
|
2839
|
+
if (!zodSchema.isCircular) lines.push(`export type ${inferredTypeName} = z.infer<typeof ${name}>;`);
|
|
2829
2840
|
if (zodSchema.isEnum) lines.push(`export const ${require_generate_utils.getZodSchemaInferedTypeName(name, resolver.options)} = ${name}.enum;`);
|
|
2830
2841
|
lines.push("");
|
|
2831
2842
|
}
|
|
2832
2843
|
if (resolver.options.tsNamespaces) lines.push("}");
|
|
2833
2844
|
return lines.join("\n").trimEnd() + "\n";
|
|
2834
2845
|
}
|
|
2846
|
+
function renderSchemaType(schema, resolver) {
|
|
2847
|
+
if (require_generate_utils.isReferenceObject(schema)) {
|
|
2848
|
+
const schemaName = resolver.getZodSchemaNameByRef(schema.$ref);
|
|
2849
|
+
return schemaName ? require_generate_utils.getZodSchemaInferedTypeName(schemaName, resolver.options) : "unknown";
|
|
2850
|
+
}
|
|
2851
|
+
const composite = schema.allOf ?? schema.oneOf ?? schema.anyOf;
|
|
2852
|
+
if (composite?.length) {
|
|
2853
|
+
const separator = schema.allOf ? " & " : " | ";
|
|
2854
|
+
return addNullable(schema, composite.map((part) => renderSchemaType(part, resolver)).join(separator));
|
|
2855
|
+
}
|
|
2856
|
+
if (schema.enum?.length) return addNullable(schema, schema.enum.map((value) => JSON.stringify(value)).join(" | "));
|
|
2857
|
+
if (schema.type === "array") return addNullable(schema, `Array<${schema.items ? renderSchemaType(schema.items, resolver) : "unknown"}>`);
|
|
2858
|
+
if (schema.type === "object" || schema.properties || schema.additionalProperties) {
|
|
2859
|
+
const properties = Object.entries(schema.properties ?? {}).map(([name, property]) => {
|
|
2860
|
+
const isRequired = resolver.options.withImplicitRequiredProps || schema.required?.includes(name);
|
|
2861
|
+
const hasDefault = !require_generate_utils.isReferenceObject(property) && property.default !== void 0;
|
|
2862
|
+
const optional = isRequired || hasDefault ? "" : "?";
|
|
2863
|
+
const propertyType = renderSchemaType(property, resolver);
|
|
2864
|
+
const outputType = resolver.options.replaceOptionalWithNullish && optional && (require_generate_utils.isReferenceObject(property) || !property.nullable) ? `${propertyType} | null` : propertyType;
|
|
2865
|
+
return `${require_generate_utils.wrapWithQuotesIfNeeded(name)}${optional}: ${outputType}`;
|
|
2866
|
+
});
|
|
2867
|
+
if (schema.additionalProperties) {
|
|
2868
|
+
const valueType = typeof schema.additionalProperties === "object" ? renderSchemaType(schema.additionalProperties, resolver) : "unknown";
|
|
2869
|
+
properties.push(`[key: string]: ${valueType}`);
|
|
2870
|
+
}
|
|
2871
|
+
return addNullable(schema, `{ ${properties.join("; ")} }`);
|
|
2872
|
+
}
|
|
2873
|
+
const primitiveType = schema.type;
|
|
2874
|
+
return addNullable(schema, primitiveType === "string" ? "string" : primitiveType === "number" || primitiveType === "integer" ? "number" : primitiveType === "boolean" ? "boolean" : primitiveType === "null" ? "null" : "unknown");
|
|
2875
|
+
}
|
|
2876
|
+
function addNullable(schema, type) {
|
|
2877
|
+
return schema.nullable && type !== "null" ? `${type} | null` : type;
|
|
2878
|
+
}
|
|
2835
2879
|
function renderModelsProxy({ resolver, data, tag }) {
|
|
2836
2880
|
const commonZodSchemas = data.get(resolver.options.defaultTag)?.zodSchemas ?? {};
|
|
2837
2881
|
const schemaNames = getUsedSchemaNames({
|
|
@@ -3389,9 +3433,10 @@ function renderInfiniteQueryOptions({ resolver, endpoint, inlineEndpoints }) {
|
|
|
3389
3433
|
const requestConfigWithSignal = renderRequestConfigWithSignal(hasRequestConfigParam);
|
|
3390
3434
|
lines.push(` queryFn: ({ pageParam, signal }: { pageParam: number; signal: AbortSignal }) => ${endpointFunction}(${endpointArgsWithPage}${hasRequestConfigParam ? `, ${requestConfigWithSignal}` : ""}),`);
|
|
3391
3435
|
lines.push(" initialPageParam: 1,");
|
|
3392
|
-
lines.push(` getNextPageParam: ({ ${resolver.options.infiniteQueryResponseParamNames.page}, ${resolver.options.infiniteQueryResponseParamNames.totalItems}, ${resolver.options.infiniteQueryResponseParamNames.limit}: limitParam }: Awaited<ReturnType<typeof ${endpointFunction}>>) => {`);
|
|
3436
|
+
lines.push(` getNextPageParam: ({ ${resolver.options.infiniteQueryResponseParamNames.page}, ${resolver.options.infiniteQueryResponseParamNames.totalItems}, ${resolver.options.infiniteQueryResponseParamNames.limit}: limitParam }: Awaited<ReturnType<typeof ${endpointFunction}>> & Partial<Record<${JSON.stringify(resolver.options.infiniteQueryResponseParamNames.page)} | ${JSON.stringify(resolver.options.infiniteQueryResponseParamNames.totalItems)} | ${JSON.stringify(resolver.options.infiniteQueryResponseParamNames.limit)}, number | null>>) => {`);
|
|
3393
3437
|
lines.push(` const pageParam = ${resolver.options.infiniteQueryResponseParamNames.page} ?? 1;`);
|
|
3394
|
-
lines.push(
|
|
3438
|
+
lines.push(" const pageSize = limitParam ?? 0;");
|
|
3439
|
+
lines.push(` return pageParam * pageSize < (${resolver.options.infiniteQueryResponseParamNames.totalItems} ?? 0) ? pageParam + 1 : null;`);
|
|
3395
3440
|
lines.push(" },");
|
|
3396
3441
|
lines.push("});");
|
|
3397
3442
|
return lines.join("\n");
|
package/dist/{generateCodeFromOpenAPIDoc--ufinTug.mjs → generateCodeFromOpenAPIDoc-idp1RVDa.mjs}
RENAMED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { r as getZodSchemaRefs, t as getDataFromOpenAPIDoc } from "./getDataFromOpenAPIDoc-
|
|
2
|
-
import { $ as getImportedAbilityFunctionName, A as getEndpointsImports, An as NATIVE_RESPONSE_TYPE, At as APP_REST_CLIENT_NAME, B as getPrefetchInfiniteQueryName, Bt as PACKAGE_IMPORT_PATH, C as getAppRestClientImportPath, Cn as ZOD_IMPORT, D as getTagFileName, Dn as AXIOS_REQUEST_CONFIG_TYPE, Dt as isEnumZodSchema, E as getQueryTypesImportPath, En as AXIOS_REQUEST_CONFIG_NAME, F as mergeImports, Ft as QUERY_MODULE_ENUM, G as getAbilityConditionType, H as getQueryName, Ht as getNamespaceName, I as getImportedInfiniteQueryName, In as shouldInlineEndpointsForTag, It as QUERY_OPTIONS_TYPES, J as getAbilityFunctionName, K as getAbilityConditionsTypes, L as getImportedQueryName, Ln as camelToSpaceSeparated, Lt as ZOD_EXTENDED, M as getInfiniteQueriesImports, Mt as DOMAIN_ERRORS_FILE, N as getModelsImports, Nn as getEndpointTag, Nt as MUTATION_EFFECTS, O as getTagImportPath, Ot as isNamedZodSchema, P as getQueriesImports, Pt as QUERY_MODULES_FILE, Q as getAppAbilitiesType, R as getInfiniteQueryName, Rn as capitalize, Rt as CONFIG_PACKAGE_IMPORT_PATH, T as getQueryModulesImportPath, Tn as AXIOS_IMPORT, U as getQueryOptionsName, V as getPrefetchQueryName, Vn as kebabToCamel, Vt as REST_PACKAGE_IMPORT_PATH, W as getAbilityAction, Wn as Profiler, X as getAbilitySubjectTypes, Y as getAbilitySubject, Z as getAclData, Zt as isParamMediaTypeAllowed, _ as hasEndpointConfig, _t as isReadAllEndpoint, at as getZodSchemaInferedTypeName, b as requiresBody, bt as invalidVariableNameCharactersToCamel, c as getDestructuredVariables, cn as isReferenceObject, ct as getSchemaDescriptions, d as isQuery, dt as DEFAULT_GENERATE_OPTIONS, et as hasAbilityConditions, f as getEndpointBody, fn as ANY_SCHEMA, ft as getPathSegments, g as getImportedEndpointName, gt as isPathSegmentParam, h as getEndpointPath, ht as isDeleteEndpoint, it as getZodSchemaDescription, j as getImportPath, jn as getRequestConfigTypeName, jt as BUILDERS_UTILS, k as getAclImports, kn as JSON_APPLICATION_FORMAT, kt as APP_REST_CLIENT_FILE, l as isInfiniteQuery, ln as isSchemaObject, m as getEndpointName, mt as isCreateEndpoint,
|
|
1
|
+
import { r as getZodSchemaRefs, t as getDataFromOpenAPIDoc } from "./getDataFromOpenAPIDoc-Cyrm3VKA.mjs";
|
|
2
|
+
import { $ as getImportedAbilityFunctionName, A as getEndpointsImports, An as NATIVE_RESPONSE_TYPE, At as APP_REST_CLIENT_NAME, B as getPrefetchInfiniteQueryName, Bt as PACKAGE_IMPORT_PATH, C as getAppRestClientImportPath, Cn as ZOD_IMPORT, D as getTagFileName, Dn as AXIOS_REQUEST_CONFIG_TYPE, Dt as isEnumZodSchema, E as getQueryTypesImportPath, En as AXIOS_REQUEST_CONFIG_NAME, F as mergeImports, Ft as QUERY_MODULE_ENUM, G as getAbilityConditionType, H as getQueryName, Ht as getNamespaceName, I as getImportedInfiniteQueryName, In as shouldInlineEndpointsForTag, It as QUERY_OPTIONS_TYPES, J as getAbilityFunctionName, K as getAbilityConditionsTypes, L as getImportedQueryName, Ln as camelToSpaceSeparated, Lt as ZOD_EXTENDED, M as getInfiniteQueriesImports, Mt as DOMAIN_ERRORS_FILE, N as getModelsImports, Nn as getEndpointTag, Nt as MUTATION_EFFECTS, O as getTagImportPath, Ot as isNamedZodSchema, P as getQueriesImports, Pt as QUERY_MODULES_FILE, Q as getAppAbilitiesType, R as getInfiniteQueryName, Rn as capitalize, Rt as CONFIG_PACKAGE_IMPORT_PATH, T as getQueryModulesImportPath, Tn as AXIOS_IMPORT, U as getQueryOptionsName, V as getPrefetchQueryName, Vn as kebabToCamel, Vt as REST_PACKAGE_IMPORT_PATH, W as getAbilityAction, Wn as Profiler, X as getAbilitySubjectTypes, Y as getAbilitySubject, Z as getAclData, Zt as isParamMediaTypeAllowed, _ as hasEndpointConfig, _t as isReadAllEndpoint, an as wrapWithQuotesIfNeeded, at as getZodSchemaInferedTypeName, b as requiresBody, bt as invalidVariableNameCharactersToCamel, c as getDestructuredVariables, cn as isReferenceObject, ct as getSchemaDescriptions, d as isQuery, dt as DEFAULT_GENERATE_OPTIONS, et as hasAbilityConditions, f as getEndpointBody, fn as ANY_SCHEMA, ft as getPathSegments, g as getImportedEndpointName, gt as isPathSegmentParam, h as getEndpointPath, ht as isDeleteEndpoint, i as shouldUseNativeCodegen, it as getZodSchemaDescription, j as getImportPath, jn as getRequestConfigTypeName, jt as BUILDERS_UTILS, k as getAclImports, kn as JSON_APPLICATION_FORMAT, kt as APP_REST_CLIENT_FILE, l as isInfiniteQuery, ln as isSchemaObject, m as getEndpointName, mt as isCreateEndpoint, nt as getImportedZodSchemaInferedTypeName, o as getOutputFileName, ot as getZodSchemaPropertyDescriptions, p as getEndpointConfig, pt as isBulkDeleteEndpoint, q as getAbilityDescription, r as compileNativeData, rt as getImportedZodSchemaName, st as getZodSchemaType, tt as renderAclCheckCall, u as isMutation, ut as getUniqueArray, v as mapEndpointParamsToFunctionParams, vt as isReadEndpoint, w as getFileNameWithExtension, wn as AXIOS_DEFAULT_IMPORT_NAME, y as renderMediaUploadMutationBody, yt as isUpdateEndpoint, z as getInfiniteQueryOptionsName, zt as NATIVE_PACKAGE_IMPORT_PATH } from "./generate.runner-BD9BbYIx.mjs";
|
|
3
3
|
import "node:module";
|
|
4
4
|
//#region \0rolldown/runtime.js
|
|
5
5
|
var __defProp = Object.defineProperty;
|
|
@@ -207,8 +207,10 @@ function getBuilderConfigs({ data, tag, resolver }) {
|
|
|
207
207
|
if (!columnsConfig) return;
|
|
208
208
|
importedEndpoints.push(readAllEndpoint);
|
|
209
209
|
importedInfiniteEndpoints.push(readAllEndpoint);
|
|
210
|
-
if (columnsConfig.zodSchema)
|
|
211
|
-
|
|
210
|
+
if (columnsConfig.zodSchema) {
|
|
211
|
+
if (isNamedZodSchema(columnsConfig.zodSchema)) importedZodSchemas.push(columnsConfig.zodSchema);
|
|
212
|
+
else hasZodImport = true;
|
|
213
|
+
}
|
|
212
214
|
if (columnsConfig.sortableEnumSchemaName) importedZodSchemas.push(columnsConfig.sortableEnumSchemaName);
|
|
213
215
|
const filter = readAllEndpoint.parameters.find((param) => param.name === resolver.options.filterParamName);
|
|
214
216
|
if (filter) importedZodSchemas.push(filter.zodSchema);
|
|
@@ -824,8 +826,8 @@ function generateModels({ resolver, data, tag }) {
|
|
|
824
826
|
for (const [key, code] of Object.entries(zodSchemas)) {
|
|
825
827
|
const schemaRef = resolver.getRefByZodSchemaName(key);
|
|
826
828
|
zodSchemasData[key] = {
|
|
827
|
-
code,
|
|
828
|
-
|
|
829
|
+
code: resolver.options.modelsInModules ? code.replace(/\b[A-Z][A-Za-z0-9]*Models\./g, "") : code,
|
|
830
|
+
isCircular: schemaRef ? resolver.isSchemaCircular(schemaRef) : false,
|
|
829
831
|
isEnum: isEnumZodSchema(code),
|
|
830
832
|
schemaObj: resolver.getZodSchemaObj(key)
|
|
831
833
|
};
|
|
@@ -846,14 +848,51 @@ function generateModels({ resolver, data, tag }) {
|
|
|
846
848
|
tag,
|
|
847
849
|
resolver
|
|
848
850
|
}));
|
|
849
|
-
|
|
850
|
-
lines.push(`export type ${
|
|
851
|
+
const inferredTypeName = getZodSchemaInferedTypeName(name, resolver.options);
|
|
852
|
+
if (zodSchema.isCircular && zodSchema.schemaObj) lines.push(`export type ${inferredTypeName} = ${renderSchemaType(zodSchema.schemaObj, resolver)};`);
|
|
853
|
+
const typeAnnotation = zodSchema.isCircular ? `: z.ZodObject<z.ZodRawShape> & z.ZodType<${inferredTypeName}>` : "";
|
|
854
|
+
const schemaCode = zodSchema.isCircular ? zodSchema.code : `z.compile(${zodSchema.code})`;
|
|
855
|
+
lines.push(`export const ${name}${typeAnnotation} = ${schemaCode};`);
|
|
856
|
+
if (!zodSchema.isCircular) lines.push(`export type ${inferredTypeName} = z.infer<typeof ${name}>;`);
|
|
851
857
|
if (zodSchema.isEnum) lines.push(`export const ${getZodSchemaInferedTypeName(name, resolver.options)} = ${name}.enum;`);
|
|
852
858
|
lines.push("");
|
|
853
859
|
}
|
|
854
860
|
if (resolver.options.tsNamespaces) lines.push("}");
|
|
855
861
|
return lines.join("\n").trimEnd() + "\n";
|
|
856
862
|
}
|
|
863
|
+
function renderSchemaType(schema, resolver) {
|
|
864
|
+
if (isReferenceObject(schema)) {
|
|
865
|
+
const schemaName = resolver.getZodSchemaNameByRef(schema.$ref);
|
|
866
|
+
return schemaName ? getZodSchemaInferedTypeName(schemaName, resolver.options) : "unknown";
|
|
867
|
+
}
|
|
868
|
+
const composite = schema.allOf ?? schema.oneOf ?? schema.anyOf;
|
|
869
|
+
if (composite?.length) {
|
|
870
|
+
const separator = schema.allOf ? " & " : " | ";
|
|
871
|
+
return addNullable(schema, composite.map((part) => renderSchemaType(part, resolver)).join(separator));
|
|
872
|
+
}
|
|
873
|
+
if (schema.enum?.length) return addNullable(schema, schema.enum.map((value) => JSON.stringify(value)).join(" | "));
|
|
874
|
+
if (schema.type === "array") return addNullable(schema, `Array<${schema.items ? renderSchemaType(schema.items, resolver) : "unknown"}>`);
|
|
875
|
+
if (schema.type === "object" || schema.properties || schema.additionalProperties) {
|
|
876
|
+
const properties = Object.entries(schema.properties ?? {}).map(([name, property]) => {
|
|
877
|
+
const isRequired = resolver.options.withImplicitRequiredProps || schema.required?.includes(name);
|
|
878
|
+
const hasDefault = !isReferenceObject(property) && property.default !== void 0;
|
|
879
|
+
const optional = isRequired || hasDefault ? "" : "?";
|
|
880
|
+
const propertyType = renderSchemaType(property, resolver);
|
|
881
|
+
const outputType = resolver.options.replaceOptionalWithNullish && optional && (isReferenceObject(property) || !property.nullable) ? `${propertyType} | null` : propertyType;
|
|
882
|
+
return `${wrapWithQuotesIfNeeded(name)}${optional}: ${outputType}`;
|
|
883
|
+
});
|
|
884
|
+
if (schema.additionalProperties) {
|
|
885
|
+
const valueType = typeof schema.additionalProperties === "object" ? renderSchemaType(schema.additionalProperties, resolver) : "unknown";
|
|
886
|
+
properties.push(`[key: string]: ${valueType}`);
|
|
887
|
+
}
|
|
888
|
+
return addNullable(schema, `{ ${properties.join("; ")} }`);
|
|
889
|
+
}
|
|
890
|
+
const primitiveType = schema.type;
|
|
891
|
+
return addNullable(schema, primitiveType === "string" ? "string" : primitiveType === "number" || primitiveType === "integer" ? "number" : primitiveType === "boolean" ? "boolean" : primitiveType === "null" ? "null" : "unknown");
|
|
892
|
+
}
|
|
893
|
+
function addNullable(schema, type) {
|
|
894
|
+
return schema.nullable && type !== "null" ? `${type} | null` : type;
|
|
895
|
+
}
|
|
857
896
|
function renderModelsProxy({ resolver, data, tag }) {
|
|
858
897
|
const commonZodSchemas = data.get(resolver.options.defaultTag)?.zodSchemas ?? {};
|
|
859
898
|
const schemaNames = getUsedSchemaNames({
|
|
@@ -1411,9 +1450,10 @@ function renderInfiniteQueryOptions({ resolver, endpoint, inlineEndpoints }) {
|
|
|
1411
1450
|
const requestConfigWithSignal = renderRequestConfigWithSignal(hasRequestConfigParam);
|
|
1412
1451
|
lines.push(` queryFn: ({ pageParam, signal }: { pageParam: number; signal: AbortSignal }) => ${endpointFunction}(${endpointArgsWithPage}${hasRequestConfigParam ? `, ${requestConfigWithSignal}` : ""}),`);
|
|
1413
1452
|
lines.push(" initialPageParam: 1,");
|
|
1414
|
-
lines.push(` getNextPageParam: ({ ${resolver.options.infiniteQueryResponseParamNames.page}, ${resolver.options.infiniteQueryResponseParamNames.totalItems}, ${resolver.options.infiniteQueryResponseParamNames.limit}: limitParam }: Awaited<ReturnType<typeof ${endpointFunction}>>) => {`);
|
|
1453
|
+
lines.push(` getNextPageParam: ({ ${resolver.options.infiniteQueryResponseParamNames.page}, ${resolver.options.infiniteQueryResponseParamNames.totalItems}, ${resolver.options.infiniteQueryResponseParamNames.limit}: limitParam }: Awaited<ReturnType<typeof ${endpointFunction}>> & Partial<Record<${JSON.stringify(resolver.options.infiniteQueryResponseParamNames.page)} | ${JSON.stringify(resolver.options.infiniteQueryResponseParamNames.totalItems)} | ${JSON.stringify(resolver.options.infiniteQueryResponseParamNames.limit)}, number | null>>) => {`);
|
|
1415
1454
|
lines.push(` const pageParam = ${resolver.options.infiniteQueryResponseParamNames.page} ?? 1;`);
|
|
1416
|
-
lines.push(
|
|
1455
|
+
lines.push(" const pageSize = limitParam ?? 0;");
|
|
1456
|
+
lines.push(` return pageParam * pageSize < (${resolver.options.infiniteQueryResponseParamNames.totalItems} ?? 0) ? pageParam + 1 : null;`);
|
|
1417
1457
|
lines.push(" },");
|
|
1418
1458
|
lines.push("});");
|
|
1419
1459
|
return lines.join("\n");
|
package/dist/generator.mjs
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
|
-
import { t as generateCodeFromOpenAPIDoc } from "./generateCodeFromOpenAPIDoc
|
|
2
|
-
import { t as getDataFromOpenAPIDoc } from "./getDataFromOpenAPIDoc-
|
|
3
|
-
import { H as getQueryName, Ht as getNamespaceName, Mn as formatTag, O as getTagImportPath, S as getTsTypeBase, Xt as isMediaTypeAllowed, Zt as isParamMediaTypeAllowed, bt as invalidVariableNameCharactersToCamel, d as isQuery, dt as DEFAULT_GENERATE_OPTIONS, u as isMutation, x as getSchemaTsMetaType } from "./
|
|
4
|
-
import { t as getOpenApiDoc } from "./generate.runner-D8AYuEFm.mjs";
|
|
1
|
+
import { t as generateCodeFromOpenAPIDoc } from "./generateCodeFromOpenAPIDoc-idp1RVDa.mjs";
|
|
2
|
+
import { t as getDataFromOpenAPIDoc } from "./getDataFromOpenAPIDoc-Cyrm3VKA.mjs";
|
|
3
|
+
import { H as getQueryName, Ht as getNamespaceName, Mn as formatTag, O as getTagImportPath, S as getTsTypeBase, Xt as isMediaTypeAllowed, Zt as isParamMediaTypeAllowed, bt as invalidVariableNameCharactersToCamel, d as isQuery, dt as DEFAULT_GENERATE_OPTIONS, t as getOpenApiDoc, u as isMutation, x as getSchemaTsMetaType } from "./generate.runner-BD9BbYIx.mjs";
|
|
5
4
|
//#region src/generators/core/getMetadataFromOpenAPIDoc.ts
|
|
6
5
|
async function getMetadataFromOpenAPIDoc(openApiDoc, options) {
|
|
7
6
|
const { resolver, data } = await getDataFromOpenAPIDoc(openApiDoc, options);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $t as isPrimitiveType, Bn as getMostCommonAdjacentCombinationSplit, Ct as getParamZodSchemaName, Et as getZodSchemaOperationName, Fn as isTagIncluded, Gt as getParameterEnumNames, Hn as removeWord, Ht as getNamespaceName, Jt as isErrorStatus, Kt as getSchemaNameByRef, Mn as formatTag, Nn as getEndpointTag, On as BODY_PARAMETER_NAME, Ot as isNamedZodSchema, Pn as getOperationTag, Qt as isPathExcluded, Rn as capitalize, Sn as VOID_SCHEMA, St as getEnumZodSchemaName, Tt as getZodSchemaName, Un as snakeToCamel, Ut as autocorrectRef, Wn as Profiler, Wt as escapeControlCharacters, Xt as isMediaTypeAllowed, Yt as isMainResponseStatus, Zt as isParamMediaTypeAllowed, _n as INT_SCHEMA, an as wrapWithQuotesIfNeeded, bn as URL_SCHEMA, bt as invalidVariableNameCharactersToCamel, cn as isReferenceObject, d as isQuery, dn as ALLOWED_PATH_IN, en as isSortingParameterObject, fn as ANY_SCHEMA, gn as ENUM_SCHEMA, hn as EMAIL_SCHEMA, in as unwrapQuotesIfNeeded, kn as JSON_APPLICATION_FORMAT, ln as isSchemaObject, lt as iterateSchema, mn as DATETIME_SCHEMA, nn as pathToVariableName, on as inferRequiredSchema, pn as BLOB_SCHEMA, qt as getSchemaRef, rn as replaceHyphenatedPath, s as pick, sn as isArraySchemaObject, tn as pathParamToVariableName, un as ALLOWED_METHODS, ut as getUniqueArray, vn as NUMBER_SCHEMA, wt as getResponseZodSchemaName, xn as UUID_SCHEMA, xt as getBodyZodSchemaName, yn as STRING_SCHEMA, zn as decapitalize } from "./
|
|
1
|
+
import { $t as isPrimitiveType, Bn as getMostCommonAdjacentCombinationSplit, Ct as getParamZodSchemaName, Et as getZodSchemaOperationName, Fn as isTagIncluded, Gt as getParameterEnumNames, Hn as removeWord, Ht as getNamespaceName, Jt as isErrorStatus, Kt as getSchemaNameByRef, Mn as formatTag, Nn as getEndpointTag, On as BODY_PARAMETER_NAME, Ot as isNamedZodSchema, Pn as getOperationTag, Qt as isPathExcluded, Rn as capitalize, Sn as VOID_SCHEMA, St as getEnumZodSchemaName, Tt as getZodSchemaName, Un as snakeToCamel, Ut as autocorrectRef, Wn as Profiler, Wt as escapeControlCharacters, Xt as isMediaTypeAllowed, Yt as isMainResponseStatus, Zt as isParamMediaTypeAllowed, _n as INT_SCHEMA, an as wrapWithQuotesIfNeeded, bn as URL_SCHEMA, bt as invalidVariableNameCharactersToCamel, cn as isReferenceObject, d as isQuery, dn as ALLOWED_PATH_IN, en as isSortingParameterObject, fn as ANY_SCHEMA, gn as ENUM_SCHEMA, hn as EMAIL_SCHEMA, in as unwrapQuotesIfNeeded, kn as JSON_APPLICATION_FORMAT, ln as isSchemaObject, lt as iterateSchema, mn as DATETIME_SCHEMA, nn as pathToVariableName, on as inferRequiredSchema, pn as BLOB_SCHEMA, qt as getSchemaRef, rn as replaceHyphenatedPath, s as pick, sn as isArraySchemaObject, tn as pathParamToVariableName, un as ALLOWED_METHODS, ut as getUniqueArray, vn as NUMBER_SCHEMA, wt as getResponseZodSchemaName, xn as UUID_SCHEMA, xt as getBodyZodSchemaName, yn as STRING_SCHEMA, zn as decapitalize } from "./generate.runner-BD9BbYIx.mjs";
|
|
2
2
|
//#region src/generators/const/validation.const.ts
|
|
3
3
|
const HTTP_STATUS_CODES = {
|
|
4
4
|
"100": "Continue",
|
|
@@ -119,12 +119,14 @@ function formatPatternIfNeeded(pattern) {
|
|
|
119
119
|
function getZodChainableNumberValidations(schema) {
|
|
120
120
|
const validations = [];
|
|
121
121
|
if (schema.enum) return "";
|
|
122
|
-
if (schema.minimum !== void 0)
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
122
|
+
if (schema.minimum !== void 0) {
|
|
123
|
+
if (schema.exclusiveMinimum === true) validations.push(`gt(${schema.minimum})`);
|
|
124
|
+
else validations.push(`gte(${schema.minimum})`);
|
|
125
|
+
} else if (typeof schema.exclusiveMinimum === "number") validations.push(`gt(${schema.exclusiveMinimum})`);
|
|
126
|
+
if (schema.maximum !== void 0) {
|
|
127
|
+
if (schema.exclusiveMaximum === true) validations.push(`lt(${schema.maximum})`);
|
|
128
|
+
else validations.push(`lte(${schema.maximum})`);
|
|
129
|
+
} else if (typeof schema.exclusiveMaximum === "number") validations.push(`lt(${schema.exclusiveMaximum})`);
|
|
128
130
|
if (schema.multipleOf) validations.push(`multipleOf(${schema.multipleOf})`);
|
|
129
131
|
return validations.join(".");
|
|
130
132
|
}
|
|
@@ -199,8 +201,10 @@ function getOpenAPISchemaComplexity(current, schema) {
|
|
|
199
201
|
const props = Object.values(schema.properties);
|
|
200
202
|
current += complexityByComposite("object") + sum(props.map((prop) => getOpenAPISchemaComplexity(0, prop)));
|
|
201
203
|
} else current += complexityByComposite("empty-object");
|
|
202
|
-
if (schema.additionalProperties)
|
|
203
|
-
|
|
204
|
+
if (schema.additionalProperties) {
|
|
205
|
+
if (typeof schema.additionalProperties === "object") current += getOpenAPISchemaComplexity(0, schema.additionalProperties);
|
|
206
|
+
else current += getOpenAPISchemaComplexity(1);
|
|
207
|
+
}
|
|
204
208
|
}
|
|
205
209
|
return current;
|
|
206
210
|
}
|
|
@@ -384,7 +388,7 @@ function getZodSchema({ schema, resolver, meta: inheritedMeta, tag }) {
|
|
|
384
388
|
propZodSchema,
|
|
385
389
|
isCircular
|
|
386
390
|
];
|
|
387
|
-
}).map(([prop, propSchema, isCircular]) => isCircular ?
|
|
391
|
+
}).map(([prop, propSchema, isCircular]) => isCircular ? `${wrapWithQuotesIfNeeded(prop)}: z.lazy(() => ${propSchema})` : `${wrapWithQuotesIfNeeded(prop)}: ${propSchema}`).join(", ")} }`;
|
|
388
392
|
let additionalPropsSchema = "";
|
|
389
393
|
if (schema.additionalProperties) additionalPropsSchema = `.catchall(${typeof schema.additionalProperties === "object" && Object.keys(schema.additionalProperties).length > 0 ? getZodSchema({
|
|
390
394
|
...params,
|
|
@@ -592,7 +596,8 @@ function getEnumZodSchema({ resolver, schema, zodSchema, meta, tag }) {
|
|
|
592
596
|
return zodSchema.assign(`${namespacePrefix}${extractedEnumZodSchema.zodSchemaName}`);
|
|
593
597
|
}
|
|
594
598
|
function getEnumZodSchemaCode(schema) {
|
|
595
|
-
|
|
599
|
+
const values = schema.enum?.filter((value) => value !== null) ?? [];
|
|
600
|
+
return `${ENUM_SCHEMA}([${values.map((value) => `"${value}"`).join(", ")}])`;
|
|
596
601
|
}
|
|
597
602
|
function getEnumZodSchemaCodeFromEnumNames(enumNames) {
|
|
598
603
|
return `${ENUM_SCHEMA}([${enumNames.map((value) => `"${value}"`).join(", ")}])`;
|
package/dist/index.d.mts
CHANGED
|
@@ -7,6 +7,6 @@ import { i as QueryModule, n as InvalidationMapFunc, r as OpenApiQueryConfig, t
|
|
|
7
7
|
import { t as RestUtils } from "./rest.utils-rezWAIYL.mjs";
|
|
8
8
|
import { t as OpenAPICodegenConfig } from "./config-DgrOddSC.mjs";
|
|
9
9
|
import { d as TransportResponse, l as TransportRequest, n as HttpError, p as UploadProgress, u as TransportRequestConfig } from "./rest-transport.types-DM5-qyOJ.mjs";
|
|
10
|
-
import { n as NativeRestInterceptor, r as NativeRestClient, t as NativeInterceptor } from "./native-rest-interceptor-
|
|
10
|
+
import { n as NativeRestInterceptor, r as NativeRestClient, t as NativeInterceptor } from "./native-rest-interceptor-PgziZt1f.mjs";
|
|
11
11
|
import { a as AppQueryOptions, i as AppMutationOptions, n as useMutationEffects, r as AppInfiniteQueryOptions, t as MutationEffectsOptions } from "./useMutationEffects-DIdL8tlx.mjs";
|
|
12
12
|
export { type AppInfiniteQueryOptions, type AppMutationOptions, type AppQueryOptions, ApplicationException, AuthContext, AuthGuard, type AuthGuardProps, type DomainErrorEntry, DomainErrorRegistry, type ErrorEntry, ErrorHandler, type ErrorHandlerOptions, type GeneralErrorCodes, type RestClient as IRestClient, type InvalidationMap, type InvalidationMapFunc, type MutationEffectsOptions, HttpError as NativeHttpError, type NativeInterceptor, type TransportRequest as NativeRequest, type TransportRequestConfig as NativeRequestConfig, type TransportResponse as NativeResponse, NativeRestClient, NativeRestInterceptor, type UploadProgress as NativeUploadProgress, OpenAPICodegenConfig, OpenApiQueryConfig, OpenApiRouter, OpenApiWorkspaceContext, type QueryModule, type RequestConfig, type RequestInfo, type Response, RestClient$1 as RestClient, RestInterceptor, RestUtils, SharedErrorHandler, type TranslateFunction, configureTranslations, ns, resources, useMutationEffects, useWorkspaceContext };
|
package/dist/index.mjs
CHANGED
|
@@ -2,7 +2,7 @@ import { i as resources, n as ns, t as configureTranslations } from "./i18n-D-Fe
|
|
|
2
2
|
import { a as RestUtils, i as SharedErrorHandler, n as DomainErrorRegistry, r as ErrorHandler, t as ApplicationException } from "./error-handling-BeydPL7s.mjs";
|
|
3
3
|
import { t as HttpError } from "./rest-transport.types-DxitRtsB.mjs";
|
|
4
4
|
import { n as RestClient, t as RestInterceptor } from "./rest-interceptor-D5NCNTm1.mjs";
|
|
5
|
-
import { n as NativeRestClient, t as NativeRestInterceptor } from "./native-rest-interceptor-
|
|
5
|
+
import { n as NativeRestClient, t as NativeRestInterceptor } from "./native-rest-interceptor-Np4Ov54n.mjs";
|
|
6
6
|
import { t as OpenApiQueryConfig } from "./queryConfig.context-CldQ5YL9.mjs";
|
|
7
7
|
import { t as useMutationEffects } from "./useMutationEffects-PB1fvKWM.mjs";
|
|
8
8
|
import { t as OpenApiRouter } from "./router.context-EPlMBk3G.mjs";
|
package/dist/metro.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_generate_utils = require("./generate.utils-
|
|
2
|
+
const require_generate_utils = require("./generate.utils-BqlgVd-i.cjs");
|
|
3
3
|
let fs = require("fs");
|
|
4
4
|
fs = require_generate_utils.__toESM(fs, 1);
|
|
5
5
|
let path = require("path");
|
|
@@ -97,7 +97,7 @@ async function runGenerate({ fileConfig, params, formatGeneratedFile, profiler =
|
|
|
97
97
|
const nativeFiles = generateFilesFromNativeOpenAPI(nativeInput.source, nativeInput.yaml, config);
|
|
98
98
|
if (nativeFiles) return nativeFiles;
|
|
99
99
|
}
|
|
100
|
-
const { generateCodeFromOpenAPIDoc } = await Promise.resolve().then(() => require("./generateCodeFromOpenAPIDoc-
|
|
100
|
+
const { generateCodeFromOpenAPIDoc } = await Promise.resolve().then(() => require("./generateCodeFromOpenAPIDoc-CkVgg5Zy.cjs"));
|
|
101
101
|
return generateCodeFromOpenAPIDoc(openApiDoc, config, profiler, {
|
|
102
102
|
source: nativeInput.source,
|
|
103
103
|
yaml: nativeInput.yaml
|
package/dist/metro.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as createOpenApiCodegenRunner } from "./openapi-codegen.runner-
|
|
2
|
-
import { i as normalizeWatchFolders, r as isTinyOpenApiFakeMode, t as createTinyOpenApiSourceRunner } from "./openapi-source.runner-
|
|
1
|
+
import { t as createOpenApiCodegenRunner } from "./openapi-codegen.runner-BZH4V6rq.mjs";
|
|
2
|
+
import { i as normalizeWatchFolders, r as isTinyOpenApiFakeMode, t as createTinyOpenApiSourceRunner } from "./openapi-source.runner-DPUNTduQ.mjs";
|
|
3
3
|
import fs from "fs";
|
|
4
4
|
import path from "path";
|
|
5
5
|
//#region src/metro/openapi-codegen.plugin.ts
|
|
@@ -3,12 +3,14 @@ import { z } from "zod";
|
|
|
3
3
|
//#region src/lib/rest/native-rest-client.ts
|
|
4
4
|
var NativeRestClient = class {
|
|
5
5
|
interceptors;
|
|
6
|
-
|
|
6
|
+
errorHandler;
|
|
7
|
+
constructor({ config, interceptors = [], errorHandler } = {}) {
|
|
7
8
|
this.baseURL = config?.baseURL ?? "";
|
|
8
9
|
this.headers = config?.headers;
|
|
9
10
|
this.credentials = config?.credentials;
|
|
10
11
|
this.fetch = config?.fetch ?? globalThis.fetch.bind(globalThis);
|
|
11
12
|
this.interceptors = [...interceptors];
|
|
13
|
+
this.errorHandler = errorHandler;
|
|
12
14
|
}
|
|
13
15
|
baseURL;
|
|
14
16
|
headers;
|
|
@@ -55,10 +57,12 @@ var NativeRestClient = class {
|
|
|
55
57
|
const headers = new Headers(this.headers);
|
|
56
58
|
new Headers(config.headers).forEach((value, key) => headers.set(key, value));
|
|
57
59
|
let body;
|
|
58
|
-
if (data != null)
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
60
|
+
if (data != null) {
|
|
61
|
+
if (data instanceof FormData || data instanceof Blob || typeof data === "string") body = data;
|
|
62
|
+
else {
|
|
63
|
+
body = JSON.stringify(data);
|
|
64
|
+
if (!headers.has("content-type")) headers.set("content-type", "application/json");
|
|
65
|
+
}
|
|
62
66
|
}
|
|
63
67
|
const request = {
|
|
64
68
|
url: this.resolveUrl(path, config.params),
|
|
@@ -84,7 +88,8 @@ var NativeRestClient = class {
|
|
|
84
88
|
} : dataResult;
|
|
85
89
|
} catch (error) {
|
|
86
90
|
if (error instanceof z.ZodError) error.name = "BE Response schema mismatch - ZodError";
|
|
87
|
-
|
|
91
|
+
const transformed = await this.runErrorInterceptors(error);
|
|
92
|
+
throw this.errorHandler ? this.errorHandler.rethrowError(transformed) : transformed;
|
|
88
93
|
}
|
|
89
94
|
}
|
|
90
95
|
async execute(request, config = {}, applyInterceptors = true) {
|
|
@@ -92,8 +97,10 @@ var NativeRestClient = class {
|
|
|
92
97
|
if (applyInterceptors) for (const interceptor of this.interceptors) next = await interceptor.onRequest?.(next) ?? next;
|
|
93
98
|
const timeoutController = config.timeout ? new AbortController() : void 0;
|
|
94
99
|
const timer = timeoutController ? setTimeout(() => timeoutController.abort(), config.timeout) : void 0;
|
|
95
|
-
if (timeoutController && next.signal)
|
|
96
|
-
|
|
100
|
+
if (timeoutController && next.signal) {
|
|
101
|
+
if (next.signal.aborted) timeoutController.abort(next.signal.reason);
|
|
102
|
+
else next.signal.addEventListener("abort", () => timeoutController.abort(next.signal?.reason), { once: true });
|
|
103
|
+
}
|
|
97
104
|
const signal = timeoutController?.signal ?? next.signal;
|
|
98
105
|
try {
|
|
99
106
|
const res = await this.fetch(next.url, {
|
package/dist/{native-rest-interceptor-Cz6saoq5.d.mts → native-rest-interceptor-PgziZt1f.d.mts}
RENAMED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
+
import { a as ErrorHandler } from "./error-handling-LPEPQV1V.mjs";
|
|
1
2
|
import { a as RestTransport, c as TransportFetch, d as TransportResponse, l as TransportRequest, o as RestTransportInterceptor, r as RestRequestInfo, s as TransportErrorContext, t as GeneralTransportErrorCode, u as TransportRequestConfig } from "./rest-transport.types-DM5-qyOJ.mjs";
|
|
2
3
|
//#region src/lib/rest/native-rest-client.d.ts
|
|
3
4
|
type NativeResult<T, IsRawRes extends boolean> = IsRawRes extends true ? TransportResponse<T> : T;
|
|
4
5
|
declare class NativeRestClient implements RestTransport {
|
|
5
6
|
private readonly interceptors;
|
|
6
|
-
|
|
7
|
+
private readonly errorHandler?;
|
|
8
|
+
constructor({ config, interceptors, errorHandler }?: {
|
|
7
9
|
config?: {
|
|
8
10
|
baseURL?: string;
|
|
9
11
|
headers?: HeadersInit;
|
|
@@ -11,6 +13,7 @@ declare class NativeRestClient implements RestTransport {
|
|
|
11
13
|
fetch?: TransportFetch;
|
|
12
14
|
};
|
|
13
15
|
interceptors?: RestTransportInterceptor[];
|
|
16
|
+
errorHandler?: ErrorHandler<any>;
|
|
14
17
|
});
|
|
15
18
|
private readonly baseURL;
|
|
16
19
|
private readonly headers?;
|
package/dist/native.d.mts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { a as RestTransport, d as TransportResponse, f as TransportResult, i as RestResponseType, l as TransportRequest, n as HttpError, o as RestTransportInterceptor, p as UploadProgress, r as RestRequestInfo, t as GeneralTransportErrorCode, u as TransportRequestConfig } from "./rest-transport.types-DM5-qyOJ.mjs";
|
|
2
|
-
import { n as NativeRestInterceptor, r as NativeRestClient, t as NativeInterceptor } from "./native-rest-interceptor-
|
|
2
|
+
import { n as NativeRestInterceptor, r as NativeRestClient, t as NativeInterceptor } from "./native-rest-interceptor-PgziZt1f.mjs";
|
|
3
3
|
export { type GeneralTransportErrorCode, HttpError, HttpError as NativeHttpError, type NativeInterceptor, type TransportRequest as NativeRequest, type TransportRequest, type TransportRequestConfig as NativeRequestConfig, type TransportRequestConfig, type TransportResponse as NativeResponse, type TransportResponse, NativeRestClient, NativeRestInterceptor, type UploadProgress as NativeUploadProgress, type UploadProgress, type RestRequestInfo, type RestResponseType, type RestTransport, type RestTransportInterceptor, type TransportResult };
|
package/dist/native.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import { t as HttpError } from "./rest-transport.types-DxitRtsB.mjs";
|
|
2
|
-
import { n as NativeRestClient, t as NativeRestInterceptor } from "./native-rest-interceptor-
|
|
2
|
+
import { n as NativeRestClient, t as NativeRestInterceptor } from "./native-rest-interceptor-Np4Ov54n.mjs";
|
|
3
3
|
export { HttpError, HttpError as NativeHttpError, NativeRestClient, NativeRestInterceptor };
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -1,5 +1,4 @@
|
|
|
1
|
-
import { Wn as Profiler } from "./
|
|
2
|
-
import { n as runGenerate } from "./generate.runner-D8AYuEFm.mjs";
|
|
1
|
+
import { Wn as Profiler, n as runGenerate } from "./generate.runner-BD9BbYIx.mjs";
|
|
3
2
|
import path from "path";
|
|
4
3
|
//#region src/plugins/openapi-codegen.runner.ts
|
|
5
4
|
function createOpenApiCodegenRunner(config, options = {}) {
|
|
@@ -314,11 +314,13 @@ function collectContractSchemas(router, routerPath = [], schemas = {}, getSchema
|
|
|
314
314
|
if (procedure) {
|
|
315
315
|
const procedureName = routerPath.map(toPascalCase).join("");
|
|
316
316
|
const { inputSchema, outputSchema, route } = procedure;
|
|
317
|
-
if (inputSchema)
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
317
|
+
if (inputSchema) {
|
|
318
|
+
if (route.inputStructure === "detailed") {
|
|
319
|
+
addContractSchema(schemas, getObjectPropertySchema(inputSchema, "params"), procedureSchemaName(procedureName, "Params"), getSchemaName);
|
|
320
|
+
addContractSchema(schemas, getObjectPropertySchema(inputSchema, "query"), procedureSchemaName(procedureName, "Query"), getSchemaName);
|
|
321
|
+
addContractSchema(schemas, getObjectPropertySchema(inputSchema, "body") ?? inputSchema, procedureSchemaName(procedureName, "Request"), getSchemaName);
|
|
322
|
+
} else addContractSchema(schemas, inputSchema, procedureSchemaName(procedureName, getProcedureInputSchemaRole(route)), getSchemaName);
|
|
323
|
+
}
|
|
322
324
|
if (outputSchema && route.successStatus !== 204) addContractSchema(schemas, outputSchema, procedureSchemaName(procedureName, "Response"), getSchemaName, "output");
|
|
323
325
|
return schemas;
|
|
324
326
|
}
|
package/dist/sh.mjs
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
-
import { i as VALIDATION_ERROR_TYPE_TITLE, n as groupByType, t as getDataFromOpenAPIDoc } from "./getDataFromOpenAPIDoc-
|
|
3
|
-
import { D as getTagFileName, Wn as Profiler,
|
|
4
|
-
import { n as runGenerate, r as resolveConfig, t as getOpenApiDoc } from "./generate.runner-D8AYuEFm.mjs";
|
|
2
|
+
import { i as VALIDATION_ERROR_TYPE_TITLE, n as groupByType, t as getDataFromOpenAPIDoc } from "./getDataFromOpenAPIDoc-Cyrm3VKA.mjs";
|
|
3
|
+
import { D as getTagFileName, Wn as Profiler, a as resolveConfig, n as runGenerate, o as getOutputFileName, t as getOpenApiDoc } from "./generate.runner-BD9BbYIx.mjs";
|
|
5
4
|
import yargs from "yargs";
|
|
6
5
|
import { hideBin } from "yargs/helpers";
|
|
7
6
|
import { styleText } from "node:util";
|
|
@@ -32,7 +31,7 @@ function logBanner(message) {
|
|
|
32
31
|
* Fetch the version from package.json
|
|
33
32
|
*/
|
|
34
33
|
function getVersion() {
|
|
35
|
-
return "3.2.
|
|
34
|
+
return "3.2.1";
|
|
36
35
|
}
|
|
37
36
|
//#endregion
|
|
38
37
|
//#region src/helpers/yargs.helper.ts
|
|
@@ -158,12 +157,12 @@ async function check({ verbose, config: configParam, includeTags: _includeTagsPa
|
|
|
158
157
|
else throw new Error(`Found ${errorMessages.length} issues. Time: ${Date.now() - start}ms`);
|
|
159
158
|
}
|
|
160
159
|
//#endregion
|
|
161
|
-
//#region \0@oxc-project+runtime@0.
|
|
160
|
+
//#region \0@oxc-project+runtime@0.148.0/helpers/esm/decorateMetadata.js
|
|
162
161
|
function __decorateMetadata(k, v) {
|
|
163
162
|
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
164
163
|
}
|
|
165
164
|
//#endregion
|
|
166
|
-
//#region \0@oxc-project+runtime@0.
|
|
165
|
+
//#region \0@oxc-project+runtime@0.148.0/helpers/esm/decorate.js
|
|
167
166
|
function __decorate(decorators, target, key, desc) {
|
|
168
167
|
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
169
168
|
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
@@ -241,8 +240,10 @@ async function generate({ prettier, verbose, config: configParam, ...params }) {
|
|
|
241
240
|
function execPrettier({ output, verbose }) {
|
|
242
241
|
if (verbose) logInfo("Running Prettier...");
|
|
243
242
|
exec(`prettier --write ${output} `, (error) => {
|
|
244
|
-
if (verbose)
|
|
245
|
-
|
|
243
|
+
if (verbose) {
|
|
244
|
+
if (error) logError(error, "Prettier error");
|
|
245
|
+
else logSuccess("Prettier finished.");
|
|
246
|
+
}
|
|
246
247
|
});
|
|
247
248
|
}
|
|
248
249
|
//#endregion
|
package/dist/tiny.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as namedControllerActionInputDtoSchema, A as generateORPCOpenAPISpec, B as getOperationController, C as collectReachableModelSchemas, D as defineOpenApiSchemas, E as createModelSchemaNameGetter, F as getModuleOpenApiController, G as isContractProcedure, H as getProcedureInputSchemaRole, I as getModuleOpenApiTag, J as isObject, K as isNullSchema, L as getObjectPropertySchema, M as getComponentSchemas, N as getContractProcedureData, O as findComponentEnumNames, P as getDerivedOperationId, Q as modelSchemaNameEntries, R as getOpenApiSchemaName, S as collectOperationTags, T as compactTagName, U as getRobodevModuleRoles, V as getPaginatedItemSchema, W as getStringEnumValues, X as isZodSchema, Y as isProcedureMeta, Z as modelSchemaExportName, _ as collectDbTableModelSchemaExports, _t as visitZodSchema, a as addContractSchema, at as operationKey, b as collectModuleModelSchemaExports, c as applyPaginatedItemSchemas, ct as routeHasPathParameters, d as applyRobodevUserRolesExtension, dt as sharedSchemaExportName, et as namedControllerActionSchema, f as asStringArray, ft as stripNoContentResponseBodies, g as collectDbTableModelSchemaExport, gt as toPascalCase, h as collectContractSchemas, ht as toOpenAPIAclRule, i as normalizeWatchFolders, it as namedOpenApiSchema, j as generateOpenApiFile, k as findEnumNames, l as applyParameterExtensions, lt as schemaComponentRef, m as collectContractSchemaRoots, mt as toOpenAPI30Schema, n as getLocalInputPath, nt as namedOpenApiRequestSchema, o as applyEnumExtensions, ot as procedureSchemaName, p as collectApiModelSchemaExports, pt as toOpenAPI30Document, q as isNullableOnlySchema, r as isTinyOpenApiFakeMode, rt as namedOpenApiResponseSchema, s as applyOperationMeta, st as resolveOpenApiOutputPath, t as createTinyOpenApiSourceRunner, tt as namedOpenApiOutputSchema, u as applyRobodevModuleExtensions, ut as schemaExportName, v as collectExtraSchemas, w as collectSchemaRegistryRoots, x as collectOperationMeta, y as collectModelSchemaExports, z as getOperationAction } from "./openapi-source.runner-
|
|
1
|
+
import { $ as namedControllerActionInputDtoSchema, A as generateORPCOpenAPISpec, B as getOperationController, C as collectReachableModelSchemas, D as defineOpenApiSchemas, E as createModelSchemaNameGetter, F as getModuleOpenApiController, G as isContractProcedure, H as getProcedureInputSchemaRole, I as getModuleOpenApiTag, J as isObject, K as isNullSchema, L as getObjectPropertySchema, M as getComponentSchemas, N as getContractProcedureData, O as findComponentEnumNames, P as getDerivedOperationId, Q as modelSchemaNameEntries, R as getOpenApiSchemaName, S as collectOperationTags, T as compactTagName, U as getRobodevModuleRoles, V as getPaginatedItemSchema, W as getStringEnumValues, X as isZodSchema, Y as isProcedureMeta, Z as modelSchemaExportName, _ as collectDbTableModelSchemaExports, _t as visitZodSchema, a as addContractSchema, at as operationKey, b as collectModuleModelSchemaExports, c as applyPaginatedItemSchemas, ct as routeHasPathParameters, d as applyRobodevUserRolesExtension, dt as sharedSchemaExportName, et as namedControllerActionSchema, f as asStringArray, ft as stripNoContentResponseBodies, g as collectDbTableModelSchemaExport, gt as toPascalCase, h as collectContractSchemas, ht as toOpenAPIAclRule, i as normalizeWatchFolders, it as namedOpenApiSchema, j as generateOpenApiFile, k as findEnumNames, l as applyParameterExtensions, lt as schemaComponentRef, m as collectContractSchemaRoots, mt as toOpenAPI30Schema, n as getLocalInputPath, nt as namedOpenApiRequestSchema, o as applyEnumExtensions, ot as procedureSchemaName, p as collectApiModelSchemaExports, pt as toOpenAPI30Document, q as isNullableOnlySchema, r as isTinyOpenApiFakeMode, rt as namedOpenApiResponseSchema, s as applyOperationMeta, st as resolveOpenApiOutputPath, t as createTinyOpenApiSourceRunner, tt as namedOpenApiOutputSchema, u as applyRobodevModuleExtensions, ut as schemaExportName, v as collectExtraSchemas, w as collectSchemaRegistryRoots, x as collectOperationMeta, y as collectModelSchemaExports, z as getOperationAction } from "./openapi-source.runner-DPUNTduQ.mjs";
|
|
2
2
|
export { addContractSchema, applyEnumExtensions, applyOperationMeta, applyPaginatedItemSchemas, applyParameterExtensions, applyRobodevModuleExtensions, applyRobodevUserRolesExtension, asStringArray, collectApiModelSchemaExports, collectContractSchemaRoots, collectContractSchemas, collectDbTableModelSchemaExport, collectDbTableModelSchemaExports, collectExtraSchemas, collectModelSchemaExports, collectModuleModelSchemaExports, collectOperationMeta, collectOperationTags, collectReachableModelSchemas, collectSchemaRegistryRoots, compactTagName, createModelSchemaNameGetter, createTinyOpenApiSourceRunner, defineOpenApiSchemas, findComponentEnumNames, findEnumNames, generateORPCOpenAPISpec, generateOpenApiFile, getComponentSchemas, getContractProcedureData, getDerivedOperationId, getModuleOpenApiController, getModuleOpenApiTag, getObjectPropertySchema, getOpenApiSchemaName, getOperationAction, getOperationController, getPaginatedItemSchema, getProcedureInputSchemaRole, getRobodevModuleRoles, getStringEnumValues, getLocalInputPath as getTinyOpenApiLocalInputPath, isContractProcedure, isNullSchema, isNullableOnlySchema, isObject, isProcedureMeta, isTinyOpenApiFakeMode, isZodSchema, modelSchemaExportName, modelSchemaNameEntries, namedControllerActionInputDtoSchema, namedControllerActionSchema, namedOpenApiOutputSchema, namedOpenApiRequestSchema, namedOpenApiResponseSchema, namedOpenApiSchema, normalizeWatchFolders as normalizeTinyOpenApiWatchFolders, operationKey, procedureSchemaName, resolveOpenApiOutputPath, routeHasPathParameters, schemaComponentRef, schemaExportName, sharedSchemaExportName, stripNoContentResponseBodies, toOpenAPI30Document, toOpenAPI30Schema, toOpenAPIAclRule, toPascalCase, visitZodSchema };
|
package/dist/vite.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as createOpenApiCodegenRunner } from "./openapi-codegen.runner-
|
|
2
|
-
import { i as normalizeWatchFolders, r as isTinyOpenApiFakeMode, t as createTinyOpenApiSourceRunner } from "./openapi-source.runner-
|
|
1
|
+
import { t as createOpenApiCodegenRunner } from "./openapi-codegen.runner-BZH4V6rq.mjs";
|
|
2
|
+
import { i as normalizeWatchFolders, r as isTinyOpenApiFakeMode, t as createTinyOpenApiSourceRunner } from "./openapi-source.runner-DPUNTduQ.mjs";
|
|
3
3
|
import path from "path";
|
|
4
4
|
//#region src/vite/openapi-codegen.plugin.ts
|
|
5
5
|
function openApiCodegen(config) {
|
package/package.json
CHANGED
|
@@ -127,7 +127,7 @@
|
|
|
127
127
|
"@casl/ability": "6.8.0",
|
|
128
128
|
"@casl/react": "5.0.1",
|
|
129
129
|
"@tanstack/react-query": "~5.90.21",
|
|
130
|
-
"@types/bun": "1.
|
|
130
|
+
"@types/bun": "1.4.1",
|
|
131
131
|
"@types/node": "^25.3.0",
|
|
132
132
|
"@types/prompt-sync": "^4.2.3",
|
|
133
133
|
"@types/react": "^19.2.14",
|
|
@@ -146,7 +146,7 @@
|
|
|
146
146
|
"vite": "npm:rolldown-vite@^7.3.1",
|
|
147
147
|
"vite-plugin-dts": "^4.5.4",
|
|
148
148
|
"vitest": "4.0.18",
|
|
149
|
-
"zod": "^4.
|
|
149
|
+
"zod": "^4.5.0"
|
|
150
150
|
},
|
|
151
151
|
"peerDependencies": {
|
|
152
152
|
"@casl/ability": "^6.7.3",
|
|
@@ -156,7 +156,7 @@
|
|
|
156
156
|
"i18next": "^25.8.11",
|
|
157
157
|
"react": "^19.1.0",
|
|
158
158
|
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
|
|
159
|
-
"zod": "^4.
|
|
159
|
+
"zod": "^4.5.0"
|
|
160
160
|
},
|
|
161
161
|
"peerDependenciesMeta": {
|
|
162
162
|
"@casl/ability": {
|
|
@@ -182,9 +182,9 @@
|
|
|
182
182
|
}
|
|
183
183
|
},
|
|
184
184
|
"engines": {
|
|
185
|
-
"bun": ">= 1.
|
|
185
|
+
"bun": ">= 1.4",
|
|
186
186
|
"node": ">= 18"
|
|
187
187
|
},
|
|
188
|
-
"packageManager": "bun@1.
|
|
189
|
-
"version": "3.2.
|
|
188
|
+
"packageManager": "bun@1.4.1",
|
|
189
|
+
"version": "3.2.1"
|
|
190
190
|
}
|
|
@@ -1,184 +0,0 @@
|
|
|
1
|
-
import { D as getTagFileName, Wn as Profiler, a as writeGenerateFileData, dt as DEFAULT_GENERATE_OPTIONS, i as removeStaleGeneratedFiles, n as shouldUseNativeCodegen, o as deepMerge, r as getOutputFileName, t as compileNativeData } from "./native-bindings-BTQGSGhU.mjs";
|
|
2
|
-
import fs from "fs";
|
|
3
|
-
import path from "path";
|
|
4
|
-
//#region src/generators/core/resolveConfig.ts
|
|
5
|
-
function resolveConfig({ fileConfig = {}, params: { includeTags, excludeTags, inlineEndpointsExcludeModules, workspaceContext, ...options } }) {
|
|
6
|
-
const resolvedConfig = deepMerge(DEFAULT_GENERATE_OPTIONS, fileConfig ?? {}, {
|
|
7
|
-
...options,
|
|
8
|
-
includeTags: includeTags?.split(","),
|
|
9
|
-
excludeTags: excludeTags?.split(","),
|
|
10
|
-
inlineEndpointsExcludeModules: inlineEndpointsExcludeModules?.split(","),
|
|
11
|
-
workspaceContext: workspaceContext?.split(",")
|
|
12
|
-
});
|
|
13
|
-
resolvedConfig.checkAcl = resolvedConfig.acl && resolvedConfig.checkAcl;
|
|
14
|
-
resolvedConfig.workspaceContext = Array.from(new Set((resolvedConfig.workspaceContext ?? []).map((value) => value.trim()).filter(Boolean)));
|
|
15
|
-
return resolvedConfig;
|
|
16
|
-
}
|
|
17
|
-
//#endregion
|
|
18
|
-
//#region src/native/generateFilesFromNativeOpenAPI.ts
|
|
19
|
-
function generateFilesFromNativeOpenAPI(source, yaml, options) {
|
|
20
|
-
if (!supportsCompleteNativeRender(options)) {
|
|
21
|
-
if (process.env.OPENAPI_CODEGEN_REQUIRE_FULL_NATIVE === "1") throw new Error("The selected options are not supported by the full native renderer");
|
|
22
|
-
return;
|
|
23
|
-
}
|
|
24
|
-
const nativeData = compileNativeData(source, yaml, JSON.stringify({
|
|
25
|
-
...options,
|
|
26
|
-
nativeCompact: true
|
|
27
|
-
})).data;
|
|
28
|
-
if (!nativeData.renderedComplete) {
|
|
29
|
-
if (process.env.OPENAPI_CODEGEN_REQUIRE_FULL_NATIVE === "1") throw new Error("The selected options are not supported by the full native renderer");
|
|
30
|
-
return;
|
|
31
|
-
}
|
|
32
|
-
const files = [];
|
|
33
|
-
const taggedRenderers = options.modelsOnly ? [["models", nativeData.renderedModels]] : [
|
|
34
|
-
["models", nativeData.renderedModels],
|
|
35
|
-
["endpoints", nativeData.renderedEndpoints],
|
|
36
|
-
["queries", nativeData.renderedQueries],
|
|
37
|
-
...options.acl ? [["acl", nativeData.renderedAcl]] : []
|
|
38
|
-
];
|
|
39
|
-
for (const tag of nativeData.renderedTags) for (const [type, rendered] of taggedRenderers) {
|
|
40
|
-
const content = rendered[tag];
|
|
41
|
-
if (content) files.push(taggedFile(options, tag, type, content));
|
|
42
|
-
}
|
|
43
|
-
if (!options.modelsOnly) {
|
|
44
|
-
if (options.acl && nativeData.renderedShared.appAcl) files.push(outputFile(options, "acl/app.ability.ts", nativeData.renderedShared.appAcl));
|
|
45
|
-
if (options.mutationEffects && nativeData.renderedShared.queryModules) files.push(outputFile(options, "queryModules.ts", nativeData.renderedShared.queryModules));
|
|
46
|
-
if (!options.restClientImportPath) files.push(outputFile(options, "app-rest-client.ts", `import { ${options.restClient === "native" ? "NativeRestClient" : "RestClient"} } from "@povio/openapi-codegen-cli${options.restClient === "native" ? "/native" : ""}";\n\nexport const AppRestClient = new ${options.restClient === "native" ? "NativeRestClient" : "RestClient"}({\n config: {\n baseURL: "${nativeData.baseUrl}"\n },\n});\n`));
|
|
47
|
-
if (nativeData.renderedShared.domainErrors) files.push(outputFile(options, "domain-errors.ts", nativeData.renderedShared.domainErrors));
|
|
48
|
-
}
|
|
49
|
-
return files;
|
|
50
|
-
}
|
|
51
|
-
function supportsCompleteNativeRender(options) {
|
|
52
|
-
return options.splitByTags && (options.modelsInCommon && options.tsNamespaces || !options.modelsInCommon && !options.tsNamespaces) && !options.inlineEndpoints && !options.builderConfigs && (options.workspaceContext?.length ?? 0) === 0;
|
|
53
|
-
}
|
|
54
|
-
function taggedFile(options, tag, type, content) {
|
|
55
|
-
return outputFile(options, getTagFileName({
|
|
56
|
-
tag,
|
|
57
|
-
type,
|
|
58
|
-
options
|
|
59
|
-
}), content);
|
|
60
|
-
}
|
|
61
|
-
function outputFile(options, fileName, content) {
|
|
62
|
-
return {
|
|
63
|
-
fileName: getOutputFileName({
|
|
64
|
-
output: options.output,
|
|
65
|
-
fileName
|
|
66
|
-
}),
|
|
67
|
-
content
|
|
68
|
-
};
|
|
69
|
-
}
|
|
70
|
-
//#endregion
|
|
71
|
-
//#region src/generators/run/generate.runner.ts
|
|
72
|
-
async function runGenerate({ fileConfig, params, formatGeneratedFile, profiler = new Profiler(process.env.OPENAPI_CODEGEN_PROFILE === "1") }) {
|
|
73
|
-
const config = profiler.runSync("config.resolve", () => resolveConfig({
|
|
74
|
-
fileConfig,
|
|
75
|
-
params: params ?? {}
|
|
76
|
-
}));
|
|
77
|
-
const useNative = shouldUseNativeCodegen();
|
|
78
|
-
const isJson = path.extname(new URL(config.input, "file://").pathname).toLowerCase() === ".json";
|
|
79
|
-
const useRawNativeInput = useNative && (isJson || typeof Bun === "undefined");
|
|
80
|
-
let nativeInput = useRawNativeInput ? await getRawOpenApiSource(config.input, profiler) : await getOpenApiSource(config.input, profiler);
|
|
81
|
-
if (useNative && !useRawNativeInput) {
|
|
82
|
-
const document = "document" in nativeInput ? nativeInput.document : void 0;
|
|
83
|
-
nativeInput = {
|
|
84
|
-
...nativeInput,
|
|
85
|
-
source: profiler.runSync("openapi.serialize", () => JSON.stringify(document)),
|
|
86
|
-
yaml: false
|
|
87
|
-
};
|
|
88
|
-
}
|
|
89
|
-
const openApiDoc = "document" in nativeInput ? nativeInput.document : {};
|
|
90
|
-
const outputExists = fs.existsSync(config.output);
|
|
91
|
-
const filesData = await profiler.runAsync("generate.total", async () => {
|
|
92
|
-
if (useNative) {
|
|
93
|
-
const nativeFiles = generateFilesFromNativeOpenAPI(nativeInput.source, nativeInput.yaml, config);
|
|
94
|
-
if (nativeFiles) return nativeFiles;
|
|
95
|
-
}
|
|
96
|
-
const { generateCodeFromOpenAPIDoc } = await import("./generateCodeFromOpenAPIDoc--ufinTug.mjs").then((n) => n.n);
|
|
97
|
-
return generateCodeFromOpenAPIDoc(openApiDoc, config, profiler, {
|
|
98
|
-
source: nativeInput.source,
|
|
99
|
-
yaml: nativeInput.yaml
|
|
100
|
-
});
|
|
101
|
-
});
|
|
102
|
-
if (config.clearOutput) profiler.runSync("files.removeStaleGenerated", () => {
|
|
103
|
-
removeStaleGeneratedFiles({
|
|
104
|
-
output: config.output,
|
|
105
|
-
filesData,
|
|
106
|
-
options: config
|
|
107
|
-
});
|
|
108
|
-
});
|
|
109
|
-
await profiler.runAsync("files.write", async () => {
|
|
110
|
-
await writeGenerateFileData(filesData, {
|
|
111
|
-
formatGeneratedFile,
|
|
112
|
-
skipExistingCheck: !outputExists
|
|
113
|
-
});
|
|
114
|
-
});
|
|
115
|
-
return {
|
|
116
|
-
skipped: false,
|
|
117
|
-
config,
|
|
118
|
-
stats: getGenerateStats(filesData, config)
|
|
119
|
-
};
|
|
120
|
-
}
|
|
121
|
-
async function getOpenApiDoc(input, profiler = new Profiler(false)) {
|
|
122
|
-
return (await getOpenApiSource(input, profiler)).document;
|
|
123
|
-
}
|
|
124
|
-
async function getOpenApiSource(input, profiler = new Profiler(false)) {
|
|
125
|
-
const raw = await getRawOpenApiSource(input, profiler);
|
|
126
|
-
const { source } = raw;
|
|
127
|
-
const document = await profiler.runAsync("openapi.parse", () => parseOpenApiSource(input, source));
|
|
128
|
-
return {
|
|
129
|
-
...raw,
|
|
130
|
-
document
|
|
131
|
-
};
|
|
132
|
-
}
|
|
133
|
-
async function getRawOpenApiSource(input, profiler = new Profiler(false)) {
|
|
134
|
-
return {
|
|
135
|
-
source: await profiler.runAsync("openapi.read", () => readOpenApiSource(input)),
|
|
136
|
-
yaml: path.extname(new URL(input, "file://").pathname).toLowerCase() !== ".json"
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
|
-
async function readOpenApiSource(input) {
|
|
140
|
-
if (/^https?:\/\//i.test(input)) {
|
|
141
|
-
const response = await fetch(input);
|
|
142
|
-
if (!response.ok) throw new Error(`Unable to load OpenAPI document: ${response.status} ${response.statusText}`);
|
|
143
|
-
return response.text();
|
|
144
|
-
}
|
|
145
|
-
return fs.promises.readFile(input, "utf-8");
|
|
146
|
-
}
|
|
147
|
-
async function parseOpenApiSource(input, source) {
|
|
148
|
-
try {
|
|
149
|
-
return JSON.parse(source.charCodeAt(0) === 65279 ? source.slice(1) : source);
|
|
150
|
-
} catch (error) {
|
|
151
|
-
if (path.extname(new URL(input, "file://").pathname).toLowerCase() === ".json") throw error;
|
|
152
|
-
if (typeof Bun !== "undefined") return Bun.YAML.parse(source);
|
|
153
|
-
const { parse } = await import("yaml");
|
|
154
|
-
return parse(source);
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
function getGenerateStats(filesData, config) {
|
|
158
|
-
const generatedFilesCount = filesData.length;
|
|
159
|
-
if (generatedFilesCount === 0) return {
|
|
160
|
-
generatedFilesCount,
|
|
161
|
-
generatedModulesCount: 0
|
|
162
|
-
};
|
|
163
|
-
if (!config.splitByTags) return {
|
|
164
|
-
generatedFilesCount,
|
|
165
|
-
generatedModulesCount: 1
|
|
166
|
-
};
|
|
167
|
-
const moduleSuffixes = new Set(Object.values(config.configs).map((generateConfig) => generateConfig.outputFileNameSuffix).filter(Boolean));
|
|
168
|
-
const modules = /* @__PURE__ */ new Set();
|
|
169
|
-
for (const file of filesData) {
|
|
170
|
-
const segments = path.relative(config.output, file.fileName).split(path.sep).filter(Boolean);
|
|
171
|
-
if (segments.length < 2) continue;
|
|
172
|
-
const moduleName = segments[0];
|
|
173
|
-
const fileName = segments[segments.length - 1];
|
|
174
|
-
if (!fileName.startsWith(`${moduleName}.`)) continue;
|
|
175
|
-
const suffix = fileName.slice(moduleName.length + 1).replace(/\.tsx?$/, "");
|
|
176
|
-
if (moduleSuffixes.has(suffix)) modules.add(moduleName);
|
|
177
|
-
}
|
|
178
|
-
return {
|
|
179
|
-
generatedFilesCount,
|
|
180
|
-
generatedModulesCount: modules.size
|
|
181
|
-
};
|
|
182
|
-
}
|
|
183
|
-
//#endregion
|
|
184
|
-
export { runGenerate as n, resolveConfig as r, getOpenApiDoc as t };
|