@povio/openapi-codegen-cli 3.2.0-rc.14 → 3.2.0-rc.16

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.
@@ -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
- 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, writeGenerateFileData 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, removeStaleGeneratedFiles 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, shouldUseNativeCodegen as n, pathToVariableName as nn, getImportedZodSchemaInferedTypeName as nt, deepMerge as o, inferRequiredSchema as on, getZodSchemaPropertyDescriptions as ot, getEndpointConfig as p, BLOB_SCHEMA as pn, isBulkDeleteEndpoint as pt, getAbilityDescription as q, getSchemaRef as qt, getOutputFileName as r, replaceHyphenatedPath as rn, getImportedZodSchemaName as rt, pick as s, isArraySchemaObject as sn, getZodSchemaType as st, compileNativeData 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 };
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
  }
@@ -1,4 +1,4 @@
1
- const require_generate_utils = require("./generate.utils-DC1pIuhK.cjs");
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) if (schema.exclusiveMinimum === true) validations.push(`gt(${schema.minimum})`);
85
- else validations.push(`gte(${schema.minimum})`);
86
- else if (typeof schema.exclusiveMinimum === "number") validations.push(`gt(${schema.exclusiveMinimum})`);
87
- if (schema.maximum !== void 0) if (schema.exclusiveMaximum === true) validations.push(`lt(${schema.maximum})`);
88
- else validations.push(`lte(${schema.maximum})`);
89
- else if (typeof schema.exclusiveMaximum === "number") validations.push(`lt(${schema.exclusiveMaximum})`);
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) if (typeof schema.additionalProperties === "object") current += getOpenAPISchemaComplexity(0, schema.additionalProperties);
165
- else current += getOpenAPISchemaComplexity(1);
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 ? `get ${require_generate_utils.wrapWithQuotesIfNeeded(prop)}() { return ${propSchema} }` : `${require_generate_utils.wrapWithQuotesIfNeeded(prop)}: ${propSchema}`).join(", ")} }`;
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,
@@ -2186,8 +2190,10 @@ function getBuilderConfigs({ data, tag, resolver }) {
2186
2190
  if (!columnsConfig) return;
2187
2191
  importedEndpoints.push(readAllEndpoint);
2188
2192
  importedInfiniteEndpoints.push(readAllEndpoint);
2189
- if (columnsConfig.zodSchema) if (require_generate_utils.isNamedZodSchema(columnsConfig.zodSchema)) importedZodSchemas.push(columnsConfig.zodSchema);
2190
- else hasZodImport = true;
2193
+ if (columnsConfig.zodSchema) {
2194
+ if (require_generate_utils.isNamedZodSchema(columnsConfig.zodSchema)) importedZodSchemas.push(columnsConfig.zodSchema);
2195
+ else hasZodImport = true;
2196
+ }
2191
2197
  if (columnsConfig.sortableEnumSchemaName) importedZodSchemas.push(columnsConfig.sortableEnumSchemaName);
2192
2198
  const filter = readAllEndpoint.parameters.find((param) => param.name === resolver.options.filterParamName);
2193
2199
  if (filter) importedZodSchemas.push(filter.zodSchema);
@@ -2828,7 +2834,8 @@ function generateModels({ resolver, data, tag }) {
2828
2834
  const inferredTypeName = require_generate_utils.getZodSchemaInferedTypeName(name, resolver.options);
2829
2835
  if (zodSchema.isCircular && zodSchema.schemaObj) lines.push(`export type ${inferredTypeName} = ${renderSchemaType(zodSchema.schemaObj, resolver)};`);
2830
2836
  const typeAnnotation = zodSchema.isCircular ? `: z.ZodObject<z.ZodRawShape> & z.ZodType<${inferredTypeName}>` : "";
2831
- lines.push(`export const ${name}${typeAnnotation} = ${zodSchema.code};`);
2837
+ const schemaCode = zodSchema.isCircular ? zodSchema.code : `z.compile(${zodSchema.code})`;
2838
+ lines.push(`export const ${name}${typeAnnotation} = ${schemaCode};`);
2832
2839
  if (!zodSchema.isCircular) lines.push(`export type ${inferredTypeName} = z.infer<typeof ${name}>;`);
2833
2840
  if (zodSchema.isEnum) lines.push(`export const ${require_generate_utils.getZodSchemaInferedTypeName(name, resolver.options)} = ${name}.enum;`);
2834
2841
  lines.push("");
@@ -1,5 +1,5 @@
1
- import { r as getZodSchemaRefs, t as getDataFromOpenAPIDoc } from "./getDataFromOpenAPIDoc-Dj0cdt9r.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, 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, n as shouldUseNativeCodegen, nt as getImportedZodSchemaInferedTypeName, ot as getZodSchemaPropertyDescriptions, p as getEndpointConfig, pt as isBulkDeleteEndpoint, q as getAbilityDescription, r as getOutputFileName, rt as getImportedZodSchemaName, st as getZodSchemaType, t as compileNativeData, 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 "./native-bindings-DHQGvV7n.mjs";
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) if (isNamedZodSchema(columnsConfig.zodSchema)) importedZodSchemas.push(columnsConfig.zodSchema);
211
- else hasZodImport = true;
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);
@@ -849,7 +851,8 @@ function generateModels({ resolver, data, tag }) {
849
851
  const inferredTypeName = getZodSchemaInferedTypeName(name, resolver.options);
850
852
  if (zodSchema.isCircular && zodSchema.schemaObj) lines.push(`export type ${inferredTypeName} = ${renderSchemaType(zodSchema.schemaObj, resolver)};`);
851
853
  const typeAnnotation = zodSchema.isCircular ? `: z.ZodObject<z.ZodRawShape> & z.ZodType<${inferredTypeName}>` : "";
852
- lines.push(`export const ${name}${typeAnnotation} = ${zodSchema.code};`);
854
+ const schemaCode = zodSchema.isCircular ? zodSchema.code : `z.compile(${zodSchema.code})`;
855
+ lines.push(`export const ${name}${typeAnnotation} = ${schemaCode};`);
853
856
  if (!zodSchema.isCircular) lines.push(`export type ${inferredTypeName} = z.infer<typeof ${name}>;`);
854
857
  if (zodSchema.isEnum) lines.push(`export const ${getZodSchemaInferedTypeName(name, resolver.options)} = ${name}.enum;`);
855
858
  lines.push("");
@@ -1,7 +1,6 @@
1
- import { t as generateCodeFromOpenAPIDoc } from "./generateCodeFromOpenAPIDoc-D9AxX3_a.mjs";
2
- import { t as getDataFromOpenAPIDoc } from "./getDataFromOpenAPIDoc-Dj0cdt9r.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, u as isMutation, x as getSchemaTsMetaType } from "./native-bindings-DHQGvV7n.mjs";
4
- import { t as getOpenApiDoc } from "./generate.runner-Caxx62-r.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 "./native-bindings-DHQGvV7n.mjs";
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) if (schema.exclusiveMinimum === true) validations.push(`gt(${schema.minimum})`);
123
- else validations.push(`gte(${schema.minimum})`);
124
- else if (typeof schema.exclusiveMinimum === "number") validations.push(`gt(${schema.exclusiveMinimum})`);
125
- if (schema.maximum !== void 0) if (schema.exclusiveMaximum === true) validations.push(`lt(${schema.maximum})`);
126
- else validations.push(`lte(${schema.maximum})`);
127
- else if (typeof schema.exclusiveMaximum === "number") validations.push(`lt(${schema.exclusiveMaximum})`);
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) if (typeof schema.additionalProperties === "object") current += getOpenAPISchemaComplexity(0, schema.additionalProperties);
203
- else current += getOpenAPISchemaComplexity(1);
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 ? `get ${wrapWithQuotesIfNeeded(prop)}() { return ${propSchema} }` : `${wrapWithQuotesIfNeeded(prop)}: ${propSchema}`).join(", ")} }`;
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,
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-Bn_XbZ1y.mjs";
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-DC1pIuhK.cjs");
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-DDThW43F.cjs"));
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-Cic6E7Lr.mjs";
2
- import { i as normalizeWatchFolders, r as isTinyOpenApiFakeMode, t as createTinyOpenApiSourceRunner } from "./openapi-source.runner-BZ6ZLgRO.mjs";
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
@@ -57,10 +57,12 @@ var NativeRestClient = class {
57
57
  const headers = new Headers(this.headers);
58
58
  new Headers(config.headers).forEach((value, key) => headers.set(key, value));
59
59
  let body;
60
- if (data != null) if (data instanceof FormData || data instanceof Blob || typeof data === "string") body = data;
61
- else {
62
- body = JSON.stringify(data);
63
- if (!headers.has("content-type")) headers.set("content-type", "application/json");
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
+ }
64
66
  }
