asphodelos 0.2.1 → 0.3.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.
@@ -1,8 +1,7 @@
1
1
  import { parseConfig } from "../index.mjs";
2
2
  import { t as FormatOptions } from "../format-B0W7HIAg.mjs";
3
- import { b as fileSystemLayer } from "../core-C1NqA5VJ.mjs";
4
- import { n as parseOpenAPI } from "../openapi-B4aAnx4P.mjs";
5
- import { i as makeJob, n as isUserCodeJob, r as jobTargets, t as cleanSplitOutputs } from "../shared-B-ADz5ww.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-Becl66EY.mjs";
4
+ import { n as parseOpenAPI } from "../openapi-C8b6Ibiu.mjs";
6
5
  import { Effect, FileSystem, Result } from "effect";
7
6
  import path from "node:path";
8
7
  import crypto from "node:crypto";
@@ -100,12 +99,11 @@ function isInputFile(filePath) {
100
99
  /**
101
100
  * Whether a change under `directory` is one to the documents the config reads.
102
101
  *
103
- * `path.relative` rather than `startsWith`: `/api` is a string prefix of `/api-old/spec.yaml`
102
+ * `isInsideDirectory` rather than `startsWith`: `/api` is a string prefix of `/api-old/spec.yaml`
104
103
  * without being its directory.
105
104
  */
106
105
  function isWatchedInput(directory, filePath) {
107
- const relative = path.relative(directory, filePath);
108
- return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative) && isInputFile(relative) && !relative.split(path.sep).slice(0, -1).some(isSkippedDirectory);
106
+ return isInsideDirectory(directory, filePath) && isInputFile(filePath) && !path.relative(directory, filePath).split(path.sep).slice(0, -1).some(isSkippedDirectory);
109
107
  }
110
108
  /** Every file under `target` (itself, when it is one), skipping what {@link isSkippedDirectory} does. */
111
109
  function listFiles(target) {
@@ -118,16 +116,18 @@ function listFiles(target) {
118
116
  });
119
117
  }
120
118
  /**
121
- * A digest of every document under the input directory, or `null` when the set cannot be read
122
- * reliably — which callers treat as "changed" and regenerate.
119
+ * A digest of every document the config reads, or `null` when the set cannot be read reliably —
120
+ * which callers treat as "changed" and regenerate.
123
121
  *
124
- * The whole directory rather than the file `input` names: a TypeSpec entry imports its siblings
125
- * and a `$ref` can point at one, so the named file is rarely the only one that matters.
122
+ * The whole input directory rather than the file `input` names: a TypeSpec entry imports its
123
+ * siblings and a `$ref` can point at one, so the named file is rarely the only one that matters.
124
+ * The files the document reads from `outside` the directory are part of the set as well.
126
125
  */
