asphodelos 0.5.1 → 0.5.3

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
@@ -280,6 +280,15 @@ client: { output: 'src/lib/client.ts', baseUrl: { env: 'API_URL', source: 'proce
280
280
  such as `/widget.json` — call `fetch` with it, so they send where the client does. A package
281
281
  entry that `client.package` names exports `clientOrigin` beside `client`.
282
282
 
283
+ Such a hook parses a JSON response the way treaty does: a string that looks like a date becomes a
284
+ `Date`, which is what the `t.Date()` of a `format: date` / `date-time` field declares. The match is
285
+ by the value, not by the schema, with treaty's patterns: an ISO 8601 date-time with a `Z` or an
286
+ offset, a `Date.prototype.toString()` string, and a short date in the years 1900–2099 such as
287
+ `2026-01-02` or `01/02/2026`. So a plain string field whose value looks like one of these arrives
288
+ as a `Date` too, and a date the patterns miss — `2026-11-24T03:10:22` without an offset,
289
+ `9999-12-31` — stays a string. What JSON does not carry is not decoded either: a `t.Uint8Array`,
290
+ `t.File` or `t.Transform` field is typed as decoded and holds the value as it was sent.
291
+
283
292
  The `index.ts` beside the client re-exports it, so it is imported as `./lib` — by `eden`, by the
284
293
  hooks, and by your own code:
285
294
 
@@ -292,6 +301,12 @@ const { data, error } = await client.users({ id: '1' }).get()
292
301
  The app is imported for its type only, so a browser bundle never pulls the server in. The project
293
302
  needs `@elysiajs/eden`, with `elysia` resolving to one copy.
294
303
 
304
+ A path key with a query string right after a path parameter, such as `/jobs/{id}?beta=true`, is
305
+ left out of the app, its types, the mock and the Eden wrappers, with a warning: Elysia reads `:id?`
306
+ as an optional parameter, which would hide the routes beside it (`/jobs/{id}/cancel`) from the
307
+ client. The hooks still reach it, with `fetch`. A module generated before keeps its handlers on
308
+ regeneration, so remove such a route from it by hand.
309
+
295
310
  ### Imports Between Generated Files
296
311
 
297
312
  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.1";
7
+ var version = "0.5.3";
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-CQsoa7gV.mjs").then((n) => n.s)
51
+ import("./shared-BWuUl_dt.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-CQsoa7gV.mjs").then((n) => n.s));
89
+ const { outsideSources } = yield* Effect.promise(() => import("./shared-BWuUl_dt.mjs").then((n) => n.s));
90
90
  const inputDirectory = path.dirname(path.resolve(config.input));
91
91
  return {
92
92
  inputDirectory,
@@ -1499,6 +1499,21 @@ function resolveUniqueNames(keys) {
1499
1499
  map: /* @__PURE__ */ new Map()
1500
1500
  }).map;
1501
1501
  }
1502
+ /**
1503
+ * The schema const the schemas generator writes for each `components.schemas` key, so a generator
1504
+ * that names a component from outside (a hook typing its data by one) names the const that was
1505
+ * actually written. A split output resolves the unique names per file — one file per group of
1506
+ * mutually-recursive schemas — the way {@link schemasCode} is called for each, so two keys that
1507
+ * collide across files keep one name there, as they do in what the split generator writes.
1508
+ */
1509
+ function schemaConstNames(schemas, split) {
1510
+ if (!schemas) return /* @__PURE__ */ new Map();
1511
+ const files = split ? sccSchemas(Object.entries(schemas).map(([name, schema]) => ({
1512
+ name,
1513
+ schema
1514
+ }))).map((group) => Object.fromEntries(group.map((member) => [member.name, member.schema]))) : [schemas];
1515
+ return new Map(files.flatMap((file) => [...resolveUniqueNames(Object.keys(file))].map(([key, unique]) => [key, `${unique}Schema`])));
1516
+ }
1502
1517
  function schemasCode(schemas, readonlyMode, exportTypes, exported = true) {
1503
1518
  if (!schemas || Object.keys(schemas).length === 0) return "";
1504
1519
  const names = resolveUniqueNames(Object.keys(schemas));
@@ -1875,6 +1890,23 @@ function renameOperationParams(operation, renames) {
1875
1890
  parameters
1876
1891
  };
1877
1892
  }
