@povio/openapi-codegen-cli 2.0.8-rc.2 → 2.0.8-rc.20

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.
Files changed (191) hide show
  1. package/README.md +63 -0
  2. package/dist/acl.d.mts +59 -0
  3. package/dist/acl.mjs +73 -7
  4. package/dist/auth.context-Bu5KW2sI.mjs +59 -0
  5. package/dist/config-BHkVxL6S.d.mts +6 -0
  6. package/dist/error-handling-CXeVTk1T.d.mts +38 -0
  7. package/dist/error-handling-DkPY7Asf.mjs +187 -0
  8. package/dist/generate.runner-DmZ5LVHf.mjs +130 -0
  9. package/dist/generateCodeFromOpenAPIDoc-DZ5swy4U.mjs +4465 -0
  10. package/dist/generator.d.mts +65 -0
  11. package/dist/generator.mjs +144 -0
  12. package/dist/index.d.mts +230 -0
  13. package/dist/index.mjs +251 -22
  14. package/dist/options-BNqkO_OS.d.mts +91 -0
  15. package/dist/sh.d.mts +1 -0
  16. package/dist/sh.mjs +439 -0
  17. package/dist/vite.d.mts +8 -0
  18. package/dist/vite.mjs +50 -0
  19. package/dist/zod.d.mts +20 -0
  20. package/dist/zod.mjs +33 -0
  21. package/package.json +54 -47
  22. package/dist/acl.d.ts +0 -4
  23. package/dist/commands/check.command.d.ts +0 -2
  24. package/dist/commands/check.d.ts +0 -7
  25. package/dist/commands/generate.command.d.ts +0 -2
  26. package/dist/commands/generate.d.ts +0 -8
  27. package/dist/generator.d.ts +0 -3
  28. package/dist/generator.js +0 -77
  29. package/dist/generators/checkOpenAPIDoc.d.ts +0 -3
  30. package/dist/generators/const/acl.const.d.ts +0 -13
  31. package/dist/generators/const/buildConfigs.const.d.ts +0 -1
  32. package/dist/generators/const/deps.const.d.ts +0 -38
  33. package/dist/generators/const/endpoints.const.d.ts +0 -11
  34. package/dist/generators/const/js.const.d.ts +0 -1
  35. package/dist/generators/const/openapi.const.d.ts +0 -7
  36. package/dist/generators/const/options.const.d.ts +0 -2
  37. package/dist/generators/const/package.const.d.ts +0 -2
  38. package/dist/generators/const/queries.const.d.ts +0 -8
  39. package/dist/generators/const/validation.const.d.ts +0 -53
  40. package/dist/generators/const/zod.const.d.ts +0 -19
  41. package/dist/generators/core/SchemaResolver.class.d.ts +0 -71
  42. package/dist/generators/core/endpoints/getEndpointAcl.d.ts +0 -8
  43. package/dist/generators/core/endpoints/getEndpointBody.d.ts +0 -13
  44. package/dist/generators/core/endpoints/getEndpointParameter.d.ts +0 -11
  45. package/dist/generators/core/endpoints/getEndpointsFromOpenAPIDoc.d.ts +0 -3
  46. package/dist/generators/core/endpoints/getEndpointsFromOpenAPIDoc.test.d.ts +0 -1
  47. package/dist/generators/core/getDataFromOpenAPIDoc.d.ts +0 -8
  48. package/dist/generators/core/getMetadataFromOpenAPIDoc.d.ts +0 -4
  49. package/dist/generators/core/getMetadataFromOpenAPIDoc.test.d.ts +0 -1
  50. package/dist/generators/core/openapi/getOpenAPISchemaComplexity.d.ts +0 -2
  51. package/dist/generators/core/openapi/getOpenAPISchemaComplexity.test.d.ts +0 -1
  52. package/dist/generators/core/openapi/getOpenAPISchemaDependencyGraph.d.ts +0 -6
  53. package/dist/generators/core/openapi/getOpenAPISchemaDependencyGraph.test.d.ts +0 -1
  54. package/dist/generators/core/openapi/getSchemaRefObjs.d.ts +0 -4
  55. package/dist/generators/core/openapi/iterateSchema.d.ts +0 -22
  56. package/dist/generators/core/resolveConfig.d.ts +0 -7
  57. package/dist/generators/core/zod/ZodSchema.class.d.ts +0 -26
  58. package/dist/generators/core/zod/enumExtraction/resolveExtractedEnumZodSchemaNames.d.ts +0 -2
  59. package/dist/generators/core/zod/enumExtraction/resolveExtractedEnumZodSchemaTags.d.ts +0 -2
  60. package/dist/generators/core/zod/enumExtraction/updateExtractedEnumZodSchemaData.d.ts +0 -17
  61. package/dist/generators/core/zod/getZodChain.d.ts +0 -8
  62. package/dist/generators/core/zod/getZodSchema.d.ts +0 -17
  63. package/dist/generators/core/zod/getZodSchema.test.d.ts +0 -1
  64. package/dist/generators/core/zod/getZodSchemaRefs.d.ts +0 -6
  65. package/dist/generators/core/zod/getZodSchemasFromOpenAPIDoc.d.ts +0 -6
  66. package/dist/generators/core/zod/resolveZodSchemaName.d.ts +0 -10
  67. package/dist/generators/core/zod/sortZodSchemasByTopology.d.ts +0 -4
  68. package/dist/generators/generate/generateAcl.d.ts +0 -3
  69. package/dist/generators/generate/generateAclCheck.d.ts +0 -2
  70. package/dist/generators/generate/generateAppRestClient.d.ts +0 -2
  71. package/dist/generators/generate/generateConfigs.d.ts +0 -2
  72. package/dist/generators/generate/generateEndpoints.d.ts +0 -2
  73. package/dist/generators/generate/generateModels.d.ts +0 -2
  74. package/dist/generators/generate/generateQueries.d.ts +0 -2
  75. package/dist/generators/generate/generateQueryModules.d.ts +0 -2
  76. package/dist/generators/generate/generateZodExtended.d.ts +0 -2
  77. package/dist/generators/generateCodeFromOpenAPIDoc.d.ts +0 -4
  78. package/dist/generators/types/builder-config.d.ts +0 -48
  79. package/dist/generators/types/common.d.ts +0 -27
  80. package/dist/generators/types/config.d.ts +0 -2
  81. package/dist/generators/types/endpoint.d.ts +0 -50
  82. package/dist/generators/types/generate.d.ts +0 -39
  83. package/dist/generators/types/metadata.d.ts +0 -51
  84. package/dist/generators/types/openapi.d.ts +0 -22
  85. package/dist/generators/types/options.d.ts +0 -66
  86. package/dist/generators/types/validation.d.ts +0 -5
  87. package/dist/generators/utils/array.utils.d.ts +0 -1
  88. package/dist/generators/utils/endpoint.utils.d.ts +0 -12
  89. package/dist/generators/utils/endpoint.utils.test.d.ts +0 -1
  90. package/dist/generators/utils/file.utils.d.ts +0 -8
  91. package/dist/generators/utils/generate/generate.acl.utils.d.ts +0 -23
  92. package/dist/generators/utils/generate/generate.configs.utils.d.ts +0 -15
  93. package/dist/generators/utils/generate/generate.endpoints.utils.d.ts +0 -39
  94. package/dist/generators/utils/generate/generate.imports.utils.d.ts +0 -39
  95. package/dist/generators/utils/generate/generate.imports.utils.test.d.ts +0 -1
  96. package/dist/generators/utils/generate/generate.openapi.utils.d.ts +0 -2
  97. package/dist/generators/utils/generate/generate.query.utils.d.ts +0 -6
  98. package/dist/generators/utils/generate/generate.utils.d.ts +0 -18
  99. package/dist/generators/utils/generate/generate.zod.utils.d.ts +0 -13
  100. package/dist/generators/utils/generate-files.utils.d.ts +0 -6
  101. package/dist/generators/utils/hbs/hbs-template.utils.d.ts +0 -3
  102. package/dist/generators/utils/hbs/hbs.acl.utils.d.ts +0 -2
  103. package/dist/generators/utils/hbs/hbs.common.utils.d.ts +0 -1
  104. package/dist/generators/utils/hbs/hbs.endpoints.utils.d.ts +0 -2
  105. package/dist/generators/utils/hbs/hbs.imports.utils.d.ts +0 -1
  106. package/dist/generators/utils/hbs/hbs.partials.utils.d.ts +0 -2
  107. package/dist/generators/utils/hbs/hbs.query.utils.d.ts +0 -2
  108. package/dist/generators/utils/hbs/hbs.zod.utils.d.ts +0 -2
  109. package/dist/generators/utils/js.utils.d.ts +0 -2
  110. package/dist/generators/utils/js.utils.test.d.ts +0 -1
  111. package/dist/generators/utils/math.utils.d.ts +0 -1
  112. package/dist/generators/utils/namespace.utils.d.ts +0 -7
  113. package/dist/generators/utils/object.utils.d.ts +0 -13
  114. package/dist/generators/utils/object.utils.test.d.ts +0 -1
  115. package/dist/generators/utils/openapi-schema.utils.d.ts +0 -15
  116. package/dist/generators/utils/openapi.utils.d.ts +0 -23
  117. package/dist/generators/utils/openapi.utils.test.d.ts +0 -1
  118. package/dist/generators/utils/operation.utils.d.ts +0 -22
  119. package/dist/generators/utils/operation.utils.test.d.ts +0 -1
  120. package/dist/generators/utils/query.utils.d.ts +0 -7
  121. package/dist/generators/utils/sort.utils.d.ts +0 -7
  122. package/dist/generators/utils/string.utils.d.ts +0 -14
  123. package/dist/generators/utils/string.utils.test.d.ts +0 -1
  124. package/dist/generators/utils/tag.utils.d.ts +0 -7
  125. package/dist/generators/utils/ts.utils.d.ts +0 -16
  126. package/dist/generators/utils/validation.utils.d.ts +0 -17
  127. package/dist/generators/utils/zod-schema.utils.d.ts +0 -15
  128. package/dist/helpers/cli.helper.d.ts +0 -22
  129. package/dist/helpers/config.helper.d.ts +0 -3
  130. package/dist/helpers/version.helper.d.ts +0 -4
  131. package/dist/helpers/yargs.helper.d.ts +0 -10
  132. package/dist/index.d.ts +0 -14
  133. package/dist/lib/acl/AclGuard.d.ts +0 -8
  134. package/dist/lib/acl/AclGuard.mjs +0 -14
  135. package/dist/lib/acl/Can.d.ts +0 -9
  136. package/dist/lib/acl/Can.mjs +0 -11
  137. package/dist/lib/acl/ability.context.d.ts +0 -15
  138. package/dist/lib/acl/ability.context.mjs +0 -37
  139. package/dist/lib/acl/appAbility.types.d.ts +0 -3
  140. package/dist/lib/assets/locales/en/translation.json.mjs +0 -8
  141. package/dist/lib/assets/locales/sl/translation.json.mjs +0 -8
  142. package/dist/lib/auth/AuthGuard.d.ts +0 -6
  143. package/dist/lib/auth/AuthGuard.mjs +0 -26
  144. package/dist/lib/auth/auth.context.d.ts +0 -22
  145. package/dist/lib/auth/auth.context.mjs +0 -41
  146. package/dist/lib/config/i18n.d.ts +0 -32
  147. package/dist/lib/config/i18n.mjs +0 -31
  148. package/dist/lib/config/queryConfig.context.d.ts +0 -17
  149. package/dist/lib/config/queryConfig.context.mjs +0 -26
  150. package/dist/lib/config/router.context.d.ts +0 -9
  151. package/dist/lib/config/router.context.mjs +0 -20
  152. package/dist/lib/react-query.types.d.ts +0 -10
  153. package/dist/lib/rest/error-handling.d.ts +0 -30
  154. package/dist/lib/rest/error-handling.mjs +0 -132
  155. package/dist/lib/rest/rest-client.d.ts +0 -22
  156. package/dist/lib/rest/rest-client.mjs +0 -62
  157. package/dist/lib/rest/rest-client.types.d.ts +0 -23
  158. package/dist/lib/rest/rest-interceptor.d.ts +0 -8
  159. package/dist/lib/rest/rest-interceptor.mjs +0 -21
  160. package/dist/lib/rest/rest.utils.d.ts +0 -7
  161. package/dist/lib/rest/rest.utils.mjs +0 -51
  162. package/dist/sh.d.ts +0 -2
  163. package/dist/sh.js +0 -634
  164. package/src/assets/useCrossTabQueryInvalidation.ts +0 -40
  165. package/src/assets/useMutationEffects.ts +0 -89
  166. package/src/generators/templates/acl-check.hbs +0 -29
  167. package/src/generators/templates/acl.hbs +0 -19
  168. package/src/generators/templates/app-acl.hbs +0 -17
  169. package/src/generators/templates/app-rest-client.hbs +0 -7
  170. package/src/generators/templates/configs.hbs +0 -80
  171. package/src/generators/templates/endpoints.hbs +0 -44
  172. package/src/generators/templates/models.hbs +0 -23
  173. package/src/generators/templates/partials/acl-check-call.hbs +0 -1
  174. package/src/generators/templates/partials/casl-ability-function.hbs +0 -12
  175. package/src/generators/templates/partials/casl-ability-query.hbs +0 -1
  176. package/src/generators/templates/partials/casl-ability-type.hbs +0 -1
  177. package/src/generators/templates/partials/columns-config.hbs +0 -11
  178. package/src/generators/templates/partials/endpoint-config.hbs +0 -31
  179. package/src/generators/templates/partials/endpoint-param-parse.hbs +0 -1
  180. package/src/generators/templates/partials/endpoint-params.hbs +0 -1
  181. package/src/generators/templates/partials/import.hbs +0 -1
  182. package/src/generators/templates/partials/inputs-config.hbs +0 -10
  183. package/src/generators/templates/partials/model-js-docs.hbs +0 -6
  184. package/src/generators/templates/partials/query-js-docs.hbs +0 -31
  185. package/src/generators/templates/partials/query-keys.hbs +0 -11
  186. package/src/generators/templates/partials/query-use-infinite-query.hbs +0 -21
  187. package/src/generators/templates/partials/query-use-mutation.hbs +0 -54
  188. package/src/generators/templates/partials/query-use-query.hbs +0 -16
  189. package/src/generators/templates/queries.hbs +0 -54
  190. package/src/generators/templates/query-modules.hbs +0 -9
  191. package/src/generators/templates/zod-extended.hbs +0 -49
