@gaganref/confect-cli 10.3.1-fork.15 → 10.3.1-fork.17

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.
@@ -12,11 +12,13 @@ import * as Path from "effect/Path";
12
12
  import * as HashSet from "effect/HashSet";
13
13
  import * as Match from "effect/Match";
14
14
  import * as Option from "effect/Option";
15
+ import * as Context from "effect/Context";
15
16
  import * as Schema from "effect/Schema";
16
17
  import * as Console from "effect/Console";
17
18
  import * as Layer from "effect/Layer";
18
19
  import * as NodeWorker from "@effect/platform-node/NodeWorker";
19
20
  import { fork } from "node:child_process";
21
+ import * as Pool from "effect/Pool";
20
22
  import * as LogLevel from "effect/LogLevel";
21
23
  import * as References from "effect/References";
22
24
  import * as Rpc from "effect/rpc/Rpc";
@@ -35,7 +37,7 @@ const RequestContext = Schema.Struct({
35
37
  });
36
38
  var EvaluationError = class extends Schema.TaggedError()("EvaluationError", { diagnostic: Schema.String }) {};
37
39
  const Failure = Schema.Union([EvaluationError, ComponentNodeGroupError]);
38
- const requests = RpcGroup.make(Rpc.make("Previous", {
40
+ const requests = RpcGroup.make(Rpc.make("Ready", { success: Schema.Void }), Rpc.make("Previous", {
39
41
  payload: RequestContext,
40
42
  success: FunctionPaths,
41
43
  error: Failure
@@ -60,6 +62,29 @@ const requests = RpcGroup.make(Rpc.make("Previous", {
60
62
  success: GenerationSnapshot,
61
63
  error: Failure
62
64
  }));
65
+ const acquireWorker = Effect.gen(function* () {
66
+ const child = yield* Effect.acquireRelease(Effect.sync(() => fork(new URL("../dist/EvaluationWorker.mjs", import.meta.url), { serialization: "advanced" })), (evaluator) => Effect.callback((resume) => {
67
+ if (evaluator.exitCode !== null || evaluator.signalCode !== null) {
68
+ resume(Effect.void);
69
+ return;
70
+ }
71
+ evaluator.once("exit", () => resume(Effect.void));
72
+ evaluator.kill("SIGKILL");
73
+ }));
74
+ const protocol = yield* Layer.build(RpcClient.layerProtocolWorker({ size: 1 }).pipe(Layer.provide(NodeWorker.layer(() => child))));
75
+ const client = yield* RpcClient.make(requests).pipe(Effect.provideContext(protocol));
76
+ yield* client.Ready();
77
+ yield* Effect.logDebug("Evaluator ready").pipe(Effect.annotateLogs({ pid: child.pid }));
78
+ return {
79
+ child,
80
+ client
81
+ };
82
+ });
83
+ var Standby = class extends Context.Service()("@confect/cli/Evaluation/Standby") {};
84
+ const prewarmedLayer = Layer.effect(Standby, Pool.make({
85
+ acquire: acquireWorker,
86
+ size: 1
87
+ }));
63
88
  const withWorker = Effect.fn("Evaluation.withWorker")(function* (run) {
64
89
  const requestContext = {
65
90
  projectRoot: yield* ProjectRoot.get,
@@ -72,17 +97,18 @@ const withWorker = Effect.fn("Evaluation.withWorker")(function* (run) {
72
97
  minimumLogLevel: yield* References.MinimumLogLevel
73
98
  };
74
99
  return yield* Effect.scoped(Effect.gen(function* () {
75
- const child = yield* Effect.acquireRelease(Effect.sync(() => fork(new URL("../dist/EvaluationWorker.mjs", import.meta.url), { serialization: "advanced" })), (evaluator) => Effect.callback((resume) => {
76
- if (evaluator.exitCode !== null || evaluator.signalCode !== null) {
77
- resume(Effect.void);
78
- return;
79
- }
80
- evaluator.once("exit", () => resume(Effect.void));
81
- evaluator.kill("SIGKILL");
82
- }));
83
- return yield* Effect.gen(function* () {
84
- return yield* run(yield* RpcClient.make(requests), requestContext);
85
- }).pipe(Effect.provide(RpcClient.layerProtocolWorker({ size: 1 }).pipe(Layer.provide(NodeWorker.layer(() => child)))));
100
+ const standby = yield* Effect.serviceOption(Standby);
101
+ return yield* run((yield* Option.match(standby, {
102
+ onNone: () => acquireWorker,
103
+ onSome: (pool) => Effect.gen(function* () {
104
+ while (true) {
105
+ const candidate = yield* Pool.get(pool);
106
+ yield* Effect.addFinalizer(() => Pool.invalidate(pool, candidate));
107
+ if (candidate.child.connected && candidate.child.exitCode === null && candidate.child.signalCode === null) return candidate;
108
+ yield* Pool.invalidate(pool, candidate);
109
+ }
110
+ })
111
+ })).client, requestContext);
86
112
  })).pipe(Effect.catchTags({
87
113
  WorkerError: (error) => Effect.fail(new EvaluationError({ diagnostic: error.message })),
88
114
  RpcClientError: (error) => Effect.fail(new EvaluationError({ diagnostic: error.message }))
@@ -112,6 +138,6 @@ const catchAndLog = (effect) => effect.pipe(Effect.asSome, Effect.catchTags({
112
138
  ComponentNodeGroupError: (error) => logCodegenError(error).pipe(Effect.as(Option.none()))
113
139
  }));
114
140
  //#endregion
115
- export { EvaluationError, RequestContext, catchAndLog, generateSnapshot, loadPreviousFunctionPaths, requests, updateDeclarations, validate };
141
+ export { EvaluationError, RequestContext, catchAndLog, generateSnapshot, loadPreviousFunctionPaths, prewarmedLayer, requests, updateDeclarations, validate };
116
142
 
117
143
  //# sourceMappingURL=Evaluation.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"Evaluation.mjs","names":["GenerationSnapshot.GenerationSnapshot","EntryPoint.Declaration","GenerationSnapshot.functionPaths"],"sources":["../src/Evaluation.ts"],"sourcesContent":["import * as NodeWorker from \"@effect/platform-node/NodeWorker\";\nimport { fork } from \"node:child_process\";\nimport * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Layer from \"effect/Layer\";\nimport * as LogLevel from \"effect/LogLevel\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport * as References from \"effect/References\";\nimport * as Rpc from \"effect/rpc/Rpc\";\nimport * as RpcClient from \"effect/rpc/RpcClient\";\nimport type { RpcClientError } from \"effect/rpc/RpcClientError\";\nimport * as RpcGroup from \"effect/rpc/RpcGroup\";\nimport type * as Array from \"effect/Array\";\nimport * as Match from \"effect/Match\";\nimport { ComponentNodeGroupError, logCodegenError } from \"./CodegenError.js\";\nimport * as EntryPoint from \"./EntryPoint.js\";\nimport * as GenerationSnapshot from \"./GenerationSnapshot.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport { FunctionPaths } from \"./FunctionPaths.js\";\nimport { ImplModulePath } from \"./ImplModulePath.js\";\nimport { ProjectRoot } from \"./ProjectRoot.js\";\n\nexport const RequestContext = Schema.Struct({\n projectRoot: Schema.String,\n confectDirectory: Schema.String,\n convexDirectory: Schema.String,\n target: Schema.Union([\n Schema.Struct({ kind: Schema.Literal(\"app\") }),\n Schema.Struct({\n kind: Schema.Literal(\"component\"),\n definition: Schema.String,\n }),\n ]),\n minimumLogLevel: Schema.Literals(LogLevel.values),\n});\nexport type RequestContext = typeof RequestContext.Type;\n\nexport class EvaluationError extends Schema.TaggedError<EvaluationError>()(\n \"EvaluationError\",\n { diagnostic: Schema.String },\n) {}\n\n// A rejected Node group stays typed so the caller can restore component output.\nconst Failure = Schema.Union([EvaluationError, ComponentNodeGroupError]);\n\nexport const requests = RpcGroup.make(\n Rpc.make(\"Previous\", {\n payload: RequestContext,\n success: FunctionPaths,\n error: Failure,\n }),\n Rpc.make(\"Generate\", {\n payload: RequestContext,\n success: GenerationSnapshot.GenerationSnapshot,\n error: Failure,\n }),\n Rpc.make(\"Validate\", {\n payload: Schema.Struct({\n ...RequestContext.fields,\n paths: Schema.Array(ImplModulePath),\n }),\n success: Schema.Void,\n error: Failure,\n }),\n Rpc.make(\"Update\", {\n payload: Schema.Struct({\n ...RequestContext.fields,\n snapshot: GenerationSnapshot.GenerationSnapshot,\n declarations: Schema.NonEmptyArray(EntryPoint.Declaration),\n paths: Schema.Array(ImplModulePath),\n }),\n success: GenerationSnapshot.GenerationSnapshot,\n error: Failure,\n }),\n);\n\nconst withWorker = Effect.fn(\"Evaluation.withWorker\")(function* <A>(\n run: (\n client: RpcClient.RpcClient<RpcGroup.Rpcs<typeof requests>, RpcClientError>,\n requestContext: RequestContext,\n ) => Effect.Effect<\n A,\n EvaluationError | ComponentNodeGroupError | RpcClientError\n >,\n) {\n const requestContext = {\n projectRoot: yield* ProjectRoot.get,\n confectDirectory: yield* ConfectDirectory.get,\n convexDirectory: yield* ConvexDirectory.get,\n target: Match.value(yield* ConvexDirectory.target).pipe(\n Match.when({ kind: \"app\" }, () => ({ kind: \"app\" as const })),\n Match.when({ kind: \"component\" }, ({ scope }) => ({\n kind: \"component\" as const,\n definition: scope.slice(\"component:\".length),\n })),\n Match.exhaustive,\n ),\n minimumLogLevel: yield* References.MinimumLogLevel,\n };\n return yield* Effect.scoped(\n Effect.gen(function* () {\n const child = yield* Effect.acquireRelease(\n Effect.sync(() =>\n fork(new URL(\"../dist/EvaluationWorker.mjs\", import.meta.url), {\n serialization: \"advanced\",\n }),\n ),\n (evaluator) =>\n Effect.callback<void>((resume) => {\n if (evaluator.exitCode !== null || evaluator.signalCode !== null) {\n resume(Effect.void);\n return;\n }\n evaluator.once(\"exit\", () => resume(Effect.void));\n evaluator.kill(\"SIGKILL\");\n }),\n );\n return yield* Effect.gen(function* () {\n const client = yield* RpcClient.make(requests);\n return yield* run(client, requestContext);\n }).pipe(\n Effect.provide(\n RpcClient.layerProtocolWorker({ size: 1 }).pipe(\n Layer.provide(NodeWorker.layer(() => child)),\n ),\n ),\n );\n }),\n ).pipe(\n Effect.catchTags({\n WorkerError: (error) =>\n Effect.fail(new EvaluationError({ diagnostic: error.message })),\n RpcClientError: (error) =>\n Effect.fail(new EvaluationError({ diagnostic: error.message })),\n }),\n );\n});\n\nexport const loadPreviousFunctionPaths = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n if (\n !(yield* fs.exists(path.join(confectDirectory, \"_generated\", \"spec.ts\")))\n ) {\n return FunctionPaths.make(HashSet.empty());\n }\n return yield* withWorker((client, requestContext) =>\n client.Previous(requestContext),\n );\n});\n\nexport const generateSnapshot = withWorker((client, requestContext) =>\n client.Generate(requestContext),\n);\n\nexport const generate = generateSnapshot.pipe(\n Effect.map(GenerationSnapshot.functionPaths),\n);\n\nexport const updateDeclarations = (\n snapshot: GenerationSnapshot.GenerationSnapshot,\n declarations: Array.NonEmptyReadonlyArray<EntryPoint.Declaration>,\n paths: ReadonlyArray<ImplModulePath>,\n) =>\n withWorker((client, requestContext) =>\n client.Update({\n ...requestContext,\n snapshot,\n declarations,\n paths,\n }),\n );\n\nexport const validate = (paths: ReadonlyArray<ImplModulePath>) =>\n withWorker((client, requestContext) =>\n client.Validate({ ...requestContext, paths }),\n );\n\nexport const catchAndLog = <A, R>(\n effect: Effect.Effect<A, EvaluationError | ComponentNodeGroupError, R>,\n): Effect.Effect<Option.Option<A>, never, R> =>\n effect.pipe(\n Effect.asSome,\n Effect.catchTags({\n EvaluationError: ({ diagnostic }) =>\n Console.error(diagnostic).pipe(Effect.as(Option.none<A>())),\n ComponentNodeGroupError: (error) =>\n logCodegenError(error).pipe(Effect.as(Option.none<A>())),\n }),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,MAAa,iBAAiB,OAAO,OAAO;CAC1C,aAAa,OAAO;CACpB,kBAAkB,OAAO;CACzB,iBAAiB,OAAO;CACxB,QAAQ,OAAO,MAAM,CACnB,OAAO,OAAO,EAAE,MAAM,OAAO,QAAQ,KAAK,EAAE,CAAC,GAC7C,OAAO,OAAO;EACZ,MAAM,OAAO,QAAQ,WAAW;EAChC,YAAY,OAAO;CACrB,CAAC,CACH,CAAC;CACD,iBAAiB,OAAO,SAAS,SAAS,MAAM;AAClD,CAAC;AAGD,IAAa,kBAAb,cAAqC,OAAO,YAA6B,CAAC,CACxE,mBACA,EAAE,YAAY,OAAO,OAAO,CAC9B,CAAC,CAAC,CAAC;AAGH,MAAM,UAAU,OAAO,MAAM,CAAC,iBAAiB,uBAAuB,CAAC;AAEvE,MAAa,WAAW,SAAS,KAC/B,IAAI,KAAK,YAAY;CACnB,SAAS;CACT,SAAS;CACT,OAAO;AACT,CAAC,GACD,IAAI,KAAK,YAAY;CACnB,SAAS;CACT,SAASA;CACT,OAAO;AACT,CAAC,GACD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B,KAAK,CAAC,CAAC,KAAK,OAAO,GAAG,OAAO,KAAQ,CAAC,CAAC;AAC3D,CAAC,CACH"}
1
+ {"version":3,"file":"Evaluation.mjs","names":["GenerationSnapshot.GenerationSnapshot","EntryPoint.Declaration","GenerationSnapshot.functionPaths"],"sources":["../src/Evaluation.ts"],"sourcesContent":["import * as NodeWorker from \"@effect/platform-node/NodeWorker\";\nimport { fork } from \"node:child_process\";\nimport * as Console from \"effect/Console\";\nimport * as Context from \"effect/Context\";\nimport * as Pool from \"effect/Pool\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Layer from \"effect/Layer\";\nimport * as LogLevel from \"effect/LogLevel\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as Schema from \"effect/Schema\";\nimport * as References from \"effect/References\";\nimport * as Rpc from \"effect/rpc/Rpc\";\nimport * as RpcClient from \"effect/rpc/RpcClient\";\nimport type { RpcClientError } from \"effect/rpc/RpcClientError\";\nimport * as RpcGroup from \"effect/rpc/RpcGroup\";\nimport type * as Array from \"effect/Array\";\nimport * as Match from \"effect/Match\";\nimport { ComponentNodeGroupError, logCodegenError } from \"./CodegenError.js\";\nimport * as EntryPoint from \"./EntryPoint.js\";\nimport * as GenerationSnapshot from \"./GenerationSnapshot.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport { FunctionPaths } from \"./FunctionPaths.js\";\nimport { ImplModulePath } from \"./ImplModulePath.js\";\nimport { ProjectRoot } from \"./ProjectRoot.js\";\n\nexport const RequestContext = Schema.Struct({\n projectRoot: Schema.String,\n confectDirectory: Schema.String,\n convexDirectory: Schema.String,\n target: Schema.Union([\n Schema.Struct({ kind: Schema.Literal(\"app\") }),\n Schema.Struct({\n kind: Schema.Literal(\"component\"),\n definition: Schema.String,\n }),\n ]),\n minimumLogLevel: Schema.Literals(LogLevel.values),\n});\nexport type RequestContext = typeof RequestContext.Type;\n\nexport class EvaluationError extends Schema.TaggedError<EvaluationError>()(\n \"EvaluationError\",\n { diagnostic: Schema.String },\n) {}\n\n// A rejected Node group stays typed so the caller can restore component output.\nconst Failure = Schema.Union([EvaluationError, ComponentNodeGroupError]);\n\nexport const requests = RpcGroup.make(\n Rpc.make(\"Ready\", { success: Schema.Void }),\n Rpc.make(\"Previous\", {\n payload: RequestContext,\n success: FunctionPaths,\n error: Failure,\n }),\n Rpc.make(\"Generate\", {\n payload: RequestContext,\n success: GenerationSnapshot.GenerationSnapshot,\n error: Failure,\n }),\n Rpc.make(\"Validate\", {\n payload: Schema.Struct({\n ...RequestContext.fields,\n paths: Schema.Array(ImplModulePath),\n }),\n success: Schema.Void,\n error: Failure,\n }),\n Rpc.make(\"Update\", {\n payload: Schema.Struct({\n ...RequestContext.fields,\n snapshot: GenerationSnapshot.GenerationSnapshot,\n declarations: Schema.NonEmptyArray(EntryPoint.Declaration),\n paths: Schema.Array(ImplModulePath),\n }),\n success: GenerationSnapshot.GenerationSnapshot,\n error: Failure,\n }),\n);\n\nconst acquireWorker = Effect.gen(function* () {\n const child = yield* Effect.acquireRelease(\n Effect.sync(() =>\n fork(new URL(\"../dist/EvaluationWorker.mjs\", import.meta.url), {\n serialization: \"advanced\",\n }),\n ),\n (evaluator) =>\n Effect.callback<void>((resume) => {\n if (evaluator.exitCode !== null || evaluator.signalCode !== null) {\n resume(Effect.void);\n return;\n }\n evaluator.once(\"exit\", () => resume(Effect.void));\n evaluator.kill(\"SIGKILL\");\n }),\n );\n const protocol = yield* Layer.build(\n RpcClient.layerProtocolWorker({ size: 1 }).pipe(\n Layer.provide(NodeWorker.layer(() => child)),\n ),\n );\n const client = yield* RpcClient.make(requests).pipe(\n Effect.provideContext(protocol),\n );\n yield* client.Ready();\n yield* Effect.logDebug(\"Evaluator ready\").pipe(\n Effect.annotateLogs({ pid: child.pid }),\n );\n return { child, client };\n});\n\nclass Standby extends Context.Service<\n Standby,\n Pool.Pool<\n Effect.Success<typeof acquireWorker>,\n Effect.Error<typeof acquireWorker>\n >\n>()(\"@confect/cli/Evaluation/Standby\") {}\n\n// Each evaluator handles one evaluation to isolate globals and module caches.\n// Discarding it bounds memory and recovers from crashes. Dev prepares the next\n// evaluator between saves.\nexport const prewarmedLayer = Layer.effect(\n Standby,\n Pool.make({ acquire: acquireWorker, size: 1 }),\n);\n\nconst withWorker = Effect.fn(\"Evaluation.withWorker\")(function* <A>(\n run: (\n client: RpcClient.RpcClient<RpcGroup.Rpcs<typeof requests>, RpcClientError>,\n requestContext: RequestContext,\n ) => Effect.Effect<\n A,\n EvaluationError | ComponentNodeGroupError | RpcClientError\n >,\n) {\n const requestContext = {\n projectRoot: yield* ProjectRoot.get,\n confectDirectory: yield* ConfectDirectory.get,\n convexDirectory: yield* ConvexDirectory.get,\n target: Match.value(yield* ConvexDirectory.target).pipe(\n Match.when({ kind: \"app\" }, () => ({ kind: \"app\" as const })),\n Match.when({ kind: \"component\" }, ({ scope }) => ({\n kind: \"component\" as const,\n definition: scope.slice(\"component:\".length),\n })),\n Match.exhaustive,\n ),\n minimumLogLevel: yield* References.MinimumLogLevel,\n };\n return yield* Effect.scoped(\n Effect.gen(function* () {\n const standby = yield* Effect.serviceOption(Standby);\n const worker = yield* Option.match(standby, {\n onNone: () => acquireWorker,\n onSome: (pool) =>\n Effect.gen(function* () {\n while (true) {\n const candidate = yield* Pool.get(pool);\n yield* Effect.addFinalizer(() =>\n Pool.invalidate(pool, candidate),\n );\n // An idle exit has no pending RPC to fail.\n if (\n candidate.child.connected &&\n candidate.child.exitCode === null &&\n candidate.child.signalCode === null\n )\n return candidate;\n yield* Pool.invalidate(pool, candidate);\n }\n }),\n });\n return yield* run(worker.client, requestContext);\n }),\n ).pipe(\n Effect.catchTags({\n WorkerError: (error) =>\n Effect.fail(new EvaluationError({ diagnostic: error.message })),\n RpcClientError: (error) =>\n Effect.fail(new EvaluationError({ diagnostic: error.message })),\n }),\n );\n});\n\nexport const loadPreviousFunctionPaths = Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n if (\n !(yield* fs.exists(path.join(confectDirectory, \"_generated\", \"spec.ts\")))\n ) {\n return FunctionPaths.make(HashSet.empty());\n }\n return yield* withWorker((client, requestContext) =>\n client.Previous(requestContext),\n );\n});\n\nexport const generateSnapshot = withWorker((client, requestContext) =>\n client.Generate(requestContext),\n);\n\nexport const generate = generateSnapshot.pipe(\n Effect.map(GenerationSnapshot.functionPaths),\n);\n\nexport const updateDeclarations = (\n snapshot: GenerationSnapshot.GenerationSnapshot,\n declarations: Array.NonEmptyReadonlyArray<EntryPoint.Declaration>,\n paths: ReadonlyArray<ImplModulePath>,\n) =>\n withWorker((client, requestContext) =>\n client.Update({\n ...requestContext,\n snapshot,\n declarations,\n paths,\n }),\n );\n\nexport const validate = (paths: ReadonlyArray<ImplModulePath>) =>\n withWorker((client, requestContext) =>\n client.Validate({ ...requestContext, paths }),\n );\n\nexport const catchAndLog = <A, R>(\n effect: Effect.Effect<A, EvaluationError | ComponentNodeGroupError, R>,\n): Effect.Effect<Option.Option<A>, never, R> =>\n effect.pipe(\n Effect.asSome,\n Effect.catchTags({\n EvaluationError: ({ diagnostic }) =>\n Console.error(diagnostic).pipe(Effect.as(Option.none<A>())),\n ComponentNodeGroupError: (error) =>\n logCodegenError(error).pipe(Effect.as(Option.none<A>())),\n }),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,iBAAiB,OAAO,OAAO;CAC1C,aAAa,OAAO;CACpB,kBAAkB,OAAO;CACzB,iBAAiB,OAAO;CACxB,QAAQ,OAAO,MAAM,CACnB,OAAO,OAAO,EAAE,MAAM,OAAO,QAAQ,KAAK,EAAE,CAAC,GAC7C,OAAO,OAAO;EACZ,MAAM,OAAO,QAAQ,WAAW;EAChC,YAAY,OAAO;CACrB,CAAC,CACH,CAA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AC,CAAC,KAAK,OAAO,GAAG,OAAO,KAAQ,CAAC,CAAC;AAC3D,CAAC,CACH"}
@@ -15,6 +15,7 @@ import * as Schema from "effect/Schema";
15
15
  import * as esbuild from "esbuild";
16
16
  import * as Layer from "effect/Layer";
17
17
  import * as IdScope from "@confect/core/IdScope";
18
+ import * as Schedule from "effect/Schedule";
18
19
  import * as References from "effect/References";
19
20
  import * as NodeWorkerRunner from "@effect/platform-node/NodeWorkerRunner";
20
21
  import * as RpcServer from "effect/rpc/RpcServer";
@@ -34,12 +35,23 @@ const evaluate = (requestContext, effect) => effect.pipe(Effect.provideService(R
34
35
  return Effect.fail(new EvaluationError({ diagnostic: Option.isSome(failure) && isCodegenError(failure.value) ? renderCodegenError(failure.value) : Cause.pretty(cause) }));
35
36
  }));
36
37
  const handlers = requests.toLayer({
38
+ Ready: () => Effect.void,
37
39
  Previous: (requestContext) => evaluate(requestContext, loadPreviousFunctionPaths),
38
40
  Generate: (requestContext) => evaluate(requestContext, generateWithSnapshot.pipe(Effect.map(({ snapshot }) => snapshot))),
39
41
  Validate: (request) => evaluate(request, validateImplFiles(request.paths)),
40
42
  Update: (request) => evaluate(request, updateDeclarations(request.snapshot, request.declarations, request.paths))
41
43
  });
42
- RpcServer.layer(requests).pipe(Layer.provide(handlers), Layer.provide(NodeServices.layer), Layer.provide(RpcServer.layerProtocolWorkerRunner.pipe(Layer.provide(NodeWorkerRunner.layer))), Layer.launch, Effect.ensuring(Effect.promise(() => esbuild.stop())), NodeRuntime.runMain);
44
+ const parentPid = process.ppid;
45
+ process.once("disconnect", () => process.exit(0));
46
+ const watchParent = Effect.sync(() => {
47
+ if (!process.connected || process.ppid !== parentPid) process.exit(0);
48
+ try {
49
+ process.kill(parentPid, 0);
50
+ } catch {
51
+ process.exit(0);
52
+ }
53
+ }).pipe(Effect.repeat({ schedule: Schedule.spaced("1 second") }));
54
+ RpcServer.layer(requests).pipe(Layer.provide(handlers), Layer.provide(NodeServices.layer), Layer.provide(RpcServer.layerProtocolWorkerRunner.pipe(Layer.provide(NodeWorkerRunner.layer))), Layer.launch, Effect.raceFirst(watchParent), Effect.ensuring(Effect.promise(() => esbuild.stop())), NodeRuntime.runMain);
43
55
  //#endregion
44
56
  export {};
45
57
 
@@ -1 +1 @@
1
- {"version":3,"file":"EvaluationWorker.mjs","names":["CodegenError.ComponentNodeGroupError","CodegenError.isCodegenError","CodegenError.renderCodegenError"],"sources":["../src/EvaluationWorker.ts"],"sourcesContent":["import * as NodeRuntime from \"@effect/platform-node/NodeRuntime\";\nimport * as NodeServices from \"@effect/platform-node/NodeServices\";\nimport * as NodeWorkerRunner from \"@effect/platform-node/NodeWorkerRunner\";\nimport * as IdScope from \"@confect/core/IdScope\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as References from \"effect/References\";\nimport * as Schema from \"effect/Schema\";\nimport * as RpcServer from \"effect/rpc/RpcServer\";\nimport * as esbuild from \"esbuild\";\nimport * as CodegenError from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport type { RequestContext } from \"./Evaluation.js\";\nimport { EvaluationError, requests } from \"./Evaluation.js\";\nimport { validateImplFiles } from \"./LeafModule.js\";\nimport { ProjectRoot } from \"./ProjectRoot.js\";\nimport {\n generateWithSnapshot,\n loadPreviousFunctionPaths,\n updateDeclarations,\n} from \"./confect/codegen.js\";\n\nconst evaluate = <A, E, R>(\n requestContext: RequestContext,\n effect: Effect.Effect<A, E, R>,\n) =>\n effect.pipe(\n Effect.provideService(\n References.MinimumLogLevel,\n requestContext.minimumLogLevel,\n ),\n Effect.provideService(ProjectRoot, {\n get: Effect.succeed(requestContext.projectRoot),\n }),\n Effect.provideService(ConfectDirectory, {\n get: Effect.succeed(requestContext.confectDirectory),\n }),\n Effect.provideService(ConvexDirectory, {\n get: Effect.succeed(requestContext.convexDirectory),\n target: Match.value(requestContext.target).pipe(\n Match.when({ kind: \"app\" }, () => ({\n kind: \"app\" as const,\n scope: IdScope.app,\n })),\n Match.when({ kind: \"component\" }, ({ definition }) => ({\n kind: \"component\" as const,\n scope: IdScope.component(definition),\n })),\n Match.exhaustive,\n ),\n }),\n Effect.catchCause(\n (\n cause,\n ): Effect.Effect<\n never,\n EvaluationError | CodegenError.ComponentNodeGroupError\n > => {\n const failure = Cause.findErrorOption(cause);\n if (\n Option.isSome(failure) &&\n Schema.is(CodegenError.ComponentNodeGroupError)(failure.value)\n )\n return Effect.fail(failure.value);\n return Effect.fail(\n new EvaluationError({\n diagnostic:\n Option.isSome(failure) &&\n CodegenError.isCodegenError(failure.value)\n ? CodegenError.renderCodegenError(failure.value)\n : Cause.pretty(cause),\n }),\n );\n },\n ),\n );\n\nconst handlers = requests.toLayer({\n Previous: (requestContext) =>\n evaluate(requestContext, loadPreviousFunctionPaths),\n Generate: (requestContext) =>\n evaluate(\n requestContext,\n generateWithSnapshot.pipe(Effect.map(({ snapshot }) => snapshot)),\n ),\n Validate: (request) => evaluate(request, validateImplFiles(request.paths)),\n Update: (request) =>\n evaluate(\n request,\n updateDeclarations(request.snapshot, request.declarations, request.paths),\n ),\n});\n\nRpcServer.layer(requests).pipe(\n Layer.provide(handlers),\n Layer.provide(NodeServices.layer),\n Layer.provide(\n RpcServer.layerProtocolWorkerRunner.pipe(\n Layer.provide(NodeWorkerRunner.layer),\n ),\n ),\n Layer.launch,\n Effect.ensuring(Effect.promise(() => esbuild.stop())),\n NodeRuntime.runMain,\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA0BA,MAAM,YACJ,gBACA,WAEA,OAAO,KACL,OAAO,eACL,WAAW,iBACX,eAAe,eACjB,GACA,OAAO,eAAe,aAAa,EACjC,KAAK,OAAO,QAAQ,eAAe,WAAW,EAChD,CAAC,GACD,OAAO,eAAe,kBAAkB,EACtC,KAAK,OAAO,QAA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,OAAO,cAAc,QAAQ,KAAK,CAAC,CAAC,GACpD,YAAY,OACd"}
1
+ {"version":3,"file":"EvaluationWorker.mjs","names":["CodegenError.ComponentNodeGroupError","CodegenError.isCodegenError","CodegenError.renderCodegenError"],"sources":["../src/EvaluationWorker.ts"],"sourcesContent":["import * as NodeRuntime from \"@effect/platform-node/NodeRuntime\";\nimport * as NodeServices from \"@effect/platform-node/NodeServices\";\nimport * as NodeWorkerRunner from \"@effect/platform-node/NodeWorkerRunner\";\nimport * as IdScope from \"@confect/core/IdScope\";\nimport * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as References from \"effect/References\";\nimport * as Schema from \"effect/Schema\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as RpcServer from \"effect/rpc/RpcServer\";\nimport * as esbuild from \"esbuild\";\nimport * as CodegenError from \"./CodegenError.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport type { RequestContext } from \"./Evaluation.js\";\nimport { EvaluationError, requests } from \"./Evaluation.js\";\nimport { validateImplFiles } from \"./LeafModule.js\";\nimport { ProjectRoot } from \"./ProjectRoot.js\";\nimport {\n generateWithSnapshot,\n loadPreviousFunctionPaths,\n updateDeclarations,\n} from \"./confect/codegen.js\";\n\nconst evaluate = <A, E, R>(\n requestContext: RequestContext,\n effect: Effect.Effect<A, E, R>,\n) =>\n effect.pipe(\n Effect.provideService(\n References.MinimumLogLevel,\n requestContext.minimumLogLevel,\n ),\n Effect.provideService(ProjectRoot, {\n get: Effect.succeed(requestContext.projectRoot),\n }),\n Effect.provideService(ConfectDirectory, {\n get: Effect.succeed(requestContext.confectDirectory),\n }),\n Effect.provideService(ConvexDirectory, {\n get: Effect.succeed(requestContext.convexDirectory),\n target: Match.value(requestContext.target).pipe(\n Match.when({ kind: \"app\" }, () => ({\n kind: \"app\" as const,\n scope: IdScope.app,\n })),\n Match.when({ kind: \"component\" }, ({ definition }) => ({\n kind: \"component\" as const,\n scope: IdScope.component(definition),\n })),\n Match.exhaustive,\n ),\n }),\n Effect.catchCause(\n (\n cause,\n ): Effect.Effect<\n never,\n EvaluationError | CodegenError.ComponentNodeGroupError\n > => {\n const failure = Cause.findErrorOption(cause);\n if (\n Option.isSome(failure) &&\n Schema.is(CodegenError.ComponentNodeGroupError)(failure.value)\n )\n return Effect.fail(failure.value);\n return Effect.fail(\n new EvaluationError({\n diagnostic:\n Option.isSome(failure) &&\n CodegenError.isCodegenError(failure.value)\n ? CodegenError.renderCodegenError(failure.value)\n : Cause.pretty(cause),\n }),\n );\n },\n ),\n );\n\nconst handlers = requests.toLayer({\n Ready: () => Effect.void,\n Previous: (requestContext) =>\n evaluate(requestContext, loadPreviousFunctionPaths),\n Generate: (requestContext) =>\n evaluate(\n requestContext,\n generateWithSnapshot.pipe(Effect.map(({ snapshot }) => snapshot)),\n ),\n Validate: (request) => evaluate(request, validateImplFiles(request.paths)),\n Update: (request) =>\n evaluate(\n request,\n updateDeclarations(request.snapshot, request.declarations, request.paths),\n ),\n});\n\n// Evaluators must not outlive the CLI, even when it is killed without cleanup.\nconst parentPid = process.ppid;\nprocess.once(\"disconnect\", () => process.exit(0));\nconst watchParent = Effect.sync(() => {\n if (!process.connected || process.ppid !== parentPid) process.exit(0);\n try {\n process.kill(parentPid, 0);\n } catch {\n process.exit(0);\n }\n}).pipe(Effect.repeat({ schedule: Schedule.spaced(\"1 second\") }));\n\nRpcServer.layer(requests).pipe(\n Layer.provide(handlers),\n Layer.provide(NodeServices.layer),\n Layer.provide(\n RpcServer.layerProtocolWorkerRunner.pipe(\n Layer.provide(NodeWorkerRunner.layer),\n ),\n ),\n Layer.launch,\n Effect.raceFirst(watchParent),\n Effect.ensuring(Effect.promise(() => esbuild.stop())),\n NodeRuntime.runMain,\n);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA2B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AACJ,CAAC;AAGD,MAAM,YAAY,QAAQ;AAC1B,QAAQ,KAAK,oBAAoB,QAAQ,KAAK,CAAC,CAAC;AAChD,MAAM,cAAc,OAAO,WAAW;CACpC,IAAI,CAAC,QAAQ,aAAa,QAAQ,SAAS,WAAW,QAAQ,KAAK,CAAC;CACpE,IAAI;EACF,QAAQ,KAAK,WAAW,CAAC;CAC3B,QAAQ;EACN,QAAQ,KAAK,CAAC;CAChB;AACF,CAAC,CAAC,CAAC,KAAK,OAAO,OAAO,EAAE,UAAU,SAAS,OAAO,UAAU,EAAE,CAAC,CAAC;AAEhE,UAAU,MAAM,QAAQ,CAAC,CAAC,KACxB,MAAM,QAAQ,QAAQ,GACtB,MAAM,QAAQ,aAAa,KAAK,GAChC,MAAM,QACJ,UAAU,0BAA0B,KAClC,MAAM,QAAQ,iBAAiB,KAAK,CACtC,CACF,GACA,MAAM,QACN,OAAO,UAAU,WAAW,GAC5B,OAAO,SAAS,OAAO,cAAc,QAAQ,KAAK,CAAC,CAAC,GACpD,YAAY,OACd"}
package/dist/Watcher.mjs CHANGED
@@ -18,6 +18,7 @@ import * as HashSet from "effect/HashSet";
18
18
  import * as Match from "effect/Match";
19
19
  import * as Option from "effect/Option";
20
20
  import { externalPlugin, loadTsConfig, tsconfigPathsToRegExp } from "bundle-require";
21
+ import * as Context from "effect/Context";
21
22
  import * as HashMap from "effect/HashMap";
22
23
  import * as Ref from "effect/Ref";
23
24
  import * as Scope from "effect/Scope";
@@ -26,8 +27,8 @@ import * as esbuild from "esbuild";
26
27
  import * as Order from "effect/Order";
27
28
  import * as Data from "effect/Data";
28
29
  import * as Schedule from "effect/Schedule";
29
- import * as Clock from "effect/Clock";
30
30
  import * as Duration from "effect/Duration";
31
+ import * as Clock from "effect/Clock";
31
32
  import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
32
33
  import * as Crypto from "effect/Crypto";
33
34
  import * as Hex from "effect/encoding/Hex";
@@ -37,7 +38,7 @@ import * as Queue from "effect/Queue";
37
38
  import * as Semaphore from "effect/Semaphore";
38
39
  import * as Stream from "effect/Stream";
39
40
  //#region src/Watcher.ts
40
- const COALESCE_QUIESCENCE = Duration.millis(300);
41
+ const CoalesceQuiescence = Context.Reference("@confect/cli/Watcher/CoalesceQuiescence", { defaultValue: () => Duration.millis(50) });
41
42
  const COALESCE_MAX_WAIT = Duration.seconds(5);
42
43
  const WatcherLifecycle = Data.taggedEnum();
43
44
  const RefreshOutcome = Data.taggedEnum();
@@ -61,6 +62,7 @@ var OperationError = class extends Schema.TaggedError()("WatcherOperationError",
61
62
  const ReportedBuildFailure = Schema.Struct({ errors: Schema.NonEmptyArray(Schema.Struct({ text: Schema.String })) });
62
63
  const parseFailure = Schema.decodeUnknownOption(ReportedBuildFailure);
63
64
  const make = Effect.fnUntraced(function* () {
65
+ const quiescence = yield* CoalesceQuiescence;
64
66
  const signal = yield* Queue.sliding(1);
65
67
  const pendingRef = yield* Ref.make(empty);
66
68
  const restartQueue = yield* Queue.sliding(1);
@@ -88,7 +90,7 @@ const make = Effect.fnUntraced(function* () {
88
90
  duringRestore: Effect.flatten(Ref.get(duringRestoreRef)),
89
91
  discardRestoreEchoes: refresh(state).pipe(Effect.ignore, Effect.andThen(Ref.set(pendingRef, empty))),
90
92
  refresh: refresh(state),
91
- next: Queue.take(signal).pipe(Effect.andThen(drainUntilQuiescent(signal, COALESCE_QUIESCENCE, COALESCE_MAX_WAIT)), Effect.andThen(state.topology.takePending), Effect.onInterrupt(() => Queue.offer(signal, void 0))),
93
+ next: Queue.take(signal).pipe(Effect.andThen(drainUntilQuiescent(signal, quiescence, COALESCE_MAX_WAIT)), Effect.andThen(state.topology.takePending), Effect.onInterrupt(() => Queue.offer(signal, void 0))),
92
94
  pending: Ref.get(pendingRef),
93
95
  requestRetry: Ref.update(pendingRef, full).pipe(Effect.andThen(Queue.offer(signal, void 0)), Effect.asVoid),
94
96
  diagnostics: Ref.get(state.observation).pipe(Effect.map(diagnostics))
@@ -98,7 +100,8 @@ const drainUntilQuiescent = Effect.fnUntraced(function* (signal, quiescence, max
98
100
  const start = yield* Clock.currentTimeMillis;
99
101
  const maxMillis = Duration.toMillis(maxWait);
100
102
  const loop = Effect.gen(function* () {
101
- yield* Effect.sleep(quiescence);
103
+ const elapsed = (yield* Clock.currentTimeMillis) - start;
104
+ yield* Effect.sleep(Duration.millis(Math.min(Duration.toMillis(quiescence), Math.max(0, maxMillis - elapsed))));
102
105
  if ((yield* Queue.clear(signal)).length === 0) return;
103
106
  if ((yield* Clock.currentTimeMillis) - start < maxMillis) yield* loop;
104
107
  });
@@ -372,6 +375,6 @@ const handleConfectChange = ({ relativePath, eventTag, signal, pendingRef, resta
372
375
  return Match.value(eventTag).pipe(Match.when("Create", () => flipDirtyAndSignal(pendingRef, signal, restart, false)), Match.whenOr("Update", "Remove", () => Effect.void), Match.exhaustive);
373
376
  };
374
377
  //#endregion
375
- export { OperationError, isRefreshSuccessful, make, parseFailure };
378
+ export { CoalesceQuiescence, OperationError, isRefreshSuccessful, make, parseFailure };
376
379
 
377
380
  //# sourceMappingURL=Watcher.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"Watcher.mjs","names":["SyncState.empty","WatchTopology.make","RestoreWatcher.make","SyncState.full","WatchBuild.diagnostics","Bundler.bundleWorkspacePlugin","WatchBuild.start","WatchBuild.emptyCapture","WatchBuild.parse","WatchBuild.observe","WatchBuild.diff","SyncState.add","SyncState.reconcile","WatchBuild.complete","EntryPoint.discover","EntryPoint.isOptional","WatchBuild.initialProgress","WatchBuild.makeRequestId","WatchBuild.verifyInputs","WatchBuild.captureBarrier","WatchBuild.request","WatchBuild.getCompletion","WatchBuild.joinedWithoutCompletion","WatchBuild.isFresh","WatchBuild.endRequest","EntryPoint.parse"],"sources":["../src/Watcher.ts"],"sourcesContent":["import * as Clock from \"effect/Clock\";\nimport * as Duration from \"effect/Duration\";\nimport * as NodeCrypto from \"@effect/platform-node/NodeCrypto\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Hex from \"effect/encoding/Hex\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Data from \"effect/Data\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as HashMap from \"effect/HashMap\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Order from \"effect/Order\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Scope from \"effect/Scope\";\nimport * as Schema from \"effect/Schema\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Stream from \"effect/Stream\";\nimport {\n externalPlugin,\n loadTsConfig,\n tsconfigPathsToRegExp,\n} from \"bundle-require\";\nimport * as esbuild from \"esbuild\";\nimport * as Bundler from \"./Bundler.js\";\nimport * as WatchBuild from \"./WatchBuild.js\";\nimport * as WatchTopology from \"./WatchTopology.js\";\nimport * as SyncState from \"./SyncState.js\";\nimport type { Pending } from \"./SyncState.js\";\nimport * as EntryPoint from \"./EntryPoint.js\";\nimport type { EntryPoint as Entry } from \"./EntryPoint.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { CONVEX_CONFIG_FILENAME } from \"./ConvexConfig.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport { ProjectRoot } from \"./ProjectRoot.js\";\nimport * as RestoreWatcher from \"./RestoreWatcher.js\";\n\nconst COALESCE_QUIESCENCE = Duration.millis(300);\n\n// Upper bound on `drainUntilQuiescent` so a pathological infinite\n// signal stream can't pin the sync loop forever.\nconst COALESCE_MAX_WAIT = Duration.seconds(5);\n\ntype WatcherLifecycle = Data.TaggedEnum<{\n Uninitialized: {};\n Empty: {};\n Active: {\n readonly initial: Deferred.Deferred<void>;\n readonly key: string;\n readonly scope: Scope.Closeable;\n readonly entries: Array.NonEmptyReadonlyArray<Entry>;\n readonly context: esbuild.BuildContext;\n readonly identifyRequest: (\n promise: Promise<esbuild.BuildResult>,\n ) => WatchBuild.RequestId;\n readonly progress: Ref.Ref<WatchBuild.Progress>;\n readonly verifyInputs: (\n snapshot: WatchBuild.Snapshot,\n ) => ReturnType<typeof WatchBuild.verifyInputs>;\n };\n}>;\nconst WatcherLifecycle = Data.taggedEnum<WatcherLifecycle>();\n\ninterface State {\n readonly lifecycle: Ref.Ref<WatcherLifecycle>;\n readonly observation: Ref.Ref<WatchBuild.State>;\n readonly lock: Semaphore.Semaphore;\n readonly topology: WatchTopology.WatchTopology;\n // Whether the last discovery found `confect/app.ts`.\n readonly declared: Ref.Ref<boolean>;\n}\n\ntype RefreshOutcome = Data.TaggedEnum<{\n Empty: {};\n Observed: { readonly outcome: WatchBuild.Outcome };\n}>;\nconst RefreshOutcome = Data.taggedEnum<RefreshOutcome>();\n\nexport const isRefreshSuccessful = (outcome: RefreshOutcome): boolean =>\n RefreshOutcome.$match(outcome, {\n Empty: () => true,\n Observed: ({ outcome: observed }) =>\n WatchBuild.Outcome.$match(observed, {\n Succeeded: () => true,\n Failed: () => false,\n }),\n });\n\nexport class OperationError extends Schema.TaggedError<OperationError>()(\n \"WatcherOperationError\",\n {\n operation: Schema.Literals([\n \"create\",\n \"watch\",\n \"rebuild\",\n \"dispose\",\n \"refresh\",\n ]),\n cause: Schema.Unknown,\n },\n) {}\n\nconst ReportedBuildFailure = Schema.Struct({\n errors: Schema.NonEmptyArray(Schema.Struct({ text: Schema.String })),\n});\nexport const parseFailure = Schema.decodeUnknownOption(ReportedBuildFailure);\n\nexport const make = Effect.fnUntraced(function* () {\n const signal = yield* Queue.sliding<void>(1);\n const pendingRef = yield* Ref.make<Pending>(SyncState.empty);\n const restartQueue = yield* Queue.sliding<void>(1);\n const state: State = {\n lifecycle: yield* Ref.make<WatcherLifecycle>(\n WatcherLifecycle.Uninitialized(),\n ),\n observation: yield* Ref.make<WatchBuild.State>(WatchBuild.State.Initial()),\n lock: yield* Semaphore.make(1),\n topology: yield* WatchTopology.make(pendingRef),\n declared: yield* Ref.make(false),\n };\n const restartWith = (invalidation: Effect.Effect<void>) =>\n invalidation.pipe(\n Effect.andThen(Queue.offer(restartQueue, undefined)),\n Effect.andThen(Queue.offer(signal, undefined)),\n );\n const restart = restartWith(state.topology.invalidate);\n const restartEntry = (entry: EntryPoint.Kind) =>\n restartWith(state.topology.invalidateEntry(entry));\n const duringRestoreRef = yield* Ref.make<\n Effect.Effect<void, never, Scope.Scope>\n >(Effect.void);\n return {\n run: Effect.gen(function* () {\n const structure = yield* RestoreWatcher.make(\n confectStructureWatcher(signal, pendingRef, restart, restartEntry),\n );\n yield* Ref.set(duringRestoreRef, structure.duringRestore);\n yield* Effect.all(\n [\n Effect.scoped(\n entryPointsWatcher(signal, pendingRef, restartQueue, state),\n ),\n structure.failure,\n convexConfigStructureWatcher(restart, state.declared),\n ],\n { concurrency: \"unbounded\" },\n );\n }).pipe(Effect.scoped),\n duringRestore: Effect.flatten(Ref.get(duringRestoreRef)),\n // Restored output makes esbuild rebuild; observe that, then drop the work\n // it queued so the restore does not trigger another generation.\n discardRestoreEchoes: refresh(state).pipe(\n Effect.ignore,\n Effect.andThen(Ref.set(pendingRef, SyncState.empty)),\n ),\n refresh: refresh(state),\n next: Queue.take(signal).pipe(\n Effect.andThen(\n drainUntilQuiescent(signal, COALESCE_QUIESCENCE, COALESCE_MAX_WAIT),\n ),\n Effect.andThen(state.topology.takePending),\n Effect.onInterrupt(() => Queue.offer(signal, undefined)),\n ),\n pending: Ref.get(pendingRef),\n requestRetry: Ref.update(pendingRef, SyncState.full).pipe(\n Effect.andThen(Queue.offer(signal, undefined)),\n Effect.asVoid,\n ),\n diagnostics: Ref.get(state.observation).pipe(\n Effect.map(WatchBuild.diagnostics),\n ),\n } as const;\n});\n\nexport type Watcher = Effect.Success<ReturnType<typeof make>>;\n\nconst drainUntilQuiescent = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n quiescence: Duration.Duration,\n maxWait: Duration.Duration,\n) {\n const start = yield* Clock.currentTimeMillis;\n const maxMillis = Duration.toMillis(maxWait);\n const loop: Effect.Effect<void> = Effect.gen(function* () {\n yield* Effect.sleep(quiescence);\n const drained = yield* Queue.clear(signal);\n if (drained.length === 0) return;\n const now = yield* Clock.currentTimeMillis;\n if (now - start < maxMillis) {\n yield* loop;\n }\n });\n yield* loop;\n});\n\nconst esbuildOptions = (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n crypto: Crypto.Crypto,\n projectRoot: string,\n generatedDirectory: string,\n entries: ReadonlyArray<Entry>,\n notExternal: ReadonlyArray<RegExp>,\n stateRef: Ref.Ref<WatchBuild.State>,\n captureRef: Ref.Ref<WatchBuild.Capture>,\n progressRef: Ref.Ref<WatchBuild.Progress>,\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n initial: Deferred.Deferred<void>,\n): esbuild.BuildOptions => {\n const encodeString = Schema.encodeSync(Schema.fromJsonString(Schema.String));\n return {\n absWorkingDir: projectRoot,\n stdin: {\n contents: entries\n .map((entry) => `import ${encodeString(entry.absolutePath)};`)\n .join(\"\\n\"),\n resolveDir: projectRoot,\n sourcefile: \"confect-watch.ts\",\n loader: \"ts\",\n },\n bundle: true,\n write: false,\n metafile: true,\n platform: \"node\",\n format: \"esm\",\n logLevel: \"silent\",\n plugins: [\n Bundler.bundleWorkspacePlugin(path, fs, notExternal),\n externalPlugin({ notExternal: [...notExternal] }),\n {\n name: \"notify-rebuild\",\n setup(build) {\n build.onStart(() =>\n Effect.runPromise(\n Effect.gen(function* () {\n yield* Ref.update(progressRef, WatchBuild.start);\n yield* Ref.set(captureRef, WatchBuild.emptyCapture);\n }).pipe(Effect.as(undefined)),\n ),\n );\n build.onLoad({ filter: /.*/ }, (args) =>\n Effect.runPromise(\n Effect.gen(function* () {\n const fingerprint = yield* fs.readFile(args.path).pipe(\n Effect.flatMap((contents) =>\n crypto.digest(\"SHA-256\", contents),\n ),\n Effect.map(Hex.encode),\n Effect.result,\n );\n yield* Ref.update(captureRef, (capture) =>\n Result.isSuccess(fingerprint)\n ? {\n ...capture,\n fingerprints: HashMap.set(\n capture.fingerprints,\n args.path,\n fingerprint.success,\n ),\n }\n : {\n ...capture,\n failures: HashMap.set(\n capture.failures,\n args.path,\n WatchBuild.Failure.InputCaptureFailed({\n file: args.path,\n cause: fingerprint.failure,\n }),\n ),\n },\n );\n }).pipe(Effect.as(undefined)),\n ),\n );\n build.onEnd((result) =>\n Effect.runPromise(\n Effect.gen(function* () {\n const { generation } = yield* Ref.get(progressRef);\n const previous = yield* Ref.get(stateRef);\n const outcome = yield* WatchBuild.parse(\n result,\n yield* Ref.get(captureRef),\n (file) => path.resolve(projectRoot, file),\n crypto,\n );\n const current = WatchBuild.observe(previous, outcome);\n yield* Ref.set(stateRef, current);\n const change = WatchBuild.diff(\n previous,\n current,\n generatedDirectory + path.sep,\n );\n yield* Ref.update(pendingRef, (pending) =>\n WatchBuild.Change.$match(change, {\n Full: () => SyncState.add(pending, entries, true),\n Affected: ({ paths }) =>\n SyncState.add(\n pending,\n entries.filter((entry) =>\n HashSet.has(paths, entry.inputPath),\n ),\n ),\n Recovered: ({ paths }) =>\n SyncState.reconcile(\n SyncState.add(\n pending,\n entries.filter((entry) =>\n HashSet.has(paths, entry.inputPath),\n ),\n ),\n ),\n }),\n );\n yield* Queue.offer(signal, undefined);\n yield* Ref.update(progressRef, (progress) =>\n WatchBuild.complete(progress, { generation, outcome }),\n );\n yield* Deferred.succeed(initial, undefined);\n }),\n ),\n );\n },\n },\n ],\n };\n};\n\nconst entryPointsWatcher = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n restartQueue: Queue.Queue<void>,\n watcher: State,\n) {\n const parentScope = yield* Effect.scope;\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const projectRoot = yield* ProjectRoot.get;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedDirectory = path.join(\n yield* fs.realPath(confectDirectory),\n \"_generated\",\n );\n const crypto = yield* Crypto.Crypto;\n const completedInitial = Deferred.make<void>().pipe(\n Effect.tap((initial) => Deferred.succeed(initial, undefined)),\n );\n\n const sync = Effect.gen(function* () {\n const revision = yield* watcher.topology.revision;\n const current = yield* Ref.get(watcher.lifecycle);\n const entries = yield* EntryPoint.discover;\n yield* Ref.set(watcher.declared, entries.some(EntryPoint.Kind.$is(\"App\")));\n const desiredPaths = HashSet.fromIterable(\n entries.map((entry) => entry.absolutePath),\n );\n const key = pipe(\n Array.fromIterable(desiredPaths),\n Array.sort(Order.String),\n Array.join(\"\\n\"),\n );\n const unchanged = WatcherLifecycle.$match(current, {\n Uninitialized: () => false,\n Empty: () => entries.length === 0,\n Active: ({ key: previousKey }) => previousKey === key,\n });\n if (unchanged) {\n const initial = yield* WatcherLifecycle.$match(current, {\n Uninitialized: () => completedInitial,\n Empty: () => completedInitial,\n Active: ({ initial: activeInitial }) => Effect.succeed(activeInitial),\n });\n yield* refreshCurrent(current).pipe(\n Effect.catchTag(\"WatcherOperationError\", () =>\n Ref.update(pendingRef, SyncState.full),\n ),\n );\n yield* watcher.topology.reconcile(revision, initial);\n return;\n }\n yield* WatcherLifecycle.$match(current, {\n Uninitialized: () => Effect.void,\n Empty: () => Ref.update(pendingRef, SyncState.full),\n Active: ({ entries: previousEntries, scope }) =>\n Effect.gen(function* () {\n const removedOptional = previousEntries.filter(\n (entry) =>\n EntryPoint.isOptional(entry) &&\n !HashSet.has(desiredPaths, entry.absolutePath),\n );\n yield* Ref.update(pendingRef, (pending) =>\n SyncState.add(SyncState.full(pending), removedOptional),\n );\n yield* Scope.close(scope, Exit.void);\n }),\n });\n yield* Ref.set(watcher.lifecycle, WatcherLifecycle.Uninitialized());\n yield* Ref.set(watcher.observation, WatchBuild.State.Initial());\n if (!Array.isReadonlyArrayNonEmpty(entries)) {\n yield* Ref.set(watcher.lifecycle, WatcherLifecycle.Empty());\n yield* Ref.update(pendingRef, SyncState.full);\n yield* Queue.offer(signal, undefined);\n const initial = yield* completedInitial;\n yield* watcher.topology.reconcile(revision, initial);\n return;\n }\n\n const scope = yield* Scope.fork(parentScope, \"sequential\");\n const captureRef = yield* Ref.make(WatchBuild.emptyCapture);\n const progress = yield* Ref.make(WatchBuild.initialProgress);\n const initial = yield* Deferred.make<void>();\n const tsconfig = loadTsConfig(projectRoot);\n const notExternal = tsconfigPathsToRegExp(\n tsconfig?.data.compilerOptions?.paths ?? {},\n );\n const context = yield* Effect.acquireRelease(\n Effect.tryPromise({\n try: () =>\n esbuild.context(\n esbuildOptions(\n path,\n fs,\n crypto,\n projectRoot,\n generatedDirectory,\n entries,\n notExternal,\n watcher.observation,\n captureRef,\n progress,\n signal,\n pendingRef,\n initial,\n ),\n ),\n catch: (cause) => new OperationError({ operation: \"create\", cause }),\n }),\n (ctx) =>\n Effect.tryPromise({\n try: () => ctx.dispose(),\n catch: (cause) => new OperationError({ operation: \"dispose\", cause }),\n }).pipe(Effect.orDie),\n ).pipe(Scope.provide(scope));\n const requestIds = new WeakMap<\n Promise<esbuild.BuildResult>,\n WatchBuild.RequestId\n >();\n yield* Ref.set(\n watcher.lifecycle,\n WatcherLifecycle.Active({\n initial,\n key,\n scope,\n entries,\n context,\n identifyRequest: (promise) => {\n const existing = requestIds.get(promise);\n if (existing !== undefined) return existing;\n const id = WatchBuild.makeRequestId();\n requestIds.set(promise, id);\n return id;\n },\n progress,\n verifyInputs: (snapshot) =>\n WatchBuild.verifyInputs(snapshot, fs, crypto),\n }),\n );\n yield* Effect.tryPromise({\n try: () => context.watch(),\n catch: (cause) => new OperationError({ operation: \"watch\", cause }),\n });\n yield* watcher.topology.reconcile(revision, initial);\n }).pipe(Semaphore.withPermit(watcher.lock));\n\n yield* sync;\n return yield* Effect.forever(\n Queue.take(restartQueue).pipe(Effect.andThen(sync)),\n );\n}, Effect.provide(NodeCrypto.layer));\n\nconst refreshCurrent = Effect.fnUntraced(function* (current: WatcherLifecycle) {\n return yield* WatcherLifecycle.$match(current, {\n Empty: () => Effect.succeed(RefreshOutcome.Empty()),\n Uninitialized: () =>\n Effect.fail(\n new OperationError({\n operation: \"refresh\",\n cause: \"The dependency watcher is not initialized\",\n }),\n ),\n Active: ({ context, identifyRequest, progress, verifyInputs }) =>\n Effect.gen(function* () {\n const runSync = Effect.runSyncWith(yield* Effect.context());\n const barrier = WatchBuild.captureBarrier(yield* Ref.get(progress));\n const rebuild = Effect.gen(function* () {\n const built = yield* Effect.tryPromise({\n try: () => {\n const promise = context.rebuild();\n runSync(\n Ref.update(progress, (currentProgress) =>\n WatchBuild.request(currentProgress, identifyRequest(promise)),\n ),\n );\n return promise;\n },\n catch: (cause) =>\n new OperationError({ operation: \"rebuild\", cause }),\n }).pipe(Effect.result);\n const currentProgress = yield* Ref.get(progress);\n const completed = WatchBuild.getCompletion(currentProgress);\n if (Result.isFailure(built)) {\n const rejected = parseFailure(built.failure.cause);\n if (Option.isNone(rejected)) return yield* built.failure;\n if (WatchBuild.joinedWithoutCompletion(currentProgress))\n return Option.none<WatchBuild.Completion>();\n if (\n Option.isNone(completed) ||\n !WatchBuild.Outcome.$is(\"Failed\")(completed.value.outcome)\n )\n return yield* new OperationError({\n operation: \"rebuild\",\n cause: rejected.value.errors,\n });\n }\n if (WatchBuild.joinedWithoutCompletion(currentProgress))\n return Option.none<WatchBuild.Completion>();\n const observed = yield* Effect.fromOption(completed).pipe(\n Effect.mapError(\n () =>\n new OperationError({\n operation: \"rebuild\",\n cause: \"esbuild completed without a build observation\",\n }),\n ),\n );\n if (\n WatchBuild.isFresh(barrier, observed) &&\n WatchBuild.Outcome.$is(\"Succeeded\")(observed.outcome)\n ) {\n const unchanged = yield* verifyInputs(\n observed.outcome.snapshot,\n ).pipe(\n Effect.mapError(\n ({ cause }) =>\n new OperationError({ operation: \"refresh\", cause }),\n ),\n );\n if (!unchanged) return Option.none<WatchBuild.Completion>();\n }\n return Option.some(observed);\n }).pipe(Effect.ensuring(Ref.update(progress, WatchBuild.endRequest)));\n const completed = yield* rebuild.pipe(\n Effect.repeat({\n while: (observed) =>\n Option.isNone(observed) ||\n !WatchBuild.isFresh(barrier, observed.value),\n }),\n Effect.flatMap((observed) =>\n Effect.fromOption(observed).pipe(Effect.orDie),\n ),\n );\n return RefreshOutcome.Observed({ outcome: completed.outcome });\n }),\n });\n});\n\nconst refresh = (watcher: State) =>\n watcher.lock.withPermit(\n Ref.get(watcher.lifecycle).pipe(Effect.flatMap(refreshCurrent)),\n );\n\nconst confectStructureWatcher = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n restart: Effect.Effect<unknown>,\n restartEntry: (entry: EntryPoint.Kind) => Effect.Effect<unknown>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const removedDirectory = Schema.Struct({\n code: Schema.Literal(\"ENOENT\"),\n syscall: Schema.Literal(\"scandir\"),\n path: Schema.String,\n });\n\n yield* pipe(\n fs.watch(confectDirectory, { recursive: true }),\n Stream.runForEach((event) =>\n handleConfectChange({\n relativePath: path.relative(\n confectDirectory,\n path.resolve(confectDirectory, event.path),\n ),\n eventTag: event._tag,\n signal,\n pendingRef,\n restart,\n restartEntry,\n }),\n ),\n Effect.retry({\n schedule: Schedule.spaced(\"10 millis\"),\n while: (error) =>\n Effect.gen(function* () {\n const removed = Schema.decodeUnknownOption(removedDirectory)(\n error.reason.cause,\n );\n if (Option.isNone(removed)) return false;\n const relative = path.relative(confectDirectory, removed.value.path);\n if (\n relative === \"\" ||\n relative === \"..\" ||\n relative.startsWith(`..${path.sep}`) ||\n path.isAbsolute(relative)\n )\n return false;\n if (\n !(yield* fs\n .exists(confectDirectory)\n .pipe(Effect.orElseSucceed(() => false)))\n ) {\n return false;\n }\n yield* restart;\n return true;\n }),\n }),\n );\n});\n\n/**\n * Non-recursive `fs.watch` on the convex directory, reacting only to\n * `convex.config.ts`. Recursion is deliberately avoided: codegen (Confect's and\n * Convex's) writes into `convex/` and `convex/_generated/` constantly, and\n * reacting to those writes would loop. Create/Remove offers to `restartQueue`\n * so the entry-point watcher set picks up (or drops) the config's esbuild\n * watcher.\n */\nconst convexConfigStructureWatcher = Effect.fnUntraced(function* (\n restart: Effect.Effect<unknown>,\n declared: Ref.Ref<boolean>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n yield* pipe(\n fs.watch(convexDirectory),\n Stream.runForEach((event) =>\n Effect.gen(function* () {\n // A declared backend's config is codegen output; reacting to its\n // writes would rerun codegen for nothing.\n if (\n path.relative(convexDirectory, event.path) !==\n CONVEX_CONFIG_FILENAME ||\n (yield* Ref.get(declared))\n )\n return;\n yield* Match.value(event).pipe(\n Match.tag(\"Update\", () => Effect.void),\n Match.tag(\"Create\", \"Remove\", () => restart),\n Match.exhaustive,\n );\n }),\n ),\n );\n});\n\nconst flipDirtyAndSignal = (\n pendingRef: Ref.Ref<Pending>,\n signal: Queue.Queue<void>,\n restart: Effect.Effect<unknown>,\n isLifecycleChange: boolean,\n) =>\n isLifecycleChange\n ? restart\n : Ref.update(pendingRef, SyncState.full).pipe(\n Effect.andThen(Queue.offer(signal, undefined)),\n );\n\nconst handleConfectChange = ({\n relativePath,\n eventTag,\n signal,\n pendingRef,\n restart,\n restartEntry,\n}: {\n relativePath: string;\n eventTag: \"Create\" | \"Update\" | \"Remove\";\n signal: Queue.Queue<void>;\n pendingRef: Ref.Ref<Pending>;\n restart: Effect.Effect<unknown>;\n restartEntry: (entry: EntryPoint.Kind) => Effect.Effect<unknown>;\n}) => {\n if (relativePath.split(/[/\\\\]/).includes(\"_generated\")) {\n return Effect.void;\n }\n\n if (!relativePath.endsWith(\".ts\")) {\n return Effect.void;\n }\n\n const isLifecycleChange = Match.value(eventTag).pipe(\n Match.when(\"Update\", () => false),\n Match.whenOr(\"Create\", \"Remove\", () => true),\n Match.exhaustive,\n );\n\n const entry = EntryPoint.parse(relativePath);\n if (Option.isSome(entry)) {\n return isLifecycleChange ? restartEntry(entry.value) : Effect.void;\n }\n\n // A stray `confect/schema.ts` (now codegen-owned at\n // `_generated/schema.ts`) shouldn't exist; flagging it here ensures the\n // next codegen pass surfaces the migration error\n // (`LegacySchemaFileError`) instead of silently ignoring the file.\n if (relativePath === \"schema.ts\") {\n return flipDirtyAndSignal(pendingRef, signal, restart, isLifecycleChange);\n }\n\n // Any other `.ts` under `confect/` (helpers like `tables/notes.ts`).\n // Updates to such files are handled by the esbuild watcher for whichever\n // entry point imports them—its onEnd flips the right dirty flag.\n // Creates are our safety net: when a previously-missing import is added,\n // esbuild may not have its parent directory on a poll path, so we\n // re-run codegen on Create here.\n return Match.value(eventTag).pipe(\n Match.when(\"Create\", () =>\n flipDirtyAndSignal(pendingRef, signal, restart, false),\n ),\n Match.whenOr(\"Update\", \"Remove\", () => Effect.void),\n Match.exhaustive,\n );\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,sBAAsB,SAAS,OAAO,GAAG;AAI/C,MAAM,oBAAoB,SAAS,QAAQ,CAAC;AAoB5C,MAAM,mBAAmB,KAAK,WAA6B;AAe3D,MAAM,iBAAiB,KAAK,WAA2B;AAEvD,MAAa,uBAAuB,YAClC,eAAe,OAAO,SAAS;CAC7B,aAAa;CACb,WAAW,EAAE,SAAS,eAAA,QACD,OAAO,UAAU;EAClC,iBAAiB;EACjB,cAAc;CAChB,CAAC;AACL,CAAC;AAEH,IAAa,iBAAb,cAAoC,OAAO,YAA4B,CAAC,CACtE,yBACA;CACE,WAAW,OAAO,SAAS;EACzB;EACA;EACA;EACA;EACA;CACF,CAAC;CACD,OAAO,OAAO;AAChB,CACF,CAAC,CAAC,CAAC;AAEH,MAAM,uBAAuB,OAAO,OAAO,EACzC,QAAQ,OAAO,cAAc,OAA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,KAAK,SAAS,iBAAiB,MAAM,IAAI,MAAA,uBAExC,OAAO,IAAI,IAAI,QAAQ,IAExB;EACF,OAAO,MAAM,MAAM,KAAK,CAAC,CAAC,KACxB,MAAM,IAAI,gBAAgB,OAAO,IAAI,GACrC,MAAM,IAAI,UAAU,gBAAgB,OAAO,GAC3C,MAAM,UACR;CACF,CAAC,CACH,CACF;AACF,CAAC;AAED,MAAM,sBACJ,YACA,QACA,SACA,sBAEA,oBACI,UACA,IAAI,OAAO,YAAYpB,IAAc,CAAC,CAAC,KACrC,OAAO,QAAQ,MAAM,MAAM,QAAQ,KAAA,CAAS,CAAC,CAC/C;AAEN,MAAM,uBAAuB,EAC3B,cACA,UACA,QACA,YACA,SACA,mBAQI;CACJ,IAAI,aAAa,MAAM,OAAO,CAAC,CAAC,SAAS,YAAY,GACnD,OAAO,OAAO;CAGhB,IAAI,CAAC,aAAa,SAAS,KAAK,GAC9B,OAAO,OAAO;CAGhB,MAAM,oBAAoB,MAAM,MAAM,QAAQ,CAAC,CAAC,KAC9C,MAAM,KAAK,gBAAgB,KAAK,GAChC,MAAM,OAAO,UAAU,gBAAgB,IAAI,GAC3C,MAAM,UACR;CAEA,MAAM,QAAQsB,MAAiB,YAAY;CAC3C,IAAI,OAAO,OAAO,KAAK,GACrB,OAAO,oBAAoB,aAAa,MAAM,KAAK,IAAI,OAAO;CAOhE,IAAI,iBAAiB,aACnB,OAAO,mBAAmB,YAAY,QAAQ,SAAS,iBAAiB;CAS1E,OAAO,MAAM,MAAM,QAAQ,CAAC,CAAC,KAC3B,MAAM,KAAK,gBACT,mBAAmB,YAAY,QAAQ,SAAS,KAAK,CACvD,GACA,MAAM,OAAO,UAAU,gBAAgB,OAAO,IAAI,GAClD,MAAM,UACR;AACF"}
1
+ {"version":3,"file":"Watcher.mjs","names":["SyncState.empty","WatchTopology.make","RestoreWatcher.make","SyncState.full","WatchBuild.diagnostics","Bundler.bundleWorkspacePlugin","WatchBuild.start","WatchBuild.emptyCapture","WatchBuild.parse","WatchBuild.observe","WatchBuild.diff","SyncState.add","SyncState.reconcile","WatchBuild.complete","EntryPoint.discover","EntryPoint.isOptional","WatchBuild.initialProgress","WatchBuild.makeRequestId","WatchBuild.verifyInputs","WatchBuild.captureBarrier","WatchBuild.request","WatchBuild.getCompletion","WatchBuild.joinedWithoutCompletion","WatchBuild.isFresh","WatchBuild.endRequest","EntryPoint.parse"],"sources":["../src/Watcher.ts"],"sourcesContent":["import * as Clock from \"effect/Clock\";\nimport * as Context from \"effect/Context\";\nimport * as Duration from \"effect/Duration\";\nimport * as NodeCrypto from \"@effect/platform-node/NodeCrypto\";\nimport * as Crypto from \"effect/Crypto\";\nimport * as Hex from \"effect/encoding/Hex\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Data from \"effect/Data\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as HashMap from \"effect/HashMap\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Order from \"effect/Order\";\nimport * as Queue from \"effect/Queue\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport * as Scope from \"effect/Scope\";\nimport * as Schema from \"effect/Schema\";\nimport * as Schedule from \"effect/Schedule\";\nimport * as Stream from \"effect/Stream\";\nimport {\n externalPlugin,\n loadTsConfig,\n tsconfigPathsToRegExp,\n} from \"bundle-require\";\nimport * as esbuild from \"esbuild\";\nimport * as Bundler from \"./Bundler.js\";\nimport * as WatchBuild from \"./WatchBuild.js\";\nimport * as WatchTopology from \"./WatchTopology.js\";\nimport * as SyncState from \"./SyncState.js\";\nimport type { Pending } from \"./SyncState.js\";\nimport * as EntryPoint from \"./EntryPoint.js\";\nimport type { EntryPoint as Entry } from \"./EntryPoint.js\";\nimport { ConfectDirectory } from \"./ConfectDirectory.js\";\nimport { CONVEX_CONFIG_FILENAME } from \"./ConvexConfig.js\";\nimport { ConvexDirectory } from \"./ConvexDirectory.js\";\nimport { ProjectRoot } from \"./ProjectRoot.js\";\nimport * as RestoreWatcher from \"./RestoreWatcher.js\";\n\nexport const CoalesceQuiescence = Context.Reference<Duration.Duration>(\n \"@confect/cli/Watcher/CoalesceQuiescence\",\n { defaultValue: () => Duration.millis(50) },\n);\n\n// Upper bound on `drainUntilQuiescent` so a pathological infinite\n// signal stream can't pin the sync loop forever.\nconst COALESCE_MAX_WAIT = Duration.seconds(5);\n\ntype WatcherLifecycle = Data.TaggedEnum<{\n Uninitialized: {};\n Empty: {};\n Active: {\n readonly initial: Deferred.Deferred<void>;\n readonly key: string;\n readonly scope: Scope.Closeable;\n readonly entries: Array.NonEmptyReadonlyArray<Entry>;\n readonly context: esbuild.BuildContext;\n readonly identifyRequest: (\n promise: Promise<esbuild.BuildResult>,\n ) => WatchBuild.RequestId;\n readonly progress: Ref.Ref<WatchBuild.Progress>;\n readonly verifyInputs: (\n snapshot: WatchBuild.Snapshot,\n ) => ReturnType<typeof WatchBuild.verifyInputs>;\n };\n}>;\nconst WatcherLifecycle = Data.taggedEnum<WatcherLifecycle>();\n\ninterface State {\n readonly lifecycle: Ref.Ref<WatcherLifecycle>;\n readonly observation: Ref.Ref<WatchBuild.State>;\n readonly lock: Semaphore.Semaphore;\n readonly topology: WatchTopology.WatchTopology;\n // Whether the last discovery found `confect/app.ts`.\n readonly declared: Ref.Ref<boolean>;\n}\n\ntype RefreshOutcome = Data.TaggedEnum<{\n Empty: {};\n Observed: { readonly outcome: WatchBuild.Outcome };\n}>;\nconst RefreshOutcome = Data.taggedEnum<RefreshOutcome>();\n\nexport const isRefreshSuccessful = (outcome: RefreshOutcome): boolean =>\n RefreshOutcome.$match(outcome, {\n Empty: () => true,\n Observed: ({ outcome: observed }) =>\n WatchBuild.Outcome.$match(observed, {\n Succeeded: () => true,\n Failed: () => false,\n }),\n });\n\nexport class OperationError extends Schema.TaggedError<OperationError>()(\n \"WatcherOperationError\",\n {\n operation: Schema.Literals([\n \"create\",\n \"watch\",\n \"rebuild\",\n \"dispose\",\n \"refresh\",\n ]),\n cause: Schema.Unknown,\n },\n) {}\n\nconst ReportedBuildFailure = Schema.Struct({\n errors: Schema.NonEmptyArray(Schema.Struct({ text: Schema.String })),\n});\nexport const parseFailure = Schema.decodeUnknownOption(ReportedBuildFailure);\n\nexport const make = Effect.fnUntraced(function* () {\n const quiescence = yield* CoalesceQuiescence;\n const signal = yield* Queue.sliding<void>(1);\n const pendingRef = yield* Ref.make<Pending>(SyncState.empty);\n const restartQueue = yield* Queue.sliding<void>(1);\n const state: State = {\n lifecycle: yield* Ref.make<WatcherLifecycle>(\n WatcherLifecycle.Uninitialized(),\n ),\n observation: yield* Ref.make<WatchBuild.State>(WatchBuild.State.Initial()),\n lock: yield* Semaphore.make(1),\n topology: yield* WatchTopology.make(pendingRef),\n declared: yield* Ref.make(false),\n };\n const restartWith = (invalidation: Effect.Effect<void>) =>\n invalidation.pipe(\n Effect.andThen(Queue.offer(restartQueue, undefined)),\n Effect.andThen(Queue.offer(signal, undefined)),\n );\n const restart = restartWith(state.topology.invalidate);\n const restartEntry = (entry: EntryPoint.Kind) =>\n restartWith(state.topology.invalidateEntry(entry));\n const duringRestoreRef = yield* Ref.make<\n Effect.Effect<void, never, Scope.Scope>\n >(Effect.void);\n return {\n run: Effect.gen(function* () {\n const structure = yield* RestoreWatcher.make(\n confectStructureWatcher(signal, pendingRef, restart, restartEntry),\n );\n yield* Ref.set(duringRestoreRef, structure.duringRestore);\n yield* Effect.all(\n [\n Effect.scoped(\n entryPointsWatcher(signal, pendingRef, restartQueue, state),\n ),\n structure.failure,\n convexConfigStructureWatcher(restart, state.declared),\n ],\n { concurrency: \"unbounded\" },\n );\n }).pipe(Effect.scoped),\n duringRestore: Effect.flatten(Ref.get(duringRestoreRef)),\n // Restored output makes esbuild rebuild; observe that, then drop the work\n // it queued so the restore does not trigger another generation.\n discardRestoreEchoes: refresh(state).pipe(\n Effect.ignore,\n Effect.andThen(Ref.set(pendingRef, SyncState.empty)),\n ),\n refresh: refresh(state),\n next: Queue.take(signal).pipe(\n Effect.andThen(\n drainUntilQuiescent(signal, quiescence, COALESCE_MAX_WAIT),\n ),\n Effect.andThen(state.topology.takePending),\n Effect.onInterrupt(() => Queue.offer(signal, undefined)),\n ),\n pending: Ref.get(pendingRef),\n requestRetry: Ref.update(pendingRef, SyncState.full).pipe(\n Effect.andThen(Queue.offer(signal, undefined)),\n Effect.asVoid,\n ),\n diagnostics: Ref.get(state.observation).pipe(\n Effect.map(WatchBuild.diagnostics),\n ),\n } as const;\n});\n\nexport type Watcher = Effect.Success<ReturnType<typeof make>>;\n\nconst drainUntilQuiescent = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n quiescence: Duration.Duration,\n maxWait: Duration.Duration,\n) {\n const start = yield* Clock.currentTimeMillis;\n const maxMillis = Duration.toMillis(maxWait);\n const loop: Effect.Effect<void> = Effect.gen(function* () {\n const elapsed = (yield* Clock.currentTimeMillis) - start;\n yield* Effect.sleep(\n Duration.millis(\n Math.min(\n Duration.toMillis(quiescence),\n Math.max(0, maxMillis - elapsed),\n ),\n ),\n );\n const drained = yield* Queue.clear(signal);\n if (drained.length === 0) return;\n const now = yield* Clock.currentTimeMillis;\n if (now - start < maxMillis) {\n yield* loop;\n }\n });\n yield* loop;\n});\n\nconst esbuildOptions = (\n path: Path.Path,\n fs: FileSystem.FileSystem,\n crypto: Crypto.Crypto,\n projectRoot: string,\n generatedDirectory: string,\n entries: ReadonlyArray<Entry>,\n notExternal: ReadonlyArray<RegExp>,\n stateRef: Ref.Ref<WatchBuild.State>,\n captureRef: Ref.Ref<WatchBuild.Capture>,\n progressRef: Ref.Ref<WatchBuild.Progress>,\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n initial: Deferred.Deferred<void>,\n): esbuild.BuildOptions => {\n const encodeString = Schema.encodeSync(Schema.fromJsonString(Schema.String));\n return {\n absWorkingDir: projectRoot,\n stdin: {\n contents: entries\n .map((entry) => `import ${encodeString(entry.absolutePath)};`)\n .join(\"\\n\"),\n resolveDir: projectRoot,\n sourcefile: \"confect-watch.ts\",\n loader: \"ts\",\n },\n bundle: true,\n write: false,\n metafile: true,\n platform: \"node\",\n format: \"esm\",\n logLevel: \"silent\",\n plugins: [\n Bundler.bundleWorkspacePlugin(path, fs, notExternal),\n externalPlugin({ notExternal: [...notExternal] }),\n {\n name: \"notify-rebuild\",\n setup(build) {\n build.onStart(() =>\n Effect.runPromise(\n Effect.gen(function* () {\n yield* Ref.update(progressRef, WatchBuild.start);\n yield* Ref.set(captureRef, WatchBuild.emptyCapture);\n }).pipe(Effect.as(undefined)),\n ),\n );\n build.onLoad({ filter: /.*/ }, (args) =>\n Effect.runPromise(\n Effect.gen(function* () {\n const fingerprint = yield* fs.readFile(args.path).pipe(\n Effect.flatMap((contents) =>\n crypto.digest(\"SHA-256\", contents),\n ),\n Effect.map(Hex.encode),\n Effect.result,\n );\n yield* Ref.update(captureRef, (capture) =>\n Result.isSuccess(fingerprint)\n ? {\n ...capture,\n fingerprints: HashMap.set(\n capture.fingerprints,\n args.path,\n fingerprint.success,\n ),\n }\n : {\n ...capture,\n failures: HashMap.set(\n capture.failures,\n args.path,\n WatchBuild.Failure.InputCaptureFailed({\n file: args.path,\n cause: fingerprint.failure,\n }),\n ),\n },\n );\n }).pipe(Effect.as(undefined)),\n ),\n );\n build.onEnd((result) =>\n Effect.runPromise(\n Effect.gen(function* () {\n const { generation } = yield* Ref.get(progressRef);\n const previous = yield* Ref.get(stateRef);\n const outcome = yield* WatchBuild.parse(\n result,\n yield* Ref.get(captureRef),\n (file) => path.resolve(projectRoot, file),\n crypto,\n );\n const current = WatchBuild.observe(previous, outcome);\n yield* Ref.set(stateRef, current);\n const change = WatchBuild.diff(\n previous,\n current,\n generatedDirectory + path.sep,\n );\n yield* Ref.update(pendingRef, (pending) =>\n WatchBuild.Change.$match(change, {\n Full: () => SyncState.add(pending, entries, true),\n Affected: ({ paths }) =>\n SyncState.add(\n pending,\n entries.filter((entry) =>\n HashSet.has(paths, entry.inputPath),\n ),\n ),\n Recovered: ({ paths }) =>\n SyncState.reconcile(\n SyncState.add(\n pending,\n entries.filter((entry) =>\n HashSet.has(paths, entry.inputPath),\n ),\n ),\n ),\n }),\n );\n yield* Queue.offer(signal, undefined);\n yield* Ref.update(progressRef, (progress) =>\n WatchBuild.complete(progress, { generation, outcome }),\n );\n yield* Deferred.succeed(initial, undefined);\n }),\n ),\n );\n },\n },\n ],\n };\n};\n\nconst entryPointsWatcher = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n restartQueue: Queue.Queue<void>,\n watcher: State,\n) {\n const parentScope = yield* Effect.scope;\n const path = yield* Path.Path;\n const fs = yield* FileSystem.FileSystem;\n const projectRoot = yield* ProjectRoot.get;\n const confectDirectory = yield* ConfectDirectory.get;\n const generatedDirectory = path.join(\n yield* fs.realPath(confectDirectory),\n \"_generated\",\n );\n const crypto = yield* Crypto.Crypto;\n const completedInitial = Deferred.make<void>().pipe(\n Effect.tap((initial) => Deferred.succeed(initial, undefined)),\n );\n\n const sync = Effect.gen(function* () {\n const revision = yield* watcher.topology.revision;\n const current = yield* Ref.get(watcher.lifecycle);\n const entries = yield* EntryPoint.discover;\n yield* Ref.set(watcher.declared, entries.some(EntryPoint.Kind.$is(\"App\")));\n const desiredPaths = HashSet.fromIterable(\n entries.map((entry) => entry.absolutePath),\n );\n const key = pipe(\n Array.fromIterable(desiredPaths),\n Array.sort(Order.String),\n Array.join(\"\\n\"),\n );\n const unchanged = WatcherLifecycle.$match(current, {\n Uninitialized: () => false,\n Empty: () => entries.length === 0,\n Active: ({ key: previousKey }) => previousKey === key,\n });\n if (unchanged) {\n const initial = yield* WatcherLifecycle.$match(current, {\n Uninitialized: () => completedInitial,\n Empty: () => completedInitial,\n Active: ({ initial: activeInitial }) => Effect.succeed(activeInitial),\n });\n yield* refreshCurrent(current).pipe(\n Effect.catchTag(\"WatcherOperationError\", () =>\n Ref.update(pendingRef, SyncState.full),\n ),\n );\n yield* watcher.topology.reconcile(revision, initial);\n return;\n }\n yield* WatcherLifecycle.$match(current, {\n Uninitialized: () => Effect.void,\n Empty: () => Ref.update(pendingRef, SyncState.full),\n Active: ({ entries: previousEntries, scope }) =>\n Effect.gen(function* () {\n const removedOptional = previousEntries.filter(\n (entry) =>\n EntryPoint.isOptional(entry) &&\n !HashSet.has(desiredPaths, entry.absolutePath),\n );\n yield* Ref.update(pendingRef, (pending) =>\n SyncState.add(SyncState.full(pending), removedOptional),\n );\n yield* Scope.close(scope, Exit.void);\n }),\n });\n yield* Ref.set(watcher.lifecycle, WatcherLifecycle.Uninitialized());\n yield* Ref.set(watcher.observation, WatchBuild.State.Initial());\n if (!Array.isReadonlyArrayNonEmpty(entries)) {\n yield* Ref.set(watcher.lifecycle, WatcherLifecycle.Empty());\n yield* Ref.update(pendingRef, SyncState.full);\n yield* Queue.offer(signal, undefined);\n const initial = yield* completedInitial;\n yield* watcher.topology.reconcile(revision, initial);\n return;\n }\n\n const scope = yield* Scope.fork(parentScope, \"sequential\");\n const captureRef = yield* Ref.make(WatchBuild.emptyCapture);\n const progress = yield* Ref.make(WatchBuild.initialProgress);\n const initial = yield* Deferred.make<void>();\n const tsconfig = loadTsConfig(projectRoot);\n const notExternal = tsconfigPathsToRegExp(\n tsconfig?.data.compilerOptions?.paths ?? {},\n );\n const context = yield* Effect.acquireRelease(\n Effect.tryPromise({\n try: () =>\n esbuild.context(\n esbuildOptions(\n path,\n fs,\n crypto,\n projectRoot,\n generatedDirectory,\n entries,\n notExternal,\n watcher.observation,\n captureRef,\n progress,\n signal,\n pendingRef,\n initial,\n ),\n ),\n catch: (cause) => new OperationError({ operation: \"create\", cause }),\n }),\n (ctx) =>\n Effect.tryPromise({\n try: () => ctx.dispose(),\n catch: (cause) => new OperationError({ operation: \"dispose\", cause }),\n }).pipe(Effect.orDie),\n ).pipe(Scope.provide(scope));\n const requestIds = new WeakMap<\n Promise<esbuild.BuildResult>,\n WatchBuild.RequestId\n >();\n yield* Ref.set(\n watcher.lifecycle,\n WatcherLifecycle.Active({\n initial,\n key,\n scope,\n entries,\n context,\n identifyRequest: (promise) => {\n const existing = requestIds.get(promise);\n if (existing !== undefined) return existing;\n const id = WatchBuild.makeRequestId();\n requestIds.set(promise, id);\n return id;\n },\n progress,\n verifyInputs: (snapshot) =>\n WatchBuild.verifyInputs(snapshot, fs, crypto),\n }),\n );\n yield* Effect.tryPromise({\n try: () => context.watch(),\n catch: (cause) => new OperationError({ operation: \"watch\", cause }),\n });\n yield* watcher.topology.reconcile(revision, initial);\n }).pipe(Semaphore.withPermit(watcher.lock));\n\n yield* sync;\n return yield* Effect.forever(\n Queue.take(restartQueue).pipe(Effect.andThen(sync)),\n );\n}, Effect.provide(NodeCrypto.layer));\n\nconst refreshCurrent = Effect.fnUntraced(function* (current: WatcherLifecycle) {\n return yield* WatcherLifecycle.$match(current, {\n Empty: () => Effect.succeed(RefreshOutcome.Empty()),\n Uninitialized: () =>\n Effect.fail(\n new OperationError({\n operation: \"refresh\",\n cause: \"The dependency watcher is not initialized\",\n }),\n ),\n Active: ({ context, identifyRequest, progress, verifyInputs }) =>\n Effect.gen(function* () {\n const runSync = Effect.runSyncWith(yield* Effect.context());\n const barrier = WatchBuild.captureBarrier(yield* Ref.get(progress));\n const rebuild = Effect.gen(function* () {\n const built = yield* Effect.tryPromise({\n try: () => {\n const promise = context.rebuild();\n runSync(\n Ref.update(progress, (currentProgress) =>\n WatchBuild.request(currentProgress, identifyRequest(promise)),\n ),\n );\n return promise;\n },\n catch: (cause) =>\n new OperationError({ operation: \"rebuild\", cause }),\n }).pipe(Effect.result);\n const currentProgress = yield* Ref.get(progress);\n const completed = WatchBuild.getCompletion(currentProgress);\n if (Result.isFailure(built)) {\n const rejected = parseFailure(built.failure.cause);\n if (Option.isNone(rejected)) return yield* built.failure;\n if (WatchBuild.joinedWithoutCompletion(currentProgress))\n return Option.none<WatchBuild.Completion>();\n if (\n Option.isNone(completed) ||\n !WatchBuild.Outcome.$is(\"Failed\")(completed.value.outcome)\n )\n return yield* new OperationError({\n operation: \"rebuild\",\n cause: rejected.value.errors,\n });\n }\n if (WatchBuild.joinedWithoutCompletion(currentProgress))\n return Option.none<WatchBuild.Completion>();\n const observed = yield* Effect.fromOption(completed).pipe(\n Effect.mapError(\n () =>\n new OperationError({\n operation: \"rebuild\",\n cause: \"esbuild completed without a build observation\",\n }),\n ),\n );\n if (\n WatchBuild.isFresh(barrier, observed) &&\n WatchBuild.Outcome.$is(\"Succeeded\")(observed.outcome)\n ) {\n const unchanged = yield* verifyInputs(\n observed.outcome.snapshot,\n ).pipe(\n Effect.mapError(\n ({ cause }) =>\n new OperationError({ operation: \"refresh\", cause }),\n ),\n );\n if (!unchanged) return Option.none<WatchBuild.Completion>();\n }\n return Option.some(observed);\n }).pipe(Effect.ensuring(Ref.update(progress, WatchBuild.endRequest)));\n const completed = yield* rebuild.pipe(\n Effect.repeat({\n while: (observed) =>\n Option.isNone(observed) ||\n !WatchBuild.isFresh(barrier, observed.value),\n }),\n Effect.flatMap((observed) =>\n Effect.fromOption(observed).pipe(Effect.orDie),\n ),\n );\n return RefreshOutcome.Observed({ outcome: completed.outcome });\n }),\n });\n});\n\nconst refresh = (watcher: State) =>\n watcher.lock.withPermit(\n Ref.get(watcher.lifecycle).pipe(Effect.flatMap(refreshCurrent)),\n );\n\nconst confectStructureWatcher = Effect.fnUntraced(function* (\n signal: Queue.Queue<void>,\n pendingRef: Ref.Ref<Pending>,\n restart: Effect.Effect<unknown>,\n restartEntry: (entry: EntryPoint.Kind) => Effect.Effect<unknown>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const confectDirectory = yield* ConfectDirectory.get;\n const removedDirectory = Schema.Struct({\n code: Schema.Literal(\"ENOENT\"),\n syscall: Schema.Literal(\"scandir\"),\n path: Schema.String,\n });\n\n yield* pipe(\n fs.watch(confectDirectory, { recursive: true }),\n Stream.runForEach((event) =>\n handleConfectChange({\n relativePath: path.relative(\n confectDirectory,\n path.resolve(confectDirectory, event.path),\n ),\n eventTag: event._tag,\n signal,\n pendingRef,\n restart,\n restartEntry,\n }),\n ),\n Effect.retry({\n schedule: Schedule.spaced(\"10 millis\"),\n while: (error) =>\n Effect.gen(function* () {\n const removed = Schema.decodeUnknownOption(removedDirectory)(\n error.reason.cause,\n );\n if (Option.isNone(removed)) return false;\n const relative = path.relative(confectDirectory, removed.value.path);\n if (\n relative === \"\" ||\n relative === \"..\" ||\n relative.startsWith(`..${path.sep}`) ||\n path.isAbsolute(relative)\n )\n return false;\n if (\n !(yield* fs\n .exists(confectDirectory)\n .pipe(Effect.orElseSucceed(() => false)))\n ) {\n return false;\n }\n yield* restart;\n return true;\n }),\n }),\n );\n});\n\n/**\n * Non-recursive `fs.watch` on the convex directory, reacting only to\n * `convex.config.ts`. Recursion is deliberately avoided: codegen (Confect's and\n * Convex's) writes into `convex/` and `convex/_generated/` constantly, and\n * reacting to those writes would loop. Create/Remove offers to `restartQueue`\n * so the entry-point watcher set picks up (or drops) the config's esbuild\n * watcher.\n */\nconst convexConfigStructureWatcher = Effect.fnUntraced(function* (\n restart: Effect.Effect<unknown>,\n declared: Ref.Ref<boolean>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n\n yield* pipe(\n fs.watch(convexDirectory),\n Stream.runForEach((event) =>\n Effect.gen(function* () {\n // A declared backend's config is codegen output; reacting to its\n // writes would rerun codegen for nothing.\n if (\n path.relative(convexDirectory, event.path) !==\n CONVEX_CONFIG_FILENAME ||\n (yield* Ref.get(declared))\n )\n return;\n yield* Match.value(event).pipe(\n Match.tag(\"Update\", () => Effect.void),\n Match.tag(\"Create\", \"Remove\", () => restart),\n Match.exhaustive,\n );\n }),\n ),\n );\n});\n\nconst flipDirtyAndSignal = (\n pendingRef: Ref.Ref<Pending>,\n signal: Queue.Queue<void>,\n restart: Effect.Effect<unknown>,\n isLifecycleChange: boolean,\n) =>\n isLifecycleChange\n ? restart\n : Ref.update(pendingRef, SyncState.full).pipe(\n Effect.andThen(Queue.offer(signal, undefined)),\n );\n\nconst handleConfectChange = ({\n relativePath,\n eventTag,\n signal,\n pendingRef,\n restart,\n restartEntry,\n}: {\n relativePath: string;\n eventTag: \"Create\" | \"Update\" | \"Remove\";\n signal: Queue.Queue<void>;\n pendingRef: Ref.Ref<Pending>;\n restart: Effect.Effect<unknown>;\n restartEntry: (entry: EntryPoint.Kind) => Effect.Effect<unknown>;\n}) => {\n if (relativePath.split(/[/\\\\]/).includes(\"_generated\")) {\n return Effect.void;\n }\n\n if (!relativePath.endsWith(\".ts\")) {\n return Effect.void;\n }\n\n const isLifecycleChange = Match.value(eventTag).pipe(\n Match.when(\"Update\", () => false),\n Match.whenOr(\"Create\", \"Remove\", () => true),\n Match.exhaustive,\n );\n\n const entry = EntryPoint.parse(relativePath);\n if (Option.isSome(entry)) {\n return isLifecycleChange ? restartEntry(entry.value) : Effect.void;\n }\n\n // A stray `confect/schema.ts` (now codegen-owned at\n // `_generated/schema.ts`) shouldn't exist; flagging it here ensures the\n // next codegen pass surfaces the migration error\n // (`LegacySchemaFileError`) instead of silently ignoring the file.\n if (relativePath === \"schema.ts\") {\n return flipDirtyAndSignal(pendingRef, signal, restart, isLifecycleChange);\n }\n\n // Any other `.ts` under `confect/` (helpers like `tables/notes.ts`).\n // Updates to such files are handled by the esbuild watcher for whichever\n // entry point imports them—its onEnd flips the right dirty flag.\n // Creates are our safety net: when a previously-missing import is added,\n // esbuild may not have its parent directory on a poll path, so we\n // re-run codegen on Create here.\n return Match.value(eventTag).pipe(\n Match.when(\"Create\", () =>\n flipDirtyAndSignal(pendingRef, signal, restart, false),\n ),\n Match.whenOr(\"Update\", \"Remove\", () => Effect.void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A,UACA,QACA,YACA,SACA,mBAQI;CACJ,IAAI,aAAa,MAAM,OAAO,CAAC,CAAC,SAAS,YAAY,GACnD,OAAO,OAAO;CAGhB,IAAI,CAAC,aAAa,SAAS,KAAK,GAC9B,OAAO,OAAO;CAGhB,MAAM,oBAAoB,MAAM,MAAM,QAAQ,CAAC,CAAC,KAC9C,MAAM,KAAK,gBAAgB,KAAK,GAChC,MAAM,OAAO,UAAU,gBAAgB,IAAI,GAC3C,MAAM,UACR;CAEA,MAAM,QAAQsB,MAAiB,YAAY;CAC3C,IAAI,OAAO,OAAO,KAAK,GACrB,OAAO,oBAAoB,aAAa,MAAM,KAAK,IAAI,OAAO;CAOhE,IAAI,iBAAiB,aACnB,OAAO,mBAAmB,YAAY,QAAQ,SAAS,iBAAiB;CAS1E,OAAO,MAAM,MAAM,QAAQ,CAAC,CAAC,KAC3B,MAAM,KAAK,gBACT,mBAAmB,YAAY,QAAQ,SAAS,KAAK,CACvD,GACA,MAAM,OAAO,UAAU,gBAAgB,OAAO,IAAI,GAClD,MAAM,UACR;AACF"}
@@ -10,8 +10,8 @@ import { functionPaths } from "../GenerationSnapshot.mjs";
10
10
  import { preserveComponentOutput } from "../Rollback.mjs";
11
11
  import { isDeclared } from "./declaration.mjs";
12
12
  import { Operation, Outcome, Phase, forBackend, isDirty, needsDeploymentNotification, plan, shouldRetry, transition } from "../SyncState.mjs";
13
- import { isRefreshSuccessful, make } from "../Watcher.mjs";
14
- import { EvaluationError, catchAndLog, generateSnapshot, loadPreviousFunctionPaths, updateDeclarations, validate } from "../Evaluation.mjs";
13
+ import { CoalesceQuiescence, isRefreshSuccessful, make } from "../Watcher.mjs";
14
+ import { EvaluationError, catchAndLog, generateSnapshot, loadPreviousFunctionPaths, prewarmedLayer, updateDeclarations, validate } from "../Evaluation.mjs";
15
15
  import * as Effect from "effect/Effect";
16
16
  import * as Command from "effect/cli/Command";
17
17
  import * as FileSystem from "effect/FileSystem";
@@ -26,6 +26,8 @@ import * as Ref from "effect/Ref";
26
26
  import * as String from "effect/String";
27
27
  import * as Console from "effect/Console";
28
28
  import * as Order from "effect/Order";
29
+ import * as Flag from "effect/cli/Flag";
30
+ import * as Duration from "effect/Duration";
29
31
  import * as Equal from "effect/Equal";
30
32
  //#region src/confect/dev.ts
31
33
  const changeChar = (change) => Match.value(change).pipe(Match.when("Added", () => ({
@@ -59,8 +61,11 @@ const devHandler = Effect.gen(function* () {
59
61
  const previousFunctionPaths = yield* loadPreviousFunctionPaths;
60
62
  const watcher = yield* make();
61
63
  yield* Effect.all([watcher.run, syncLoop(previousFunctionPaths, watcher)], { concurrency: "unbounded" });
62
- });
63
- const dev = Command.make("dev", flags, () => devHandler).pipe(Command.withDescription("Start the Confect development server"), Command.provide(layer));
64
+ }).pipe(Effect.provide(prewarmedLayer));
65
+ const dev = Command.make("dev", {
66
+ ...flags,
67
+ coalesceMs: Flag.Int("coalesce-ms").pipe(Flag.filter((ms) => ms >= 0 && ms <= 5e3, () => "Set --coalesce-ms to an integer between 0 and 5000 milliseconds."), Flag.withDefault(Duration.toMillis(CoalesceQuiescence.defaultValue())), Flag.withDescription("Quiet period before processing saved files, in milliseconds."))
68
+ }, ({ coalesceMs }) => devHandler.pipe(Effect.provideService(CoalesceQuiescence, Duration.millis(coalesceMs)))).pipe(Command.withDescription("Start the Confect development server"), Command.provide((options) => layer(options)));
64
69
  const esbuildMessageKey = (m) => `${m.location?.file ?? ""}:${m.location?.line ?? ""}:${m.location?.column ?? ""}:${m.text}`;
65
70
  const dedupeWatcherMessages = (messages) => pipe(messages, Array.dedupeWith((messageA, messageB) => esbuildMessageKey(messageA) === esbuildMessageKey(messageB)));
66
71
  const watcherMessagesSignature = (messages) => pipe(messages, Array.map(esbuildMessageKey), Array.dedupe, Array.sort(Order.String), Array.join("\n"));
@@ -1 +1 @@
1
- {"version":3,"file":"dev.mjs","names":["Ansi.green","Ansi.red","Ansi.magenta","Ansi.blackBright","FunctionPaths.diff","Evaluation.loadPreviousFunctionPaths","Watcher.make","DirectoryOptions.flags","DirectoryOptions.layer","SyncState.isDirty","SyncState.forBackend","SyncState.plan","GenerationSnapshot.functionPaths","Evaluation.catchAndLog","Watcher.isRefreshSuccessful","Evaluation.EvaluationError","validate","Evaluation.validate","Evaluation.generateSnapshot","Evaluation.updateDeclarations","SyncState.transition","SyncState.shouldRetry","SyncState.needsDeploymentNotification"],"sources":["../../src/confect/dev.ts"],"sourcesContent":["import * as Command from \"effect/cli/Command\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport * as Equal from \"effect/Equal\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Order from \"effect/Order\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as String from \"effect/String\";\nimport type * as esbuild from \"esbuild\";\nimport * as Ansi from \"../Ansi.js\";\nimport { renderCodegenError } from \"../CodegenError.js\";\nimport * as SyncState from \"../SyncState.js\";\nimport type { OptionalFile } from \"../EntryPoint.js\";\nimport * as Watcher from \"../Watcher.js\";\nimport * as Evaluation from \"../Evaluation.js\";\nimport { ConvexDirectory } from \"../ConvexDirectory.js\";\nimport * as DirectoryOptions from \"../DirectoryOptions.js\";\nimport * as FunctionPaths from \"../FunctionPaths.js\";\nimport * as GenerationSnapshot from \"../GenerationSnapshot.js\";\nimport type { ImplModulePath } from \"../ImplModulePath.js\";\nimport type * as GroupPath from \"../GroupPath.js\";\nimport type * as GroupPaths from \"../GroupPaths.js\";\nimport {\n logCoalescedBuildErrors,\n logCoalescedBuildWarnings,\n logFunctionAdded,\n logFunctionRemoved,\n logPending,\n logSuccess,\n} from \"../log.js\";\nimport { ProjectRoot } from \"../ProjectRoot.js\";\nimport { preserveComponentOutput } from \"../Rollback.js\";\nimport {\n generateAuthConfig,\n generateCrons,\n generateHttp,\n touchConvexSchema,\n} from \"../utils.js\";\nimport { isDeclared } from \"./declaration.js\";\n\nconst changeChar = (change: \"Added\" | \"Removed\" | \"Modified\") =>\n Match.value(change).pipe(\n Match.when(\"Added\", () => ({ char: \"+\", color: Ansi.green })),\n Match.when(\"Removed\", () => ({ char: \"-\", color: Ansi.red })),\n Match.when(\"Modified\", () => ({ char: \"~\", color: Ansi.magenta })),\n Match.exhaustive,\n );\n\nconst logFileChangeIndented = Effect.fnUntraced(function* (\n change: \"Added\" | \"Removed\" | \"Modified\",\n fullPath: string,\n) {\n const projectRoot = yield* ProjectRoot.get;\n const path = yield* Path.Path;\n\n const prefix = projectRoot + path.sep;\n const suffix = pipe(fullPath, String.startsWith(prefix))\n ? pipe(fullPath, String.slice(prefix.length))\n : fullPath;\n\n const { char, color } = changeChar(change);\n\n yield* Console.log(\n `${color(char)} ${Ansi.blackBright(prefix)}${color(suffix)}`,\n );\n});\n\nconst logFunctionPathDiff = Effect.fnUntraced(function* (\n previous: FunctionPaths.FunctionPaths,\n current: FunctionPaths.FunctionPaths,\n) {\n const {\n functionsAdded,\n functionsRemoved,\n groupsRemoved,\n groupsAdded,\n groupsChanged,\n } = FunctionPaths.diff(previous, current);\n\n const logForGroups = (\n groupPaths: GroupPaths.GroupPaths,\n fnPaths: FunctionPaths.FunctionPaths,\n logFn: typeof logFunctionAdded,\n ) =>\n Effect.forEach(groupPaths, (gp) =>\n Effect.forEach(\n Array.fromIterable(\n HashSet.filter(fnPaths, (fp) => Equal.equals(fp.groupPath, gp)),\n ),\n logFn,\n ),\n );\n\n yield* logForGroups(groupsRemoved, functionsRemoved, logFunctionRemoved);\n yield* logForGroups(groupsAdded, functionsAdded, logFunctionAdded);\n yield* Effect.forEach(\n groupsChanged,\n Effect.fnUntraced(function* (gp: GroupPath.GroupPath) {\n yield* Effect.forEach(\n Array.fromIterable(\n HashSet.filter(functionsAdded, (fp) =>\n Equal.equals(fp.groupPath, gp),\n ),\n ),\n logFunctionAdded,\n );\n yield* Effect.forEach(\n Array.fromIterable(\n HashSet.filter(functionsRemoved, (fp) =>\n Equal.equals(fp.groupPath, gp),\n ),\n ),\n logFunctionRemoved,\n );\n }),\n );\n});\n\nexport const devHandler = Effect.gen(function* () {\n yield* logPending(\"Performing initial sync…\");\n const previousFunctionPaths = yield* Evaluation.loadPreviousFunctionPaths;\n\n const watcher = yield* Watcher.make();\n\n yield* Effect.all([watcher.run, syncLoop(previousFunctionPaths, watcher)], {\n concurrency: \"unbounded\",\n });\n});\n\nexport const dev = Command.make(\n \"dev\",\n DirectoryOptions.flags,\n () => devHandler,\n).pipe(\n Command.withDescription(\"Start the Confect development server\"),\n Command.provide(DirectoryOptions.layer),\n);\n\nconst esbuildMessageKey = (m: esbuild.Message): string =>\n `${m.location?.file ?? \"\"}:${m.location?.line ?? \"\"}:${m.location?.column ?? \"\"}:${m.text}`;\n\nconst dedupeWatcherMessages = (\n messages: ReadonlyArray<esbuild.Message>,\n): ReadonlyArray<esbuild.Message> =>\n pipe(\n messages,\n Array.dedupeWith(\n (messageA, messageB) =>\n esbuildMessageKey(messageA) === esbuildMessageKey(messageB),\n ),\n );\n\nconst watcherMessagesSignature = (\n messages: ReadonlyArray<esbuild.Message>,\n): string =>\n pipe(\n messages,\n Array.map(esbuildMessageKey),\n Array.dedupe,\n Array.sort(Order.String),\n Array.join(\"\\n\"),\n );\n\n/**\n * Log any watcher messages (errors or warnings) that haven't already been\n * logged at their current signature. Suppresses the per-watcher fanout that\n * happens when one root cause (e.g. a missing import) breaks every entry\n * point's build at the same source location.\n */\nconst logChangedWatcherMessages = Effect.fnUntraced(function* (\n messages: ReadonlyArray<esbuild.Message>,\n lastLoggedSignatureRef: Ref.Ref<string>,\n log: (messages: ReadonlyArray<esbuild.Message>) => Effect.Effect<void>,\n) {\n const signature = watcherMessagesSignature(messages);\n const previous = yield* Ref.get(lastLoggedSignatureRef);\n if (signature === previous) return;\n yield* Ref.set(lastLoggedSignatureRef, signature);\n if (messages.length === 0) return;\n yield* log(dedupeWatcherMessages(messages));\n});\n\nconst syncLoop = Effect.fnUntraced(function* (\n initialFunctionPaths: FunctionPaths.FunctionPaths,\n watcher: Watcher.Watcher,\n) {\n const functionPathsRef = yield* Ref.make(initialFunctionPaths);\n const lastLoggedErrorsRef = yield* Ref.make<string>(\"\");\n const lastLoggedWarningsRef = yield* Ref.make<string>(\"\");\n const phaseRef = yield* Ref.make<SyncState.Phase>(\n SyncState.Phase.Bootstrapping(),\n );\n const optionalPendingRef = yield* Ref.make(HashSet.empty<OptionalFile>());\n const logMessages = Effect.gen(function* () {\n const { errors, warnings } = yield* watcher.diagnostics;\n yield* logChangedWatcherMessages(\n errors,\n lastLoggedErrorsRef,\n logCoalescedBuildErrors,\n );\n yield* logChangedWatcherMessages(\n warnings,\n lastLoggedWarningsRef,\n logCoalescedBuildWarnings,\n );\n });\n\n return yield* Effect.forever(\n Effect.gen(function* () {\n yield* Effect.logDebug(\"Running sync loop…\");\n const taken = yield* watcher.next;\n\n const phase = yield* Ref.get(phaseRef);\n const firstSync = SyncState.Phase.$is(\"Bootstrapping\")(phase);\n if (!firstSync) yield* logMessages;\n\n if (!SyncState.isDirty(taken)) return;\n\n const declared = yield* isDeclared;\n const pending = SyncState.forBackend(\n {\n ...taken,\n optional: yield* Ref.updateAndGet(\n optionalPendingRef,\n HashSet.union(taken.optional),\n ),\n },\n {\n declared,\n component: (yield* ConvexDirectory.target).kind === \"component\",\n },\n );\n const optional = pending.optional;\n const operation = SyncState.plan(phase, pending);\n yield* Effect.logDebug(\"Planned development sync\").pipe(\n Effect.annotateLogs({\n phase: phase._tag,\n work: pending.work._tag,\n operation: operation._tag,\n }),\n );\n if (\n !firstSync &&\n !(\n SyncState.Operation.$is(\"Validate\")(operation) &&\n operation.paths.length === 0\n )\n )\n yield* logPending(\"Dependencies may have changed, reloading…\");\n\n const regenerate = <R>(\n generation: Effect.Effect<\n GenerationSnapshot.GenerationSnapshot,\n Effect.Error<typeof Evaluation.generateSnapshot>,\n R\n >,\n ) =>\n Effect.gen(function* () {\n const current = yield* generation.pipe(\n Effect.tap((snapshot) =>\n Effect.gen(function* () {\n const nextFunctionPaths =\n GenerationSnapshot.functionPaths(snapshot);\n const previous = yield* Ref.get(functionPathsRef);\n yield* logFunctionPathDiff(previous, nextFunctionPaths);\n yield* Ref.set(functionPathsRef, nextFunctionPaths);\n }),\n ),\n Evaluation.catchAndLog,\n );\n if (Option.isNone(current)) {\n return SyncState.Outcome.GenerationFailed();\n }\n const refreshed = yield* watcher.refresh.pipe(Effect.result);\n if (Result.isFailure(refreshed)) {\n yield* Console.error(\n `Dependency watcher could not ${refreshed.failure.operation}: ${globalThis.String(refreshed.failure.cause)}`,\n );\n return SyncState.Outcome.ReconciliationFailed();\n }\n if (!Watcher.isRefreshSuccessful(refreshed.success)) {\n yield* logMessages;\n return SyncState.Outcome.ReconciliationFailed();\n }\n return SyncState.Outcome.Succeeded({ snapshot: current.value });\n });\n const preserved = <R>(\n generation: Effect.Effect<\n GenerationSnapshot.GenerationSnapshot,\n Effect.Error<typeof Evaluation.generateSnapshot>,\n R\n >,\n ) =>\n preserveComponentOutput(generation, watcher.duringRestore).pipe(\n Effect.tapErrorTag(\n \"ComponentNodeGroupError\",\n () => watcher.discardRestoreEchoes,\n ),\n Effect.catchTags({\n RemoveBusyError: (error) =>\n Effect.fail(\n new Evaluation.EvaluationError({\n diagnostic: renderCodegenError(error),\n }),\n ),\n // Output that cannot be restored leaves nothing to serve.\n PlatformError: Effect.die,\n }),\n );\n const validate = (\n paths: ReadonlyArray<ImplModulePath>,\n snapshot: GenerationSnapshot.GenerationSnapshot,\n ) =>\n Effect.gen(function* () {\n if (Array.isReadonlyArrayNonEmpty(paths)) {\n const validated = yield* Evaluation.validate(paths).pipe(\n Evaluation.catchAndLog,\n );\n if (Option.isNone(validated)) {\n return SyncState.Outcome.ValidationFailed({ paths, snapshot });\n }\n }\n return SyncState.Outcome.Succeeded({ snapshot });\n });\n const outcome = yield* SyncState.Operation.$match(operation, {\n Generate: () => regenerate(preserved(Evaluation.generateSnapshot)),\n Validate: ({ paths, snapshot }) => validate(paths, snapshot),\n Update: ({ snapshot, declarations, paths }) =>\n regenerate(\n preserved(\n Evaluation.updateDeclarations(snapshot, declarations, paths),\n ),\n ),\n });\n yield* Ref.set(phaseRef, SyncState.transition(outcome));\n if (SyncState.shouldRetry(phase, outcome)) {\n yield* watcher.requestRetry;\n }\n if (!SyncState.Outcome.$is(\"Succeeded\")(outcome)) return;\n\n const dirtyOptionalFiles = [\n ...(HashSet.has(optional, \"Http\")\n ? [syncOptionalFile(generateHttp, \"http.ts\")]\n : []),\n ...(HashSet.has(optional, \"Crons\")\n ? [syncOptionalFile(generateCrons, \"crons.ts\")]\n : []),\n ...(HashSet.has(optional, \"Auth\")\n ? [syncOptionalFile(generateAuthConfig, \"auth.config.ts\")]\n : []),\n ];\n\n yield* Array.isReadonlyArrayNonEmpty(dirtyOptionalFiles)\n ? Effect.all(dirtyOptionalFiles, { concurrency: \"unbounded\" })\n : Effect.void;\n yield* Ref.set(optionalPendingRef, HashSet.empty());\n\n if (SyncState.needsDeploymentNotification(phase))\n yield* touchConvexSchema;\n\n if (!SyncState.isDirty(yield* watcher.pending)) {\n yield* logSuccess(\"Generated files are up-to-date\");\n }\n }),\n );\n});\n\nconst syncOptionalFile = (generate: typeof generateHttp, convexFile: string) =>\n pipe(\n generate,\n Effect.andThen(\n Option.match({\n onSome: ({ change, convexFilePath }) =>\n Match.value(change).pipe(\n Match.when(\"Unchanged\", () => Effect.void),\n Match.whenOr(\"Added\", \"Modified\", (addedOrModified) =>\n logFileChangeIndented(addedOrModified, convexFilePath),\n ),\n Match.exhaustive,\n ),\n onNone: () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n const convexFilePath = path.join(convexDirectory, convexFile);\n\n if (yield* fs.exists(convexFilePath)) {\n yield* fs.remove(convexFilePath);\n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,OAAO,IAAI,aAAa;EACtB,MAAM,KAAK,OAAO,WAAW;EAC7B,MAAM,OAAO,OAAO,KAAK;EACzB,MAAM,kBAAkB,OAAO,gBAAgB;EAC/C,MAAM,iBAAiB,KAAK,KAAK,iBAAiB,UAAU;EAE5D,IAAI,OAAO,GAAG,OAAO,cAAc,GAAG;GACpC,OAAO,GAAG,OAAO,cAAc;GAC/B,OAAO,sBAAsB,WAAW,cAAc;EACxD;CACF,CAAC;AACL,CAAC,CACH,CACF"}
1
+ {"version":3,"file":"dev.mjs","names":["Ansi.green","Ansi.red","Ansi.magenta","Ansi.blackBright","FunctionPaths.diff","Evaluation.loadPreviousFunctionPaths","Watcher.make","Evaluation.prewarmedLayer","DirectoryOptions.flags","Watcher.CoalesceQuiescence","DirectoryOptions.layer","SyncState.isDirty","SyncState.forBackend","SyncState.plan","GenerationSnapshot.functionPaths","Evaluation.catchAndLog","Watcher.isRefreshSuccessful","Evaluation.EvaluationError","validate","Evaluation.validate","Evaluation.generateSnapshot","Evaluation.updateDeclarations","SyncState.transition","SyncState.shouldRetry","SyncState.needsDeploymentNotification"],"sources":["../../src/confect/dev.ts"],"sourcesContent":["import * as Command from \"effect/cli/Command\";\nimport * as Flag from \"effect/cli/Flag\";\nimport * as Duration from \"effect/Duration\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Path from \"effect/Path\";\nimport { pipe } from \"effect/Function\";\nimport * as Array from \"effect/Array\";\nimport * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport * as Equal from \"effect/Equal\";\nimport * as HashSet from \"effect/HashSet\";\nimport * as Match from \"effect/Match\";\nimport * as Option from \"effect/Option\";\nimport * as Order from \"effect/Order\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as String from \"effect/String\";\nimport type * as esbuild from \"esbuild\";\nimport * as Ansi from \"../Ansi.js\";\nimport { renderCodegenError } from \"../CodegenError.js\";\nimport * as SyncState from \"../SyncState.js\";\nimport type { OptionalFile } from \"../EntryPoint.js\";\nimport * as Watcher from \"../Watcher.js\";\nimport * as Evaluation from \"../Evaluation.js\";\nimport { ConvexDirectory } from \"../ConvexDirectory.js\";\nimport * as DirectoryOptions from \"../DirectoryOptions.js\";\nimport * as FunctionPaths from \"../FunctionPaths.js\";\nimport * as GenerationSnapshot from \"../GenerationSnapshot.js\";\nimport type { ImplModulePath } from \"../ImplModulePath.js\";\nimport type * as GroupPath from \"../GroupPath.js\";\nimport type * as GroupPaths from \"../GroupPaths.js\";\nimport {\n logCoalescedBuildErrors,\n logCoalescedBuildWarnings,\n logFunctionAdded,\n logFunctionRemoved,\n logPending,\n logSuccess,\n} from \"../log.js\";\nimport { ProjectRoot } from \"../ProjectRoot.js\";\nimport { preserveComponentOutput } from \"../Rollback.js\";\nimport {\n generateAuthConfig,\n generateCrons,\n generateHttp,\n touchConvexSchema,\n} from \"../utils.js\";\nimport { isDeclared } from \"./declaration.js\";\n\nconst changeChar = (change: \"Added\" | \"Removed\" | \"Modified\") =>\n Match.value(change).pipe(\n Match.when(\"Added\", () => ({ char: \"+\", color: Ansi.green })),\n Match.when(\"Removed\", () => ({ char: \"-\", color: Ansi.red })),\n Match.when(\"Modified\", () => ({ char: \"~\", color: Ansi.magenta })),\n Match.exhaustive,\n );\n\nconst logFileChangeIndented = Effect.fnUntraced(function* (\n change: \"Added\" | \"Removed\" | \"Modified\",\n fullPath: string,\n) {\n const projectRoot = yield* ProjectRoot.get;\n const path = yield* Path.Path;\n\n const prefix = projectRoot + path.sep;\n const suffix = pipe(fullPath, String.startsWith(prefix))\n ? pipe(fullPath, String.slice(prefix.length))\n : fullPath;\n\n const { char, color } = changeChar(change);\n\n yield* Console.log(\n `${color(char)} ${Ansi.blackBright(prefix)}${color(suffix)}`,\n );\n});\n\nconst logFunctionPathDiff = Effect.fnUntraced(function* (\n previous: FunctionPaths.FunctionPaths,\n current: FunctionPaths.FunctionPaths,\n) {\n const {\n functionsAdded,\n functionsRemoved,\n groupsRemoved,\n groupsAdded,\n groupsChanged,\n } = FunctionPaths.diff(previous, current);\n\n const logForGroups = (\n groupPaths: GroupPaths.GroupPaths,\n fnPaths: FunctionPaths.FunctionPaths,\n logFn: typeof logFunctionAdded,\n ) =>\n Effect.forEach(groupPaths, (gp) =>\n Effect.forEach(\n Array.fromIterable(\n HashSet.filter(fnPaths, (fp) => Equal.equals(fp.groupPath, gp)),\n ),\n logFn,\n ),\n );\n\n yield* logForGroups(groupsRemoved, functionsRemoved, logFunctionRemoved);\n yield* logForGroups(groupsAdded, functionsAdded, logFunctionAdded);\n yield* Effect.forEach(\n groupsChanged,\n Effect.fnUntraced(function* (gp: GroupPath.GroupPath) {\n yield* Effect.forEach(\n Array.fromIterable(\n HashSet.filter(functionsAdded, (fp) =>\n Equal.equals(fp.groupPath, gp),\n ),\n ),\n logFunctionAdded,\n );\n yield* Effect.forEach(\n Array.fromIterable(\n HashSet.filter(functionsRemoved, (fp) =>\n Equal.equals(fp.groupPath, gp),\n ),\n ),\n logFunctionRemoved,\n );\n }),\n );\n});\n\nexport const devHandler = Effect.gen(function* () {\n yield* logPending(\"Performing initial sync…\");\n const previousFunctionPaths = yield* Evaluation.loadPreviousFunctionPaths;\n\n const watcher = yield* Watcher.make();\n\n yield* Effect.all([watcher.run, syncLoop(previousFunctionPaths, watcher)], {\n concurrency: \"unbounded\",\n });\n}).pipe(Effect.provide(Evaluation.prewarmedLayer));\n\nexport const dev = Command.make(\n \"dev\",\n {\n ...DirectoryOptions.flags,\n coalesceMs: Flag.Int(\"coalesce-ms\").pipe(\n Flag.filter(\n (ms) => ms >= 0 && ms <= 5000,\n () =>\n \"Set --coalesce-ms to an integer between 0 and 5000 milliseconds.\",\n ),\n Flag.withDefault(\n Duration.toMillis(Watcher.CoalesceQuiescence.defaultValue()),\n ),\n Flag.withDescription(\n \"Quiet period before processing saved files, in milliseconds.\",\n ),\n ),\n },\n ({ coalesceMs }) =>\n devHandler.pipe(\n Effect.provideService(\n Watcher.CoalesceQuiescence,\n Duration.millis(coalesceMs),\n ),\n ),\n).pipe(\n Command.withDescription(\"Start the Confect development server\"),\n Command.provide(\n (options: { componentDir: Option.Option<string>; coalesceMs: number }) =>\n DirectoryOptions.layer(options),\n ),\n);\n\nconst esbuildMessageKey = (m: esbuild.Message): string =>\n `${m.location?.file ?? \"\"}:${m.location?.line ?? \"\"}:${m.location?.column ?? \"\"}:${m.text}`;\n\nconst dedupeWatcherMessages = (\n messages: ReadonlyArray<esbuild.Message>,\n): ReadonlyArray<esbuild.Message> =>\n pipe(\n messages,\n Array.dedupeWith(\n (messageA, messageB) =>\n esbuildMessageKey(messageA) === esbuildMessageKey(messageB),\n ),\n );\n\nconst watcherMessagesSignature = (\n messages: ReadonlyArray<esbuild.Message>,\n): string =>\n pipe(\n messages,\n Array.map(esbuildMessageKey),\n Array.dedupe,\n Array.sort(Order.String),\n Array.join(\"\\n\"),\n );\n\n/**\n * Log any watcher messages (errors or warnings) that haven't already been\n * logged at their current signature. Suppresses the per-watcher fanout that\n * happens when one root cause (e.g. a missing import) breaks every entry\n * point's build at the same source location.\n */\nconst logChangedWatcherMessages = Effect.fnUntraced(function* (\n messages: ReadonlyArray<esbuild.Message>,\n lastLoggedSignatureRef: Ref.Ref<string>,\n log: (messages: ReadonlyArray<esbuild.Message>) => Effect.Effect<void>,\n) {\n const signature = watcherMessagesSignature(messages);\n const previous = yield* Ref.get(lastLoggedSignatureRef);\n if (signature === previous) return;\n yield* Ref.set(lastLoggedSignatureRef, signature);\n if (messages.length === 0) return;\n yield* log(dedupeWatcherMessages(messages));\n});\n\nconst syncLoop = Effect.fnUntraced(function* (\n initialFunctionPaths: FunctionPaths.FunctionPaths,\n watcher: Watcher.Watcher,\n) {\n const functionPathsRef = yield* Ref.make(initialFunctionPaths);\n const lastLoggedErrorsRef = yield* Ref.make<string>(\"\");\n const lastLoggedWarningsRef = yield* Ref.make<string>(\"\");\n const phaseRef = yield* Ref.make<SyncState.Phase>(\n SyncState.Phase.Bootstrapping(),\n );\n const optionalPendingRef = yield* Ref.make(HashSet.empty<OptionalFile>());\n const logMessages = Effect.gen(function* () {\n const { errors, warnings } = yield* watcher.diagnostics;\n yield* logChangedWatcherMessages(\n errors,\n lastLoggedErrorsRef,\n logCoalescedBuildErrors,\n );\n yield* logChangedWatcherMessages(\n warnings,\n lastLoggedWarningsRef,\n logCoalescedBuildWarnings,\n );\n });\n\n return yield* Effect.forever(\n Effect.gen(function* () {\n yield* Effect.logDebug(\"Running sync loop…\");\n const taken = yield* watcher.next;\n\n const phase = yield* Ref.get(phaseRef);\n const firstSync = SyncState.Phase.$is(\"Bootstrapping\")(phase);\n if (!firstSync) yield* logMessages;\n\n if (!SyncState.isDirty(taken)) return;\n\n const declared = yield* isDeclared;\n const pending = SyncState.forBackend(\n {\n ...taken,\n optional: yield* Ref.updateAndGet(\n optionalPendingRef,\n HashSet.union(taken.optional),\n ),\n },\n {\n declared,\n component: (yield* ConvexDirectory.target).kind === \"component\",\n },\n );\n const optional = pending.optional;\n const operation = SyncState.plan(phase, pending);\n yield* Effect.logDebug(\"Planned development sync\").pipe(\n Effect.annotateLogs({\n phase: phase._tag,\n work: pending.work._tag,\n operation: operation._tag,\n }),\n );\n if (\n !firstSync &&\n !(\n SyncState.Operation.$is(\"Validate\")(operation) &&\n operation.paths.length === 0\n )\n )\n yield* logPending(\"Dependencies may have changed, reloading…\");\n\n const regenerate = <R>(\n generation: Effect.Effect<\n GenerationSnapshot.GenerationSnapshot,\n Effect.Error<typeof Evaluation.generateSnapshot>,\n R\n >,\n ) =>\n Effect.gen(function* () {\n const current = yield* generation.pipe(\n Effect.tap((snapshot) =>\n Effect.gen(function* () {\n const nextFunctionPaths =\n GenerationSnapshot.functionPaths(snapshot);\n const previous = yield* Ref.get(functionPathsRef);\n yield* logFunctionPathDiff(previous, nextFunctionPaths);\n yield* Ref.set(functionPathsRef, nextFunctionPaths);\n }),\n ),\n Evaluation.catchAndLog,\n );\n if (Option.isNone(current)) {\n return SyncState.Outcome.GenerationFailed();\n }\n const refreshed = yield* watcher.refresh.pipe(Effect.result);\n if (Result.isFailure(refreshed)) {\n yield* Console.error(\n `Dependency watcher could not ${refreshed.failure.operation}: ${globalThis.String(refreshed.failure.cause)}`,\n );\n return SyncState.Outcome.ReconciliationFailed();\n }\n if (!Watcher.isRefreshSuccessful(refreshed.success)) {\n yield* logMessages;\n return SyncState.Outcome.ReconciliationFailed();\n }\n return SyncState.Outcome.Succeeded({ snapshot: current.value });\n });\n const preserved = <R>(\n generation: Effect.Effect<\n GenerationSnapshot.GenerationSnapshot,\n Effect.Error<typeof Evaluation.generateSnapshot>,\n R\n >,\n ) =>\n preserveComponentOutput(generation, watcher.duringRestore).pipe(\n Effect.tapErrorTag(\n \"ComponentNodeGroupError\",\n () => watcher.discardRestoreEchoes,\n ),\n Effect.catchTags({\n RemoveBusyError: (error) =>\n Effect.fail(\n new Evaluation.EvaluationError({\n diagnostic: renderCodegenError(error),\n }),\n ),\n // Output that cannot be restored leaves nothing to serve.\n PlatformError: Effect.die,\n }),\n );\n const validate = (\n paths: ReadonlyArray<ImplModulePath>,\n snapshot: GenerationSnapshot.GenerationSnapshot,\n ) =>\n Effect.gen(function* () {\n if (Array.isReadonlyArrayNonEmpty(paths)) {\n const validated = yield* Evaluation.validate(paths).pipe(\n Evaluation.catchAndLog,\n );\n if (Option.isNone(validated)) {\n return SyncState.Outcome.ValidationFailed({ paths, snapshot });\n }\n }\n return SyncState.Outcome.Succeeded({ snapshot });\n });\n const outcome = yield* SyncState.Operation.$match(operation, {\n Generate: () => regenerate(preserved(Evaluation.generateSnapshot)),\n Validate: ({ paths, snapshot }) => validate(paths, snapshot),\n Update: ({ snapshot, declarations, paths }) =>\n regenerate(\n preserved(\n Evaluation.updateDeclarations(snapshot, declarations, paths),\n ),\n ),\n });\n yield* Ref.set(phaseRef, SyncState.transition(outcome));\n if (SyncState.shouldRetry(phase, outcome)) {\n yield* watcher.requestRetry;\n }\n if (!SyncState.Outcome.$is(\"Succeeded\")(outcome)) return;\n\n const dirtyOptionalFiles = [\n ...(HashSet.has(optional, \"Http\")\n ? [syncOptionalFile(generateHttp, \"http.ts\")]\n : []),\n ...(HashSet.has(optional, \"Crons\")\n ? [syncOptionalFile(generateCrons, \"crons.ts\")]\n : []),\n ...(HashSet.has(optional, \"Auth\")\n ? [syncOptionalFile(generateAuthConfig, \"auth.config.ts\")]\n : []),\n ];\n\n yield* Array.isReadonlyArrayNonEmpty(dirtyOptionalFiles)\n ? Effect.all(dirtyOptionalFiles, { concurrency: \"unbounded\" })\n : Effect.void;\n yield* Ref.set(optionalPendingRef, HashSet.empty());\n\n if (SyncState.needsDeploymentNotification(phase))\n yield* touchConvexSchema;\n\n if (!SyncState.isDirty(yield* watcher.pending)) {\n yield* logSuccess(\"Generated files are up-to-date\");\n }\n }),\n );\n});\n\nconst syncOptionalFile = (generate: typeof generateHttp, convexFile: string) =>\n pipe(\n generate,\n Effect.andThen(\n Option.match({\n onSome: ({ change, convexFilePath }) =>\n Match.value(change).pipe(\n Match.when(\"Unchanged\", () => Effect.void),\n Match.whenOr(\"Added\", \"Modified\", (addedOrModified) =>\n logFileChangeIndented(addedOrModified, convexFilePath),\n ),\n Match.exhaustive,\n ),\n onNone: () =>\n Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const convexDirectory = yield* ConvexDirectory.get;\n const convexFilePath = path.join(convexDirectory, convexFile);\n\n if (yield* fs.exists(convexFilePath)) {\n yield* fs.remove(convexFilePath);\n yield* logFileChangeIndented(\"Removed\", convexFilePath);\n }\n }),\n }),\n ),\n );\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAM,cAAc,WAClB,MAAM,MAAM,MAAM,CAAC,CAAC,KAClB,MAAM,KAAK,gBAAgB;CAAE,MAAM;CAAK,OAAOA;AAAW,EAAE,GAC5D,MAAM,KAAK,kBAAkB;CAAE,MAAM;CAAK,OAAOC;AAAS,EAAE,GAC5D,MAAM,KAAK,m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ACA,MAAM,UACR;CACF,cACE,OAAO,IAAI,aAAa;EACtB,MAAM,KAAK,OAAO,WAAW;EAC7B,MAAM,OAAO,OAAO,KAAK;EACzB,MAAM,kBAAkB,OAAO,gBAAgB;EAC/C,MAAM,iBAAiB,KAAK,KAAK,iBAAiB,UAAU;EAE5D,IAAI,OAAO,GAAG,OAAO,cAAc,GAAG;GACpC,OAAO,GAAG,OAAO,cAAc;GAC/B,OAAO,sBAAsB,WAAW,cAAc;EACxD;CACF,CAAC;AACL,CAAC,CACH,CACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gaganref/confect-cli",
3
- "version": "10.3.1-fork.15",
3
+ "version": "10.3.1-fork.17",
4
4
  "dependencies": {
5
5
  "@effect/platform-node": "^4.0.4",
6
6
  "bundle-require": "^5.1.0",
@@ -9,8 +9,8 @@
9
9
  "exsolve": "^1.1.3"
10
10
  },
11
11
  "peerDependencies": {
12
- "@confect/core": "npm:@gaganref/confect-core@10.3.1-fork.15",
13
- "@confect/server": "npm:@gaganref/confect-server@10.3.1-fork.15",
12
+ "@confect/core": "npm:@gaganref/confect-core@10.3.1-fork.17",
13
+ "@confect/server": "npm:@gaganref/confect-server@10.3.1-fork.17",
14
14
  "effect": "^4.0.4"
15
15
  },
16
16
  "description": "Developer tooling for codegen and sync",