1893
+ const warnedQueryKeys = /* @__PURE__ */ new Set();
1894
+ /**
1895
+ * Whether a path key can become an Elysia route path.
1896
+ *
1897
+ * A key with a query string right after a `{param}` segment, such as `/jobs/{id}?beta=true`, cannot:
1898
+ * Elysia reads `:id?` as an optional parameter, so the route tree Eden types would lose the routes
1899
+ * beside it (`/jobs/{id}/cancel`). Such a key is left out of the app, its types, the mock and the
1900
+ * Eden wrappers, with a warning once per key; the hooks reach it with `fetch`.
1901
+ */
1902
+ function isElysiaRoutePath(pathKey) {
1903
+ if (!/\{[^/{}]+\}\?/u.test(pathKey)) return true;
1904
+ if (!warnedQueryKeys.has(pathKey)) {
1905
+ warnedQueryKeys.add(pathKey);
1906
+ 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`);
1907
+ }
1908
+ return false;
1909
+ }
1878
1910
  // src/helper/openapi.ts
1879
1911
  /**
1880
1912
  * Generates prefix-only query-key getters (`get<Prefix>Key() => ['<prefix>']`)
@@ -2081,7 +2113,7 @@ function walk(path, resource, pathItem, api, canonical) {
2081
2113
  });
2082
2114
  }
2083
2115
  function operationsByResource(api) {
2084
- const canonical = canonicalParamNames([...Object.keys(api.paths ?? {}), ...Object.keys(api.webhooks ?? {}).map((event) => `/webhooks/${event}`)]);
2116
+ const canonical = canonicalParamNames([...Object.keys(api.paths ?? {}).filter(isElysiaRoutePath), ...Object.keys(api.webhooks ?? {}).map((event) => `/webhooks/${event}`)]);
2085
2117
  const grouped = /* @__PURE__ */ new Map();
2086
2118
  const collect = (resource, item) => {
2087
2119
  const bucket = grouped.get(resource) ?? [];
@@ -2089,7 +2121,7 @@ function operationsByResource(api) {
2089
2121
  grouped.set(resource, bucket);
2090
2122
  };
2091
2123
  for (const [path, pathItem] of Object.entries(api.paths ?? {})) {
2092
- if (!pathItem) continue;
2124
+ if (!pathItem || !isElysiaRoutePath(path)) continue;
2093
2125
  for (const [resource, route] of walk(path, resourceName(path), pathItem, api, canonical)) collect(resource, route);
2094
2126
  }
2095
2127
  for (const [event, pathItem] of Object.entries(api.webhooks ?? {})) {
@@ -2394,7 +2426,7 @@ function eden(openAPI, output, importPath, client, basePath) {
2394
2426
  const prefix = basePath && basePath !== "/" ? basePath : "";
2395
2427
  const operations = [];
2396
2428
  for (const [pathStr, pathItem] of Object.entries(openAPI.paths ?? {})) {
2397
- if (!pathItem) continue;
2429
+ if (!pathItem || !isElysiaRoutePath(pathStr)) continue;
2398
2430
  for (const method of HTTP_METHODS) {
2399
2431
  const operation = pathItem[method];
2400
2432
  if (!operation) continue;
@@ -2770,12 +2802,12 @@ function needsFetchHook(pathStr) {
2770
2802
  function pathParamNames(pathStr) {
2771
2803
  return [...pathStr.matchAll(/\{([^}]+)\}/gu)].map((m) => m[1] ?? "");
2772
2804
  }
2773
- function successType(operation) {
2805
+ function successType(operation, schemaNames) {
2774
2806
  const ok = Object.entries(operation.responses ?? {}).find(([status]) => status.startsWith("2"));
2775
2807
  if (!ok) return { dataT: "void" };
2776
2808
  const info = responseInfo(ok[1]);
2777
2809
  if (info.ref) {
2778
- const ident = `${pascalCase(info.ref)}Schema`;
2810
+ const ident = schemaNames?.get(info.ref) ?? `${pascalCase(info.ref)}Schema`;
2779
2811
  return {
2780
2812
  dataT: `Static<typeof ${ident}>`,
2781
2813
  importName: ident
@@ -2820,19 +2852,29 @@ function edenTarget(fullPath, method, operation, client) {
2820
2852
  }
2821
2853
  /** The origin the client module exports beside the client, which a `fetch` fallback's URL starts at. */
2822
2854
  const ORIGIN = "clientOrigin";
2823
- function fetchTarget(fullPath, method, operation) {
2855
+ /** The JSON reviver a `fetch` fallback parses its response with, written into the hooks file. */
2856
+ const REVIVER = "reviveDate";
2857
+ const REVIVER_CODE = String.raw`const ISO8601=/(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))/u
2858
+
2859
+ const FORMAL_DATE=/(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)\s(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s\d{2}\s\d{4}\s\d{2}:\d{2}:\d{2}\sGMT(?:\+|-)\d{4}\s\([^)]+\)/u
2860
+
2861
+ const SHORTENED_DATE=/^(?:(?:(?:(?:0?[1-9]|[12][0-9]|3[01])[/\s-](?:0?[1-9]|1[0-2])[/\s-](?:19|20)\d{2})|(?:(?:19|20)\d{2}[/\s-](?:0?[1-9]|1[0-2])[/\s-](?:0?[1-9]|[12][0-9]|3[01]))))(?:\s(?:1[012]|0?[1-9]):[0-5][0-9](?::[0-5][0-9])?(?:\s[AP]M)?)?$/u
2862
+
2863
+ function ${REVIVER}(_key:string,value:unknown){if(typeof value!=='string')return value;const text=value.replace(/"/gu,'');if(!ISO8601.test(text)&&!FORMAL_DATE.test(text)&&!SHORTENED_DATE.test(text))return value;const date=new Date(text);return Number.isNaN(date.getTime())?value:date}`;
2864
+ function fetchTarget(fullPath, method, operation, schemaNames) {
2824
2865
  const names = pathParamNames(fullPath);
2825
2866
  const params = names.map((_, index) => index === 0 ? "params" : `params${index + 1}`);
2826
2867
  const hasQuery = (operation.parameters ?? []).some((p) => "in" in p && p.in === "query");
2827
2868
  const optionsType = hasQuery ? "{ headers?: Record<string, string>; query?: Record<string, unknown> }" : "{ headers?: Record<string, string> }";
2828
2869
  const withBody = isBodyMethod(method);
2829
- const { dataT, importName } = successType(operation);
2870
+ const { dataT, importName } = successType(operation, schemaNames);
2830
2871
  const url = (exprs) => {
2831
2872
  const inner = fullPath.replaceAll(/\{([^}]+)\}/gu, (_, n) => {
2832
2873
  const index = names.indexOf(n);
2833
2874
  return `\${encodeURIComponent(${exprs[index] ?? params[index]})}`;
2834
2875
  });
2835
- return hasQuery ? `\`\${${ORIGIN}}${inner}\${search.size ? \`?\${search}\` : ''}\`` : `\`\${${ORIGIN}}${inner}\``;
2876
+ const separator = inner.includes("?") ? "&" : "?";
2877
+ return hasQuery ? `\`\${${ORIGIN}}${inner}\${search.size ? \`${separator}\${search}\` : ''}\`` : `\`\${${ORIGIN}}${inner}\``;
2836
2878
  };
2837
2879
  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))}}` : "";
2838
2880
  return {
@@ -2848,8 +2890,8 @@ function fetchTarget(fullPath, method, operation) {
2848
2890
  errorT: "unknown",
2849
2891
  ...withBody ? { bodyType: "unknown" } : {},
2850
2892
  bodyRequired: false,
2851
- queryBody: (exprs, options, signal) => `${search(options)}const res=await fetch(${url(exprs)},{headers:${options}?.headers${signal ? ",signal" : ""}});if(!res.ok)throw await res.json();return JSON.parse(await res.text())`,
2852
- mutationBody: (exprs, body, options) => `${search(options)}const res=await fetch(${url(exprs)},{method:'${method.toUpperCase()}',headers:{'content-type':'application/json',...${options}?.headers},body:${body}===undefined?undefined:JSON.stringify(${body})});if(!res.ok)throw await res.json();return JSON.parse(await res.text())`,
2893
+ queryBody: (exprs, options, signal) => `${search(options)}const res=await fetch(${url(exprs)},{headers:${options}?.headers${signal ? ",signal" : ""}});if(!res.ok)throw await res.json();return JSON.parse(await res.text(),${REVIVER})`,
2894
+ mutationBody: (exprs, body, options) => `${search(options)}const res=await fetch(${url(exprs)},{method:'${method.toUpperCase()}',headers:{'content-type':'application/json',...${options}?.headers},body:${body}===undefined?undefined:JSON.stringify(${body})});if(!res.ok)throw await res.json();return JSON.parse(await res.text(),${REVIVER})`,
2853
2895
  ...importName ? { fetchType: importName } : {},
2854
2896
  usesFetch: true
2855
2897
  };
@@ -3139,8 +3181,8 @@ function swrMutationCode(config, method, pathStr, target, prefix, fullPath) {
3139
3181
  return [keyCode, `export function ${hookName}<TError = ${target.errorT}>(${sig.join(", ")}){const{mutation:mutationOptions}=options??{};const{swrKey:customKey,...restMutationOptions}=mutationOptions??{};const swrKey=customKey??${keyName}();return{swrKey,...useSWRMutation<${target.dataT},TError,Key,${variables}>(swrKey,async(_key:Key,{arg}:{arg:${variables}})=>{${target.mutationBody(PLAIN.paramRead(target), bodyExpr, "arg.options")}},restMutationOptions)}}`];
3140
3182
  }
3141
3183
  /** Every hook and helper of one operation, in the order they are written. */
3142
- function operationCode(config, pathStr, fullPath, method, operation, client) {
3143
- const target = needsFetchHook(fullPath) ? fetchTarget(fullPath, method, operation) : edenTarget(fullPath, method, operation, client);
3184
+ function operationCode(config, pathStr, fullPath, method, operation, client, schemaNames) {
3185
+ const target = needsFetchHook(fullPath) ? fetchTarget(fullPath, method, operation, schemaNames) : edenTarget(fullPath, method, operation, client);
3144
3186
  const prefix = resourcePrefix(fullPath);
3145
3187
  const isQuery = method === "get" || method === "head";
3146
3188
  const paginated = isQuery && operation["x-pagination"] === true;
@@ -3201,18 +3243,23 @@ function headerCode(config, client, importPath, body, fetchTypes, schemasImport,
3201
3243
  lines.push(`import { ${clientImports.join(", ")} } from '${importPath}'`);
3202
3244
  return `${lines.join("\n")}\n\n`;
3203
3245
  }
3204
- function makeQueryHooks(openAPI, output, importPath, config, client, basePath, schemasImport = "./components/schemas") {
3246
+ function makeQueryHooks(openAPI, output, importPath, config, client, basePath, schemasImport = "./components/schemas", schemaNames) {
3205
3247
  return Effect.gen(function* () {
3206
3248
  const prefix = basePath && basePath !== "/" ? basePath : "";
3207
3249
  const operations = Object.entries(openAPI.paths ?? {}).flatMap(([pathStr, pathItem]) => pathItem ? HTTP_METHODS.flatMap((method) => {
3208
3250
  const rawOperation = pathItem[method];
3209
3251
  if (!rawOperation) return [];
3210
3252
  const operation = resolveOperation(rawOperation, openAPI.components);
3211
- return [operationCode(config, pathStr, `${prefix}${pathStr}`, method, operation, client)];
3253
+ return [operationCode(config, pathStr, `${prefix}${pathStr}`, method, operation, client, schemaNames)];
3212
3254
  }) : []);
3213
3255
  if (operations.length === 0) return "No operations found";
3214
- const body = `${[...makePrefixKeyCodes(openAPI, prefix), ...operations.map((op) => op.code)].join("\n\n")}\n`;
3215
- yield* emit(`${headerCode(config, client, importPath, body, [...new Set(filterDefined(operations.map((op) => op.fetchType)))].toSorted(), schemasImport, operations.some((op) => op.usesFetch))}${body}`, path.dirname(output), output);
3256
+ const usesFetch = operations.some((op) => op.usesFetch);
3257
+ const body = `${[
3258
+ ...usesFetch ? [REVIVER_CODE] : [],
3259
+ ...makePrefixKeyCodes(openAPI, prefix),
3260
+ ...operations.map((op) => op.code)
3261
+ ].join("\n\n")}\n`;
3262
+ yield* emit(`${headerCode(config, client, importPath, body, [...new Set(filterDefined(operations.map((op) => op.fetchType)))].toSorted(), schemasImport, usesFetch)}${body}`, path.dirname(output), output);
3216
3263
  return `Generated ${config.label} code written to ${output}`;
3217
3264
  });
3218
3265
  }
@@ -3328,14 +3375,15 @@ const HOOK_CONFIGS = {
3328
3375
  * `schemas` is where `components.schemas` is written: a hook for a path Eden cannot type (a
3329
3376
  * segment with a `.` or a partial parameter) falls back to `fetch` and types its data by the
3330
3377
  * component the response names, so it has to import that component from wherever the schemas
3331
- * generator put it — by the specifier the config names, or relative to `output`.
3378
+ * generator put it — by the specifier the config names, or relative to `output` — under the name
3379
+ * that generator gave it, which is not the key's own when two keys differ only in case.
3332
3380
  */
3333
3381
  function hooks(openAPI, output, importPath, library, options) {
3334
3382
  const schemasImport = options.schemas?.import ?? (options.schemas ? makeModuleSpec(path.resolve(process.cwd(), output), {
3335
3383
  output: path.resolve(process.cwd(), options.schemas.output),
3336
3384
  split: options.schemas.split
3337
3385
  }) : void 0);
3338
- return makeQueryHooks(openAPI, output, importPath, HOOK_CONFIGS[library], options.client, options.basePath, schemasImport);
3386
+ return makeQueryHooks(openAPI, output, importPath, HOOK_CONFIGS[library], options.client, options.basePath, schemasImport, schemaConstNames(openAPI.components?.schemas, options.schemas?.split));
3339
3387
  }
3340
3388
  // src/helper/faker.ts
3341
3389
  function hasNumericConstraint(schema) {
@@ -3982,7 +4030,7 @@ function makeMock(spec, options = {}) {
3982
4030
  };
3983
4031
  const components = spec.components;
3984
4032
  const routes = Object.entries(spec.paths ?? {}).flatMap(([path, pathItem]) => {
3985
- if (!pathItem) return [];
4033
+ if (!pathItem || !isElysiaRoutePath(path)) return [];
3986
4034
  return HTTP_METHODS.flatMap((method) => {
3987
4035
  const operation = pathItem[method];
3988
4036
  if (!operation) return [];
@@ -4219,7 +4267,7 @@ function makeRoutes(openAPI, prefix) {
4219
4267
  const out = [];
4220
4268
  const prefixKeys = prefix && prefix !== "/" ? pathToKeys(prefix) : [];
4221
4269
  for (const [pathStr, pathItem] of Object.entries(openAPI.paths ?? {})) {
4222
- if (!pathItem) continue;
4270
+ if (!pathItem || !isElysiaRoutePath(pathStr)) continue;
4223
4271
  const keys = [...prefixKeys, ...pathToKeys(pathStr)];
4224
4272
  for (const method of HTTP_METHODS) {
4225
4273
  const operation = pathItem[method];
@@ -4271,8 +4319,8 @@ function collectRefs(openAPI) {
4271
4319
  }
4272
4320
  if ("schema" in p) enqueue(parameterSchema(p));
4273
4321
  };
4274
- for (const [, pathItem] of Object.entries(openAPI.paths ?? {})) {
4275
- if (!pathItem) continue;
4322
+ for (const [pathStr, pathItem] of Object.entries(openAPI.paths ?? {})) {
4323
+ if (!pathItem || !isElysiaRoutePath(pathStr)) continue;
4276
4324
  for (const method of HTTP_METHODS) {
4277
4325
  const op = pathItem[method];
4278
4326
  if (!op) continue;
@@ -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-CQsoa7gV.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-BWuUl_dt.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.1",
3
+ "version": "0.5.3",
4
4
  "description": "Asphodelos is a code generator from OpenAPI to Elysia",
5
5
  "keywords": [
6
6
  "elysia",