asphodelos 0.5.0 → 0.5.2

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/README.md CHANGED
@@ -292,6 +292,12 @@ const { data, error } = await client.users({ id: '1' }).get()
292
292
  The app is imported for its type only, so a browser bundle never pulls the server in. The project
293
293
  needs `@elysiajs/eden`, with `elysia` resolving to one copy.
294
294
 
295
+ A path key with a query string right after a path parameter, such as `/jobs/{id}?beta=true`, is
296
+ left out of the app, its types, the mock and the Eden wrappers, with a warning: Elysia reads `:id?`
297
+ as an optional parameter, which would hide the routes beside it (`/jobs/{id}/cancel`) from the
298
+ client. The hooks still reach it, with `fetch`. A module generated before keeps its handlers on
299
+ regeneration, so remove such a route from it by hand.
300
+
295
301
  ### Imports Between Generated Files
296
302
 
297
303
  Nothing is configured per file: how one generated file imports another follows from where the two
package/dist/cli.mjs CHANGED
@@ -4,7 +4,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
4
4
  import { Console, Effect, FileSystem, Option, Path, Ref, Stream } from "effect";
5
5
  import { CliError, Command, Flag } from "effect/cli";
6
6
  // package.json
7
- var version = "0.5.0";
7
+ var version = "0.5.2";
8
8
  var description = "Asphodelos is a code generator from OpenAPI to Elysia";
9
9
  // src/cli/index.ts
10
10
  const COMMAND_NAME = "asphodelos";
@@ -48,7 +48,7 @@ function runJobs(config) {
48
48
  const [{ parseOpenAPI }, { FormatOptions }, { cleanSplitOutputs, makeJob }] = yield* Effect.promise(() => Promise.all([
49
49
  import("./openapi-4yNuDK_n.mjs").then((n) => n.t),
50
50
  import("./format-DC258z--.mjs").then((n) => n.r),
51
- import("./shared-Bb1qvBpw.mjs").then((n) => n.s)
51
+ import("./shared-Ch_ArUGQ.mjs").then((n) => n.s)
52
52
  ]));
53
53
  const jobs = makeJob(yield* parseOpenAPI(config.input), config);
54
54
  yield* cleanSplitOutputs(jobs);
@@ -86,7 +86,7 @@ function reportJobs(config, previous) {
86
86
  onFailure: (error) => Console.error(`❌ ${error.message}`),
87
87
  onSuccess: (report) => Console.log(report)
88
88
  }));
89
- const { outsideSources } = yield* Effect.promise(() => import("./shared-Bb1qvBpw.mjs").then((n) => n.s));
89
+ const { outsideSources } = yield* Effect.promise(() => import("./shared-Ch_ArUGQ.mjs").then((n) => n.s));
90
90
  const inputDirectory = path.dirname(path.resolve(config.input));
91
91
  return {
92
92
  inputDirectory,
@@ -1669,6 +1669,23 @@ function makeModuleSpec(fromFile, target) {
1669
1669
  const stripped = path.relative(path.dirname(fromFile), target.output).replaceAll("\\", "/").replace(/\.ts$/u, "").replace(/(^|\/)index$/u, "");
1670
1670
  return stripped === "" ? "." : stripped.startsWith(".") ? stripped : `./${stripped}`;
1671
1671
  }
1672
+ /**
1673
+ * The path `from` imports the generated file `target` by.
1674
+ *
1675
+ * Through the alias when the config names one and `target` sits under the app entry's directory —
1676
+ * `@/` stands for that directory, so `src/client.ts` is `@/client` from anywhere — and relative to
1677
+ * `from` otherwise. The extension goes. A barrel is imported by its directory; any other file
1678
+ * keeps its `index`, so an entry is named rather than left to directory resolution.
1679
+ */
1680
+ function makeImportPath(from, target, alias, kind = "file") {
1681
+ const module = posix.normalize(target).replace(kind === "barrel" ? /(?:\/index)?\.ts$/u : /\.ts$/u, "");
1682
+ if (alias !== void 0) {
1683
+ const inside = posix.relative(alias.directory, module);
1684
+ if (inside !== "" && !inside.startsWith("..")) return `${alias.prefix}/${inside}`;
1685
+ }
1686
+ const relative = posix.relative(posix.dirname(posix.normalize(from)), module);
1687
+ return relative.startsWith(".") ? relative : `./${relative}`;
1688
+ }
1672
1689
  function makeBarrel(value) {
1673
1690
  return `${Object.keys(value).toSorted().map((k) => `export * from './${k.charAt(0).toLowerCase() + k.slice(1)}'`).join("\n")}\n`;
1674
1691
  }
@@ -1858,6 +1875,23 @@ function renameOperationParams(operation, renames) {
1858
1875
  parameters
1859
1876
  };
1860
1877
  }
