hono-takibi 0.15.0 → 0.17.0

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
@@ -48,7 +48,7 @@ npx hono-takibi
48
48
  - [Configuration](https://hono-takibi.dev/docs/guides/config)
49
49
  - [Template](https://hono-takibi.dev/docs/guides/template)
50
50
  - [Client](https://hono-takibi.dev/docs/guides/client)
51
- - [Test & Mock](https://hono-takibi.dev/docs/guides/test-mock)
51
+ - [Mock](https://hono-takibi.dev/docs/guides/mock)
52
52
  - [API Docs](https://hono-takibi.dev/docs/guides/api-docs)
53
53
  - [Vendor Extensions](https://hono-takibi.dev/docs/guides/vendor)
54
54
  - [Vite Plugin](https://hono-takibi.dev/docs/guides/vite-plugin)
package/dist/cli.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
3
- import * as NodeServices from "@effect/platform-node/NodeServices";
4
- import { Console, Effect, FileSystem, Option, Ref, Result, Runtime, Schema, Stream } from "effect";
5
- import path from "node:path";
6
- import { fileURLToPath } from "node:url";
7
- import { Argument, CliError, CliOutput, Command, Flag } from "effect/unstable/cli";
2
+ import { NodeRuntime, NodeServices } from "@effect/platform-node";
3
+ import { Console, Effect, FileSystem, Option, Path, Ref, Schema, Stream } from "effect";
4
+ import { Argument, CliError, Command, Flag } from "effect/unstable/cli";
5
+ //#region package.json
6
+ var version = "0.17.0";
7
+ var description = "Hono Takibi is a code generator from OpenAPI to @hono/zod-openapi";
8
+ //#endregion
8
9
  //#region src/cli/index.ts
9
10
  const COMMAND_NAME = "hono-takibi";
10
- /** Config file `hono-takibi` picks up from the working directory when `--config` is omitted. */
11
11
  const DEFAULT_CONFIG_FILE = "hono-takibi.config.ts";
12
12
  const DocumentPathSchema = Schema.String.pipe(Schema.refine(Schema.is(Schema.TemplateLiteral([Schema.String, Schema.Literals([
13
13
  ".yaml",
@@ -27,127 +27,173 @@ const TypeScriptPathSchema = Schema.String.pipe(Schema.refine(Schema.is(Schema.T
27
27
  description: "TypeScript file the one-shot mode writes the generated routes to.",
28
28
  examples: ["./src/routes.ts", "src/api/routes.ts"]
29
29
  });
30
- /**
31
- * The command line itself: what `hono-takibi` accepts, what each piece means, and the
32
- * schema every value is decoded through before {@link generate} ever sees it.
33
- */
34
30
  const commandLine = {
35
31
  input: Argument.File("input", { mustExist: true }).pipe(Argument.withSchema(DocumentPathSchema), Argument.withDescription("OpenAPI (.yaml, .json) or TypeSpec (.tsp) document to generate from"), Argument.withMetavar("input.{yaml,json,tsp}"), Argument.optional),
36
32
  output: Flag.String("output").pipe(Flag.withAlias("o"), Flag.withSchema(TypeScriptPathSchema), Flag.withDescription("TypeScript file the generated routes are written to"), Flag.withMetavar("output.ts"), Flag.optional),
37
33
  config: Flag.File("config", { mustExist: true }).pipe(Flag.withAlias("c"), Flag.withDescription(`Config file to run (default: ./${DEFAULT_CONFIG_FILE})`), Flag.withMetavar("file"), Flag.optional),
38
34
  watch: Flag.Boolean("watch").pipe(Flag.withAlias("w"), Flag.withDescription("Rerun the config on every change to its documents or itself"), Flag.withDefault(false))
39
35
  };
40
- /** Extensions a change has to carry to be worth regenerating for. */
41
36
  const INPUT_EXTENSIONS = [
42
37
  ".yaml",
43
38
  ".json",
44
39
  ".tsp"
45
40
  ];
46
- /**
47
- * One pass over a config file: read it, parse the document it names, and run every
48
- * generator it opts into.
49
- *
50
- * `reload` is for the passes after the first, where the config file may have been edited
51
- * since it was imported.
52
- *
53
- * The generator pipeline pulls in the OpenAPI parser, the TypeSpec compiler and ts-morph.
54
- * `--help`, `--version`, `--completions` and every rejected command line must not pay for
55
- * that, so it is loaded here rather than at module scope. After the first pass the loader
56
- * answers from cache, so a watch tick pays nothing.
57
- */
58
- function runConfigPass(configPath, reload) {
41
+ function loadConfig(configPath, reload) {
59
42
  return Effect.gen(function* () {
60
- const [{ readConfig }, { parseOpenAPI }, { FormatOptions }, { cleanSplitOutputs, makeJob }] = yield* Effect.promise(() => Promise.all([
61
- import("./index.js"),
43
+ const { readConfig } = yield* Effect.promise(() => import("./index.js"));
44
+ return yield* readConfig(configPath, reload);
45
+ });
46
+ }
47
+ function runJobs(config) {
48
+ return Effect.gen(function* () {
49
+ const [{ parseOpenAPI }, { FormatOptions }, { cleanSplitOutputs, makeJob }] = yield* Effect.promise(() => Promise.all([
62
50
  import("./openapi-DQRxq2_O.js").then((n) => n.t),
63
- import("./format-Bm9LZ_ki.js").then((n) => n.r),
64
- import("./shared-DVLeJFoN.js").then((n) => n.i)
51
+ import("./format-CuHABcKC.js").then((n) => n.r),
52
+ import("./shared-CU8tD0KG.js").then((n) => n.i)
65
53
  ]));
66
- const config = yield* readConfig(configPath, reload);
67
54
  const jobs = makeJob(yield* parseOpenAPI(config.input), config);
68
55
  yield* cleanSplitOutputs(jobs.filter((job) => job.split).map((job) => job.output));
56
+ return (yield* Effect.forEach(jobs, (job) => job.run(job.output), { concurrency: "unbounded" }).pipe(Effect.provideService(FormatOptions, config.format ?? {}))).filter((message) => message !== "").join("\n");
57
+ });
58
+ }
59
+ function runConfigPass(configPath, reload) {
60
+ return Effect.gen(function* () {
61
+ const config = yield* loadConfig(configPath, reload);
69
62
  return {
70
63
  config,
71
- report: (yield* Effect.all(jobs.map((job) => job.run(job.output)), { concurrency: "unbounded" }).pipe(Effect.provideService(FormatOptions, config.format ?? {}))).filter((message) => message !== "").join("\n")
64
+ report: yield* runJobs(config)
72
65
  };
73
66
  });
74
67
  }
68
+ function isSameTarget(left, right) {
69
+ return left?.inputDirectory === right?.inputDirectory && left?.outside.join("\n") === right?.outside.join("\n");
70
+ }
75
71
  /**
76
- * A pass whose failure is printed rather than raised, so the watch loop survives it, and
77
- * which answers with the input directory the config now names.
72
+ * Generates from a config that was read, and answers what to watch for its documents.
73
+ *
74
+ * The directory comes from the config alone, so a pass that fails here — a document
75
+ * that does not parse, say — still names it. Otherwise the very edit that fixes the
76
+ * document would never be seen.
78
77
  *
79
- * `undefined` means the pass did not get far enough to say — the config is missing, will
80
- * not import, or does not validate. The loop keeps watching the config either way.
78
+ * The files outside the directory come from the document, and a broken document cannot
79
+ * list them. `previous` is what stands in then: the fix may well belong in one of the
80
+ * files the last readable version pointed at.
81
81
  */
82
- function reportConfigPass(configPath, reload) {
82
+ function reportJobs(config, previous) {
83
83
  return Effect.gen(function* () {
84
- const result = yield* Effect.result(runConfigPass(configPath, reload));
85
- if (Result.isFailure(result)) {
86
- yield* Console.error(`❌ ${result.failure.message}`);
87
- return;
88
- }
89
- yield* Console.log(result.success.report);
90
- return path.dirname(path.resolve(process.cwd(), result.success.config.input));
84
+ const path = yield* Path.Path;
85
+ yield* runJobs(config).pipe(Effect.matchEffect({
86
+ onFailure: (error) => Console.error(`❌ ${error.message}`),
87
+ onSuccess: (report) => Console.log(report)
88
+ }));
89
+ const { outsideSources } = yield* Effect.promise(() => import("./shared-CU8tD0KG.js").then((n) => n.i));
90
+ const inputDirectory = path.dirname(path.resolve(config.input));
91
+ return {
92
+ inputDirectory,
93
+ outside: yield* outsideSources(config.input).pipe(Effect.orElseSucceed(() => previous?.inputDirectory === inputDirectory ? previous.outside : []))
94
+ };
91
95
  });
92
96
  }
93
97
  /**
94
- * Watches the config, and the input documents when a pass has said where they are, until
95
- * the answer changes — then hands the new directory back so {@link watchConfig} restarts.
98
+ * Runs one pass and answers what to watch for the documents.
96
99
  *
97
- * `runForEachWhile` is what ends the round: a pass that reports a different directory
98
- * returns `false`, and the directory it reported is in the `Ref` for the caller. The
99
- * `Ref` is what carries a value out of a stream that otherwise only returns `void`.
100
+ * Two separate things happen to the document here. `runJobs` generates from it, reading
101
+ * it the way every other mode does. `outsideSources` then only asks which files it was
102
+ * read from, so that an edit to any of them brings the session back to this function;
103
+ * what it answers never reaches a generator.
104
+ *
105
+ * The answer is `undefined` only when the config itself could not be read.
100
106
  */
101
- function watchRound(configPath, inputDirectory) {
107
+ function reportConfigPass(configPath, reload, previous) {
108
+ return loadConfig(configPath, reload).pipe(Effect.matchEffect({
109
+ onFailure: (error) => Console.error(`❌ ${error.message}`).pipe(Effect.as(void 0)),
110
+ onSuccess: (config) => reportJobs(config, previous)
111
+ }));
112
+ }
113
+ /**
114
+ * `directory`, or the closest directory above it that exists.
115
+ *
116
+ * A directory that is not there cannot be watched, but the one it will appear in can.
117
+ */
118
+ function nearestExisting(directory) {
102
119
  return Effect.gen(function* () {
103
120
  const fs = yield* FileSystem.FileSystem;
104
- const configFile = path.basename(configPath);
105
- const nextDirectory = yield* Ref.make(inputDirectory);
106
- const configEvents = fs.watch(path.dirname(configPath)).pipe(Stream.filter((event) => event.path === configFile));
107
- yield* (inputDirectory === void 0 ? configEvents : Stream.merge(fs.watch(inputDirectory, { recursive: true }).pipe(Stream.filter((event) => INPUT_EXTENSIONS.some((extension) => event.path.endsWith(extension)))), configEvents)).pipe(Stream.debounce("200 millis"), Stream.runForEachWhile(() => reportConfigPass(configPath, true).pipe(Effect.tap((directory) => Ref.set(nextDirectory, directory ?? inputDirectory)), Effect.map((directory) => directory === void 0 || directory === inputDirectory))));
108
- return yield* Ref.get(nextDirectory);
121
+ const path = yield* Path.Path;
122
+ const exists = yield* fs.exists(directory).pipe(Effect.orElseSucceed(() => false));
123
+ const parent = path.dirname(directory);
124
+ return exists || parent === directory ? directory : yield* nearestExisting(parent);
109
125
  });
110
126
  }
111
127
  /**
112
- * Regenerates on every change to the input documents or the config, until interrupted.
113
- *
114
- * Two watchers, because two things can invalidate the output. The input document's
115
- * directory is watched recursively — a TypeSpec entry imports its siblings and a `$ref`
116
- * can point at one, so the file named by `input` is rarely the only one that matters. The
117
- * config file is watched through its directory rather than directly, so an editor that
118
- * saves by renaming does not take the watcher down with it.
119
- *
120
- * `WatchEvent.path` is relative to the directory it came from, which is why each stream
121
- * is filtered before the merge rather than after.
122
- *
123
- * `debounce` collapses the burst an editor emits on save into one pass — a plain write
124
- * already reports twice. Generated files are `.ts` and `.md`, so a pass cannot trigger
125
- * the next one.
126
- *
127
- * `inputDirectory` is `undefined` until a pass has read a config far enough to name one;
128
- * only the config is watched until then, which is what keeps a config that does not
129
- * validate at startup from ending the command the caller asked to keep running.
128
+ * One pass inside a round; answers whether the round's watchers are still the right ones.
130
129
  */
131
- function watchConfig(configPath, inputDirectory) {
130
+ function watchPass(configPath, target, watched, nextTarget) {
132
131
  return Effect.gen(function* () {
133
- yield* Console.log(inputDirectory === void 0 ? `\n👀 Watching ${configPath} — Ctrl-C to stop` : `\n👀 Watching ${inputDirectory} and ${configPath} — Ctrl-C to stop`);
134
- return yield* watchConfig(configPath, yield* watchRound(configPath, inputDirectory));
132
+ const next = (yield* reportConfigPass(configPath, true, target)) ?? target;
133
+ yield* Ref.set(nextTarget, next);
134
+ if (!isSameTarget(next, target)) return false;
135
+ return next === void 0 || (yield* nearestExisting(next.inputDirectory)) === watched;
135
136
  });
136
137
  }
137
138
  /**
138
- * Everything the command does once the command line has parsed.
139
+ * The edits to the files a document reads from outside its own directory.
139
140
  *
140
- * It resolves to one of two modes and nothing else: an `<input>` with an `-o` writes a
141
- * single routes file, and anything else runs a config file — which is what opts in the
142
- * routes, components, webhooks, types, mock, docs, test and tanstack-query generators.
143
- * `--config` and `<input>` are mutually exclusive, and each of `<input>` / `--output` is
144
- * meaningless without the other.
141
+ * Each one is watched through the directory it sits in, which is how an editor's
142
+ * write-then-rename save is still seen. A directory that is not there is skipped rather
143
+ * than failed on: the pass that follows reports the missing file in its own words.
144
+ */
145
+ function outsideEvents(outside) {
146
+ return Effect.gen(function* () {
147
+ const fs = yield* FileSystem.FileSystem;
148
+ const path = yield* Path.Path;
149
+ const directories = [...new Set(outside.map((file) => path.dirname(file)))];
150
+ const present = yield* Effect.forEach(directories, (directory) => fs.exists(directory).pipe(Effect.orElseSucceed(() => false)), { concurrency: "unbounded" });
151
+ return directories.filter((_, index) => present[index]).map((directory) => fs.watch(directory).pipe(Stream.filter((event) => outside.includes(path.join(directory, event.path)))));
152
+ });
153
+ }
154
+ /**
155
+ * Watches until what has to be watched changes, and answers the next target.
145
156
  *
146
- * Everything past the guard clauses fails with something carrying a `message`, so the
147
- * single `mapError` at the end is where all of it turns into rendered CLI output. The
148
- * `FileSystem` the generators write through comes from the environment the caller
149
- * provides.
157
+ * `watched` is where the watcher for the input directory actually sits. It is that
158
+ * directory while it exists; once it is removed — or before it is created — it is the
159
+ * closest directory above, and the only event that matters there is the missing path
160
+ * coming into being. A watcher left on a removed directory reports nothing, even after
161
+ * the directory is back, so the round ends whenever `watched` stops being the right place.
150
162
  */
163
+ function watchRound(configPath, target, watched) {
164
+ return Effect.gen(function* () {
165
+ const fs = yield* FileSystem.FileSystem;
166
+ const path = yield* Path.Path;
167
+ const configFile = path.basename(configPath);
168
+ const nextTarget = yield* Ref.make(target);
169
+ const configEvents = fs.watch(path.dirname(configPath)).pipe(Stream.filter((event) => event.path === configFile));
170
+ const inputEvents = target === void 0 || watched === void 0 ? [] : [watched === target.inputDirectory ? fs.watch(target.inputDirectory, { recursive: true }).pipe(Stream.filter((event) => INPUT_EXTENSIONS.some((extension) => event.path.endsWith(extension)))) : fs.watch(watched).pipe(Stream.filter((event) => event.path === path.relative(watched, target.inputDirectory).split(path.sep)[0]))];
171
+ yield* Stream.mergeAll([
172
+ configEvents,
173
+ ...inputEvents,
174
+ ...yield* outsideEvents(target?.outside ?? [])
175
+ ], { concurrency: "unbounded" }).pipe(Stream.debounce("200 millis"), Stream.runForEachWhile(() => watchPass(configPath, target, watched, nextTarget)));
176
+ return yield* Ref.get(nextTarget);
177
+ });
178
+ }
179
+ /**
180
+ * Announces what a round watches, runs it, and leaves the next target in `current`.
181
+ */
182
+ function watchCycle(configPath, current) {
183
+ return Effect.gen(function* () {
184
+ const target = yield* Ref.get(current);
185
+ const watched = target === void 0 ? void 0 : yield* nearestExisting(target.inputDirectory);
186
+ const documents = [target?.inputDirectory, ...target?.outside ?? []].filter((entry) => entry !== void 0).join(", ");
187
+ yield* Console.log(target === void 0 ? `\n👀 Watching ${configPath} — Ctrl-C to stop` : watched === target.inputDirectory ? `\n👀 Watching ${documents} and ${configPath} — Ctrl-C to stop` : `\n👀 Watching ${configPath}, waiting for ${target.inputDirectory} — Ctrl-C to stop`);
188
+ yield* Ref.set(current, yield* watchRound(configPath, target, watched));
189
+ });
190
+ }
191
+ function watchConfig(configPath, target) {
192
+ return Effect.gen(function* () {
193
+ const current = yield* Ref.make(target);
194
+ return yield* Effect.forever(watchCycle(configPath, current));
195
+ });
196
+ }
151
197
  function generate(args) {
152
198
  return Effect.gen(function* () {
153
199
  const input = Option.getOrUndefined(args.input);
@@ -167,32 +213,25 @@ function generate(args) {
167
213
  })]
168
214
  });
169
215
  if (input !== void 0 && output !== void 0) {
170
- const [{ parseOpenAPI }, { takibi }] = yield* Effect.promise(() => Promise.all([import("./openapi-DQRxq2_O.js").then((n) => n.t), import("./core-BIzYFvM2.js").then((n) => n.t)]));
216
+ const [{ parseOpenAPI }, { takibi }] = yield* Effect.promise(() => Promise.all([import("./openapi-DQRxq2_O.js").then((n) => n.t), import("./core-B31BC8gp.js").then((n) => n.t)]));
171
217
  return yield* Console.log(yield* takibi(yield* parseOpenAPI(input), output));
172
218
  }
173
219
  const resolvedConfig = configPath ?? DEFAULT_CONFIG_FILE;
174
- if (args.watch) return yield* watchConfig(resolvedConfig, yield* reportConfigPass(resolvedConfig, false));
175
- const first = yield* runConfigPass(resolvedConfig, false).pipe(Effect.mapError((error) => configPath === void 0 && error._tag === "ConfigError" && error.notFound === true ? new CliError.ShowHelp({
220
+ if (args.watch) return yield* watchConfig(resolvedConfig, yield* reportConfigPass(resolvedConfig, false, void 0));
221
+ const first = yield* runConfigPass(resolvedConfig, false).pipe(Effect.catchTag("ConfigError", (error) => Effect.fail(configPath === void 0 && error.notFound === true ? new CliError.ShowHelp({
176
222
  commandPath: [COMMAND_NAME],
177
223
  errors: [new CliError.UserError({
178
224
  cause: error,
179
225
  userMessage: error.message
180
226
  })]
181
- }) : error));
227
+ }) : error)));
182
228
  yield* Console.log(first.report);
183
229
  }).pipe(Effect.mapError((error) => CliError.isCliError(error) ? error : new CliError.UserError({
184
230
  cause: error,
185
231
  userMessage: error.message
186
232
  })));
187
233
  }
188
- /**
189
- * The `hono-takibi` command: parsing, validation, `--help`, `--version` and shell
190
- * completions are owned by `effect/unstable/cli`, {@link generate} is the rest.
191
- *
192
- * `description` is the manifest's, so the sentence `--help` prints and the one npm shows
193
- * cannot drift apart — {@link honoTakibi} is already reading that file for `--version`.
194
- */
195
- function makeCli(description) {
234
+ function makeCli() {
196
235
  return Command.make(COMMAND_NAME, commandLine, generate).pipe(Command.withDescription(description), Command.withExamples([
197
236
  {
198
237
  command: "hono-takibi openapi.yaml -o src/routes.ts",
@@ -212,69 +251,11 @@ function makeCli(description) {
212
251
  }
213
252
  ]));
214
253
  }
215
- /**
216
- * The manifest could not be read: the `package.json` beside the entry is missing, is not
217
- * JSON, or carries no `version` / `description`. That is a broken install, not anything
218
- * the caller typed.
219
- *
220
- * `Command.runWith` renders the errors raised inside the command, but this one is raised
221
- * before it runs. So it is rendered here through the same formatter — the `ERROR` block
222
- * every other failure prints — and marked as already reported, so `runMain` does not
223
- * print it a second time in its own shape.
224
- */
225
- function reportBrokenInstall(cause) {
226
- return Effect.gen(function* () {
227
- const error = new CliError.UserError({
228
- cause,
229
- userMessage: `Cannot read the version and description from package.json: ${cause.message}`
230
- });
231
- error[Runtime.errorReported] = false;
232
- const formatter = yield* CliOutput.Formatter;
233
- yield* Console.error(formatter.formatError(error));
234
- return yield* error;
235
- });
236
- }
237
- /**
238
- * Runs `hono-takibi` against an argument list.
239
- *
240
- * `entryUrl` is the `import.meta.url` of the executable, and both `--version` and the
241
- * description `--help` prints are read from the `package.json` beside it. The entry has
242
- * to supply that URL: it is the only module whose
243
- * depth is the same in source and in the bundle (`src/index.ts` and the `dist/cli.js` it
244
- * is packed into both sit one directory below the manifest), so a relative URL written
245
- * anywhere else resolves to two different files.
246
- *
247
- * A manifest that is missing or malformed is a broken install, so it fails rather than
248
- * reporting a placeholder version — but through the error channel, which prints a
249
- * sentence instead of an unhandled `SchemaError` and its whole AST. One `Schema.Struct`
250
- * is what says which fields have to be there for the command to describe itself.
251
- */
252
- function honoTakibi(argv, entryUrl) {
253
- return Effect.gen(function* () {
254
- const manifestPath = fileURLToPath(new URL("../package.json", entryUrl));
255
- const source = yield* (yield* FileSystem.FileSystem).readFileString(manifestPath);
256
- const manifest = yield* Effect.try({
257
- try: () => JSON.parse(source),
258
- catch: (cause) => new Error(`${manifestPath} is not valid JSON`, { cause })
259
- });
260
- const { version, description } = yield* Schema.decodeUnknownEffect(Schema.Struct({
261
- version: Schema.String.annotate({
262
- description: "What `--version` prints.",
263
- examples: ["1.2.3"]
264
- }),
265
- description: Schema.String.annotate({
266
- description: "The sentence `--help` prints under DESCRIPTION.",
267
- examples: ["Hono Takibi is a code generator from OpenAPI to @hono/zod-openapi"]
268
- })
269
- }).annotate({
270
- title: "Package manifest",
271
- description: "The fields `hono-takibi` reads from the package.json beside its entry."
272
- }))(manifest);
273
- return yield* Command.runWith(makeCli(description), { version })(argv);
274
- }).pipe(Effect.catchIf((error) => !CliError.isCliError(error), reportBrokenInstall));
254
+ function honoTakibi() {
255
+ return Command.run(makeCli(), { version });
275
256
  }
276
257
  //#endregion
277
258
  //#region src/index.ts
278
- NodeRuntime.runMain(honoTakibi(process.argv.slice(2), import.meta.url).pipe(Effect.provide(NodeServices.layer)));
259
+ NodeRuntime.runMain(honoTakibi().pipe(Effect.provide(NodeServices.layer)));
279
260
  //#endregion
280
261
  export {};
@@ -1,2 +1,2 @@
1
- import { t as docs } from "../../docs-Bo4-6xBy.js";
1
+ import { t as docs } from "../../docs-BxfKU8TG.js";
2
2
  export { docs };
@@ -1,6 +1,6 @@
1
1
  import { t as OpenAPI } from "../../index-tsPqeV6H.js";
2
- import { t as FormatError } from "../../index-wD0wV6VQ.js";
3
- import { t as GenerateError } from "../../index-6-_xlYFY.js";
2
+ import { n as GenerateError, t as FormatError } from "../../index-D_gf3Xzx.js";
3
+ import { t as Grouping } from "../../index-DKui1bHG.js";
4
4
  //#region src/core/hooks/index.d.ts
5
5
  declare const HOOK_CONFIGS: {
6
6
  readonly swr: {
@@ -164,5 +164,7 @@ declare const HOOK_CONFIGS: {
164
164
  export type HookLibrary = keyof typeof HOOK_CONFIGS;
165
165
  export declare function hooks(openAPI: OpenAPI, output: string, importPath: string, library: HookLibrary, options?: {
166
166
  readonly clientName?: string;
167
+ readonly grouping?: Grouping;
168
+ readonly basePath?: string;
167
169
  }): import("effect/Effect").Effect<string, FormatError | GenerateError | import("effect/PlatformError").PlatformError, import("effect/FileSystem").FileSystem>;
168
170
  //#endregion
@@ -1,2 +1,2 @@
1
- import { t as hooks } from "../../hooks-kkOg8Baa.js";
1
+ import { t as hooks } from "../../hooks-sH69j0o0.js";
2
2
  export { hooks };
@@ -1,10 +1,10 @@
1
1
  import { t as OpenAPI } from "../../index-tsPqeV6H.js";
2
- import { t as FormatError } from "../../index-wD0wV6VQ.js";
3
- import { t as GenerateError } from "../../index-6-_xlYFY.js";
2
+ import { n as GenerateError, t as FormatError } from "../../index-D_gf3Xzx.js";
3
+ import { t as Grouping } from "../../index-DKui1bHG.js";
4
4
  import { Effect } from "effect";
5
5
  //#region src/core/rpc/index.d.ts
6
6
  /**
7
7
  * Generates RPC client wrapper functions from OpenAPI specification.
8
8
  */
9
- export declare function rpc(openAPI: OpenAPI, output: string, importPath: string, clientName?: string, useParseResponse?: boolean, basePath?: string, docs?: boolean): Effect.Effect<string, FormatError | GenerateError | import("effect/PlatformError").PlatformError, import("effect/FileSystem").FileSystem>;
9
+ export declare function rpc(openAPI: OpenAPI, output: string, importPath: string, clientName?: string, useParseResponse?: boolean, basePath?: string, docs?: boolean, grouping?: Grouping): Effect.Effect<string, FormatError | GenerateError | import("effect/PlatformError").PlatformError, import("effect/FileSystem").FileSystem>;
10
10
  //#endregion
@@ -1,6 +1,7 @@
1
- import { f as methodPath, j as isOperationLike, k as isOpenAPIPaths, l as makeInferRequestType, z as isRecord } from "../../utils-BtWoIX8v.js";
2
- import { t as emit } from "../../emit-B_3fXoto.js";
3
- import { a as parsePathItem, i as operationHasArgs, o as GenerateError, r as makeOperationDeps, t as formatPath } from "../../rpc-CQFRTmcC.js";
1
+ import { i as GenerateError } from "../../format-CuHABcKC.js";
2
+ import { A as isOperationLike, O as isOpenAPIPaths, R as isRecord, f as methodPath, l as makeInferRequestType } from "../../utils-BvdDxide.js";
3
+ import { t as emit } from "../../emit-CSV6od97.js";
4
+ import { a as parsePathItem, i as operationHasArgs, o as groupClientName, r as makeOperationDeps, t as formatPath } from "../../rpc-BvVFjspk.js";
4
5
  import { Effect } from "effect";
5
6
  import { dirname } from "node:path";
6
7
  //#region src/core/rpc/index.ts
@@ -19,9 +20,14 @@ function makeJsDoc(operation, method, path) {
19
20
  sections.push([`${method.toUpperCase()} ${path}`]);
20
21
  return `/**\n${sections.map((lines) => lines.join("\n")).join("\n\n").split("\n").map((line) => line ? ` * ${line}` : " *").join("\n")}\n */\n`;
21
22
  }
22
- function makeOperationCode(path, method, item, deps, useParseResponse, hasBasePath, docs) {
23
+ function makeOperationCode(path, method, item, base, useParseResponse, hasBasePath, docs, grouping) {
23
24
  const operation = item[method];
24
25
  if (!isOperationLike(operation)) return null;
26
+ const group = grouping?.(path, operationTags(operation));
27
+ const deps = group === void 0 ? base : {
28
+ ...base,
29
+ client: groupClientName(group)
30
+ };
25
31
  const funcName = methodPath(method, path);
26
32
  const pathResult = formatPath(path, hasBasePath);
27
33
  const hasArgs = operationHasArgs(item, operation, deps);
@@ -31,10 +37,15 @@ function makeOperationCode(path, method, item, deps, useParseResponse, hasBasePa
31
37
  const call = useParseResponse ? `parseResponse(${clientCall})` : clientCall;
32
38
  return {
33
39
  code: `${docs ? makeJsDoc(operation, method, path) : ""}export async function ${funcName}(${argSig}){return await ${call}}`,
34
- hasArgs
40
+ hasArgs,
41
+ client: deps.client
35
42
  };
36
43
  }
37
- function makeOperationCodes(paths, deps, useParseResponse, hasBasePath, docs) {
44
+ function operationTags(operation) {
45
+ const tags = "tags" in operation ? operation.tags : void 0;
46
+ return Array.isArray(tags) ? tags.filter((tag) => typeof tag === "string") : void 0;
47
+ }
48
+ function makeOperationCodes(paths, deps, useParseResponse, hasBasePath, docs, grouping) {
38
49
  return Object.entries(paths).filter((entry) => isRecord(entry[1])).flatMap(([p, rawItem]) => {
39
50
  const pathItem = parsePathItem(rawItem);
40
51
  return [
@@ -47,25 +58,27 @@ function makeOperationCodes(paths, deps, useParseResponse, hasBasePath, docs) {
47
58
  "patch",
48
59
  "trace",
49
60
  "query"
50
- ].map((method) => makeOperationCode(p, method, pathItem, deps, useParseResponse, hasBasePath, docs)).filter((item) => item !== null);
61
+ ].map((method) => makeOperationCode(p, method, pathItem, deps, useParseResponse, hasBasePath, docs, grouping)).filter((item) => item !== null);
51
62
  });
52
63
  }
53
- function makeHeader(importPath, needsInferRequestType, clientName, useParseResponse) {
54
- return `import type{${needsInferRequestType ? "InferRequestType,ClientRequestOptions" : "ClientRequestOptions"}}from'hono/client'\n${useParseResponse ? `import{parseResponse}from'hono/client'\n` : ""}import{${clientName}}from'${importPath}'\n\n`;
64
+ function makeHeader(importPath, needsInferRequestType, clientNames, useParseResponse) {
65
+ return `import type{${needsInferRequestType ? "InferRequestType,ClientRequestOptions" : "ClientRequestOptions"}}from'hono/client'\n${useParseResponse ? `import{parseResponse}from'hono/client'\n` : ""}import{${clientNames.join(",")}}from'${importPath}'\n\n`;
55
66
  }
56
67
  /**
57
68
  * Generates RPC client wrapper functions from OpenAPI specification.
58
69
  */
59
- function rpc(openAPI, output, importPath, clientName = "client", useParseResponse, basePath, docs) {
70
+ function rpc(openAPI, output, importPath, clientName = "client", useParseResponse, basePath, docs, grouping) {
60
71
  return Effect.gen(function* () {
61
72
  const paths = openAPI.paths;
62
73
  if (!isOpenAPIPaths(paths)) return yield* new GenerateError({ message: "Invalid OpenAPI paths" });
63
74
  const hasBasePath = basePath !== void 0 && basePath !== "/";
64
75
  const componentsParameters = openAPI.components?.parameters ?? {};
65
76
  const componentsRequestBodies = openAPI.components?.requestBodies ?? {};
66
- const operationCodes = makeOperationCodes(paths, makeOperationDeps(clientName, componentsParameters, componentsRequestBodies), useParseResponse, hasBasePath, docs);
77
+ const operationCodes = makeOperationCodes(paths, makeOperationDeps(clientName, componentsParameters, componentsRequestBodies), useParseResponse, hasBasePath, docs, grouping);
67
78
  const body = operationCodes.map(({ code }) => code).join("\n\n");
68
- const code = `${makeHeader(importPath, operationCodes.some(({ hasArgs }) => hasArgs), clientName, useParseResponse)}${body}${operationCodes.length > 0 ? "\n" : ""}`;
79
+ const needsInferRequestType = operationCodes.some(({ hasArgs }) => hasArgs);
80
+ const clientNames = [...new Set(operationCodes.map(({ client }) => client))];
81
+ const code = `${makeHeader(importPath, needsInferRequestType, clientNames.length > 0 ? clientNames : [clientName], useParseResponse)}${body}${operationCodes.length > 0 ? "\n" : ""}`;
69
82
  yield* emit(code, dirname(output), output);
70
83
  return `Generated rpc code written to ${output}`;
71
84
  });
@@ -1,5 +1,5 @@
1
1
  import { t as OpenAPI } from "../../index-tsPqeV6H.js";
2
- import { t as FormatError } from "../../index-wD0wV6VQ.js";
2
+ import { t as FormatError } from "../../index-D_gf3Xzx.js";
3
3
  import { Effect } from "effect";
4
4
  //#region src/core/type/index.d.ts
5
5
  /**
@@ -1,5 +1,5 @@
1
- import { A as isOperation, D as isMediaWithSchema, H as isRequestBody, M as isParameter, N as isParameterArray, T as isHttpMethod, W as isSchemaArray, X as isStringRef, g as statusCodeToNumber, k as isOpenAPIPaths, u as makeSafeKey } from "../../utils-BtWoIX8v.js";
2
- import { t as emit } from "../../emit-B_3fXoto.js";
1
+ import { D as isMediaWithSchema, M as isParameterArray, O as isOpenAPIPaths, T as isHttpMethod, U as isSchemaArray, V as isRequestBody, Y as isStringRef, g as statusCodeToNumber, j as isParameter, k as isOperation, u as makeSafeKey } from "../../utils-BvdDxide.js";
2
+ import { t as emit } from "../../emit-CSV6od97.js";
3
3
  import { Effect } from "effect";
4
4
  import path from "node:path";
5
5
  //#region src/core/type/index.ts
@@ -161,9 +161,11 @@ function makeSchemaTypeString(schema, components, visited) {
161
161
  if (schema.oneOf && schema.oneOf.length > 0) return schema.oneOf.map((s) => makeSchemaTypeString(s, components, visited)).join("|");
162
162
  if (schema.anyOf && schema.anyOf.length > 0) return schema.anyOf.map((s) => makeSchemaTypeString(s, components, visited)).join("|");
163
163
  if (schema.allOf && schema.allOf.length > 0) return makeAllOfTypeString(schema.allOf, components, visited);
164
- if (schema.enum && schema.enum.length > 0) return schema.enum.map((v) => typeof v === "string" ? `'${v.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'` : String(v)).join("|");
164
+ const isBigintLiteral = (value) => typeof value === "number" && Number.isInteger(value) && (Array.isArray(schema.type) ? schema.type.includes("integer") : schema.type === "integer") && (schema.format === "int64" || schema.format === "uint64" || schema.format === "bigint");
165
+ if (schema.enum && schema.enum.length > 0) return schema.enum.map((v) => typeof v === "string" ? `'${v.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'` : isBigintLiteral(v) ? `${v}n` : String(v)).join("|");
165
166
  if (schema.const !== void 0) {
166
167
  if (typeof schema.const === "string") return `'${schema.const.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'`;
168
+ if (isBigintLiteral(schema.const)) return `${schema.const}n`;
167
169
  if (typeof schema.const === "number" || typeof schema.const === "boolean") return String(schema.const);
168
170
  return JSON.stringify(schema.const);
169
171
  }