@lukoweb/apitogo 0.2.51 → 0.2.52

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.
@@ -1,328 +1,328 @@
1
- import fs from "node:fs/promises";
2
- import path from "node:path";
3
- import { deepEqual } from "fast-equals";
4
- import { type Plugin, runnerImport } from "vite";
5
- import { ZuploEnv } from "../app/env.js";
6
- import { getZudokuRootDir } from "../cli/common/package-json.js";
7
- import { getCurrentConfig } from "../config/loader.js";
8
- import {
9
- getBuildConfig,
10
- type Processor,
11
- } from "../config/validators/BuildSchema.js";
12
- import { getAllTags } from "../lib/oas/graphql/index.js";
13
- import type {
14
- ApiCatalogItem,
15
- ApiCatalogPluginOptions,
16
- } from "../lib/plugins/api-catalog/index.js";
17
- import type { VersionedInput } from "../lib/plugins/openapi/interfaces.js";
18
- import { injectApitogoGatewayServer } from "../lib/plugins/openapi/processors/injectApitogoGatewayServer.js";
19
- import { ensureArray } from "../lib/util/ensureArray.js";
20
- import { SchemaManager } from "./api/SchemaManager.js";
21
- import { reload } from "./plugin-config-reload.js";
22
- import { invalidate as invalidateNavigation } from "./plugin-navigation.js";
23
-
24
- const viteApiPlugin = async (): Promise<Plugin> => {
25
- const virtualModuleId = "virtual:zudoku-api-plugins";
26
- const resolvedVirtualModuleId = `\0${virtualModuleId}`;
27
-
28
- const initialConfig = getCurrentConfig();
29
-
30
- // Load Zuplo-specific processors if in Zuplo environment
31
- const zuploProcessors = ZuploEnv.isZuplo
32
- ? await runnerImport<{ default: (rootDir: string) => Processor[] }>(
33
- path.resolve(getZudokuRootDir(), "src/zuplo/with-zuplo-processors.ts"),
34
- ).then((m) => m.module.default(initialConfig.__meta.rootDir))
35
- : [];
36
-
37
- const buildConfig = await getBuildConfig();
38
- const buildProcessors = buildConfig?.processors ?? [];
39
-
40
- const tmpStoreDir = path.posix.join(
41
- initialConfig.__meta.rootDir,
42
- "node_modules/.apitogo/processed",
43
- );
44
-
45
- const processors = [
46
- ...buildProcessors,
47
- ...zuploProcessors,
48
- injectApitogoGatewayServer(),
49
- ];
50
- const schemaManager = new SchemaManager({
51
- storeDir: tmpStoreDir,
52
- config: initialConfig,
53
- processors,
54
- });
55
-
56
- return {
57
- name: "zudoku-api-plugins",
58
- async buildStart() {
59
- await fs.rm(tmpStoreDir, { recursive: true, force: true });
60
- await fs.mkdir(tmpStoreDir, { recursive: true });
61
-
62
- await schemaManager.processAllSchemas();
63
-
64
- schemaManager
65
- .getAllTrackedFiles()
66
- .forEach((file) => this.addWatchFile(file));
67
- },
68
- configureServer(server) {
69
- // Serve original OpenAPI schema files
70
- server.middlewares.use(async (req, res, next) => {
71
- if (req.method !== "GET" || !req.url) return next();
72
- if (
73
- !req.url.toLowerCase().endsWith(".json") &&
74
- !req.url.toLowerCase().endsWith(".yaml")
75
- ) {
76
- return next();
77
- }
78
-
79
- const pathMap = schemaManager.getUrlToFilePathMap();
80
-
81
- const inputPath = pathMap.get(req.url);
82
- if (!inputPath) return next();
83
-
84
- const content = await fs.readFile(inputPath, "utf-8");
85
- const mimeType =
86
- path.extname(inputPath).toLowerCase() === ".json"
87
- ? "application/json"
88
- : "application/x-yaml";
89
-
90
- res.setHeader("Content-Type", `${mimeType}; charset=utf-8`);
91
- return res.end(content);
92
- });
93
-
94
- server.watcher.on("change", async (id) => {
95
- const mainFiles = schemaManager.getFilesToReprocess(id);
96
- if (mainFiles.length === 0) return;
97
-
98
- // biome-ignore lint/suspicious/noConsole: Logging allowed here
99
- console.log(`Re-processing schema ${id}`);
100
-
101
- for (const inputConfig of mainFiles) {
102
- await schemaManager.processSchema(inputConfig);
103
- }
104
- schemaManager
105
- .getAllTrackedFiles()
106
- .forEach((file) => server.watcher.add(file));
107
-
108
- invalidateNavigation(server);
109
- reload(server);
110
- });
111
- },
112
- resolveId(id) {
113
- if (id === virtualModuleId) {
114
- return resolvedVirtualModuleId;
115
- }
116
- },
117
- async load(id) {
118
- if (id !== resolvedVirtualModuleId) return;
119
-
120
- const config = getCurrentConfig();
121
-
122
- if (!deepEqual(schemaManager.config.apis, config.apis)) {
123
- schemaManager.config = config;
124
- await schemaManager.processAllSchemas();
125
- schemaManager
126
- .getAllTrackedFiles()
127
- .forEach((file) => this.addWatchFile(file));
128
- }
129
-
130
- if (
131
- config.__meta.mode === "standalone" ||
132
- !config.__resolvedModules.docs.enabled
133
- ) {
134
- return [
135
- "export const configuredApiPlugins = [];",
136
- "export const configuredApiCatalogPlugins = [];",
137
- ].join("\n");
138
- }
139
-
140
- const code = [
141
- `import config from "virtual:zudoku-config";`,
142
- `const configuredApiPlugins = [];`,
143
- `const configuredApiCatalogPlugins = [];`,
144
- ];
145
-
146
- if (config.apis) {
147
- code.push(
148
- 'import { openApiPlugin } from "@lukoweb/apitogo/plugins/openapi";',
149
- );
150
- code.push(
151
- `const apis = Array.isArray(config.apis) ? config.apis : [config.apis]`,
152
- );
153
- const apis = ensureArray(config.apis);
154
- const apiMetadata: ApiCatalogItem[] = [];
155
-
156
- for (const apiConfig of apis) {
157
- if (apiConfig.type === "file" && apiConfig.path) {
158
- const latestSchema = schemaManager.getLatestSchema(apiConfig.path);
159
- if (!latestSchema?.schema.info) continue;
160
-
161
- apiMetadata.push({
162
- path: apiConfig.path,
163
- label: latestSchema.schema.info.title,
164
- description: latestSchema.schema.info.description ?? "",
165
- categories: apiConfig.categories ?? [],
166
- });
167
- }
168
- }
169
-
170
- // Generate API plugin code
171
- let apiIndex = -1;
172
- for (const apiConfig of apis) {
173
- apiIndex++;
174
- if (apiConfig.type === "file") {
175
- if (!apiConfig.path) continue;
176
-
177
- const schemas = schemaManager.getSchemasForPath(apiConfig.path);
178
-
179
- if (!schemas?.length) continue;
180
-
181
- const allSlugs = new Set<string>();
182
- const versionedInput = schemas.map<VersionedInput>((s) => {
183
- const versionTags = getAllTags(s.schema);
184
- versionTags.forEach(({ slug }) => {
185
- if (slug) allSlugs.add(slug);
186
- });
187
-
188
- return {
189
- path: s.path,
190
- version: s.version,
191
- downloadUrl: s.downloadUrl,
192
- label: s.label ?? s.schema.info?.version,
193
- input: s.importKey,
194
- hasUntaggedOperations: versionTags.some(
195
- (tag) => tag.name === undefined,
196
- ),
197
- tagPages: versionTags.flatMap((t) => t.slug ?? []),
198
- };
199
- });
200
-
201
- const tags = Array.from(allSlugs);
202
-
203
- const schemaImports = schemaManager.getSchemaImports();
204
-
205
- code.push(
206
- "configuredApiPlugins.push(openApiPlugin({",
207
- ` type: "file",`,
208
- ` input: ${JSON.stringify(versionedInput)},`,
209
- ` path: ${JSON.stringify(apiConfig.path)},`,
210
- ` tagPages: ${JSON.stringify(tags)},`,
211
- ` options: {`,
212
- ` examplesLanguage: config.defaults?.apis?.examplesLanguage ?? config.defaults?.examplesLanguage,`,
213
- ` supportedLanguages: config.defaults?.apis?.supportedLanguages,`,
214
- ` disablePlayground: config.defaults?.apis?.disablePlayground,`,
215
- ` disableSidecar: config.defaults?.apis?.disableSidecar,`,
216
- ` showVersionSelect: config.defaults?.apis?.showVersionSelect ?? "if-available",`,
217
- ` expandAllTags: config.defaults?.apis?.expandAllTags ?? true,`,
218
- ` showInfoPage: config.defaults?.apis?.showInfoPage ?? true,`,
219
- ` schemaDownload: config.defaults?.apis?.schemaDownload,`,
220
- ` transformExamples: config.defaults?.apis?.transformExamples,`,
221
- ` generateCodeSnippet: config.defaults?.apis?.generateCodeSnippet,`,
222
- ` ...(apis[${apiIndex}].options ?? {}),`,
223
- ` },`,
224
- ` schemaImports: {`,
225
- ...schemaImports.map(
226
- (s) =>
227
- ` "${s.importKey.replaceAll("\\", "\\\\")}": () => import("${s.importKey.replaceAll("\\", "/")}?d=${s.processedTime}"),`,
228
- ),
229
- ` },`,
230
- "}));",
231
- );
232
- } else {
233
- code.push(
234
- "configuredApiPlugins.push(openApiPlugin({",
235
- ` ...${JSON.stringify(apiConfig)},`,
236
- " options: {",
237
- ` examplesLanguage: config.defaults?.apis?.examplesLanguage ?? config.defaults?.examplesLanguage,`,
238
- ` supportedLanguages: config.defaults?.apis?.supportedLanguages,`,
239
- ` disablePlayground: config.defaults?.apis?.disablePlayground,`,
240
- ` disableSidecar: config.defaults?.apis?.disableSidecar,`,
241
- ` showVersionSelect: config.defaults?.apis?.showVersionSelect ?? "if-available",`,
242
- ` expandAllTags: config.defaults?.apis?.expandAllTags ?? false,`,
243
- ` showInfoPage: config.defaults?.apis?.showInfoPage ?? true,`,
244
- ` schemaDownload: config.defaults?.apis?.schemaDownload,`,
245
- ` ...${JSON.stringify(apiConfig.options ?? {})},`,
246
- " },",
247
- "}));",
248
- );
249
- }
250
- }
251
-
252
- if (config.catalogs) {
253
- code.push(
254
- 'import { apiCatalogPlugin } from "@lukoweb/apitogo/plugins/api-catalog";',
255
- );
256
-
257
- const catalogs = ensureArray(config.catalogs);
258
-
259
- const categories = apis
260
- .flatMap((api) => api.categories ?? [])
261
- .reduce((acc, catalog) => {
262
- if (!acc.has(catalog.label)) {
263
- acc.set(catalog.label ?? "", new Set(catalog.tags));
264
- }
265
- for (const tag of catalog.tags) {
266
- acc.get(catalog.label ?? "")?.add(tag);
267
- }
268
- return acc;
269
- }, new Map<string, Set<string>>());
270
-
271
- const categoryList = Array.from(categories.entries()).map(
272
- ([label, tags]) => ({
273
- label,
274
- tags: Array.from(tags),
275
- }),
276
- );
277
-
278
- for (let i = 0; i < catalogs.length; i++) {
279
- const catalog = catalogs[i];
280
- if (!catalog) {
281
- continue;
282
- }
283
- const apiCatalogConfig: ApiCatalogPluginOptions = {
284
- ...catalog,
285
- items: apiMetadata,
286
- label: catalog.label,
287
- categories: categoryList,
288
- filterCatalogItems: catalog.filterItems,
289
- };
290
-
291
- code.push(
292
- `configuredApiCatalogPlugins.push(apiCatalogPlugin({`,
293
- ` ...${JSON.stringify(apiCatalogConfig, null, 2)},`,
294
- ` filterCatalogItems: Array.isArray(config.catalogs)`,
295
- ` ? config.catalogs[${i}].filterItems`,
296
- ` : config.catalogs.filterItems,`,
297
- `}));`,
298
- );
299
- }
300
- }
301
- }
302
-
303
- code.push(
304
- `export { configuredApiPlugins, configuredApiCatalogPlugins };`,
305
- );
306
-
307
- return code.join("\n");
308
- },
309
- async closeBundle() {
310
- if (this.environment.name === "ssr") return;
311
-
312
- const config = getCurrentConfig();
313
- const pathMap = schemaManager.getUrlToFilePathMap();
314
-
315
- if (process.env.NODE_ENV !== "production") return;
316
-
317
- for (const [urlPath, inputPath] of pathMap) {
318
- const content = await fs.readFile(inputPath, "utf-8");
319
- const outputPath = path.join(config.__meta.rootDir, "dist", urlPath);
320
-
321
- await fs.mkdir(path.dirname(outputPath), { recursive: true });
322
- await fs.writeFile(outputPath, content, "utf-8");
323
- }
324
- },
325
- };
326
- };
327
-
328
- export default viteApiPlugin;
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { deepEqual } from "fast-equals";
4
+ import { type Plugin, runnerImport } from "vite";
5
+ import { ZuploEnv } from "../app/env.js";
6
+ import { getZudokuRootDir } from "../cli/common/package-json.js";
7
+ import { getCurrentConfig } from "../config/loader.js";
8
+ import {
9
+ getBuildConfig,
10
+ type Processor,
11
+ } from "../config/validators/BuildSchema.js";
12
+ import { getAllTags } from "../lib/oas/graphql/index.js";
13
+ import type {
14
+ ApiCatalogItem,
15
+ ApiCatalogPluginOptions,
16
+ } from "../lib/plugins/api-catalog/index.js";
17
+ import type { VersionedInput } from "../lib/plugins/openapi/interfaces.js";
18
+ import { injectApitogoGatewayServer } from "../lib/plugins/openapi/processors/injectApitogoGatewayServer.js";
19
+ import { ensureArray } from "../lib/util/ensureArray.js";
20
+ import { SchemaManager } from "./api/SchemaManager.js";
21
+ import { reload } from "./plugin-config-reload.js";
22
+ import { invalidate as invalidateNavigation } from "./plugin-navigation.js";
23
+
24
+ const viteApiPlugin = async (): Promise<Plugin> => {
25
+ const virtualModuleId = "virtual:zudoku-api-plugins";
26
+ const resolvedVirtualModuleId = `\0${virtualModuleId}`;
27
+
28
+ const initialConfig = getCurrentConfig();
29
+
30
+ // Load Zuplo-specific processors if in Zuplo environment
31
+ const zuploProcessors = ZuploEnv.isZuplo
32
+ ? await runnerImport<{ default: (rootDir: string) => Processor[] }>(
33
+ path.resolve(getZudokuRootDir(), "src/zuplo/with-zuplo-processors.ts"),
34
+ ).then((m) => m.module.default(initialConfig.__meta.rootDir))
35
+ : [];
36
+
37
+ const buildConfig = await getBuildConfig();
38
+ const buildProcessors = buildConfig?.processors ?? [];
39
+
40
+ const tmpStoreDir = path.posix.join(
41
+ initialConfig.__meta.rootDir,
42
+ "node_modules/.apitogo/processed",
43
+ );
44
+
45
+ const processors = [
46
+ ...buildProcessors,
47
+ ...zuploProcessors,
48
+ injectApitogoGatewayServer(),
49
+ ];
50
+ const schemaManager = new SchemaManager({
51
+ storeDir: tmpStoreDir,
52
+ config: initialConfig,
53
+ processors,
54
+ });
55
+
56
+ return {
57
+ name: "zudoku-api-plugins",
58
+ async buildStart() {
59
+ await fs.rm(tmpStoreDir, { recursive: true, force: true });
60
+ await fs.mkdir(tmpStoreDir, { recursive: true });
61
+
62
+ await schemaManager.processAllSchemas();
63
+
64
+ schemaManager
65
+ .getAllTrackedFiles()
66
+ .forEach((file) => this.addWatchFile(file));
67
+ },
68
+ configureServer(server) {
69
+ // Serve original OpenAPI schema files
70
+ server.middlewares.use(async (req, res, next) => {
71
+ if (req.method !== "GET" || !req.url) return next();
72
+ if (
73
+ !req.url.toLowerCase().endsWith(".json") &&
74
+ !req.url.toLowerCase().endsWith(".yaml")
75
+ ) {
76
+ return next();
77
+ }
78
+
79
+ const pathMap = schemaManager.getUrlToFilePathMap();
80
+
81
+ const inputPath = pathMap.get(req.url);
82
+ if (!inputPath) return next();
83
+
84
+ const content = await fs.readFile(inputPath, "utf-8");
85
+ const mimeType =
86
+ path.extname(inputPath).toLowerCase() === ".json"
87
+ ? "application/json"
88
+ : "application/x-yaml";
89
+
90
+ res.setHeader("Content-Type", `${mimeType}; charset=utf-8`);
91
+ return res.end(content);
92
+ });
93
+
94
+ server.watcher.on("change", async (id) => {
95
+ const mainFiles = schemaManager.getFilesToReprocess(id);
96
+ if (mainFiles.length === 0) return;
97
+
98
+ // biome-ignore lint/suspicious/noConsole: Logging allowed here
99
+ console.log(`Re-processing schema ${id}`);
100
+
101
+ for (const inputConfig of mainFiles) {
102
+ await schemaManager.processSchema(inputConfig);
103
+ }
104
+ schemaManager
105
+ .getAllTrackedFiles()
106
+ .forEach((file) => server.watcher.add(file));
107
+
108
+ invalidateNavigation(server);
109
+ reload(server);
110
+ });
111
+ },
112
+ resolveId(id) {
113
+ if (id === virtualModuleId) {
114
+ return resolvedVirtualModuleId;
115
+ }
116
+ },
117
+ async load(id) {
118
+ if (id !== resolvedVirtualModuleId) return;
119
+
120
+ const config = getCurrentConfig();
121
+
122
+ if (!deepEqual(schemaManager.config.apis, config.apis)) {
123
+ schemaManager.config = config;
124
+ await schemaManager.processAllSchemas();
125
+ schemaManager
126
+ .getAllTrackedFiles()
127
+ .forEach((file) => this.addWatchFile(file));
128
+ }
129
+
130
+ if (
131
+ config.__meta.mode === "standalone" ||
132
+ !config.__resolvedModules.docs.enabled
133
+ ) {
134
+ return [
135
+ "export const configuredApiPlugins = [];",
136
+ "export const configuredApiCatalogPlugins = [];",
137
+ ].join("\n");
138
+ }
139
+
140
+ const code = [
141
+ `import config from "virtual:zudoku-config";`,
142
+ `const configuredApiPlugins = [];`,
143
+ `const configuredApiCatalogPlugins = [];`,
144
+ ];
145
+
146
+ if (config.apis) {
147
+ code.push(
148
+ 'import { openApiPlugin } from "@lukoweb/apitogo/plugins/openapi";',
149
+ );
150
+ code.push(
151
+ `const apis = Array.isArray(config.apis) ? config.apis : [config.apis]`,
152
+ );
153
+ const apis = ensureArray(config.apis);
154
+ const apiMetadata: ApiCatalogItem[] = [];
155
+
156
+ for (const apiConfig of apis) {
157
+ if (apiConfig.type === "file" && apiConfig.path) {
158
+ const latestSchema = schemaManager.getLatestSchema(apiConfig.path);
159
+ if (!latestSchema?.schema.info) continue;
160
+
161
+ apiMetadata.push({
162
+ path: apiConfig.path,
163
+ label: latestSchema.schema.info.title,
164
+ description: latestSchema.schema.info.description ?? "",
165
+ categories: apiConfig.categories ?? [],
166
+ });
167
+ }
168
+ }
169
+
170
+ // Generate API plugin code
171
+ let apiIndex = -1;
172
+ for (const apiConfig of apis) {
173
+ apiIndex++;
174
+ if (apiConfig.type === "file") {
175
+ if (!apiConfig.path) continue;
176
+
177
+ const schemas = schemaManager.getSchemasForPath(apiConfig.path);
178
+
179
+ if (!schemas?.length) continue;
180
+
181
+ const allSlugs = new Set<string>();
182
+ const versionedInput = schemas.map<VersionedInput>((s) => {
183
+ const versionTags = getAllTags(s.schema);
184
+ versionTags.forEach(({ slug }) => {
185
+ if (slug) allSlugs.add(slug);
186
+ });
187
+
188
+ return {
189
+ path: s.path,
190
+ version: s.version,
191
+ downloadUrl: s.downloadUrl,
192
+ label: s.label ?? s.schema.info?.version,
193
+ input: s.importKey,
194
+ hasUntaggedOperations: versionTags.some(
195
+ (tag) => tag.name === undefined,
196
+ ),
197
+ tagPages: versionTags.flatMap((t) => t.slug ?? []),
198
+ };
199
+ });
200
+
201
+ const tags = Array.from(allSlugs);
202
+
203
+ const schemaImports = schemaManager.getSchemaImports();
204
+
205
+ code.push(
206
+ "configuredApiPlugins.push(openApiPlugin({",
207
+ ` type: "file",`,
208
+ ` input: ${JSON.stringify(versionedInput)},`,
209
+ ` path: ${JSON.stringify(apiConfig.path)},`,
210
+ ` tagPages: ${JSON.stringify(tags)},`,
211
+ ` options: {`,
212
+ ` examplesLanguage: config.defaults?.apis?.examplesLanguage ?? config.defaults?.examplesLanguage,`,
213
+ ` supportedLanguages: config.defaults?.apis?.supportedLanguages,`,
214
+ ` disablePlayground: config.defaults?.apis?.disablePlayground,`,
215
+ ` disableSidecar: config.defaults?.apis?.disableSidecar,`,
216
+ ` showVersionSelect: config.defaults?.apis?.showVersionSelect ?? "if-available",`,
217
+ ` expandAllTags: config.defaults?.apis?.expandAllTags ?? true,`,
218
+ ` showInfoPage: config.defaults?.apis?.showInfoPage ?? true,`,
219
+ ` schemaDownload: config.defaults?.apis?.schemaDownload,`,
220
+ ` transformExamples: config.defaults?.apis?.transformExamples,`,
221
+ ` generateCodeSnippet: config.defaults?.apis?.generateCodeSnippet,`,
222
+ ` ...(apis[${apiIndex}].options ?? {}),`,
223
+ ` },`,
224
+ ` schemaImports: {`,
225
+ ...schemaImports.map(
226
+ (s) =>
227
+ ` ${JSON.stringify(s.importKey)}: () => import("${s.processedFilePath.replaceAll("\\", "/")}?d=${s.processedTime}"),`,
228
+ ),
229
+ ` },`,
230
+ "}));",
231
+ );
232
+ } else {
233
+ code.push(
234
+ "configuredApiPlugins.push(openApiPlugin({",
235
+ ` ...${JSON.stringify(apiConfig)},`,
236
+ " options: {",
237
+ ` examplesLanguage: config.defaults?.apis?.examplesLanguage ?? config.defaults?.examplesLanguage,`,
238
+ ` supportedLanguages: config.defaults?.apis?.supportedLanguages,`,
239
+ ` disablePlayground: config.defaults?.apis?.disablePlayground,`,
240
+ ` disableSidecar: config.defaults?.apis?.disableSidecar,`,
241
+ ` showVersionSelect: config.defaults?.apis?.showVersionSelect ?? "if-available",`,
242
+ ` expandAllTags: config.defaults?.apis?.expandAllTags ?? false,`,
243
+ ` showInfoPage: config.defaults?.apis?.showInfoPage ?? true,`,
244
+ ` schemaDownload: config.defaults?.apis?.schemaDownload,`,
245
+ ` ...${JSON.stringify(apiConfig.options ?? {})},`,
246
+ " },",
247
+ "}));",
248
+ );
249
+ }
250
+ }
251
+
252
+ if (config.catalogs) {
253
+ code.push(
254
+ 'import { apiCatalogPlugin } from "@lukoweb/apitogo/plugins/api-catalog";',
255
+ );
256
+
257
+ const catalogs = ensureArray(config.catalogs);
258
+
259
+ const categories = apis
260
+ .flatMap((api) => api.categories ?? [])
261
+ .reduce((acc, catalog) => {
262
+ if (!acc.has(catalog.label)) {
263
+ acc.set(catalog.label ?? "", new Set(catalog.tags));
264
+ }
265
+ for (const tag of catalog.tags) {
266
+ acc.get(catalog.label ?? "")?.add(tag);
267
+ }
268
+ return acc;
269
+ }, new Map<string, Set<string>>());
270
+
271
+ const categoryList = Array.from(categories.entries()).map(
272
+ ([label, tags]) => ({
273
+ label,
274
+ tags: Array.from(tags),
275
+ }),
276
+ );
277
+
278
+ for (let i = 0; i < catalogs.length; i++) {
279
+ const catalog = catalogs[i];
280
+ if (!catalog) {
281
+ continue;
282
+ }
283
+ const apiCatalogConfig: ApiCatalogPluginOptions = {
284
+ ...catalog,
285
+ items: apiMetadata,
286
+ label: catalog.label,
287
+ categories: categoryList,
288
+ filterCatalogItems: catalog.filterItems,
289
+ };
290
+
291
+ code.push(
292
+ `configuredApiCatalogPlugins.push(apiCatalogPlugin({`,
293
+ ` ...${JSON.stringify(apiCatalogConfig, null, 2)},`,
294
+ ` filterCatalogItems: Array.isArray(config.catalogs)`,
295
+ ` ? config.catalogs[${i}].filterItems`,
296
+ ` : config.catalogs.filterItems,`,
297
+ `}));`,
298
+ );
299
+ }
300
+ }
301
+ }
302
+
303
+ code.push(
304
+ `export { configuredApiPlugins, configuredApiCatalogPlugins };`,
305
+ );
306
+
307
+ return code.join("\n");
308
+ },
309
+ async closeBundle() {
310
+ if (this.environment.name === "ssr") return;
311
+
312
+ const config = getCurrentConfig();
313
+ const pathMap = schemaManager.getUrlToFilePathMap();
314
+
315
+ if (process.env.NODE_ENV !== "production") return;
316
+
317
+ for (const [urlPath, inputPath] of pathMap) {
318
+ const content = await fs.readFile(inputPath, "utf-8");
319
+ const outputPath = path.join(config.__meta.rootDir, "dist", urlPath);
320
+
321
+ await fs.mkdir(path.dirname(outputPath), { recursive: true });
322
+ await fs.writeFile(outputPath, content, "utf-8");
323
+ }
324
+ },
325
+ };
326
+ };
327
+
328
+ export default viteApiPlugin;