asphodelos 0.5.2 → 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
 
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.2";
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-Ch_ArUGQ.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-Ch_ArUGQ.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));
@@ -2787,12 +2802,12 @@ function needsFetchHook(pathStr) {
2787
2802
  function pathParamNames(pathStr) {
2788
2803
  return [...pathStr.matchAll(/\{([^}]+)\}/gu)].map((m) => m[1] ?? "");
2789
2804
  }
2790
- function successType(operation) {
2805
+ function successType(operation, schemaNames) {
2791
2806
  const ok = Object.entries(operation.responses ?? {}).find(([status]) => status.startsWith("2"));
2792
2807
  if (!ok) return { dataT: "void" };
2793
2808
  const info = responseInfo(ok[1]);
2794
2809
  if (info.ref) {
2795
- const ident = `${pascalCase(info.ref)}Schema`;
2810
+ const ident = schemaNames?.get(info.ref) ?? `${pascalCase(info.ref)}Schema`;
2796
2811
  return {
2797
2812
  dataT: `Static<typeof ${ident}>`,
2798
2813
  importName: ident
@@ -2837,13 +2852,22 @@ function edenTarget(fullPath, method, operation, client) {
2837
2852
  }
2838
2853
  /** The origin the client module exports beside the client, which a `fetch` fallback's URL starts at. */
2839
2854
  const ORIGIN = "clientOrigin";
2840
- 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) {
2841
2865
  const names = pathParamNames(fullPath);
2842
2866
  const params = names.map((_, index) => index === 0 ? "params" : `params${index + 1}`);
2843
2867
  const hasQuery = (operation.parameters ?? []).some((p) => "in" in p && p.in === "query");
2844
2868
  const optionsType = hasQuery ? "{ headers?: Record<string, string>; query?: Record<string, unknown> }" : "{ headers?: Record<string, string> }";
2845
2869
  const withBody = isBodyMethod(method);
2846
- const { dataT, importName } = successType(operation);
2870
+ const { dataT, importName } = successType(operation, schemaNames);
2847
2871
  const url = (exprs) => {
2848
2872
  const inner = fullPath.replaceAll(/\{([^}]+)\}/gu, (_, n) => {
2849
2873
  const index = names.indexOf(n);
@@ -2866,8 +2890,8 @@ function fetchTarget(fullPath, method, operation) {
2866
2890
  errorT: "unknown",
2867
2891
  ...withBody ? { bodyType: "unknown" } : {},
2868
2892
  bodyRequired: false,
2869
- 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())`,
2870
- 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})`,
2871
2895
  ...importName ? { fetchType: importName } : {},
2872
2896
  usesFetch: true
2873
2897
  };
@@ -3157,8 +3181,8 @@ function swrMutationCode(config, method, pathStr, target, prefix, fullPath) {
3157
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)}}`];
3158
3182
  }
3159
3183
  /** Every hook and helper of one operation, in the order they are written. */
3160
- function operationCode(config, pathStr, fullPath, method, operation, client) {
3161
- 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);
3162
3186
  const prefix = resourcePrefix(fullPath);
3163
3187
  const isQuery = method === "get" || method === "head";
3164
3188
  const paginated = isQuery && operation["x-pagination"] === true;
@@ -3219,18 +3243,23 @@ function headerCode(config, client, importPath, body, fetchTypes, schemasImport,
3219
3243
  lines.push(`import { ${clientImports.join(", ")} } from '${importPath}'`);
3220
3244
  return `${lines.join("\n")}\n\n`;
3221
3245
  }
3222
- function makeQueryHooks(openAPI, output, importPath, config, client, basePath, schemasImport = "./components/schemas") {
3246
+ function makeQueryHooks(openAPI, output, importPath, config, client, basePath, schemasImport = "./components/schemas", schemaNames) {
3223
3247
  return Effect.gen(function* () {
3224
3248
  const prefix = basePath && basePath !== "/" ? basePath : "";
3225
3249
  const operations = Object.entries(openAPI.paths ?? {}).flatMap(([pathStr, pathItem]) => pathItem ? HTTP_METHODS.flatMap((method) => {
3226
3250
  const rawOperation = pathItem[method];
3227
3251
  if (!rawOperation) return [];
3228
3252
  const operation = resolveOperation(rawOperation, openAPI.components);
3229
- return [operationCode(config, pathStr, `${prefix}${pathStr}`, method, operation, client)];
3253
+ return [operationCode(config, pathStr, `${prefix}${pathStr}`, method, operation, client, schemaNames)];
3230
3254
  }) : []);
3231
3255
  if (operations.length === 0) return "No operations found";
3232
- const body = `${[...makePrefixKeyCodes(openAPI, prefix), ...operations.map((op) => op.code)].join("\n\n")}\n`;
3233
- 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);
3234
3263
  return `Generated ${config.label} code written to ${output}`;
3235
3264
  });
3236
3265
  }
@@ -3346,14 +3375,15 @@ const HOOK_CONFIGS = {
3346
3375
  * `schemas` is where `components.schemas` is written: a hook for a path Eden cannot type (a
3347
3376
  * segment with a `.` or a partial parameter) falls back to `fetch` and types its data by the
3348
3377
  * component the response names, so it has to import that component from wherever the schemas
3349
- * 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.
3350
3380
  */
3351
3381
  function hooks(openAPI, output, importPath, library, options) {
3352
3382
  const schemasImport = options.schemas?.import ?? (options.schemas ? makeModuleSpec(path.resolve(process.cwd(), output), {
3353
3383
  output: path.resolve(process.cwd(), options.schemas.output),
3354
3384
  split: options.schemas.split
3355
3385
  }) : void 0);
3356
- 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));
3357
3387
  }
3358
3388
  // src/helper/faker.ts
3359
3389
  function hasNumericConstraint(schema) {
@@ -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-Ch_ArUGQ.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.2",
3
+ "version": "0.5.3",
4
4
  "description": "Asphodelos is a code generator from OpenAPI to Elysia",
5
5
  "keywords": [
6
6
  "elysia",