package/README.md CHANGED
@@ -69,6 +69,7 @@ yarn openapi-codegen generate --config my-config.ts
69
69
  --config Path to TS config file (default: 'openapi-codegen.config.ts')
70
70
  --input Path/URL to OpenAPI JSON/YAML document
71
71
  --output Output directory path (default: 'output')
72
+ --incremental Skip generation when OpenAPI and config are unchanged (default: true)
72
73
  --format Format the generated code using Oxfmt (default: true)
73
74
  --verbose Display detailed log messages during execution (default: false)
74
75
 
@@ -84,11 +85,16 @@ yarn openapi-codegen generate --config my-config.ts
84
85
  --tsPath (Requires `--importPath` to be 'ts') Typescript import path (default: '@/data')
85
86
  --removeOperationPrefixEndingWith Remove operation name prefixes that end with the specified string (default: 'Controller_')
86
87
  --extractEnums Extract enums into separate Zod schemas (default: true)
88
+ --modelsInCommon Keep all schema declarations in defaultTag models and emit per-module proxy exports (default: false)
87
89
  --replaceOptionalWithNullish Replace `.optional()` chains with `.nullish()` in generated Zod schemas (default: false)
88
90
 
89
91
  --axiosRequestConfig Include Axios request config parameters in query hooks (default: false)
