swagger-sdk-generator 0.0.0-stage → 3.0.0

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 (217) hide show
  1. package/README.md +58 -2
  2. package/dist/cli/commands/generate.d.ts +2 -0
  3. package/dist/cli/commands/generate.js +196 -0
  4. package/dist/cli/commands/init.d.ts +2 -0
  5. package/dist/cli/commands/init.js +130 -0
  6. package/dist/cli/commands/inspect.d.ts +2 -0
  7. package/dist/cli/commands/inspect.js +164 -0
  8. package/dist/cli/commands/templates.d.ts +2 -0
  9. package/dist/cli/commands/templates.js +126 -0
  10. package/dist/cli/context.d.ts +16 -0
  11. package/dist/cli/context.js +85 -0
  12. package/dist/cli/main.d.ts +2 -0
  13. package/dist/cli/main.js +25 -0
  14. package/dist/config/dotenv.d.ts +2 -0
  15. package/dist/config/dotenv.js +82 -0
  16. package/dist/config/interpolate.d.ts +8 -0
  17. package/dist/config/interpolate.js +85 -0
  18. package/dist/config/load.d.ts +11 -0
  19. package/dist/config/load.js +182 -0
  20. package/dist/config/migrate-v3.d.ts +5 -0
  21. package/dist/config/migrate-v3.js +6 -0
  22. package/dist/config/mode-compatibility.d.ts +9 -0
  23. package/dist/config/mode-compatibility.js +17 -0
  24. package/dist/config/modes.d.ts +13 -0
  25. package/dist/config/modes.js +27 -0
  26. package/dist/config/preset-definitions.d.ts +2 -0
  27. package/dist/config/preset-definitions.js +4 -0
  28. package/dist/config/presets.d.ts +25 -0
  29. package/dist/config/presets.js +36 -0
  30. package/dist/config/resolve.d.ts +32 -0
  31. package/dist/config/resolve.js +288 -0
  32. package/dist/config/schema.d.ts +93 -0
  33. package/dist/config/schema.js +173 -0
  34. package/dist/config/types.d.ts +42 -0
  35. package/dist/config/types.js +2 -0
  36. package/dist/config/workspace.d.ts +30 -0
  37. package/dist/config/workspace.js +95 -0
  38. package/dist/core/case-align.d.ts +5 -0
  39. package/dist/core/case-align.js +90 -0
  40. package/dist/core/deep-merge.d.ts +2 -0
  41. package/dist/core/deep-merge.js +21 -0
  42. package/dist/core/file-set.d.ts +10 -0
  43. package/dist/core/file-set.js +31 -0
  44. package/dist/core/import-module.d.ts +1 -0
  45. package/dist/core/import-module.js +61 -0
  46. package/dist/core/log.d.ts +9 -0
  47. package/dist/core/log.js +24 -0
  48. package/dist/core/manifest.d.ts +17 -0
  49. package/dist/core/manifest.js +195 -0
  50. package/dist/core/overlaps.d.ts +6 -0
  51. package/dist/core/overlaps.js +67 -0
  52. package/dist/core/package-version.d.ts +1 -0
  53. package/dist/core/package-version.js +44 -0
  54. package/dist/core/pipeline.d.ts +30 -0
  55. package/dist/core/pipeline.js +335 -0
  56. package/dist/core/plugin.d.ts +72 -0
  57. package/dist/core/plugin.js +2 -0
  58. package/dist/core/targets.d.ts +14 -0
  59. package/dist/core/targets.js +120 -0
  60. package/dist/core/unmanaged.d.ts +3 -0
  61. package/dist/core/unmanaged.js +101 -0
  62. package/dist/core/writer.d.ts +28 -0
  63. package/dist/core/writer.js +148 -0
  64. package/dist/index.d.ts +20 -0
  65. package/dist/index.js +37 -0
  66. package/dist/ir/casing.d.ts +5 -0
  67. package/dist/ir/casing.js +22 -0
  68. package/dist/ir/graph.d.ts +8 -0
  69. package/dist/ir/graph.js +95 -0
  70. package/dist/ir/operations/grouping.d.ts +17 -0
  71. package/dist/ir/operations/grouping.js +39 -0
  72. package/dist/ir/operations/legacy-naming.d.ts +2 -0
  73. package/dist/ir/operations/legacy-naming.js +8 -0
  74. package/dist/ir/operations/naming.d.ts +6 -0
  75. package/dist/ir/operations/naming.js +54 -0
  76. package/dist/ir/option-errors.d.ts +3 -0
  77. package/dist/ir/option-errors.js +68 -0
  78. package/dist/ir/transforms/builtins.d.ts +2 -0
  79. package/dist/ir/transforms/builtins.js +4 -0
  80. package/dist/ir/transforms/index.d.ts +10 -0
  81. package/dist/ir/transforms/index.js +39 -0
  82. package/dist/ir/transforms/types.d.ts +9 -0
  83. package/dist/ir/transforms/types.js +2 -0
  84. package/dist/ir/types.d.ts +140 -0
  85. package/dist/ir/types.js +2 -0
  86. package/dist/runtime/axios.d.ts +28 -0
  87. package/dist/runtime/axios.js +132 -0
  88. package/dist/runtime/fetch.d.ts +6 -0
  89. package/dist/runtime/fetch.js +38 -0
  90. package/dist/runtime/index.d.ts +54 -0
  91. package/dist/runtime/index.js +167 -0
  92. package/dist/runtime/rtk.d.ts +35 -0
  93. package/dist/runtime/rtk.js +36 -0
  94. package/dist/runtime/transport.d.ts +38 -0
  95. package/dist/runtime/transport.js +30 -0
  96. package/dist/runtime/wire.d.ts +27 -0
  97. package/dist/runtime/wire.js +148 -0
  98. package/dist/spec/html-entities.d.ts +1 -0
  99. package/dist/spec/html-entities.js +25 -0
  100. package/dist/spec/load.d.ts +26 -0
  101. package/dist/spec/load.js +130 -0
  102. package/dist/spec/openapi/all-of.d.ts +3 -0
  103. package/dist/spec/openapi/all-of.js +9 -0
  104. package/dist/spec/openapi/normalize.d.ts +4 -0
  105. package/dist/spec/openapi/normalize.js +31 -0
  106. package/dist/spec/openapi/operations.d.ts +4 -0
  107. package/dist/spec/openapi/operations.js +173 -0
  108. package/dist/spec/openapi/schema.d.ts +51 -0
  109. package/dist/spec/openapi/schema.js +307 -0
  110. package/dist/targets/declarative/config.d.ts +533 -0
  111. package/dist/targets/declarative/config.js +280 -0
  112. package/dist/targets/declarative/extensions.d.ts +45 -0
  113. package/dist/targets/declarative/extensions.js +123 -0
  114. package/dist/targets/declarative/files.d.ts +13 -0
  115. package/dist/targets/declarative/files.js +127 -0
  116. package/dist/targets/declarative/format.d.ts +4 -0
  117. package/dist/targets/declarative/format.js +104 -0
  118. package/dist/targets/declarative/index.d.ts +9 -0
  119. package/dist/targets/declarative/index.js +170 -0
  120. package/dist/targets/declarative/liquid.d.ts +8 -0
  121. package/dist/targets/declarative/liquid.js +57 -0
  122. package/dist/targets/declarative/naming-case.d.ts +3 -0
  123. package/dist/targets/declarative/naming-case.js +31 -0
  124. package/dist/targets/declarative/naming.d.ts +42 -0
  125. package/dist/targets/declarative/naming.js +174 -0
  126. package/dist/targets/declarative/scaffold.d.ts +5 -0
  127. package/dist/targets/declarative/scaffold.js +146 -0
  128. package/dist/targets/declarative/types.d.ts +52 -0
  129. package/dist/targets/declarative/types.js +287 -0
  130. package/dist/targets/declarative/views.d.ts +180 -0
  131. package/dist/targets/declarative/views.js +447 -0
  132. package/dist/targets/python/extensions.js +152 -0
  133. package/dist/targets/python/target.json +549 -0
  134. package/dist/targets/python/templates/client/client.liquid +114 -0
  135. package/dist/targets/python/templates/client/httpx_transport.liquid +172 -0
  136. package/dist/targets/python/templates/client/init.liquid +20 -0
  137. package/dist/targets/python/templates/client/partials/operation_method.liquid +41 -0
  138. package/dist/targets/python/templates/client/resource.liquid +28 -0
  139. package/dist/targets/python/templates/client/runtime.liquid +133 -0
  140. package/dist/targets/python/templates/client/transport.liquid +62 -0
  141. package/dist/targets/python/templates/models/module.liquid +48 -0
  142. package/dist/targets/python/templates/models/partials/docstring.liquid +5 -0
  143. package/dist/targets/python/templates/models/partials/enum_class.liquid +11 -0
  144. package/dist/targets/python/templates/models/partials/field_line.liquid +5 -0
  145. package/dist/targets/python/templates/models/partials/model_class.liquid +17 -0
  146. package/dist/targets/typescript/compatibility-naming.d.ts +6 -0
  147. package/dist/targets/typescript/compatibility-naming.js +28 -0
  148. package/dist/targets/typescript/compatibility-options.d.ts +5 -0
  149. package/dist/targets/typescript/compatibility-options.js +8 -0
  150. package/dist/targets/typescript/compatibility-target.d.ts +5 -0
  151. package/dist/targets/typescript/compatibility-target.js +10 -0
  152. package/dist/targets/typescript/http-operations.d.ts +34 -0
  153. package/dist/targets/typescript/http-operations.js +155 -0
  154. package/dist/targets/typescript/imports.d.ts +43 -0
  155. package/dist/targets/typescript/imports.js +154 -0
  156. package/dist/targets/typescript/index.d.ts +7 -0
  157. package/dist/targets/typescript/index.js +52 -0
  158. package/dist/targets/typescript/mock-compatibility.d.ts +4 -0
  159. package/dist/targets/typescript/mock-compatibility.js +6 -0
  160. package/dist/targets/typescript/mock-hints.d.ts +13 -0
  161. package/dist/targets/typescript/mock-hints.js +75 -0
  162. package/dist/targets/typescript/mock-reachability.d.ts +12 -0
  163. package/dist/targets/typescript/mock-reachability.js +87 -0
  164. package/dist/targets/typescript/model-compatibility.d.ts +14 -0
  165. package/dist/targets/typescript/model-compatibility.js +16 -0
  166. package/dist/targets/typescript/naming.d.ts +13 -0
  167. package/dist/targets/typescript/naming.js +50 -0
  168. package/dist/targets/typescript/options.d.ts +124 -0
  169. package/dist/targets/typescript/options.js +90 -0
  170. package/dist/targets/typescript/outputs/client.d.ts +67 -0
  171. package/dist/targets/typescript/outputs/client.js +187 -0
  172. package/dist/targets/typescript/outputs/mocks.d.ts +32 -0
  173. package/dist/targets/typescript/outputs/mocks.js +371 -0
  174. package/dist/targets/typescript/outputs/models.d.ts +85 -0
  175. package/dist/targets/typescript/outputs/models.js +246 -0
  176. package/dist/targets/typescript/outputs/rtk-query.d.ts +69 -0
  177. package/dist/targets/typescript/outputs/rtk-query.js +266 -0
  178. package/dist/targets/typescript/prettier.d.ts +7 -0
  179. package/dist/targets/typescript/prettier.js +44 -0
  180. package/dist/targets/typescript/templates/client/client.liquid +30 -0
  181. package/dist/targets/typescript/templates/client/partials/api-member.liquid +13 -0
  182. package/dist/targets/typescript/templates/client/partials/jsdoc.liquid +10 -0
  183. package/dist/targets/typescript/templates/client/partials/method.liquid +26 -0
  184. package/dist/targets/typescript/templates/client/partials/query-type.liquid +10 -0
  185. package/dist/targets/typescript/templates/client/resource.liquid +34 -0
  186. package/dist/targets/typescript/templates/mocks/mock.liquid +15 -0
  187. package/dist/targets/typescript/templates/mocks/partials/factory.liquid +12 -0
  188. package/dist/targets/typescript/templates/mocks/partials/imports.liquid +7 -0
  189. package/dist/targets/typescript/templates/models/alias.liquid +16 -0
  190. package/dist/targets/typescript/templates/models/enum.liquid +27 -0
  191. package/dist/targets/typescript/templates/models/index.liquid +14 -0
  192. package/dist/targets/typescript/templates/models/model.liquid +25 -0
  193. package/dist/targets/typescript/templates/models/partials/const.liquid +10 -0
  194. package/dist/targets/typescript/templates/models/partials/imports.liquid +9 -0
  195. package/dist/targets/typescript/templates/models/partials/jsdoc.liquid +9 -0
  196. package/dist/targets/typescript/templates/models/partials/property.liquid +7 -0
  197. package/dist/targets/typescript/templates/rtk-query/api.liquid +16 -0
  198. package/dist/targets/typescript/templates/rtk-query/partials/arg-types.liquid +6 -0
  199. package/dist/targets/typescript/templates/rtk-query/partials/endpoint-mutation.liquid +13 -0
  200. package/dist/targets/typescript/templates/rtk-query/partials/endpoint-query.liquid +13 -0
  201. package/dist/targets/typescript/templates/rtk-query/partials/file-warning.liquid +7 -0
  202. package/dist/targets/typescript/templates/rtk-query/partials/hooks.liquid +9 -0
  203. package/dist/targets/typescript/templates/rtk-query/partials/imports.liquid +7 -0
  204. package/dist/targets/typescript/templates/rtk-query/partials/request-config.liquid +9 -0
  205. package/dist/targets/typescript/templates/rtk-query/resource.liquid +40 -0
  206. package/dist/targets/typescript/ts-type.d.ts +70 -0
  207. package/dist/targets/typescript/ts-type.js +62 -0
  208. package/dist/targets/typescript/type-printer.d.ts +21 -0
  209. package/dist/targets/typescript/type-printer.js +115 -0
  210. package/dist/templates/engine.d.ts +20 -0
  211. package/dist/templates/engine.js +161 -0
  212. package/dist/templates/inspect.d.ts +27 -0
  213. package/dist/templates/inspect.js +331 -0
  214. package/package.json +65 -4
  215. package/schema/sdk-gen.local.schema.json +75 -0
  216. package/schema/sdk-gen.schema.json +980 -0
  217. package/schema/sdk-gen.target.schema.json +1384 -0
