@kubb/core 5.8.0 → 5.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,11 +1,13 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_KubbDriver = require("./KubbDriver-DXDTb9_c.cjs");
2
+ const require_KubbDriver = require("./KubbDriver-DQ7pt93q.cjs");
3
+ let verkit = require("verkit");
3
4
  let node_util = require("node:util");
4
5
  let node_process = require("node:process");
5
6
  node_process = require_KubbDriver.__toESM(node_process, 1);
6
7
  let tinyexec = require("tinyexec");
7
8
  let node_fs_promises = require("node:fs/promises");
8
9
  let node_path = require("node:path");
10
+ node_path = require_KubbDriver.__toESM(node_path, 1);
9
11
  let node_crypto = require("node:crypto");
10
12
  let node_fs = require("node:fs");
11
13
  let node_os = require("node:os");
@@ -14,60 +16,7 @@ let unstorage = require("unstorage");
14
16
  let unstorage_drivers_fs = require("unstorage/drivers/fs");
15
17
  unstorage_drivers_fs = require_KubbDriver.__toESM(unstorage_drivers_fs, 1);
16
18
  let node_url = require("node:url");
17
- //#region src/createAdapter.ts
18
- /**
19
- * Defines a custom adapter that translates a spec format into Kubb's universal
20
- * AST, for example GraphQL, gRPC, or AsyncAPI. The built-in `@kubb/adapter-oas`
21
- * handles OpenAPI/Swagger documents.
22
- *
23
- * Adapters must return an `InputNode` from `parse`. That node is what every
24
- * plugin in the build consumes.
25
- *
26
- * @example
27
- * ```ts
28
- * import { createAdapter, type AdapterFactoryOptions } from '@kubb/core'
29
- * import { ast } from '@kubb/ast'
30
- *
31
- * type MyAdapter = AdapterFactoryOptions<'my-adapter', { validate?: boolean }>
32
- *
33
- * export const myAdapter = createAdapter<MyAdapter>((options) => ({
34
- * name: 'my-adapter',
35
- * options,
36
- * document: null,
37
- * async parse(_source) {
38
- * // Convert the source (path or inline data) into an InputNode.
39
- * return ast.factory.createInput()
40
- * },
41
- * async validate() {
42
- * // Throw here when the spec is invalid.
43
- * },
44
- * }))
45
- * ```
46
- */
47
- function createAdapter(build) {
48
- return (options) => build(options ?? {});
49
- }
50
- //#endregion
51
- //#region src/applyConfigDefaults.ts
52
- /**
53
- * Fills in the config defaults shared by `defineConfig` and the unplugin factory: the fallback
54
- * adapter, `defaultOutput`'s fields, and appending the barrel plugin when it's not already
55
- * registered. Both entry points construct their own adapter, barrel plugin, and output defaults
56
- * (`barrel` is a `@kubb/plugin-barrel` extension field core doesn't know about) and pass them in,
57
- * so `@kubb/core` doesn't need to depend on `@kubb/adapter-oas` or `@kubb/plugin-barrel`.
58
- */
59
- function applyConfigDefaults(config, { defaultAdapter, barrelPlugin, barrelPluginName, defaultOutput }) {
60
- const plugins = config.plugins?.some((plugin) => plugin.name === barrelPluginName) ? config.plugins ?? [] : [...config.plugins ?? [], barrelPlugin];
61
- return {
62
- adapter: config.adapter ?? defaultAdapter,
63
- plugins,
64
- output: {
65
- ...defaultOutput,
66
- ...config.output
67
- }
68
- };
69
- }
70
- //#endregion
19
+ let node_module = require("node:module");
71
20
  //#region ../../internals/utils/src/isCIEnvironment.ts