90
92
  --infiniteQueries Generate infinite queries for paginated API endpoints (default: false)
91
93
  --mutationEffects Add mutation effects options to mutation hooks (default: true)
94
+ --workspaceContext Allow generated hooks to resolve path/ACL params from OpenApiWorkspaceContext (default: false)
95
+ --inlineEndpoints Inline endpoint implementations into generated query files (default: false)
96
+ --inlineEndpointsExcludeModules Comma-separated modules/tags to keep as separate API files while inlineEndpoints=true
97
+ --modelsOnly Generate only model files (default: false)
92
98
  --parseRequestParams Add Zod parsing to API endpoints (default: true)
93
99
 
94
100
  --acl Generate ACL related files (default: true)
@@ -186,6 +192,63 @@ const config: OpenAPICodegenConfig = {
186
192
  export default config;
187
193
  ```
188
194
 
195
+ ### OpenApiWorkspaceContext (Path + ACL defaults)
196
+
197
+ Enable `workspaceContext: true` in codegen config (or pass `--workspaceContext`) and wrap your app subtree with `OpenApiWorkspaceContext.Provider` if generated hooks frequently repeat workspace-scoped params (for example `officeId`).
198
+
199
+ ```tsx
200
+ import { OpenApiWorkspaceContext } from "@povio/openapi-codegen-cli";
201
+ // openapi-codegen.config.ts -> { workspaceContext: true }
202
+
203
+ <OpenApiWorkspaceContext.Provider values={{ officeId: "office_123" }}>
204
+ <MyWorkspacePages />
205
+ </OpenApiWorkspaceContext.Provider>;
206
+ ```
207
+
208
+ Generated query/mutation hooks can then omit matching path/ACL params and resolve them from `OpenApiWorkspaceContext`.
209
+
210
+ ### Generation Modes
211
+
212
+ You can control whether API endpoint files are emitted, inlined into query files, or skipped entirely.
213
+
214
+ ```ts
215
+ import type { OpenAPICodegenConfig } from "@povio/openapi-codegen-cli";
216
+
217
+ const config: OpenAPICodegenConfig = {
218
+ // 1) Default mode: separate *.api.ts files are generated
219
+ // 2) Inline mode: endpoint logic is generated inside *.queries.ts
220
+ // and can be used without separate api files:
221
+ // inlineEndpoints: true,
222
+ // inlineEndpointsExcludeModules: ["Users", "Billing"],
223
+ // 3) Models-only mode: generate only *.models.ts files
224
+ // modelsOnly: true,
225
+ // 4) Keep all model declarations in common.models and generate per-module model proxies
226
+ // modelsInCommon: true,
227
+ };
228
+ ```
229
+
230
+ ### Vite Plugin
231
+
232
+ You can run codegen directly from Vite config (without CLI config file):
233
+
234
+ ```ts
235
+ import { defineConfig } from "vite";
236
+ import { openApiCodegen } from "@povio/openapi-codegen-cli/vite";
237
+
238
+ export default defineConfig({
239
+ plugins: [
240
+ openApiCodegen({
241
+ input: "./openapi.yaml",
242
+ output: "./src/data",
243
+ inlineEndpoints: true,
244
+ incremental: true,
245
+ }),
246
+ ],
247
+ });
248
+ ```
249
+
250
+ The plugin runs on both `vite serve` and `vite build`, and watches local OpenAPI files in dev mode.
251
+
189
252
  ### Enums
190
253
 
191
254
  If you're using Enums in your backend DTOs with `@Expose()` and `@IsEnum`, they may still not appear correctly in the OpenAPI schema unless you also provide both `enum` **and** `enumName` to `@ApiProperty`.
package/dist/acl.d.mts ADDED
@@ -0,0 +1,59 @@
1
+ import { r as ErrorHandler } from "./error-handling-CXeVTk1T.mjs";
2
+ import * as react from "react";
3
+ import { PropsWithChildren } from "react";
4
+ import * as react_jsx_runtime0 from "react/jsx-runtime";
5
+ import { AbilityTuple, PureAbility, RawRuleOf, Subject } from "@casl/ability";
6
+ import { PackRule } from "@casl/ability/extra";
7
+ import { BoundCanProps } from "@casl/react";
8
+
9
+ //#region src/lib/acl/appAbility.types.d.ts
10
+ type AppAbilities = AbilityTuple<string, Subject>;
11
+ type AppAbility = PureAbility<AppAbilities>;
12
+ //#endregion
13
+ //#region src/lib/acl/ability.context.d.ts
14
+ declare namespace AbilityContext {
15
+ export const Consumer: react.Consumer<AppAbility>;
16
+ interface ProviderProps {
17
+ user?: {
18
+ aclRules?: PackRule<RawRuleOf<AppAbility>>[];
19
+ } | null;
20
+ }
21
+ export const Provider: ({
22
+ children
23
+ }: PropsWithChildren<ProviderProps>) => react_jsx_runtime0.JSX.Element;
24
+ export const useAbility: <TAppAbilities extends AppAbilities = AppAbilities>() => PureAbility<TAppAbilities>;
25
+ export {};
26
+ }
27
+ //#endregion
28
+ //#region src/lib/acl/AclGuard.d.ts
29
+ interface AclGuardProps<TAppAbilities extends AppAbilities = AppAbilities> {
30
+ canUse: TAppAbilities;
31
+ redirectTo?: string;
32
+ }
33
+ declare const createAclGuard: <TAppAbilities extends AppAbilities = AppAbilities>() => ({
34
+ canUse,
35
+ redirectTo,
36
+ children
37
+ }: PropsWithChildren<AclGuardProps<TAppAbilities>>) => react.ReactNode;
38
+ //#endregion
39
+ //#region src/lib/acl/Can.d.ts
40
+ type CanAbility = PureAbility<AbilityTuple<AppAbilities[0], AppAbilities[1]>>;
41
+ type CanProps<TAppAbilities extends AppAbilities = AppAbilities> = {
42
+ use: TAppAbilities;
43
+ } & Omit<BoundCanProps<CanAbility>, "do" | "I" | "on" | "a" | "an" | "this">;
44
+ declare const Can: <TAppAbilities extends AppAbilities = AppAbilities>({
45
+ use,
46
+ ...props
47
+ }: CanProps<TAppAbilities>) => react_jsx_runtime0.JSX.Element;
48
+ //#endregion
49
+ //#region src/lib/acl/useAclCheck.d.ts
50
+ interface UseAclCheckProps {
51
+ errorHandler?: ErrorHandler<never>;
52
+ }
53
+ declare function useAclCheck<TAppAbilities extends AppAbilities = AppAbilities>({
54
+ errorHandler
55
+ }?: UseAclCheckProps): {
56
+ checkAcl: (appAbility: TAppAbilities) => void;
57
+ };
58
+ //#endregion
59
+ export { AbilityContext, type AppAbilities, type AppAbility, Can, createAclGuard, useAclCheck };
package/dist/acl.mjs CHANGED
@@ -1,8 +1,74 @@
1
- import { AbilityContext } from "./lib/acl/ability.context.mjs";
2
- import { createAclGuard } from "./lib/acl/AclGuard.mjs";
3
- import { Can } from "./lib/acl/Can.mjs";
4
- export {
5
- AbilityContext,
6
- Can,
7
- createAclGuard
1
+ import { r as SharedErrorHandler } from "./error-handling-DkPY7Asf.mjs";
2
+ import { n as OpenApiRouter, t as AuthContext } from "./auth.context-Bu5KW2sI.mjs";
3
+ import { createContext, useCallback, useEffect, useState } from "react";
4
+ import { jsx } from "react/jsx-runtime";
5
+ import { AbilityBuilder, createMongoAbility } from "@casl/ability";
6
+ import { unpackRules } from "@casl/ability/extra";
7
+ import { createContextualCan, useAbility } from "@casl/react";
8
+
9
+ //#region src/lib/acl/ability.context.tsx
10
+ let AbilityContext;
11
+ (function(_AbilityContext) {
12
+ const createAppAbilityBuilder = () => new AbilityBuilder(createMongoAbility);
13
+ const initialAppAbility = createAppAbilityBuilder().build();
14
+ const Context = createContext({});
15
+ const { Consumer } = Context;
16
+ _AbilityContext.Consumer = Consumer;
17
+ _AbilityContext.Provider = ({ children }) => {
18
+ const [ability, setAbility] = useState(initialAppAbility);
19
+ const { user } = AuthContext.useAuth();
20
+ useEffect(() => {
21
+ if (!user || !("aclRules" in user)) return;
22
+ const { can, build } = createAppAbilityBuilder();
23
+ const packedRules = user.aclRules;
24
+ unpackRules(packedRules).forEach(({ action, subject, conditions }) => {
25
+ can(action, subject, conditions);
26
+ });
27
+ setAbility(build());
28
+ }, [user]);
29
+ return /* @__PURE__ */ jsx(Context.Provider, {
30
+ value: ability,
31
+ children
32
+ });
33
+ };
34
+ _AbilityContext.useAbility = () => {
35
+ return useAbility(Context);
36
+ };
37
+ })(AbilityContext || (AbilityContext = {}));
38
+
39
+ //#endregion
40
+ //#region src/lib/acl/AclGuard.tsx
41
+ const createAclGuard = () => ({ canUse, redirectTo = "/", children }) => {
42
+ const ability = AbilityContext.useAbility();
43
+ const { replace } = OpenApiRouter.useRouter();
44
+ if (!ability.can(canUse[0], canUse[1])) {
45
+ replace(redirectTo);
46
+ return null;
47
+ }
48
+ return children;
8
49
  };
50
+
51
+ //#endregion
52
+ //#region src/lib/acl/Can.tsx
53
+ const ContextualCan = createContextualCan(AbilityContext.Consumer);
54
+ const Can = ({ use, ...props }) => {
55
+ const [action, subject] = use;
56
+ return /* @__PURE__ */ jsx(ContextualCan, {
57
+ ...props,
58
+ do: action,
59
+ on: subject
60
+ });
61
+ };
62
+
63
+ //#endregion
64
+ //#region src/lib/acl/useAclCheck.ts
65
+ function useAclCheck({ errorHandler } = {}) {
66
+ const ability = AbilityContext.useAbility();
67
+ return { checkAcl: useCallback((appAbility) => {
68
+ const can = ability.can;
69
+ if (!can(...appAbility)) (errorHandler ?? SharedErrorHandler).rethrowError(/* @__PURE__ */ new Error("ACL check failed"));
70
+ }, [ability, errorHandler]) };
71
+ }
72
+
73
+ //#endregion
74
+ export { AbilityContext, Can, createAclGuard, useAclCheck };
@@ -0,0 +1,59 @@
1
+ import { createContext, use, useMemo } from "react";
2
+ import { jsx } from "react/jsx-runtime";
3
+
4
+ //#region src/lib/config/router.context.tsx
5
+ let OpenApiRouter;
6
+ (function(_OpenApiRouter) {
7
+ const Context = createContext(null);
8
+ _OpenApiRouter.Provider = ({ children, replace }) => {
9
+ return /* @__PURE__ */ jsx(Context, {
10
+ value: useMemo(() => ({ replace }), [replace]),
11
+ children
12
+ });
13
+ };
14
+ _OpenApiRouter.useRouter = () => {
15
+ const context = use(Context);
16
+ if (!context) throw new Error("useRouter must be used within an OpenApiRouter.Provider");
17
+ return context;
18
+ };
19
+ })(OpenApiRouter || (OpenApiRouter = {}));
20
+
21
+ //#endregion
22
+ //#region src/lib/auth/auth.context.tsx
23
+ let AuthContext;
24
+ (function(_AuthContext) {
25
+ const Context = createContext({});
26
+ _AuthContext.Provider = ({ isAuthenticated, isInitializing, logout, updateTokens, accessToken, user, userPromise, routes, loadingState, children }) => {
27
+ const value = useMemo(() => ({
28
+ isAuthenticated,
29
+ isInitializing,
30
+ logout,
31
+ updateTokens,
32
+ accessToken,
33
+ user,
34
+ userPromise,
35
+ routes,
36
+ loadingState
37
+ }), [
38
+ isAuthenticated,
39
+ isInitializing,
40
+ logout,
41
+ updateTokens,
42
+ accessToken,
43
+ user,
44
+ userPromise,
45
+ routes,
46
+ loadingState
47
+ ]);
48
+ return /* @__PURE__ */ jsx(Context.Provider, {
49
+ value,
50
+ children
51
+ });
52
+ };
53
+ _AuthContext.useAuth = () => {
54
+ return use(Context);
55
+ };
56
+ })(AuthContext || (AuthContext = {}));
57
+
58
+ //#endregion
59
+ export { OpenApiRouter as n, AuthContext as t };
@@ -0,0 +1,6 @@
1
+ import { t as GenerateOptions } from "./options-BNqkO_OS.mjs";
2
+
3
+ //#region src/generators/types/config.d.ts
4
+ type OpenAPICodegenConfig = Partial<GenerateOptions>;
5
+ //#endregion
6
+ export { OpenAPICodegenConfig as t };
@@ -0,0 +1,38 @@
1
+ import { TFunction } from "i18next";
2
+
3
+ //#region src/lib/rest/error-handling.d.ts
4
+ type GeneralErrorCodes = "DATA_VALIDATION_ERROR" | "NETWORK_ERROR" | "CANCELED_ERROR" | "INTERNAL_ERROR" | "UNKNOWN_ERROR";
5
+ declare class ApplicationException<CodeT> extends Error {
6
+ code: CodeT;
7
+ serverMessage: string | null;
8
+ constructor(message: string, code: CodeT, serverMessage: string | null);
9
+ }
10
+ interface ErrorEntry<CodeT> {
11
+ code: CodeT;
12
+ condition?: (error: unknown) => boolean;
13
+ getMessage: (t: TFunction, error: unknown) => string;
14
+ }
15
+ interface ErrorHandlerOptions<CodeT extends string> {
16
+ entries: ErrorEntry<CodeT>[];
17
+ t?: TFunction;
18
+ onRethrowError?: (error: unknown, exception: ApplicationException<CodeT | GeneralErrorCodes>) => void;
19
+ }
20
+ declare class ErrorHandler<CodeT extends string> {
21
+ entries: ErrorEntry<CodeT | GeneralErrorCodes>[];
22
+ private t;
23
+ private onRethrowError?;
24
+ constructor({
25
+ entries,
26
+ t,
27
+ onRethrowError
28
+ }: ErrorHandlerOptions<CodeT>);
29
+ private matchesEntry;
30
+ setTranslateFunction(t: TFunction): void;
31
+ rethrowError(error: unknown): ApplicationException<CodeT | GeneralErrorCodes>;
32
+ getError(error: unknown): ApplicationException<CodeT | GeneralErrorCodes> | null;
33
+ getErrorCode(error: unknown): CodeT | GeneralErrorCodes | null;
34
+ static getErrorMessage(error: unknown, fallbackToUnknown?: boolean): string | null;
35
+ }
36
+ declare const SharedErrorHandler: ErrorHandler<never>;
37
+ //#endregion
38
+ export { GeneralErrorCodes as a, ErrorHandlerOptions as i, ErrorEntry as n, SharedErrorHandler as o, ErrorHandler as r, ApplicationException as t };
@@ -0,0 +1,187 @@
1
+ import { isAxiosError, isCancel } from "axios";
2
+ import { z } from "zod";
3
+ import i18next from "i18next";
4
+
5
+ //#region src/lib/assets/locales/en/translation.json
6
+ var translation_default$1 = { openapi: { "sharedErrors": {
7
+ "dataValidation": "An error occurred while validating the data",
8
+ "internalError": "An internal error occurred. This is most likely a bug on our end. Please try again later.",
9
+ "networkError": "A network error occurred. Are you connected to the internet?",
10
+ "canceledError": "The request was canceled.",
11
+ "unknownError": "An unknown error occurred. Please try again later.",
12
+ "unknownErrorWithCode": "An unknown error occurred. Error code: \"{{code}}\""
13
+ } } };
14
+
15
+ //#endregion
16
+ //#region src/lib/assets/locales/sl/translation.json
17
+ var translation_default = { openapi: { "sharedErrors": {
18
+ "dataValidation": "Pri preverjanju podatkov je prišlo do napake",
19
+ "internalError": "Prišlo je do notranje napake.",
20
+ "networkError": "Prišlo je do napake v omrežju.",
21
+ "canceledError": "Zahteva je bila preklicana.",
22
+ "unknownError": "Prišlo je do neznane napake.",
23
+ "unknownErrorWithCode": "Prišlo je do neznane napake. Koda napake: \"{{code}}\""
24
+ } } };
25
+
26
+ //#endregion
27
+ //#region src/lib/config/i18n.ts
28
+ const ns = "openapi";
29
+ const resources = {
30
+ en: { [ns]: translation_default$1 },
31
+ sl: { [ns]: translation_default }
32
+ };
33
+ const defaultLanguage = "en";
34
+ const i18n = i18next.createInstance();
35
+ i18n.init({
36
+ compatibilityJSON: "v4",
37
+ lng: defaultLanguage,
38
+ fallbackLng: defaultLanguage,
39
+ resources,
40
+ ns: Object.keys(resources.en),
41
+ defaultNS: ns,
42
+ interpolation: { escapeValue: false }
43
+ });
44
+ const defaultT = i18n.t.bind(i18n);
45
+
46
+ //#endregion
47
+ //#region src/lib/rest/rest.utils.ts
48
+ let RestUtils;
49
+ (function(_RestUtils) {
50
+ _RestUtils.extractServerResponseCode = (e) => {
51
+ if (e instanceof z.ZodError) return "validation-exception";
52
+ if (!isAxiosError(e)) return null;
53
+ if (!e.response) return null;
54
+ const data = e.response.data;
55
+ if (typeof data?.code === "string") return data.code;
56
+ return null;
57
+ };
58
+ _RestUtils.doesServerErrorMessageContain = (e, text) => {
59
+ const message = extractServerErrorMessage(e);
60
+ if (message === null || message === void 0) return false;
61
+ return message.toLowerCase().includes(text.toLowerCase());
62
+ };
63
+ const extractServerErrorMessage = _RestUtils.extractServerErrorMessage = (e) => {
64
+ if (e instanceof z.ZodError) return e.message;
65
+ if (!isAxiosError(e)) return null;
66
+ if (!e.response) return null;
67
+ const data = e.response.data;
68
+ if (typeof data?.message === "string") return data.message;
69
+ return null;
70
+ };
71
+ _RestUtils.extractContentDispositionFilename = (headers) => {
72
+ const contentDisposition = headers["content-disposition"];
73
+ return contentDisposition ? /filename=["']?([^"';]+)/i.exec(contentDisposition)?.[1] : void 0;
74
+ };
75
+ })(RestUtils || (RestUtils = {}));
76
+
77
+ //#endregion
78
+ //#region src/lib/rest/error-handling.ts
79
+ var ApplicationException = class extends Error {
80
+ code;
81
+ serverMessage = null;
82
+ constructor(message, code, serverMessage) {
83
+ super(message);
84
+ this.code = code;
85
+ this.serverMessage = serverMessage;
86
+ }
87
+ };
88
+ var ErrorHandler = class {
89
+ entries = [];
90
+ t;
91
+ onRethrowError;
92
+ constructor({ entries, t = defaultT, onRethrowError }) {
93
+ this.t = t;
94
+ this.onRethrowError = onRethrowError;
95
+ const dataValidationError = {
96
+ code: "DATA_VALIDATION_ERROR",
97
+ condition: (e) => {
98
+ return e instanceof z.ZodError;
99
+ },
100
+ getMessage: () => this.t("openapi.sharedErrors.dataValidation")
101
+ };
102
+ const internalError = {
103
+ code: "INTERNAL_ERROR",
104
+ condition: (e) => {
105
+ if (isAxiosError(e)) return e.response?.status != null && e.response.status >= 500 && e.response.status < 600;
106
+ return false;
107
+ },
108
+ getMessage: () => this.t("openapi.sharedErrors.internalError")
109
+ };
110
+ const networkError = {
111
+ code: "NETWORK_ERROR",
112
+ condition: (e) => {
113
+ if (isAxiosError(e)) return e.code === "ERR_NETWORK";
114
+ return false;
115
+ },
116
+ getMessage: () => this.t("openapi.sharedErrors.networkError")
117
+ };
118
+ const canceledError = {
119
+ code: "CANCELED_ERROR",
120
+ condition: (e) => {
121
+ if (isCancel(e)) return true;
122
+ if (isAxiosError(e) && e.code === "ECONNABORTED") return true;
123
+ return false;
124
+ },
125
+ getMessage: () => this.t("openapi.sharedErrors.canceledError")
126
+ };
127
+ const unknownError = {
128
+ code: "UNKNOWN_ERROR",
129
+ condition: () => true,
130
+ getMessage: (_, e) => {
131
+ const code = RestUtils.extractServerResponseCode(e);
132
+ const serverMessage = RestUtils.extractServerErrorMessage(e);
133
+ if (code) {
134
+ let message = `Unknown error, message from server: ${code}`;
135
+ if (serverMessage) message += ` ${serverMessage}`;
136
+ return message;
137
+ }
138
+ return this.t("openapi.sharedErrors.unknownError");
139
+ }
140
+ };
141
+ this.entries = [
142
+ ...entries,
143
+ dataValidationError,
144
+ internalError,
145
+ networkError,
146
+ canceledError,
147
+ unknownError
148
+ ];
149
+ }
150
+ matchesEntry(error, entry, code) {
151
+ if (entry.condition) return entry.condition(error);
152
+ return code === entry.code;
153
+ }
154
+ setTranslateFunction(t) {
155
+ this.t = t;
156
+ }
157
+ rethrowError(error) {
158
+ const code = RestUtils.extractServerResponseCode(error);
159
+ const errorEntry = this.entries.find((entry) => this.matchesEntry(error, entry, code));
160
+ const serverMessage = RestUtils.extractServerErrorMessage(error);
161
+ const exception = new ApplicationException(errorEntry.getMessage(this.t, error), errorEntry.code, serverMessage);
162
+ this.onRethrowError?.(error, exception);
163
+ throw exception;
164
+ }
165
+ getError(error) {
166
+ if (error instanceof ApplicationException) return error;
167
+ return null;
168
+ }
169
+ getErrorCode(error) {
170
+ if (error instanceof ApplicationException) return error.code;
171
+ return null;
172
+ }
173
+ static getErrorMessage(error, fallbackToUnknown = true) {
174
+ if (typeof error === "string") return error;
175
+ if (error instanceof Error) return error.message;
176
+ if (error instanceof ApplicationException) {
177
+ if (error.serverMessage != null) return error.serverMessage;
178
+ return error.message;
179
+ }
180
+ if (fallbackToUnknown) return defaultT("openapi.sharedErrors.unknownError");
181
+ return null;
182
+ }
183
+ };
184
+ const SharedErrorHandler = new ErrorHandler({ entries: [] });
185
+
186
+ //#endregion
187
+ export { ns as a, RestUtils as i, ErrorHandler as n, resources as o, SharedErrorHandler as r, ApplicationException as t };
@@ -0,0 +1,130 @@
1
+ import { a as deepMerge, p as DEFAULT_GENERATE_OPTIONS, r as writeGenerateFileData, t as generateCodeFromOpenAPIDoc, x as Profiler } from "./generateCodeFromOpenAPIDoc-DZ5swy4U.mjs";
2
+ import fs from "fs";
3
+ import path from "path";
4
+ import SwaggerParser from "@apidevtools/swagger-parser";
5
+
6
+ //#region src/generators/core/resolveConfig.ts
7
+ function resolveConfig({ fileConfig = {}, params: { excludeTags, inlineEndpointsExcludeModules, ...options } }) {
8
+ const resolvedConfig = deepMerge(DEFAULT_GENERATE_OPTIONS, fileConfig ?? {}, {
9
+ ...options,
10
+ excludeTags: excludeTags?.split(","),
11
+ inlineEndpointsExcludeModules: inlineEndpointsExcludeModules?.split(",")
12
+ });
13
+ resolvedConfig.checkAcl = resolvedConfig.acl && resolvedConfig.checkAcl;
14
+ return resolvedConfig;
15
+ }
16
+
17
+ //#endregion
18
+ //#region src/generators/run/generate.runner.ts
19
+ const CACHE_FILE_NAME = ".openapi-codegen-cache.json";
20
+ async function runGenerate({ fileConfig, params, profiler = new Profiler(process.env.OPENAPI_CODEGEN_PROFILE === "1") }) {
21
+ const config = profiler.runSync("config.resolve", () => resolveConfig({
22
+ fileConfig,
23
+ params: params ?? {}
24
+ }));
25
+ const openApiDoc = await getOpenApiDoc(config.input, profiler);
26
+ const openApiHash = hashString(stableStringify(openApiDoc));
27
+ const optionsHash = hashString(stableStringify(getCacheableConfig(config)));
28
+ const cacheFilePath = path.resolve(config.output, CACHE_FILE_NAME);
29
+ if (config.incremental) {
30
+ const cached = readCache(cacheFilePath);
31
+ if (cached && cached.openApiHash === openApiHash && cached.optionsHash === optionsHash) return {
32
+ skipped: true,
33
+ config,
34
+ stats: {
35
+ generatedFilesCount: 0,
36
+ generatedModulesCount: 0
37
+ }
38
+ };
39
+ }
40
+ const filesData = profiler.runSync("generate.total", () => generateCodeFromOpenAPIDoc(openApiDoc, config, profiler));
41
+ profiler.runSync("files.write", () => writeGenerateFileData(filesData));
42
+ const stats = getGenerateStats(filesData, config);
43
+ if (config.incremental) writeCache(cacheFilePath, {
44
+ openApiHash,
45
+ optionsHash
46
+ });
47
+ return {
48
+ skipped: false,
49
+ config,
50
+ stats
51
+ };
52
+ }
53
+ async function getOpenApiDoc(input, profiler) {
54
+ const parsedDoc = await profiler.runAsync("openapi.parse", async () => await SwaggerParser.parse(input));
55
+ if (!profiler.runSync("openapi.detectExternalRefs", () => hasExternalRef(parsedDoc))) return parsedDoc;
56
+ return await profiler.runAsync("openapi.bundle", async () => await SwaggerParser.bundle(input));
57
+ }
58
+ function hasExternalRef(value) {
59
+ const stack = [value];
60
+ const visited = /* @__PURE__ */ new Set();
61
+ while (stack.length > 0) {
62
+ const current = stack.pop();
63
+ if (!current || typeof current !== "object") continue;
64
+ if (visited.has(current)) continue;
65
+ visited.add(current);
66
+ if ("$ref" in current && typeof current.$ref === "string" && !current.$ref.startsWith("#/")) return true;
67
+ for (const nested of Object.values(current)) if (nested && typeof nested === "object") stack.push(nested);
68
+ }
69
+ return false;
70
+ }
71
+ function getCacheableConfig(config) {
72
+ const { output, incremental, ...cacheableConfig } = config;
73
+ return cacheableConfig;
74
+ }
75
+ function readCache(filePath) {
76
+ if (!fs.existsSync(filePath)) return null;
77
+ try {
78
+ return JSON.parse(fs.readFileSync(filePath, "utf-8"));
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+ function writeCache(filePath, data) {
84
+ const dir = path.dirname(filePath);
85
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
86
+ fs.writeFileSync(filePath, JSON.stringify(data), "utf-8");
87
+ }
88
+ function hashString(input) {
89
+ let hash = 2166136261;
90
+ for (let i = 0; i < input.length; i += 1) {
91
+ hash ^= input.charCodeAt(i);
92
+ hash = Math.imul(hash, 16777619);
93
+ }
94
+ return (hash >>> 0).toString(16);
95
+ }
96
+ function stableStringify(input) {
97
+ if (input === null || typeof input !== "object") return JSON.stringify(input);
98
+ if (Array.isArray(input)) return `[${input.map((item) => stableStringify(item)).join(",")}]`;
99
+ const obj = input;
100
+ return `{${Object.keys(obj).sort((a, b) => a.localeCompare(b)).map((key) => `${JSON.stringify(key)}:${stableStringify(obj[key])}`).join(",")}}`;
101
+ }
102
+ function getGenerateStats(filesData, config) {
103
+ const generatedFilesCount = filesData.length;
104
+ if (generatedFilesCount === 0) return {
105
+ generatedFilesCount,
106
+ generatedModulesCount: 0
107
+ };
108
+ if (!config.splitByTags) return {
109
+ generatedFilesCount,
110
+ generatedModulesCount: 1
111
+ };
112
+ const moduleSuffixes = new Set(Object.values(config.configs).map((generateConfig) => generateConfig.outputFileNameSuffix).filter(Boolean));
113
+ const modules = /* @__PURE__ */ new Set();
114
+ for (const file of filesData) {
115
+ const segments = path.relative(config.output, file.fileName).split(path.sep).filter(Boolean);
116
+ if (segments.length < 2) continue;
117
+ const moduleName = segments[0];
118
+ const fileName = segments[segments.length - 1];
119
+ if (!fileName.startsWith(`${moduleName}.`)) continue;
120
+ const suffix = fileName.slice(moduleName.length + 1).replace(/\.tsx?$/, "");
121
+ if (moduleSuffixes.has(suffix)) modules.add(moduleName);
122
+ }
123
+ return {
124
+ generatedFilesCount,
125
+ generatedModulesCount: modules.size
126
+ };
127
+ }
128
+
129
+ //#endregion
130
+ export { resolveConfig as n, runGenerate as t };