@@ -0,0 +1,146 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.scaffoldFiles = scaffoldFiles;
37
+ exports.scaffoldConfigTarget = scaffoldConfigTarget;
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ function scaffoldFiles(name, schemaRef = '../../node_modules/swagger-sdk-generator/schema/sdk-gen.target.schema.json') {
41
+ const target = {
42
+ $schema: schemaRef,
43
+ name,
44
+ naming: {
45
+ type: 'pascal',
46
+ property: 'preserve',
47
+ enumKey: { case: 'upper_snake', numeric: 'value_{% if negative %}minus_{% endif %}{{ abs }}', unique: true },
48
+ namespace: { case: 'pascal', identifier: true },
49
+ },
50
+ types: {
51
+ string: 'string',
52
+ 'string:date-time': 'datetime',
53
+ integer: 'integer',
54
+ number: 'number',
55
+ boolean: 'boolean',
56
+ null: 'null',
57
+ any: 'any',
58
+ ref: '{{ name }}',
59
+ array: 'list of {{ items }}',
60
+ map: 'map of {{ values }}',
61
+ object: 'object',
62
+ enum: '{{ valueType }} ({{ literals | join: ", " }})',
63
+ literal: '{{ literal }}',
64
+ union: '{{ members | uniq | join: " or " }}',
65
+ intersection: '{{ members | join: " and " }}',
66
+ nullable: '{% if hasNull or isTop %}{{ type }}{% else %}{{ type }} or null{% endif %}',
67
+ fallback: 'any',
68
+ },
69
+ files: [{ each: 'model', template: 'model', path: "{% if namespace.size > 0 %}{{ namespace | join: '/' }}/{% endif %}{{ name }}.md" }],
70
+ outputs: {
71
+ models: {
72
+ description: `${name}: one Markdown page per model`,
73
+ options: { title: { type: 'string', default: 'API models', description: 'Heading prefix of every page.' } },
74
+ },
75
+ },
76
+ format: { maxBlankLines: 1 },
77
+ };
78
+ return {
79
+ 'target.json': `${JSON.stringify(target, null, 2)}\n`,
80
+ 'templates/model.liquid': `{% comment %}
81
+ One page per model (entry template of files[0]).
82
+ Data: FileView (each model): model (ModelView: name, kind, doc, properties[], members[], type), options
83
+ {% endcomment -%}
84
+ # {{ options.title }}: {{ model.name }}
85
+ {% if model.doc %}
86
+ {{ model.doc }}
87
+ {% endif %}
88
+ {% case model.kind -%}
89
+ {% when 'object' -%}
90
+ | property | type | required |
91
+ |---|---|---|
92
+ {% for property in model.properties -%}
93
+ {% render 'partials/property', property: property %}
94
+ {% endfor -%}
95
+ {% when 'enum' -%}
96
+ {% for member in model.members -%}
97
+ - \`{{ member.key }}\` = \`{{ member.literal }}\`
98
+ {% endfor -%}
99
+ {% else -%}
100
+ Alias of {{ model.type }}.
101
+ {% endcase -%}
102
+ `,
103
+ 'templates/partials/property.liquid': `{% comment %}
104
+ One table row. Data: PropertyView (as \`property\`)
105
+ {% endcomment -%}
106
+ | \`{{ property.name }}\` | {{ property.type }} | {% if property.required %}yes{% else %}no{% endif %} |`,
107
+ 'README.md': `# ${name} (sdk-gen config target)
108
+
109
+ Use it from \`sdk-gen.config.json\`: \`"target": "./sdk-targets/${name}"\`, then \`sdk-gen generate\`.
110
+
111
+ - \`target.json\`: naming, type map, file plan, outputs (JSON-schema'd: \`$schema\`).
112
+ - \`templates/*.liquid\`: entry templates + partials (\`sdk-gen templates tree --target ./sdk-targets/${name}\`).
113
+ - \`extensions.js\` (optional): functions for what config can't say.
114
+
115
+ Optional \`target.json\` sections (docs/TARGETS.md has every key):
116
+
117
+ | key | what |
118
+ |---|---|
119
+ | \`extends\` | inherit another config target (deep-merged, its templates as fallback) |
120
+ | \`naming.<kind>\` | \`type\`, \`property\`, \`enumKey\` (+ \`numeric\`, \`null\`), \`file\`, \`operation\`, \`param\`, \`resource\`, \`namespace\`; \`reserved\`, \`escape\` |
121
+ | \`types.<key>\` | \`{ "type": "…", "imports": […], "position": { "<position>": "…" } }\`; \`nullable\` / \`optional\` get \`isTop\`, \`hasNull\`, \`isUnion\` |
122
+ | \`positions\` | named spelling positions (\`{ "doc": { "inherits": "return", "spells": ["property"] } }\`) |
123
+ | \`aliases\` | \`reference\` (default) or \`inline\` |
124
+ | \`literals\` | value spelling: \`null\`, \`true\`, \`false\`, \`number\`, \`string\` (template or \`{ "quote", "escapes" }\`) |
125
+ | \`imports\` | \`ref\` (how to import a model), \`skip\`, \`group\`, \`order\`, \`names\` |
126
+ | \`files\` | \`each: model|resource\` (+ \`where\`) or \`once: true\`; \`template\`, \`path\`, \`order\`, \`contents\` |
127
+ | \`resources\` | \`by\` (path | tag | operationId), \`stripPrefixes\` (both also output options) |
128
+ | \`format\` | \`command\`, \`stdin\`, \`enabled\`, \`maxBlankLines\` |
129
+ | \`transforms\` | IR transforms on/off |
130
+ `,
131
+ };
132
+ }
133
+ function scaffoldConfigTarget(dir, name, opts = {}) {
134
+ var _a;
135
+ if (fs.existsSync(dir) && fs.readdirSync(dir).length && !opts.force)
136
+ throw new Error(`${dir} already exists and is not empty (use --force).`);
137
+ const schema = path.relative(dir, path.join((_a = opts.projectDir) !== null && _a !== void 0 ? _a : process.cwd(), 'node_modules/swagger-sdk-generator/schema/sdk-gen.target.schema.json')).split(path.sep).join('/');
138
+ const written = [];
139
+ for (const [file, content] of Object.entries(scaffoldFiles(name, schema))) {
140
+ const out = path.join(dir, file);
141
+ fs.mkdirSync(path.dirname(out), { recursive: true });
142
+ fs.writeFileSync(out, content);
143
+ written.push(out);
144
+ }
145
+ return written;
146
+ }
@@ -0,0 +1,52 @@
1
+ import type { EnumValue, ModelId, TypeNode } from '../../ir/types';
2
+ import type { ImportSpec, StringLiteralSpec, TargetConfig } from './config';
3
+ import type { ExtensionContext, Position, TargetExtensions } from './extensions';
4
+ import type { StringTemplates } from './liquid';
5
+ export interface Spelled {
6
+ text: string;
7
+ comment?: string;
8
+ }
9
+ export interface RefInfo {
10
+ inlined?: boolean;
11
+ }
12
+ export interface ImportSink {
13
+ add(spec: ImportSpec): void;
14
+ ref(id: ModelId, info?: RefInfo): void;
15
+ }
16
+ export interface Speller {
17
+ spell(node: TypeNode, position: Position, sink: ImportSink): Spelled;
18
+ optional(node: TypeNode, inner: Spelled, position: Position, sink: ImportSink): Spelled;
19
+ literal(value: EnumValue): string;
20
+ }
21
+ export interface RefTarget {
22
+ name: string;
23
+ namespace: string[];
24
+ id: ModelId;
25
+ kind: 'object' | 'enum' | 'alias';
26
+ type: TypeNode;
27
+ }
28
+ export interface SpellerDeps {
29
+ types: TargetConfig['types'];
30
+ literals: TargetConfig['literals'];
31
+ aliases?: TargetConfig['aliases'];
32
+ positionChain?: (position: Position) => Position[];
33
+ templates: StringTemplates;
34
+ options: Record<string, unknown>;
35
+ extensions?: TargetExtensions['types'];
36
+ context: (sink: ImportSink) => ExtensionContext;
37
+ refModel: (id: ModelId) => RefTarget | undefined;
38
+ }
39
+ export type ValueType = 'string' | 'integer' | 'number' | 'boolean' | 'null' | 'mixed';
40
+ export declare function valueTypeOf(values: EnumValue[]): ValueType;
41
+ export declare function stringLiteral(spec: StringLiteralSpec, value: string): string;
42
+ export declare function createSpeller(deps: SpellerDeps): Speller;
43
+ export declare class ImportSet implements ImportSink {
44
+ private readonly onRef;
45
+ private readonly modules;
46
+ private readonly order;
47
+ private readonly lines;
48
+ constructor(onRef?: (id: ModelId, set: ImportSet, info: RefInfo) => void);
49
+ add(spec: ImportSpec): void;
50
+ ref(id: ModelId, info?: RefInfo): void;
51
+ render(config: TargetConfig['imports'], templates: StringTemplates): string[];
52
+ }
@@ -0,0 +1,287 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ImportSet = void 0;
4
+ exports.valueTypeOf = valueTypeOf;
5
+ exports.stringLiteral = stringLiteral;
6
+ exports.createSpeller = createSpeller;
7
+ const DEFAULT_LITERALS = { null: 'null', true: 'true', false: 'false', string: '{{ value | quote }}', number: '{{ value }}' };
8
+ const MAX_ALIAS_DEPTH = 20;
9
+ const NULL_SINK = { add: () => { }, ref: () => { } };
10
+ function valueTypeOf(values) {
11
+ var _a;
12
+ if (!values.length)
13
+ return 'mixed';
14
+ const types = new Set(values.map((v) => (v === null ? 'null' : typeof v === 'number' ? (Number.isInteger(v) ? 'integer' : 'number') : typeof v)));
15
+ if (types.size === 2 && types.has('integer') && types.has('number'))
16
+ return 'number';
17
+ if (types.size !== 1)
18
+ return 'mixed';
19
+ const [only] = types;
20
+ return (_a = ['string', 'integer', 'number', 'boolean', 'null'].find((t) => t === only)) !== null && _a !== void 0 ? _a : 'mixed';
21
+ }
22
+ function stringLiteral(spec, value) {
23
+ var _a, _b;
24
+ const keys = Object.keys((_a = spec.escapes) !== null && _a !== void 0 ? _a : {}).sort((a, b) => b.length - a.length);
25
+ const body = keys.length ? value.replace(new RegExp(keys.map(escapeRegExp).join('|'), 'g'), (m) => spec.escapes[m]) : value;
26
+ return `${spec.quote}${body}${(_b = spec.close) !== null && _b !== void 0 ? _b : spec.quote}`;
27
+ }
28
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
29
+ function createSpeller(deps) {
30
+ var _a, _b;
31
+ const map = (_a = deps.types) !== null && _a !== void 0 ? _a : {};
32
+ const literals = Object.assign(Object.assign({}, DEFAULT_LITERALS), deps.literals);
33
+ const inline = deps.aliases === 'inline';
34
+ const chain = (_b = deps.positionChain) !== null && _b !== void 0 ? _b : ((p) => [p]);
35
+ const entryFor = (spelling, position) => {
36
+ var _a;
37
+ var _b, _c;
38
+ if (spelling === undefined)
39
+ return undefined;
40
+ if (typeof spelling === 'string')
41
+ return { type: spelling, imports: [] };
42
+ let positioned;
43
+ for (const p of chain(position))
44
+ if ((positioned = (_a = spelling.position) === null || _a === void 0 ? void 0 : _a[p]) !== undefined)
45
+ break;
46
+ if (typeof positioned === 'string')
47
+ return { type: positioned, imports: (_b = spelling.imports) !== null && _b !== void 0 ? _b : [], comment: spelling.comment };
48
+ const chosen = positioned !== null && positioned !== void 0 ? positioned : spelling;
49
+ return { type: chosen.type, imports: (_c = chosen.imports) !== null && _c !== void 0 ? _c : [], comment: chosen.comment };
50
+ };
51
+ const literal = (value) => {
52
+ if (value === null)
53
+ return deps.templates.render(literals.null, { value });
54
+ if (value === true)
55
+ return deps.templates.render(literals.true, { value });
56
+ if (value === false)
57
+ return deps.templates.render(literals.false, { value });
58
+ if (typeof value === 'number')
59
+ return deps.templates.render(literals.number, { value });
60
+ const spec = literals.string;
61
+ return typeof spec === 'string' ? deps.templates.render(spec, { value }) : stringLiteral(spec, String(value));
62
+ };
63
+ const keysFor = (node) => {
64
+ switch (node.kind) {
65
+ case 'primitive':
66
+ return node.format ? [`${node.type}:${node.format}`, node.type] : [node.type];
67
+ case 'ref':
68
+ return node.unresolved ? ['ref:unresolved', 'ref'] : ['ref'];
69
+ case 'object':
70
+ return node.properties.length ? ['object'] : ['object:free', 'object'];
71
+ case 'enum':
72
+ return ['enum:inline', 'enum'];
73
+ default:
74
+ return [node.kind];
75
+ }
76
+ };
77
+ const extend = (key, node, position, sink, fallback, type) => {
78
+ var _a;
79
+ const fn = (_a = deps.extensions) === null || _a === void 0 ? void 0 : _a[key];
80
+ if (!fn)
81
+ return fallback;
82
+ const ctx = Object.assign(Object.assign(Object.assign({}, deps.context(sink)), { position, key }), (type !== undefined ? { type } : {}));
83
+ return fn(node, ctx, fallback);
84
+ };
85
+ const resolveAlias = (node, seen = []) => {
86
+ if (!inline || node.kind !== 'ref' || node.unresolved)
87
+ return { node };
88
+ const target = deps.refModel(node.id);
89
+ if (!target || target.kind !== 'alias')
90
+ return { node };
91
+ if (seen.includes(node.id) || seen.length >= MAX_ALIAS_DEPTH)
92
+ return { node: Object.assign({ kind: 'any' }, (node.nullable ? { nullable: true } : {})), via: node.id };
93
+ const inner = resolveAlias(target.type, [...seen, node.id]).node;
94
+ return { node: node.nullable && !inner.nullable ? Object.assign(Object.assign({}, inner), { nullable: true }) : inner, via: node.id };
95
+ };
96
+ const spellKind = (node, position, sink) => {
97
+ var _a;
98
+ var _b, _c, _d, _e, _f, _g, _h, _j;
99
+ const keys = keysFor(node);
100
+ const key = (_b = keys.find((k) => { var _a; return map[k] !== undefined || ((_a = deps.extensions) === null || _a === void 0 ? void 0 : _a[k]); })) !== null && _b !== void 0 ? _b : 'fallback';
101
+ const own = map[key] !== undefined;
102
+ let entry = entryFor(own ? map[key] : map.fallback, position);
103
+ if (!entry) {
104
+ if (!((_a = deps.extensions) === null || _a === void 0 ? void 0 : _a[key]))
105
+ throw new Error(`types: no spelling for "${keys[0]}" and no "fallback" key`);
106
+ entry = { type: '', imports: [] };
107
+ }
108
+ if (!own)
109
+ entry = { type: entry.type, imports: [] };
110
+ const comments = [];
111
+ const uses = (name) => deps.templates.references(entry.type, name);
112
+ const child = (n) => {
113
+ const s = spell(n, position, sink);
114
+ comments.push(s.comment);
115
+ return s.text;
116
+ };
117
+ const data = { kind: node.kind, position, options: deps.options, nullable: Boolean(node.nullable) };
118
+ switch (node.kind) {
119
+ case 'primitive':
120
+ data.format = (_c = node.format) !== null && _c !== void 0 ? _c : null;
121
+ data.primitive = node.type;
122
+ break;
123
+ case 'array':
124
+ if (uses('items'))
125
+ data.items = child(node.items);
126
+ break;
127
+ case 'map':
128
+ if (uses('values'))
129
+ data.values = child(node.values);
130
+ break;
131
+ case 'union':
132
+ if (uses('members'))
133
+ data.members = node.variants.map(child);
134
+ break;
135
+ case 'intersection':
136
+ if (uses('members'))
137
+ data.members = node.members.map(child);
138
+ break;
139
+ case 'enum':
140
+ data.values = node.values;
141
+ data.valueType = valueTypeOf(node.values);
142
+ data.base = (_d = node.base) !== null && _d !== void 0 ? _d : null;
143
+ if (uses('literals'))
144
+ data.literals = node.values.map(literal);
145
+ break;
146
+ case 'literal':
147
+ data.value = node.value;
148
+ data.valueType = valueTypeOf([node.value]);
149
+ if (uses('literal'))
150
+ data.literal = literal(node.value);
151
+ break;
152
+ case 'ref': {
153
+ const target = node.unresolved ? undefined : deps.refModel(node.id);
154
+ data.id = node.id;
155
+ data.name = (_f = (_e = target === null || target === void 0 ? void 0 : target.name) !== null && _e !== void 0 ? _e : node.id.split('.').pop()) !== null && _f !== void 0 ? _f : node.id;
156
+ data.namespace = (_g = target === null || target === void 0 ? void 0 : target.namespace) !== null && _g !== void 0 ? _g : node.id.split('.').slice(0, -1);
157
+ data.modelKind = (_h = target === null || target === void 0 ? void 0 : target.kind) !== null && _h !== void 0 ? _h : null;
158
+ data.valueType = (target === null || target === void 0 ? void 0 : target.kind) === 'enum' && target.type.kind === 'enum' ? valueTypeOf(target.type.values) : null;
159
+ if (target)
160
+ sink.ref(node.id);
161
+ break;
162
+ }
163
+ case 'object':
164
+ data.properties = node.properties.length;
165
+ break;
166
+ }
167
+ for (const spec of entry.imports)
168
+ sink.add(spec);
169
+ const text = extend(key, node, position, sink, entry.type ? deps.templates.render(entry.type, data) : '');
170
+ return { text, comment: (_j = entry.comment) !== null && _j !== void 0 ? _j : comments.find((c) => c !== undefined) };
171
+ };
172
+ const topText = new Map();
173
+ const isTop = (node, text, position) => {
174
+ if (node.kind === 'any')
175
+ return true;
176
+ let top = topText.get(position);
177
+ if (top === undefined)
178
+ topText.set(position, (top = spellKind({ kind: 'any' }, position, NULL_SINK).text));
179
+ return text === top;
180
+ };
181
+ const admitsNull = (node) => {
182
+ switch (node.kind) {
183
+ case 'primitive':
184
+ return node.type === 'null';
185
+ case 'union':
186
+ return node.variants.some((v) => v.nullable || admitsNull(resolveAlias(v).node));
187
+ case 'enum':
188
+ return node.values.includes(null);
189
+ case 'literal':
190
+ return node.value === null;
191
+ default:
192
+ return false;
193
+ }
194
+ };
195
+ const facts = (key, node, text, position, template) => {
196
+ const uses = (name) => deps.templates.references(template, name);
197
+ const data = {
198
+ kind: node.kind,
199
+ isNullable: Boolean(node.nullable),
200
+ hasNull: admitsNull(node) || (key === 'optional' && Boolean(node.nullable)),
201
+ };
202
+ if (uses('isTop'))
203
+ data.isTop = isTop(node, text, position);
204
+ if (uses('isUnion') || uses('members')) {
205
+ const members = node.kind === 'union' ? [...new Set(node.variants.map((v) => spell(v, position, NULL_SINK).text))] : [];
206
+ data.members = members;
207
+ data.isUnion = members.length > 1;
208
+ }
209
+ return data;
210
+ };
211
+ const wrap = (key, node, inner, position, sink) => {
212
+ var _a;
213
+ const entry = entryFor(map[key], position);
214
+ if (!entry && !((_a = deps.extensions) === null || _a === void 0 ? void 0 : _a[key]))
215
+ return inner;
216
+ if (entry)
217
+ for (const spec of entry.imports)
218
+ sink.add(spec);
219
+ const fallback = entry
220
+ ? deps.templates.render(entry.type, Object.assign({ type: inner.text, position, options: deps.options }, facts(key, node, inner.text, position, entry.type)))
221
+ : inner.text;
222
+ return { text: extend(key, node, position, sink, fallback, inner.text), comment: inner.comment };
223
+ };
224
+ const spell = (raw, position, sink) => {
225
+ const { node, via } = resolveAlias(raw);
226
+ if (via)
227
+ sink.ref(via, { inlined: true });
228
+ const inner = spellKind(node, position, sink);
229
+ return node.nullable ? wrap('nullable', node, inner, position, sink) : inner;
230
+ };
231
+ return {
232
+ spell,
233
+ optional: (node, inner, position, sink) => wrap('optional', resolveAlias(node).node, inner, position, sink),
234
+ literal,
235
+ };
236
+ }
237
+ class ImportSet {
238
+ constructor(onRef = () => { }) {
239
+ this.onRef = onRef;
240
+ this.modules = new Map();
241
+ this.order = [];
242
+ this.lines = new Set();
243
+ }
244
+ add(spec) {
245
+ if (typeof spec === 'string' || spec.name === undefined) {
246
+ const line = typeof spec === 'string' ? spec : spec.module;
247
+ if (!this.lines.has(line)) {
248
+ this.lines.add(line);
249
+ this.order.push({ kind: 'line', key: line });
250
+ }
251
+ return;
252
+ }
253
+ let names = this.modules.get(spec.module);
254
+ if (!names) {
255
+ this.modules.set(spec.module, (names = []));
256
+ this.order.push({ kind: 'module', key: spec.module });
257
+ }
258
+ if (!names.includes(spec.name))
259
+ names.push(spec.name);
260
+ }
261
+ ref(id, info = {}) {
262
+ this.onRef(id, this, info);
263
+ }
264
+ render(config, templates) {
265
+ var _a;
266
+ const order = (_a = config === null || config === void 0 ? void 0 : config.order) !== null && _a !== void 0 ? _a : 'insertion';
267
+ const entries = [...this.order];
268
+ if (order === 'alphabetical')
269
+ entries.sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0));
270
+ else if (Array.isArray(order)) {
271
+ const rank = (key) => (order.includes(key) ? order.indexOf(key) : order.length);
272
+ entries.sort((a, b) => rank(a.key) - rank(b.key) || (rank(a.key) === order.length ? (a.key < b.key ? -1 : a.key > b.key ? 1 : 0) : 0));
273
+ }
274
+ return entries.map(({ kind, key }) => {
275
+ var _a;
276
+ if (kind === 'line')
277
+ return key;
278
+ const names = [...this.modules.get(key)];
279
+ if (((_a = config === null || config === void 0 ? void 0 : config.names) !== null && _a !== void 0 ? _a : 'alphabetical') === 'alphabetical')
280
+ names.sort();
281
+ if (!(config === null || config === void 0 ? void 0 : config.group))
282
+ throw new Error(`imports: "${key}" imports names (${names.join(', ')}) but imports.group is not configured`);
283
+ return templates.render(config.group, { module: key, names });
284
+ });
285
+ }
286
+ }
287
+ exports.ImportSet = ImportSet;
@@ -0,0 +1,180 @@
1
+ import type { Logger } from '../../core/log';
2
+ import { type ResourceGroup } from '../../ir/operations/grouping';
3
+ import type { ApiInfo, ApiSpec, EnumValue, Model, ModelId, Operation, Parameter, TypeNode } from '../../ir/types';
4
+ import { type PositionSpec, type SpelledElement, type TargetConfig } from './config';
5
+ import type { ExtensionContext, TargetExtensions, ViewKind } from './extensions';
6
+ import type { StringTemplates } from './liquid';
7
+ import { type NamingEngine } from './naming';
8
+ import { ImportSet, type Speller, type ValueType } from './types';
9
+ export interface ModelView {
10
+ name: string;
11
+ wireName: string;
12
+ id: ModelId;
13
+ namespace: string[];
14
+ wireNamespace: string[];
15
+ kind: 'object' | 'enum' | 'alias';
16
+ valueType: ValueType | null;
17
+ doc: string | null;
18
+ deprecated: boolean;
19
+ properties: PropertyView[];
20
+ members: MemberView[];
21
+ type: string | null;
22
+ types: Record<string, string>;
23
+ typeComment: string | null;
24
+ typeNode: TypeNode;
25
+ additionalProperties: boolean;
26
+ refs: string[];
27
+ refIds: ModelId[];
28
+ cyclic: boolean;
29
+ raw: unknown;
30
+ computed: Record<string, unknown>;
31
+ }
32
+ export interface PropertyView {
33
+ name: string;
34
+ wireName: string;
35
+ type: string;
36
+ baseType: string;
37
+ types: Record<string, string>;
38
+ typeComment: string | null;
39
+ typeNode: TypeNode;
40
+ required: boolean;
41
+ nullable: boolean;
42
+ optional: boolean;
43
+ default: unknown;
44
+ doc: string | null;
45
+ readOnly: boolean;
46
+ writeOnly: boolean;
47
+ deprecated: boolean;
48
+ format: string | null;
49
+ raw: unknown;
50
+ computed: Record<string, unknown>;
51
+ }
52
+ export interface MemberView {
53
+ key: string;
54
+ value: EnumValue;
55
+ literal: string;
56
+ }
57
+ export interface ParamView {
58
+ name: string;
59
+ wireName: string;
60
+ in: Parameter['in'];
61
+ type: string;
62
+ baseType: string;
63
+ types: Record<string, string>;
64
+ typeNode: TypeNode;
65
+ required: boolean;
66
+ doc: string | null;
67
+ deprecated: boolean;
68
+ raw: unknown;
69
+ }
70
+ export interface BodyView {
71
+ type: string;
72
+ types: Record<string, string>;
73
+ typeNode: TypeNode;
74
+ contentType: string;
75
+ required: boolean;
76
+ contentTypes: string[];
77
+ }
78
+ export interface ResponseView {
79
+ status: string;
80
+ type: string | null;
81
+ types: Record<string, string>;
82
+ typeNode: TypeNode | null;
83
+ contentType: string | null;
84
+ doc: string | null;
85
+ }
86
+ export interface OperationView {
87
+ id: string;
88
+ operationId: string | null;
89
+ name: string;
90
+ method: string;
91
+ path: string;
92
+ summary: string | null;
93
+ doc: string | null;
94
+ deprecated: boolean;
95
+ tags: string[];
96
+ params: ParamView[];
97
+ pathParams: ParamView[];
98
+ queryParams: ParamView[];
99
+ headerParams: ParamView[];
100
+ cookieParams: ParamView[];
101
+ body: BodyView | null;
102
+ responses: ResponseView[];
103
+ success: ResponseView | null;
104
+ raw: unknown;
105
+ computed: Record<string, unknown>;
106
+ }
107
+ export interface ResourceView {
108
+ name: string;
109
+ wireName: string;
110
+ folder: string;
111
+ key: string;
112
+ operations: OperationView[];
113
+ computed: Record<string, unknown>;
114
+ }
115
+ export interface FileView {
116
+ file: {
117
+ path: string;
118
+ dir: string;
119
+ };
120
+ imports: string[];
121
+ options: Record<string, unknown>;
122
+ target: {
123
+ name: string;
124
+ naming: TargetConfig['naming'];
125
+ };
126
+ api: {
127
+ info: ApiInfo;
128
+ models: ModelView[];
129
+ resources: ResourceView[];
130
+ };
131
+ model?: ModelView;
132
+ resource?: ResourceView;
133
+ models?: ModelView[];
134
+ resources?: ResourceView[];
135
+ cycles?: string[][];
136
+ computed: Record<string, unknown>;
137
+ }
138
+ export interface Env {
139
+ api: ApiSpec;
140
+ options: Record<string, unknown>;
141
+ config: TargetConfig;
142
+ extensions: TargetExtensions;
143
+ templates: StringTemplates;
144
+ log: Logger;
145
+ namer: NamingEngine;
146
+ speller: Speller;
147
+ typeNames: Map<ModelId, string>;
148
+ modelsById: Map<ModelId, Model>;
149
+ dependencyOrder(): Model[];
150
+ cycles(): ModelId[][];
151
+ cyclic(): Set<ModelId>;
152
+ resources(): ResourceGroup[];
153
+ scope: Scope;
154
+ positionsFor(element: SpelledElement): string[];
155
+ namespace(raw: string[]): string[];
156
+ context(scope?: Scope): ExtensionContext;
157
+ }
158
+ export interface Scope {
159
+ imports: ImportSet;
160
+ declared: Set<ModelId>;
161
+ namespace?: string[];
162
+ }
163
+ export declare const DEFAULT_POSITIONS: Record<string, PositionSpec>;
164
+ export declare function createEnv(api: ApiSpec, options: Record<string, unknown>, config: TargetConfig, extensions: TargetExtensions, templates: StringTemplates, log: Logger): Env;
165
+ export declare function createScope(env: Env, declared?: Iterable<ModelId>, namespace?: string[]): Scope;
166
+ export declare function kindOf(model: Model): ModelView['kind'];
167
+ export type ResourceGrouping = 'path' | 'tag' | 'operationId';
168
+ export declare function groupResources(operations: Operation[], options: {
169
+ by: ResourceGrouping;
170
+ stripPrefixes: string[];
171
+ folders: boolean;
172
+ }): ResourceGroup[];
173
+ export declare function inScope<T>(env: Env, scope: Scope, fn: () => T): T;
174
+ export declare function buildModelView(env: Env, model: Model): ModelView;
175
+ export declare function resourceNames(env: Env): Map<ResourceGroup, string>;
176
+ export declare function buildResourceView(env: Env, group: ResourceGroup, name: string): ResourceView;
177
+ export declare function applyComputed(env: Env, kind: ViewKind, view: {
178
+ computed: Record<string, unknown>;
179
+ }): void;
180
+ export declare function dependenciesOf(model: Model): ModelId[];