65
67
  const request = {
66
68
  url: this.resolveUrl(path, config.params),
@@ -95,8 +97,10 @@ var NativeRestClient = class {
95
97
  if (applyInterceptors) for (const interceptor of this.interceptors) next = await interceptor.onRequest?.(next) ?? next;
96
98
  const timeoutController = config.timeout ? new AbortController() : void 0;
97
99
  const timer = timeoutController ? setTimeout(() => timeoutController.abort(), config.timeout) : void 0;
98
- if (timeoutController && next.signal) if (next.signal.aborted) timeoutController.abort(next.signal.reason);
99
- else next.signal.addEventListener("abort", () => timeoutController.abort(next.signal?.reason), { once: true });
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
+ }
100
104
  const signal = timeoutController?.signal ?? next.signal;
101
105
  try {
102
106
  const res = await this.fetch(next.url, {
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-Bn_XbZ1y.mjs";
2
+ import { n as NativeRestClient, t as NativeRestInterceptor } from "./native-rest-interceptor-Np4Ov54n.mjs";
3
3
  export { HttpError, HttpError as NativeHttpError, NativeRestClient, NativeRestInterceptor };
@@ -1,5 +1,4 @@
1
- import { Wn as Profiler } from "./native-bindings-DHQGvV7n.mjs";
2
- import { n as runGenerate } from "./generate.runner-Caxx62-r.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) if (route.inputStructure === "detailed") {
318
- addContractSchema(schemas, getObjectPropertySchema(inputSchema, "params"), procedureSchemaName(procedureName, "Params"), getSchemaName);
319
- addContractSchema(schemas, getObjectPropertySchema(inputSchema, "query"), procedureSchemaName(procedureName, "Query"), getSchemaName);
320
- addContractSchema(schemas, getObjectPropertySchema(inputSchema, "body") ?? inputSchema, procedureSchemaName(procedureName, "Request"), getSchemaName);
321
- } else addContractSchema(schemas, inputSchema, procedureSchemaName(procedureName, getProcedureInputSchemaRole(route)), getSchemaName);
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-Dj0cdt9r.mjs";
3
- import { D as getTagFileName, Wn as Profiler, r as getOutputFileName } from "./native-bindings-DHQGvV7n.mjs";
4
- import { n as runGenerate, r as resolveConfig, t as getOpenApiDoc } from "./generate.runner-Caxx62-r.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.0-rc.14";
34
+ return "3.2.0-rc.16";
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.142.0/helpers/esm/decorateMetadata.js
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.142.0/helpers/esm/decorate.js
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) if (error) logError(error, "Prettier error");
245
- else logSuccess("Prettier finished.");
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-BZ6ZLgRO.mjs";
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-Cic6E7Lr.mjs";
2
- import { i as normalizeWatchFolders, r as isTinyOpenApiFakeMode, t as createTinyOpenApiSourceRunner } from "./openapi-source.runner-BZ6ZLgRO.mjs";
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.3.14",
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.3.6"
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.1.12"
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.3.14",
185
+ "bun": ">= 1.4",
186
186
  "node": ">= 18"
187
187
  },
188
- "packageManager": "bun@1.3.14",
189
- "version": "3.2.0-rc.14"
188
+ "packageManager": "bun@1.4.1",
189
+ "version": "3.2.0-rc.16"
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-DHQGvV7n.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-D9AxX3_a.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 };