72
21
  /**
73
22
  * Returns `true` when a known CI provider has set its environment variable.
@@ -206,6 +155,47 @@ function tokenize(command) {
206
155
  return (command.match(/[^\s"']+|"([^"]*)"|'([^']*)'/g) ?? []).map((token) => token.replace(/^["']|["']$/g, ""));
207
156
  }
208
157
  //#endregion
158
+ //#region src/createAdapter.ts
159
+ function createAdapter(input) {
160
+ if (typeof input === "function") return require_KubbDriver.defineExtension({
161
+ kind: "adapter",
162
+ build: (options) => input(options)
163
+ });
164
+ const { meta, setup, build } = input;
165
+ return require_KubbDriver.defineExtension({
166
+ kind: "adapter",
167
+ meta,
168
+ build: (raw) => {
169
+ const options = setup ? setup(raw) : raw;
170
+ return Object.assign(build(options), {
171
+ name: meta.name,
172
+ meta,
173
+ options
174
+ });
175
+ }
176
+ });
177
+ }
178
+ //#endregion
179
+ //#region src/applyConfigDefaults.ts
180
+ /**
181
+ * Fills in the config defaults shared by `defineConfig` and the unplugin factory: the fallback
182
+ * adapter, `defaultOutput`'s fields, and appending the barrel plugin when it's not already
183
+ * registered. Both entry points construct their own adapter, barrel plugin, and output defaults
184
+ * (`barrel` is a `@kubb/plugin-barrel` extension field core doesn't know about) and pass them in,
185
+ * so `@kubb/core` doesn't need to depend on `@kubb/adapter-oas` or `@kubb/plugin-barrel`.
186
+ */
187
+ function applyConfigDefaults(config, { defaultAdapter, barrelPlugin, barrelPluginName, defaultOutput }) {
188
+ const plugins = config.plugins?.some((plugin) => plugin.name === barrelPluginName) ? config.plugins ?? [] : [...config.plugins ?? [], barrelPlugin];
189
+ return {
190
+ adapter: config.adapter ?? defaultAdapter,
191
+ plugins,
192
+ output: {
193
+ ...defaultOutput,
194
+ ...config.output
195
+ }
196
+ };
197
+ }
198
+ //#endregion
209
199
  //#region src/outputManifest.ts