1878
+ const warnedQueryKeys = /* @__PURE__ */ new Set();
1879
+ /**
1880
+ * Whether a path key can become an Elysia route path.
1881
+ *
1882
+ * A key with a query string right after a `{param}` segment, such as `/jobs/{id}?beta=true`, cannot:
1883
+ * Elysia reads `:id?` as an optional parameter, so the route tree Eden types would lose the routes
1884
+ * beside it (`/jobs/{id}/cancel`). Such a key is left out of the app, its types, the mock and the
1885
+ * Eden wrappers, with a warning once per key; the hooks reach it with `fetch`.
1886
+ */
1887
+ function isElysiaRoutePath(pathKey) {
1888
+ if (!/\{[^/{}]+\}\?/u.test(pathKey)) return true;
1889
+ if (!warnedQueryKeys.has(pathKey)) {
1890
+ warnedQueryKeys.add(pathKey);
1891
+ console.warn(`[asphodelos] path '${pathKey}' has a query string after a path parameter, which Elysia reads as an optional parameter; it is left out of the app, its types, the mock and the Eden wrappers`);
1892
+ }
1893
+ return false;
1894
+ }
1861
1895
  // src/helper/openapi.ts
1862
1896
  /**
1863
1897
  * Generates prefix-only query-key getters (`get<Prefix>Key() => ['<prefix>']`)
@@ -2064,7 +2098,7 @@ function walk(path, resource, pathItem, api, canonical) {
2064
2098
  });
2065
2099
  }
2066
2100
  function operationsByResource(api) {
2067
- const canonical = canonicalParamNames([...Object.keys(api.paths ?? {}), ...Object.keys(api.webhooks ?? {}).map((event) => `/webhooks/${event}`)]);
2101
+ const canonical = canonicalParamNames([...Object.keys(api.paths ?? {}).filter(isElysiaRoutePath), ...Object.keys(api.webhooks ?? {}).map((event) => `/webhooks/${event}`)]);
2068
2102
  const grouped = /* @__PURE__ */ new Map();