127
- function hashInputs(directory) {
126
+ function hashInputs(directory, outside) {
128
127
  return Effect.gen(function* () {
129
128
  const fs = yield* FileSystem.FileSystem;
130
- const files = (yield* listFiles(directory)).filter(isInputFile).toSorted();
129
+ const inside = (yield* listFiles(directory)).filter(isInputFile);
130
+ const files = [...new Set([...inside, ...outside])].toSorted();
131
131
  if (files.length === 0) return null;
132
132
  const contents = yield* Effect.all(files.map((file) => fs.readFileString(file).pipe(Effect.orElseSucceed(() => null))), { concurrency: "unbounded" });
133
133
  if (contents.includes(null)) return null;
@@ -183,7 +183,7 @@ function removeStaleOutput(output, keep) {
183
183
  * narrower than a recursive delete, because a path the config used to name may be shared with the
184
184
  * user:
185
185
  *
186
- * - outputs that merge into the user's code (`elysia`, `test`) are never removed;
186
+ * - the app entry and its `modules/`, which merge into the user's code, are never removed;
187
187
  * - a stale file is removed only when it is a `.ts` file;
188
188
  * - a stale split directory loses only its direct `.ts` children, never a subdirectory, and the
189
189
  * directory itself stays;
@@ -239,6 +239,7 @@ function asphodelosVite() {
239
239
  const state = {
240
240
  config: null,
241
241
  inputDirectory: null,
242
+ outside: [],
242
243
  inputHash: null,
243
244
  jobs: null,
244
245
  queue: Promise.resolve()
@@ -256,12 +257,29 @@ function asphodelosVite() {
256
257
  state.queue = queued;
257
258
  return queued;
258
259
  };
260
+ /**
261
+ * Learns which files outside the input directory the document reads, and watches them.
262
+ *
263
+ * Generation is over by the time this runs and nothing here feeds it: the list only decides
264
+ * which edits bring the next pass about. A document that cannot be read keeps the list it had.
265
+ * The digest is taken again because it has to cover the same files the next comparison will.
266
+ */
267
+ const watchOutside = async (server) => {
268
+ const { config, inputDirectory } = state;
269
+ if (!config || inputDirectory === null) return;
270
+ const outside = await runWithFileSystem(outsideSources(config.input).pipe(Effect.orElseSucceed(() => state.outside)));
271
+ if (outside.join("\n") === state.outside.join("\n")) return;
272
+ state.outside = outside;
273
+ if (outside.length > 0) server.watcher.add(outside);
274
+ state.inputHash = await runWithFileSystem(hashInputs(inputDirectory, outside));
275
+ };
259
276
  const runPass = async (server) => {
260
277
  const { config } = state;
261
278
  if (!config) return;
262
279
  console.log("🌸 asphodelos");
263
280
  const { logs, changed, jobs } = await runWithFileSystem(generate(config));
264
281
  for (const line of logs) console.log(line);
282
+ await watchOutside(server);
265
283
  if (!jobs) return;
266
284
  const removed = state.jobs === null ? [] : await runWithFileSystem(removeStaleOutputs(state.jobs, jobs));
267
285
  for (const removedPath of removed) console.log(`🧹 removed ${removedPath}`);
@@ -284,8 +302,9 @@ function asphodelosVite() {
284
302
  const inputPath = path.resolve(process.cwd(), loaded.success.input);
285
303
  const inputDirectory = path.dirname(inputPath);
286
304
  server.watcher.add([inputPath, ...INPUT_EXTENSIONS.map((extension) => path.join(inputDirectory, `**/*${extension}`))]);
305
+ if (inputDirectory !== state.inputDirectory) state.outside = [];
287
306
  state.inputDirectory = inputDirectory;
288
- state.inputHash = await runWithFileSystem(hashInputs(inputDirectory));
307
+ state.inputHash = await runWithFileSystem(hashInputs(inputDirectory, state.outside));
289
308
  await runPass(server);
290
309
  };
291
310
  /**
@@ -296,7 +315,7 @@ function asphodelosVite() {
296
315
  const applyInputChange = async (server) => {
297
316
  const { inputDirectory, jobs } = state;
298
317
  if (inputDirectory === null) return;
299
- const [inputHash, outputsExist] = await runWithFileSystem(Effect.all([hashInputs(inputDirectory), hasAllOutputs(jobs ?? [])]));
318
+ const [inputHash, outputsExist] = await runWithFileSystem(Effect.all([hashInputs(inputDirectory, state.outside), hasAllOutputs(jobs ?? [])]));
300
319
  if (inputHash !== null && inputHash === state.inputHash && jobs !== null && outputsExist) {
301
320
  console.log("⏭️ asphodelos: input unchanged - skipped regeneration");
302
321
  return;
@@ -321,7 +340,7 @@ function asphodelosVite() {
321
340
  queueConfigChange(server);
322
341
  return;
323
342
  }
324
- if (state.inputDirectory !== null && isWatchedInput(state.inputDirectory, changedPath)) queueInputChange(server);
343
+ if (state.outside.includes(changedPath) || state.inputDirectory !== null && isWatchedInput(state.inputDirectory, changedPath)) queueInputChange(server);
325
344
  });
326
345
  enqueue(() => applyConfig(server));
327
346
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "asphodelos",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Asphodelos is a code generator from OpenAPI to Elysia",
5
5
  "keywords": [
6
6
  "elysia",
@@ -43,11 +43,11 @@
43
43
  },
44
44
  "dependencies": {
45
45
  "@apidevtools/swagger-parser": "^12.1.0",
46
- "@effect/platform-node": "4.0.0-rc.112",
47
- "@effect/platform-node-shared": "4.0.0-rc.112",
46
+ "@effect/platform-node": "4.0.0",
47
+ "@effect/platform-node-shared": "4.0.0",
48
48
  "@typespec/compiler": "^1.16.0",
49
49
  "@typespec/openapi3": "^1.16.0",
50
- "effect": "4.0.0-rc.112",
50
+ "effect": "4.0.0",
51
51
  "oxfmt": "^0.67.0",
52
52
  "ts-morph": "^28.0.0"
53
53
  },
@@ -1,40 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-wcPFST8Q.mjs";
2
- import { Data, Effect } from "effect";
3
- import path from "node:path";
4
- import SwaggerParser from "@apidevtools/swagger-parser";
5
- import { NodeHost, compile } from "@typespec/compiler";
6
- import { getOpenAPI3 } from "@typespec/openapi3";
7
- //#region src/openapi/index.ts
8
- var openapi_exports = /* @__PURE__ */ __exportAll({
9
- OpenAPIError: () => OpenAPIError,
10
- parseOpenAPI: () => parseOpenAPI,
11
- pathEntries: () => pathEntries
12
- });
13
- /** The document could not be read, compiled or parsed into an OpenAPI object. */
14
- var OpenAPIError = class extends Data.TaggedError("OpenAPIError") {};
15
- /** Compiles a TypeSpec entry point into the plain document `SwaggerParser` expects. */
16
- async function readTypeSpec(input) {
17
- const program = await compile(NodeHost, path.resolve(input), { noEmit: true });
18
- if (program.diagnostics.length > 0) throw new Error(`TypeSpec compile failed:\n${program.diagnostics.map((d) => d.message).join("\n")}`);
19
- const [record] = await getOpenAPI3(program);
20
- const tsp = record && ("document" in record ? record.document : record.versions[0]?.document);
21
- return JSON.parse(JSON.stringify(tsp));
22
- }
23
- /** Parses `input` into an OpenAPI document. */
24
- function parseOpenAPI(input) {
25
- return Effect.tryPromise({
26
- try: async () => await SwaggerParser.bundle(input.endsWith(".tsp") ? await readTypeSpec(input) : input),
27
- catch: (error) => new OpenAPIError({ message: error instanceof Error ? error.message : String(error) })
28
- });
29
- }
30
- /**
31
- * `Object.entries(openAPI.paths)` on its own yields `any` values: swagger-parser types the
32
- * document as a union of the OpenAPI 2 / 3.0 / 3.1 shapes, and inference over that union drops
33
- * the value type. Going through the annotation below is what keeps every caller on `PathItem`.
34
- */
35
- function pathEntries(openAPI) {
36
- const paths = openAPI.paths;
37
- return Object.entries(paths);
38
- }
39
- //#endregion
40
- export { parseOpenAPI as n, pathEntries as r, openapi_exports as t };
@@ -1,221 +0,0 @@
1
- import { t as __exportAll } from "./rolldown-runtime-wcPFST8Q.mjs";
2
- import { S as unlink, _ as responses, a as hooks, c as mediaTypes, d as links, f as securitySchemes, g as parameters, h as examples, i as mock, l as pathItems, m as requestBodies, n as types, o as elysia, p as headers, r as test, s as eden, u as callbacks, v as schemas, x as readdir, y as components } from "./core-C1NqA5VJ.mjs";
3
- import { Effect } from "effect";
4
- import path, { posix } from "node:path";
5
- //#region src/shared/index.ts
6
- var shared_exports = /* @__PURE__ */ __exportAll({
7
- cleanSplitOutputs: () => cleanSplitOutputs,
8
- isUserCodeJob: () => isUserCodeJob,
9
- jobTargets: () => jobTargets,
10
- makeJob: () => makeJob
11
- });
12
- function edenJob(openAPI, edenConfig, prefix) {
13
- return {
14
- name: "eden",
15
- output: edenConfig.output,
16
- split: false,
17
- run: (output) => eden(openAPI, output, edenConfig.import, edenConfig.client, prefix, edenConfig.docs)
18
- };
19
- }
20
- function makeJob(openAPI, config) {
21
- const baseDir = posix.normalize(posix.dirname(config.output ?? "src/index.ts"));
22
- const { output: componentsOutput, ...componentTargets } = config.components ?? {};
23
- const componentJobs = componentsOutput ? [{
24
- name: "components",
25
- output: componentsOutput,
26
- split: false,
27
- run: (output) => components(openAPI.components, output, config.readonly)
28
- }] : perTypeComponentJobs(openAPI, componentTargets, baseDir, config.readonly);
29
- return [
30
- {
31
- name: "elysia",
32
- output: config.output ?? "src/index.ts",
33
- split: false,
34
- run: (output) => elysia(openAPI, {
35
- output,
36
- prefix: config.prefix,
37
- port: config.port,
38
- integration: config.integration === true,
39
- readonly: config.readonly === true,
40
- pathAlias: config.pathAlias === true ? `@/${baseDir.replace(/^\.?\/?/u, "")}` : void 0,
41
- components: componentTargets,
42
- componentsOutput
43
- })
44
- },
45
- ...componentJobs,
46
- config.eden ? edenJob(openAPI, config.eden, config.prefix) : void 0,
47
- config.types ? {
48
- name: "types",
49
- output: config.types.output,
50
- split: false,
51
- run: (output) => types(openAPI, output, config.prefix)
52
- } : void 0,
53
- config.test ? {
54
- name: "test",
55
- output: config.test.split ? `${baseDir}/modules` : config.test.output,
56
- split: config.test.split,
57
- run: (output) => test(openAPI, config.test?.split === true ? void 0 : output, {
58
- appOutput: config.output ?? "src/index.ts",
59
- split: config.test?.split === true,
60
- pathAlias: config.test?.pathAlias,
61
- prefix: config.prefix
62
- })
63
- } : void 0,
64
- config.mock ? {
65
- name: "mock",
66
- output: config.mock.output,
67
- split: false,
68
- run: (output) => mock(openAPI, output, {
69
- ...config.mock,
70
- prefix: config.prefix,
71
- port: config.port
72
- })
73
- } : void 0,
74
- ...[
75
- "swr",
76
- "tanstack-query",
77
- "preact-query",
78
- "vue-query",
79
- "svelte-query",
80
- "solid-query",
81
- "angular-query"
82
- ].map((library) => {
83
- const cfg = config[library];
84
- return cfg ? {
85
- name: library,
86
- output: cfg.output,
87
- split: cfg.split,
88
- run: (output) => hooks(openAPI, output, cfg.import, library, {
89
- client: cfg.client,
90
- basePath: config.prefix,
91
- split: cfg.split
92
- })
93
- } : void 0;
94
- })
95
- ].filter((job) => job !== void 0);
96
- }
97
- function perTypeComponentJobs(openAPI, componentTargets, baseDir, readonly) {
98
- return [
99
- openAPI.components?.schemas ? {
100
- name: "schemas",
101
- output: componentTargets.schemas?.output ?? `${baseDir}/components/schemas.ts`,
102
- split: componentTargets.schemas?.split ?? false,
103
- run: (output) => schemas(openAPI.components?.schemas, output, componentTargets.schemas?.split ?? false, componentTargets.schemas?.exportTypes ?? false, componentTargets, readonly)
104
- } : void 0,
105
- openAPI.components?.responses ? {
106
- name: "responses",
107
- output: componentTargets.responses?.output ?? `${baseDir}/components/responses.ts`,
108
- split: componentTargets.responses?.split ?? false,
109
- run: (output) => responses(openAPI.components?.responses, output, componentTargets.responses?.split ?? false, componentTargets.responses?.exportTypes ?? false, componentTargets, readonly)
110
- } : void 0,
111
- openAPI.components?.parameters ? {
112
- name: "parameters",
113
- output: componentTargets.parameters?.output ?? `${baseDir}/components/parameters.ts`,
114
- split: componentTargets.parameters?.split ?? false,
115
- run: (output) => parameters(openAPI.components?.parameters, output, componentTargets.parameters?.split ?? false, componentTargets.parameters?.exportTypes ?? false, componentTargets, readonly)
116
- } : void 0,
117
- openAPI.components?.examples ? {
118
- name: "examples",
119
- output: componentTargets.examples?.output ?? `${baseDir}/components/examples.ts`,
120
- split: componentTargets.examples?.split ?? false,
121
- run: (output) => examples(openAPI.components?.examples, output, componentTargets.examples?.split ?? false, componentTargets)
122
- } : void 0,
123
- openAPI.components?.requestBodies ? {
124
- name: "requestBodies",
125
- output: componentTargets.requestBodies?.output ?? `${baseDir}/components/requestBodies.ts`,
126
- split: componentTargets.requestBodies?.split ?? false,
127
- run: (output) => requestBodies(openAPI.components?.requestBodies, output, componentTargets.requestBodies?.split ?? false, componentTargets.requestBodies?.exportTypes ?? false, componentTargets, readonly)
128
- } : void 0,
129
- openAPI.components?.headers ? {
130
- name: "headers",
131
- output: componentTargets.headers?.output ?? `${baseDir}/components/headers.ts`,
132
- split: componentTargets.headers?.split ?? false,
133
- run: (output) => headers(openAPI.components?.headers, output, componentTargets.headers?.split ?? false, componentTargets.headers?.exportTypes ?? false, componentTargets, readonly)
134
- } : void 0,
135
- openAPI.components?.securitySchemes ? {
136
- name: "securitySchemes",
137
- output: componentTargets.securitySchemes?.output ?? `${baseDir}/components/securitySchemes.ts`,
138
- split: componentTargets.securitySchemes?.split ?? false,
139
- run: (output) => securitySchemes(openAPI.components?.securitySchemes, output, componentTargets.securitySchemes?.split ?? false, componentTargets)
140
- } : void 0,
141
- openAPI.components?.links ? {
142
- name: "links",
143
- output: componentTargets.links?.output ?? `${baseDir}/components/links.ts`,
144
- split: componentTargets.links?.split ?? false,
145
- run: (output) => links(openAPI.components?.links, output, componentTargets.links?.split ?? false, componentTargets)
146
- } : void 0,
147
- openAPI.components?.callbacks ? {
148
- name: "callbacks",
149
- output: componentTargets.callbacks?.output ?? `${baseDir}/components/callbacks.ts`,
150
- split: componentTargets.callbacks?.split ?? false,
151
- run: (output) => callbacks(openAPI.components?.callbacks, output, componentTargets.callbacks?.split ?? false, componentTargets)
152
- } : void 0,
153
- openAPI.components?.pathItems ? {
154
- name: "pathItems",
155
- output: componentTargets.pathItems?.output ?? `${baseDir}/components/pathItems.ts`,
156
- split: componentTargets.pathItems?.split ?? false,
157
- run: (output) => pathItems(openAPI.components?.pathItems, output, componentTargets.pathItems?.split ?? false, componentTargets)
158
- } : void 0,
159
- openAPI.components?.mediaTypes ? {
160
- name: "mediaTypes",
161
- output: componentTargets.mediaTypes?.output ?? `${baseDir}/components/mediaTypes.ts`,
162
- split: componentTargets.mediaTypes?.split ?? false,
163
- run: (output) => mediaTypes(openAPI.components?.mediaTypes, output, componentTargets.mediaTypes?.split ?? false, componentTargets.mediaTypes?.exportTypes ?? false, componentTargets, readonly)
164
- } : void 0
165
- ];
166
- }
167
- /**
168
- * Generators that merge into what is already at their output rather than overwrite it.
169
- *
170
- * `elysia` and `test` read the file back and keep whatever the user wrote there (`mergeSource`),
171
- * so what they write holds the user's code as much as the generator's. Nothing that deletes — the
172
- * split clean below, the Vite plugin's stale-output cleanup — may touch one.
173
- */
174
- const USER_CODE_JOBS = new Set(["elysia", "test"]);
175
- function isUserCodeJob(job) {
176
- return USER_CODE_JOBS.has(job.name);
177
- }
178
- /**
179
- * Every absolute path a job writes under.
180
- *
181
- * The output itself, and for `elysia` the `modules/` directory it fills beside the app entry —
182
- * one file per resource, which a caller that watches for changed output has to see as well.
183
- */
184
- function jobTargets(job) {
185
- const output = path.resolve(process.cwd(), job.output);
186
- return job.name === "elysia" ? [output, path.join(path.dirname(output), "modules")] : [output];
187
- }
188
- function cleanSplitDirectory(directory, keep) {
189
- return Effect.gen(function* () {
190
- const stale = (yield* readdir(directory)).filter((name) => name.endsWith(".ts")).map((name) => path.join(directory, name)).filter((file) => !keep.has(file));
191
- yield* Effect.all(stale.map(unlink), { concurrency: "unbounded" });
192
- return stale;
193
- });
194
- }
195
- /**
196
- * Empties every split output directory before the generators refill them, answering with what
197
- * was removed.
198
- *
199
- * A split generator writes one file per entry plus a barrel beside them, and knows only what it
200
- * writes — so an entry that leaves the document leaves its file behind, orphaned and still
201
- * importing names the document no longer defines. A split directory is therefore the generator's,
202
- * not a place to keep anything by hand.
203
- *
204
- * Only the direct `.ts` children are removed, never a subdirectory, and never a file another job
205
- * writes on its own: a single-file output that lives inside a split directory is left where it is
206
- * rather than deleted and rewritten. A split job that merges into the user's code is never
207
- * cleaned at all.
208
- *
209
- * This runs before any job writes, never per job as it goes: two jobs can be aimed at one
210
- * directory, and a clean that lands after a sibling has filled it would take the fresh files with
211
- * it.
212
- */
213
- function cleanSplitOutputs(jobs) {
214
- return Effect.gen(function* () {
215
- const keep = new Set(jobs.filter((job) => !job.split).map((job) => path.resolve(process.cwd(), job.output)));
216
- const directories = new Set(jobs.filter((job) => job.split && !isUserCodeJob(job)).map((job) => path.resolve(process.cwd(), job.output)));
217
- return (yield* Effect.all([...directories].map((directory) => cleanSplitDirectory(directory, keep)), { concurrency: "unbounded" })).flat();
218
- });
219
- }
220
- //#endregion
221
- export { shared_exports as a, makeJob as i, isUserCodeJob as n, jobTargets as r, cleanSplitOutputs as t };