210
200
  /**
211
201
  * Bumped when the stored shape changes, so an older cache is discarded instead of misread.
@@ -1300,7 +1290,7 @@ function defineGenerator(generator) {
1300
1290
  function defineParser(input) {
1301
1291
  if (typeof input === "function") return require_KubbDriver.defineExtension({
1302
1292
  kind: "parser",
1303
- build: ({ options }) => {
1293
+ build: (options) => {
1304
1294
  const parser = input(options);
1305
1295
  return {
1306
1296
  ...parser,
@@ -1308,14 +1298,16 @@ function defineParser(input) {
1308
1298
  };
1309
1299
  }
1310
1300
  });
1311
- const { meta, setup } = input;
1301
+ const { meta } = input;
1302
+ const build = "build" in input ? input.build : input.setup;
1312
1303
  return require_KubbDriver.defineExtension({
1313
1304
  kind: "parser",
1314
1305
  meta,
1315
- build: ({ options }) => ({
1316
- ...setup(options),
1306
+ build: (options) => ({
1307
+ ...build(options),
1317
1308
  name: meta.name,
1318
- meta
1309
+ meta,
1310
+ options
1319
1311
  })
1320
1312
  });
1321
1313
  }
@@ -1370,6 +1362,118 @@ const memoryStorage = createStorage(() => {
1370
1362
  };
1371
1363
  });
1372
1364
  //#endregion
1365
+ //#region src/manifest.ts
1366
+ const EXTENSION_KINDS = /* @__PURE__ */ new Set([
1367
+ "plugin",
1368
+ "adapter",
1369
+ "parser"
1370
+ ]);
1371
+ const OPTION_TYPES = /* @__PURE__ */ new Set([
1372
+ "select",
1373
+ "boolean",
1374
+ "text",
1375
+ "number",
1376
+ "list"
1377
+ ]);
1378
+ const PACKAGE_NAME = /^(?:@[a-z0-9~][a-z0-9._~-]*\/)?[a-z0-9~][a-z0-9._~-]*$/;
1379
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;
1380
+ const REGISTRY_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*\/[a-z0-9]+(?:-[a-z0-9]+)*$/;
1381
+ /** Option path segments that would reach an object's prototype when Studio writes the value by path. */
1382
+ const UNSAFE_KEYS = /* @__PURE__ */ new Set([
1383
+ "__proto__",
1384
+ "constructor",
1385
+ "prototype"
1386
+ ]);
1387
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
1388
+ const isOptionalString = (value) => value === void 0 || typeof value === "string";
1389
+ const isFilledString = (value) => typeof value === "string" && value !== "";
1390
+ /** Serializes with sorted object keys, so equal JSON values give equal strings whatever their key order. */
1391
+ const canonicalJSON = (value) => JSON.stringify(value, (_key, item) => isObject(item) ? Object.fromEntries(Object.keys(item).sort().map((key) => [key, item[key]])) : item);
1392
+ /**
1393
+ * Whether `name` is a valid npm package name, such as `@kubb/plugin-ts`. Rejects paths, URLs,
1394
+ * `node:` specifiers, and names that start with `-`, so the result is safe to pass to `import()` or
1395
+ * a package manager.
1396
+ */
1397
+ function isPackageName(name) {
1398
+ return typeof name === "string" && name.length <= 214 && PACKAGE_NAME.test(name);
1399
+ }
1400
+ /** Checks the shape of one manifest option, including that its path cannot reach a prototype. */
1401
+ function isOption(value) {
1402
+ if (!isObject(value)) return false;
1403
+ const { key, path, label, description, type, choices, itemCase } = value;
1404
+ return isFilledString(key) && Array.isArray(path) && path.length > 0 && path.every((segment) => isFilledString(segment) && !UNSAFE_KEYS.has(segment)) && isFilledString(label) && isOptionalString(description) && OPTION_TYPES.has(type) && (choices === void 0 || Array.isArray(choices) && choices.every((choice) => isObject(choice) && "value" in choice && isOptionalString(choice.label))) && (itemCase === void 0 || itemCase === "upper");
1405
+ }
1406
+ /**
1407
+ * What is wrong with the options of a well-formed manifest, beyond their shape: keys are unique, a
1408
+ * select has choices, and a select's default is one of its choice values. Empty when they pass.
1409
+ */
1410
+ function manifestProblems({ options = [] }) {
1411
+ const seen = /* @__PURE__ */ new Set();
1412
+ return options.flatMap((option) => {
1413
+ const problems = seen.has(option.key) ? [`option "${option.key}" is declared more than once`] : [];
1414
+ seen.add(option.key);
1415
+ if (option.type !== "select") return problems;
1416
+ if (!option.choices?.length) return [...problems, `option "${option.key}" is a select without choices`];
1417
+ return !("default" in option) || option.choices.some((choice) => canonicalJSON(choice.value) === canonicalJSON(option.default)) ? problems : [...problems, `option "${option.key}" has a default that is not one of its choices`];
1418
+ });
1419
+ }
1420
+ /**
1421
+ * Checks a parsed `kubb-extension.json` or a registry response before Kubb or Studio uses it: the
1422
+ * fields Kubb reads, every option's shape (including option paths that cannot reach a prototype),
1423
+ * and `manifestProblems`. A malformed manifest is skipped instead of trusted.
1424
+ */
1425
+ function isExtensionManifest(value) {
1426
+ if (!isObject(value)) return false;
1427
+ const { kind, name, export: exportName, displayName, description, compatibility, options } = value;
1428
+ return EXTENSION_KINDS.has(kind) && isPackageName(name) && typeof exportName === "string" && IDENTIFIER.test(exportName) && typeof displayName === "string" && typeof description === "string" && (compatibility === void 0 || isObject(compatibility) && Object.entries(compatibility).every(([key, range]) => (key === "kubb" || key === "node") && typeof range === "string")) && (options === void 0 || Array.isArray(options) && options.every(isOption)) && manifestProblems(value).length === 0;
1429
+ }
1430
+ /**
1431
+ * Checks one entry of a registry's `index.json` or `<owner>/<slug>.json`: a full `<owner>/<slug>` id,
1432
+ * an npm artifact pinned to a valid version, and a valid manifest of the entry's kind.
1433
+ */
1434
+ function isRegistryEntry(value) {
1435
+ if (!isObject(value)) return false;
1436
+ const { id, kind, type, artifact, manifest } = value;
1437
+ return typeof id === "string" && REGISTRY_ID.test(id) && EXTENSION_KINDS.has(kind) && (type === "official" || type === "community") && isObject(artifact) && artifact.kind === "npm" && isPackageName(artifact.package) && typeof artifact.version === "string" && (0, verkit.isValid)(artifact.version) && isExtensionManifest(manifest) && manifest.kind === kind;
1438
+ }
1439
+ //#endregion
1440
+ //#region src/installedPackages.ts
1441
+ /** Reads and parses a JSON file. Throws when it is missing or not JSON. */
1442
+ const readJSON = async (file) => JSON.parse(await (0, node_fs_promises.readFile)(file, "utf8"));
1443
+ /**
1444
+ * The `dependencies` and `devDependencies` of the project at `root`, plus `packages`, with the
1445
+ * installed version and the valid `kubb-extension.json` each one ships, when it does. A package
1446
+ * also counts as installed when it resolves from one of the `resolveFrom` packages, such as `kubb`
1447
+ * for the extensions it ships with.
1448
+ */
1449
+ async function readInstalledPackages({ root, packages = [], resolveFrom = [] }) {
1450
+ const project = (0, node_module.createRequire)(node_path.default.join(root, "package.json"));
1451
+ const requires = [project, ...resolveFrom.flatMap((name) => {
1452
+ try {
1453
+ return [(0, node_module.createRequire)(project.resolve(`${name}/package.json`))];
1454
+ } catch {
1455
+ return [];
1456
+ }
1457
+ })];
1458
+ const packageJSON = await readJSON(node_path.default.join(root, "package.json")).catch(() => null);
1459
+ const dependencies = [packageJSON?.dependencies, packageJSON?.devDependencies].flatMap((record) => typeof record === "object" && record !== null ? Object.keys(record) : []);
1460
+ return Promise.all([.../* @__PURE__ */ new Set([...dependencies, ...packages])].filter(isPackageName).map(async (name) => {
1461
+ const dir = requires.flatMap((require$1) => require$1.resolve.paths(name) ?? []).map((dir) => node_path.default.join(dir, name)).find((dir) => (0, node_fs.existsSync)(node_path.default.join(dir, "package.json")));
1462
+ if (!dir) return { package: name };
1463
+ try {
1464
+ const { version } = await readJSON(node_path.default.join(dir, "package.json"));
1465
+ const manifest = await readJSON(node_path.default.join(dir, "kubb-extension.json")).catch(() => void 0);
1466
+ return {
1467
+ package: name,
1468
+ version: typeof version === "string" ? version : void 0,
1469
+ manifest: isExtensionManifest(manifest) ? manifest : void 0
1470
+ };
1471
+ } catch {
1472
+ return { package: name };
1473
+ }
1474
+ }));
1475
+ }
1476
+ //#endregion
1373
1477
  exports.Diagnostics = require_KubbDriver.Diagnostics;