2069
2103
  const collect = (resource, item) => {
2070
2104
  const bucket = grouped.get(resource) ?? [];
@@ -2072,7 +2106,7 @@ function operationsByResource(api) {
2072
2106
  grouped.set(resource, bucket);
2073
2107
  };
2074
2108
  for (const [path, pathItem] of Object.entries(api.paths ?? {})) {
2075
- if (!pathItem) continue;
2109
+ if (!pathItem || !isElysiaRoutePath(path)) continue;
2076
2110
  for (const [resource, route] of walk(path, resourceName(path), pathItem, api, canonical)) collect(resource, route);
2077
2111
  }
2078
2112
  for (const [event, pathItem] of Object.entries(api.webhooks ?? {})) {
@@ -2377,7 +2411,7 @@ function eden(openAPI, output, importPath, client, basePath) {
2377
2411
  const prefix = basePath && basePath !== "/" ? basePath : "";
2378
2412
  const operations = [];
2379
2413
  for (const [pathStr, pathItem] of Object.entries(openAPI.paths ?? {})) {
2380
- if (!pathItem) continue;
2414
+ if (!pathItem || !isElysiaRoutePath(pathStr)) continue;
2381
2415
  for (const method of HTTP_METHODS) {
2382
2416
  const operation = pathItem[method];
2383
2417
  if (!operation) continue;
@@ -2815,7 +2849,8 @@ function fetchTarget(fullPath, method, operation) {
2815
2849
  const index = names.indexOf(n);
2816
2850
  return `\${encodeURIComponent(${exprs[index] ?? params[index]})}`;
2817
2851
  });
2818
- return hasQuery ? `\`\${${ORIGIN}}${inner}\${search.size ? \`?\${search}\` : ''}\`` : `\`\${${ORIGIN}}${inner}\``;
2852
+ const separator = inner.includes("?") ? "&" : "?";
2853
+ return hasQuery ? `\`\${${ORIGIN}}${inner}\${search.size ? \`${separator}\${search}\` : ''}\`` : `\`\${${ORIGIN}}${inner}\``;
2819
2854
  };
2820
2855
  const search = (options) => hasQuery ? `const search=new URLSearchParams();for(const[k,v]of Object.entries(${options}?.query??{})){if(v===undefined)continue;if(Array.isArray(v)){for(const x of v){search.append(k,String(x))}}else{search.set(k,String(v))}}` : "";
2821
2856
  return {
@@ -3965,7 +4000,7 @@ function makeMock(spec, options = {}) {
3965
4000
  };
3966
4001
  const components = spec.components;
3967
4002
  const routes = Object.entries(spec.paths ?? {}).flatMap(([path, pathItem]) => {
3968
- if (!pathItem) return [];
4003
+ if (!pathItem || !isElysiaRoutePath(path)) return [];
3969
4004
  return HTTP_METHODS.flatMap((method) => {
3970
4005
  const operation = pathItem[method];
3971
4006
  if (!operation) return [];
@@ -4202,7 +4237,7 @@ function makeRoutes(openAPI, prefix) {
4202
4237
  const out = [];
4203
4238
  const prefixKeys = prefix && prefix !== "/" ? pathToKeys(prefix) : [];
4204
4239
  for (const [pathStr, pathItem] of Object.entries(openAPI.paths ?? {})) {
4205
- if (!pathItem) continue;
4240
+ if (!pathItem || !isElysiaRoutePath(pathStr)) continue;
4206
4241
  const keys = [...prefixKeys, ...pathToKeys(pathStr)];
4207
4242
  for (const method of HTTP_METHODS) {
4208
4243
  const operation = pathItem[method];
@@ -4254,8 +4289,8 @@ function collectRefs(openAPI) {
4254
4289
  }
4255
4290
  if ("schema" in p) enqueue(parameterSchema(p));
4256
4291
  };
4257
- for (const [, pathItem] of Object.entries(openAPI.paths ?? {})) {
4258
- if (!pathItem) continue;
4292
+ for (const [pathStr, pathItem] of Object.entries(openAPI.paths ?? {})) {
4293
+ if (!pathItem || !isElysiaRoutePath(pathStr)) continue;
4259
4294
  for (const method of HTTP_METHODS) {
4260
4295
  const op = pathItem[method];
4261
4296
  if (!op) continue;
@@ -4314,23 +4349,6 @@ var shared_exports = /* @__PURE__ */ __exportAll({
4314
4349
  outsideSources: () => outsideSources
4315
4350
  });
4316
4351
  /**
4317
- * The specifier `from` imports the generated file `target` by.
4318
- *
4319
- * Through the alias when the config names one and `target` sits under the app entry's directory —
4320
- * `@/` stands for that directory, so `src/client.ts` is `@/client` from anywhere — and relative to
4321
- * `from` otherwise. The extension goes. A barrel is imported by its directory; any other file
4322
- * keeps its `index`, so an entry is named rather than left to directory resolution.
4323
- */
4324
- function importSpecifier(from, target, alias, kind = "file") {
4325
- const module = posix.normalize(target).replace(kind === "barrel" ? /(?:\/index)?\.ts$/u : /\.ts$/u, "");
4326
- if (alias !== void 0) {
4327
- const inside = posix.relative(alias.directory, module);
4328
- if (inside !== "" && !inside.startsWith("..")) return `${alias.prefix}/${inside}`;
4329
- }
4330
- const relative = posix.relative(posix.dirname(posix.normalize(from)), module);
4331
- return relative.startsWith(".") ? relative : `./${relative}`;
4332
- }
4333
- /**
4334
4352
  * The directory of the nearest `package.json` at or above `dir`, or `undefined` when there is
4335
4353
  * none: the package a file belongs to, read from where it sits and nothing else.
4336
4354
  */
@@ -4409,7 +4427,7 @@ function settleTarget(from, target, pathAlias) {
4409
4427
  import: target.package
4410
4428
  };
4411
4429
  if (pathAlias === void 0) return target;
4412
- const specifier = importSpecifier(from, target.output, pathAlias, "barrel");
4430
+ const specifier = makeImportPath(from, target.output, pathAlias, "barrel");
4413
4431
  return specifier.startsWith(".") ? target : {
4414
4432
  ...target,
4415
4433
  import: specifier
@@ -4451,7 +4469,7 @@ function makeJob(openAPI, config) {
4451
4469
  const clientImport = (field, output) => {
4452
4470
  if (clientConfig === void 0) return Effect.fail(new GenerateError({ message: `${field} needs the top-level client it imports` }));
4453
4471
  const isBeside = posix.dirname(posix.normalize(output)) === posix.dirname(clientConfig.output);
4454
- return packageImport(output, clientConfig.output, isBeside || clientBarrel === void 0 ? importSpecifier(output, clientConfig.output, pathAlias) : importSpecifier(output, clientBarrel, pathAlias, "barrel"), clientConfig.package, `${field}.output is in another package than the client: name the package the client is published as, client.package, for the file to import it by.`);
4472
+ return packageImport(output, clientConfig.output, isBeside || clientBarrel === void 0 ? makeImportPath(output, clientConfig.output, pathAlias) : makeImportPath(output, clientBarrel, pathAlias, "barrel"), clientConfig.package, `${field}.output is in another package than the client: name the package the client is published as, client.package, for the file to import it by.`);
4455
4473
  };
4456
4474
  const { output: componentsOutput, package: componentsPackage, ...componentTargets } = config.components ?? {};
4457
4475
  const targetOf = (kind) => componentTargets[kind] ?? { output: `${baseDir}/components/${kind}.ts` };
@@ -4491,7 +4509,7 @@ function makeJob(openAPI, config) {
4491
4509
  name: "client",
4492
4510
  output: clientConfig.output,
4493
4511
  split: false,
4494
- run: (output) => clientRun(output, packageImport(output, appOutput, importSpecifier(output, appOutput, pathAlias), config.package, "client.output is in another package than the app entry: name the package the app is published as, the top-level package, for the client to import it by."), {
4512
+ run: (output) => clientRun(output, packageImport(output, appOutput, makeImportPath(output, appOutput, pathAlias), config.package, "client.output is in another package than the app entry: name the package the app is published as, the top-level package, for the client to import it by."), {
4495
4513
  baseUrl: clientConfig.baseUrl,
4496
4514
  sameOrigin: clientConfig.sameOrigin === true,
4497
4515
  barrel: clientBarrel
@@ -1,6 +1,6 @@
1
1
  import { INPUT_EXTENSIONS, parseConfig } from "../index.mjs";
2
2
  import { t as FormatOptions } from "../format-DC258z--.mjs";
3
- import { a as makeJob, c as fileSystemLayer, i as jobTargets, n as isInsideDirectory, o as outsideSources, r as isUserCodeJob, t as cleanSplitOutputs } from "../shared-Bb1qvBpw.mjs";
3
+ import { a as makeJob, c as fileSystemLayer, i as jobTargets, n as isInsideDirectory, o as outsideSources, r as isUserCodeJob, t as cleanSplitOutputs } from "../shared-Ch_ArUGQ.mjs";
4
4
  import { n as parseOpenAPI } from "../openapi-4yNuDK_n.mjs";
5
5
  import { Effect, FileSystem, Result } from "effect";
6
6
  import path from "node:path";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asphodelos",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "Asphodelos is a code generator from OpenAPI to Elysia",
5
5
  "keywords": [
6
6
  "elysia",