1374
1478
  exports.Hookable = require_KubbDriver.Hookable;
1375
1479
  exports.KubbDriver = require_KubbDriver.KubbDriver;
@@ -1379,6 +1483,7 @@ exports.addMacro = require_KubbDriver.addMacro;
1379
1483
  exports.applyConfigDefaults = applyConfigDefaults;
1380
1484
  exports.assertPluginOption = require_KubbDriver.assertPluginOption;
1381
1485
  exports.cacheStorage = cacheStorage;
1486
+ exports.checkCompatibility = require_KubbDriver.checkCompatibility;
1382
1487
  exports.cliReporter = cliReporter;
1383
1488
  exports.createAdapter = createAdapter;
1384
1489
  exports.createCliReporter = createCliReporter;
@@ -1395,11 +1500,16 @@ exports.fsStorage = fsStorage;
1395
1500
  exports.getInputKind = require_KubbDriver.getInputKind;
1396
1501
  exports.htmlReporter = htmlReporter;
1397
1502
  exports.injectFile = require_KubbDriver.injectFile;
1503
+ exports.isExtensionManifest = isExtensionManifest;
1504
+ exports.isPackageName = isPackageName;
1505
+ exports.isRegistryEntry = isRegistryEntry;
1398
1506
  exports.jsonReporter = jsonReporter;
1399
1507
  exports.kubbContext = require_KubbDriver.kubbContext;
1400
1508
  exports.kubbStorage = kubbStorage;
1401
1509
  exports.logLevel = logLevel;
1510
+ exports.manifestProblems = manifestProblems;
1402
1511
  exports.memoryStorage = memoryStorage;
1512
+ exports.readInstalledPackages = readInstalledPackages;
1403
1513
  exports.requirePlugin = require_KubbDriver.requirePlugin;
1404
1514
  exports.resolveCacheDir = resolveCacheDir;
1405
1515
  exports.resolveKubbDir = resolveKubbDir;