@gaganref/confect-server 10.3.1-fork.35 → 10.3.1-fork.38

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.
@@ -46,31 +46,28 @@ export declare const applyMiddleware: <A, E, R>(effect: Effect.Effect<A, E, R>,
46
46
  */
47
47
  export declare const combineErrorSchemas: (error: Schema.Codec<any, any> | undefined, resolvedMiddlewares: ReadonlyArray<ResolvedMiddleware.ResolvedMiddleware>) => Schema.Codec<any, any> | undefined;
48
48
  /**
49
- * Run the `Effect` as a `Promise`. The error schema acts as an allowlist of
50
- * failures that may be surfaced to the client as a `ConvexError`:
49
+ * Run the `Effect` as a `Promise`. Inspect the complete `Exit` before encoding
50
+ * a declared error so a typed failure cannot hide a defect.
51
51
  *
52
- * - With a schema: typed errors are schema-encoded and wrapped in a
53
- * `ConvexError`, then thrown so Convex surfaces the data to the client.
54
- * `Effect.either` escapes the failure channel before `runPromise` so the
55
- * thrown `ConvexError` retains its `Symbol.for("ConvexError")` identity
56
- * instead of being wrapped in Effect's `FiberFailure`.
57
- * - Without a schema: every failure is converted to a defect via `Effect.orDie`,
58
- * so nothing—not even a `ConvexError` the handler placed in its error
59
- * channel—reaches the client as a `ConvexError`. The fiber dies and
60
- * `runPromise` rejects with a generic failure.
52
+ * Any `Die` reason takes the defect path. Without a `Die`, the first `Fail` in
53
+ * cause order is schema-encoded and thrown as a `ConvexError` outside the
54
+ * Effect runtime so Convex surfaces its data to the client. Other failures and
55
+ * interruptions alongside that `Fail` are ignored. Without an error schema, the
56
+ * selected failure is treated as a defect.
61
57
  *
62
- * Either way, a `ConvexError` _defect_—thrown imperatively rather than placed
63
- * in the error channel, e.g. the pagination protocol's `InvalidCursor` signal
64
- * from `QueryStream.paginate`—is rethrown bare so it retains its identity and
65
- * Convex serializes its `data` to the client, matching how a thrown
66
- * `ConvexError` behaves in a plain Convex handler.
58
+ * A lone `ConvexError` defect or a selected undeclared `ConvexError` failure is
59
+ * rethrown bare so it keeps Convex's meaning. Pagination and Workpool rely on
60
+ * its data for their control signals. Other causes with a `Die`, interrupt-only
61
+ * or empty causes, and error-encoding failures reject with a plain `Error`
62
+ * whose message renders the complete cause and whose `cause` holds it for
63
+ * server diagnostics.
67
64
  *
68
65
  * A `scheduler` in `runOptions` must be passed here as a run option rather than
69
66
  * provided via `Effect.provideService` inside `effect`: the run option lands in
70
67
  * the fiber's root context, while a service provided within `effect` pops
71
- * before the `orDie`/`catch`/`result` wrappers this function adds. The fiber's
72
- * op counter survives context pops, so a cooperative yield can fire inside
73
- * those wrappers—only a root-context scheduler covers them.
68
+ * before the exit/encoding wrappers this function adds. The fiber's op counter
69
+ * survives context pops, so a cooperative yield can fire inside those wrappers.
70
+ * Only a root-context scheduler covers them.
74
71
  */
75
72
  export declare const runHandlerPromise: (errorSchema: Schema.Codec<any, any> | undefined, runOptions?: {
76
73
  readonly scheduler?: EffectScheduler.Scheduler | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"RegisteredFunction.d.ts","sourceRoot":"","sources":["../src/RegisteredFunction.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAC1E,OAAO,KAAK,OAAO,MAAM,uBAAuB,CAAC;AACjD,OAAO,KAAK,KAAK,kBAAkB,MAAM,kCAAkC,CAAC;AAC5E,OAAO,KAAK,cAAc,MAAM,8BAA8B,CAAC;AAK/D,OAAO,EACL,KAAK,mBAAmB,EACxB,KAAK,kBAAkB,EACvB,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,aAAa,IAAI,mBAAmB,EACzC,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EACvB,KAAK,eAAe,EACrB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,eAAe,CAAC;AAI3C,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAExC,OAAO,KAAK,KAAK,MAAM,cAA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AIG;AACH,eAAO,MAAM,eAAe,GAAI,eAAe,SAAS,gBAAgB,OACjE,gBAAgB,CAAC,eAAe,CAAC;;;;;;;;;;;;;;;;;;;;;;gBAcrC,CAAC;AAEJ,eAAO,MAAM,WAAW,GACtB,eAAe,SAAS,cAAc,CAAC,YAAY,kBAEnC,eAAe,OAC1B,gBAAgB,CACnB,SAAS,CAAC,QAAQ,CAAC,SAAS,CAAC,UAAU,CAAC,eAAe,CAAC,CAAC,CAC1D;;;;;;;;;;;;;;;;;;sbA6BA,CAAC;AAIJ,eAAO,MAAM,YAAY,GAAI,KAAK,SAAS,OAAO,CAAC,OAAO,UAChD,mBAAmB,KAC1B,KAAK,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,GAAG,aAAa,CAAC,QAAQ,CAAC,KAAK,CAAC,CAG3D,CAAC"}
@@ -23,7 +23,9 @@ import { compileArgsSchema, compileReturnsSchema } from "@confect/core/SchemaToV
23
23
  import { ConvexError } from "convex/values";
24
24
  import * as Result from "effect/Result";
25
25
  import * as IdScope from "@confect/core/IdScope";
26
+ import * as Cause from "effect/Cause";
26
27
  import * as Console from "effect/Console";
28
+ import * as Exit from "effect/Exit";
27
29
  //#region src/RegisteredFunction.ts
28
30
  var RegisteredFunction_exports = /* @__PURE__ */ __exportAll({
29
31
  actionFunctionBase: () => actionFunctionBase,
@@ -63,36 +65,48 @@ const combineErrorSchemas = (error, resolvedMiddlewares) => {
63
65
  return schemas.length === 0 ? void 0 : schemas.length === 1 ? schemas[0] : Schema.Union(schemas);
64
66
  };
65
67
  /**
66
- * Run the `Effect` as a `Promise`. The error schema acts as an allowlist of
67
- * failures that may be surfaced to the client as a `ConvexError`:
68
+ * Run the `Effect` as a `Promise`. Inspect the complete `Exit` before encoding
69
+ * a declared error so a typed failure cannot hide a defect.
68
70
  *
69
- * - With a schema: typed errors are schema-encoded and wrapped in a
70
- * `ConvexError`, then thrown so Convex surfaces the data to the client.
71
- * `Effect.either` escapes the failure channel before `runPromise` so the
72
- * thrown `ConvexError` retains its `Symbol.for("ConvexError")` identity
73
- * instead of being wrapped in Effect's `FiberFailure`.
74
- * - Without a schema: every failure is converted to a defect via `Effect.orDie`,
75
- * so nothing—not even a `ConvexError` the handler placed in its error
76
- * channel—reaches the client as a `ConvexError`. The fiber dies and
77
- * `runPromise` rejects with a generic failure.
71
+ * Any `Die` reason takes the defect path. Without a `Die`, the first `Fail` in
72
+ * cause order is schema-encoded and thrown as a `ConvexError` outside the
73
+ * Effect runtime so Convex surfaces its data to the client. Other failures and
74
+ * interruptions alongside that `Fail` are ignored. Without an error schema, the
75
+ * selected failure is treated as a defect.
78
76
  *
79
- * Either way, a `ConvexError` _defect_—thrown imperatively rather than placed
80
- * in the error channel, e.g. the pagination protocol's `InvalidCursor` signal
81
- * from `QueryStream.paginate`—is rethrown bare so it retains its identity and
82
- * Convex serializes its `data` to the client, matching how a thrown
83
- * `ConvexError` behaves in a plain Convex handler.
77
+ * A lone `ConvexError` defect or a selected undeclared `ConvexError` failure is
78
+ * rethrown bare so it keeps Convex's meaning. Pagination and Workpool rely on
79
+ * its data for their control signals. Other causes with a `Die`, interrupt-only
80
+ * or empty causes, and error-encoding failures reject with a plain `Error`
81
+ * whose message renders the complete cause and whose `cause` holds it for
82
+ * server diagnostics.
84
83
  *
85
84
  * A `scheduler` in `runOptions` must be passed here as a run option rather than
86
85
  * provided via `Effect.provideService` inside `effect`: the run option lands in
87
86
  * the fiber's root context, while a service provided within `effect` pops
88
- * before the `orDie`/`catch`/`result` wrappers this function adds. The fiber's
89
- * op counter survives context pops, so a cooperative yield can fire inside
90
- * those wrappers—only a root-context scheduler covers them.
87
+ * before the exit/encoding wrappers this function adds. The fiber's op counter
88
+ * survives context pops, so a cooperative yield can fire inside those wrappers.
89
+ * Only a root-context scheduler covers them.
91
90
  */
92
91
  const runHandlerPromise = (errorSchema, runOptions) => (effect) => {
93
- const rethrowConvexErrorDefects = Effect.catchDefect((defect) => defect instanceof ConvexError ? Effect.fail(defect) : Effect.die(defect));
94
- const withConvexError = errorSchema === void 0 ? Effect.orDie(effect) : effect.pipe(Effect.catch((typedError) => pipe(Schema.encodeEffect(errorSchema)(typedError), Effect.catchTag("SchemaError", Effect.die), Effect.andThen((encodedError) => Effect.fail(new ConvexError(encodedError))))));
95
- return Effect.runPromise(Effect.result(rethrowConvexErrorDefects(withConvexError)).pipe(Effect.provide(layer$8), Effect.provideService(Console.Console, globalThis.console)), runOptions).then(Result.match({
92
+ const withConvexError = Effect.gen(function* () {
93
+ const exit = yield* Effect.exit(effect);
94
+ if (Exit.isSuccess(exit)) return Result.succeed(exit.value);
95
+ const { cause } = exit;
96
+ const reason = cause.reasons.find(Cause.isDieReason) ?? cause.reasons.find(Cause.isFailReason);
97
+ if (reason?._tag === "Die" && cause.reasons.length === 1 && reason.defect instanceof ConvexError) return Result.fail(reason.defect);
98
+ if (reason?._tag === "Fail") {
99
+ if (errorSchema === void 0) {
100
+ if (reason.error instanceof ConvexError) return Result.fail(reason.error);
101
+ return yield* Effect.die(reason.error);
102
+ }
103
+ const encoded = yield* Effect.exit(Schema.encodeEffect(errorSchema)(reason.error));
104
+ if (Exit.isSuccess(encoded)) return Result.fail(new ConvexError(encoded.value));
105
+ return yield* Effect.die(new Error(Cause.pretty(encoded.cause), { cause: encoded.cause }));
106
+ }
107
+ return yield* Effect.die(new Error(Cause.pretty(cause), { cause }));
108
+ });
109
+ return Effect.runPromise(withConvexError.pipe(Effect.provide(layer$8), Effect.provideService(Console.Console, globalThis.console)), runOptions).then(Result.match({
96
110
  onFailure: (error) => {
97
111
  throw error;
98
112
  },
@@ -1 +1 @@
1
- {"version":3,"file":"RegisteredFunction.js","names":["ConvexLogger.layer","Scheduler.layer","Auth.layer","ExecutionMetadata.layer","RequestMetadata.layer","Storage.layer","QueryRunner.layer","MutationRunner.layer","ActionRunner.layer","ActionCtx.ActionCtx","Auth.layerForTarget","ActionCtx.layer","VectorSearch.layer","ActionCall.ActionCallAlreadyUsed","ActionCall.SchedulingNotAllowed","ActionCall.NestedActionNotAllowed","ActionCall.ActionCallNotUsed"],"sources":["../src/RegisteredFunction.ts"],"sourcesContent":["import * as ActionCallSpec from \"@confect/core/ActionCall\";\nimport * as ActionCall from \"./ActionCall.js\";\nimport type { FunctionSpec, RuntimeAndFunctionType } from \"@confect/core\";\nimport * as IdScope from \"@confect/core/IdScope\";\nimport type * as FunctionProvenance from \"@confect/core/FunctionProvenance\";\nimport * as MiddlewareSpec from \"@confect/core/MiddlewareSpec\";\nimport {\n compileArgsSchema,\n compileReturnsSchema,\n} from \"@confect/core/SchemaToValidator\";\nimport {\n type DefaultFunctionArgs,\n type FunctionVisibility,\n type GenericActionCtx,\n type GenericDataModel,\n type StorageReader as ConvexStorageReader,\n type RegisteredAction,\n type RegisteredMutation,\n type RegisteredQuery,\n} from \"convex/server\";\nimport type { Value } from \"convex/values\";\nimport { ConvexError } from \"convex/values\";\nimport { pipe } from \"effect/Function\";\nimport * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport * as Result from \"effect/Result\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport type * as EffectScheduler from \"effect/Scheduler\";\nimport * as ActionCtx from \"./ActionCtx.js\";\nimport * as ActionRunner from \"./ActionRunner.js\";\nimport * as Auth from \"./Auth.js\";\nimport * as ConvexLogger from \"./ConvexLogger.js\";\nimport type * as DatabaseSchema from \"./DatabaseSchema.js\";\nimport type * as DataModel from \"./DataModel.js\";\nimport * as ExecutionMetadata from \"./ExecutionMetadata.js\";\nimport * as RequestMetadata from \"./RequestMetadata.js\";\nimport * as MutationRunner from \"./MutationRunner.js\";\nimport * as QueryRunner from \"./QueryRunner.js\";\nimport type * as ResolvedMiddleware from \"./ResolvedMiddleware.js\";\nimport * as Scheduler from \"./Scheduler.js\";\nimport * as Storage from \"./Storage.js\";\nimport * as StorageActionWriter from \"./StorageActionWriter.js\";\nimport type * as StorageReader from \"./StorageReader.js\";\nimport * as StorageWriter from \"./StorageWriter.js\";\nimport * as VectorSearch from \"./VectorSearch.js\";\nimport type * as Handler from \"./Handler.js\";\n\nexport type Any =\n | RegisteredQuery<FunctionVisibility, DefaultFunctionArgs, any>\n | RegisteredMutation<FunctionVisibility, DefaultFunctionArgs, any>\n | RegisteredAction<FunctionVisibility, DefaultFunctionArgs, any>;\n\ntype ConfectRegisteredFunction<\n FunctionSpec_ extends FunctionSpec.AnyWithProps,\n> =\n FunctionSpec.EncodedArgs<FunctionSpec_> extends infer Args_ extends\n DefaultFunctionArgs\n ? RuntimeAndFunctionType.GetFunctionType<\n FunctionSpec_[\"runtimeAndFunctionType\"]\n > extends \"query\"\n ? RegisteredQuery<\n FunctionSpec.GetFunctionVisibility<FunctionSpec_>,\n Args_,\n Promise<FunctionSpec.EncodedReturns<FunctionSpec_>>\n >\n : RuntimeAndFunctionType.GetFunctionType<\n FunctionSpec_[\"runtimeAndFunctionType\"]\n > extends \"mutation\"\n ? RegisteredMutation<\n FunctionSpec.GetFunctionVisibility<FunctionSpec_>,\n Args_,\n Promise<FunctionSpec.EncodedReturns<FunctionSpec_>>\n >\n : RuntimeAndFunctionType.GetFunctionType<\n FunctionSpec_[\"runtimeAndFunctionType\"]\n > extends \"action\"\n ? RegisteredAction<\n FunctionSpec.GetFunctionVisibility<FunctionSpec_>,\n Args_,\n Promise<FunctionSpec.EncodedReturns<FunctionSpec_>>\n >\n : never\n : never;\n\nexport type ConvexRegisteredFunction<\n FunctionSpec_ extends FunctionSpec.AnyWithProps,\n> = FunctionSpec_ extends FunctionSpec.AnyWithProps\n ? FunctionSpec.GetFunctionProvenance<FunctionSpec_> extends FunctionProvenance.Convex<\n infer Args_ extends DefaultFunctionArgs,\n infer Returns_\n >\n ? RuntimeAndFunctionType.GetFunctionType<\n FunctionSpec_[\"runtimeAndFunctionType\"]\n > extends \"query\"\n ? RegisteredQuery<\n FunctionSpec.GetFunctionVisibility<FunctionSpec_>,\n Args_,\n Returns_\n >\n : RuntimeAndFunctionType.GetFunctionType<\n FunctionSpec_[\"runtimeAndFunctionType\"]\n > extends \"mutation\"\n ? RegisteredMutation<\n FunctionSpec.GetFunctionVisibility<FunctionSpec_>,\n Args_,\n Returns_\n >\n : RuntimeAndFunctionType.GetFunctionType<\n FunctionSpec_[\"runtimeAndFunctionType\"]\n > extends \"action\"\n ? RegisteredAction<\n FunctionSpec.GetFunctionVisibility<FunctionSpec_>,\n Args_,\n Returns_\n >\n : never\n : never\n : never;\n\nexport type RegisteredFunction<\n FunctionSpec_ extends FunctionSpec.AnyWithProps,\n> =\n FunctionSpec_ extends FunctionSpec.WithFunctionProvenance<\n FunctionSpec_,\n FunctionProvenance.AnyConvex\n >\n ? ConvexRegisteredFunction<FunctionSpec_>\n : FunctionSpec_ extends FunctionSpec.WithFunctionProvenance<\n FunctionSpec_,\n FunctionProvenance.AnyConfect\n >\n ? ConfectRegisteredFunction<FunctionSpec_>\n : never;\n\n/**\n * Wrap a function's handler effect in its resolved middleware chain, per\n * invocation, after args decode. Iterated innermost-first so that the\n * first-attached (group-level, in attachment order) middleware ends up\n * outermost and runs first. Erased types: the public safety story lives at the\n * `MiddlewareSpec.MiddlewareImpl`/`MiddlewareImpl.make` signatures, and the\n * composed effect's error channel is re-accounted by\n * {@link combineErrorSchemas}.\n */\nexport const applyMiddleware = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n resolvedMiddlewares: ReadonlyArray<ResolvedMiddleware.ResolvedMiddleware>,\n invocation: MiddlewareSpec.MiddlewareOptions[\"invocation\"],\n): Effect.Effect<A, any, R> => {\n return resolvedMiddlewares.reduceRight<Effect.Effect<any, any, any>>(\n // oxlint-disable-next-line effecttsgo/any-unknown-in-error-context -- The erased middleware error remains intact so runHandlerPromise can validate it against the combined error schema.\n (wrapped, middleware) => {\n const context =\n \"options\" in middleware.middlewareSpec\n ? { options: middleware.options, invocation }\n : { invocation };\n // oxlint-disable-next-line effecttsgo/any-unknown-in-error-context -- Resolved middleware is type-erased after its public implementation boundary; its error and service channels are restored by the surrounding function contract.\n return middleware.middlewareImpl(wrapped, context);\n },\n effect,\n );\n};\n\n/**\n * The error-schema allowlist for a function with middleware: the function's own\n * declared `error` schema unioned with every covering middleware's error\n * schema. `undefined` (⇒ every failure dies) only when neither declares\n * one—mirroring the ref-side union clients decode against.\n */\nexport const combineErrorSchemas = (\n error: Schema.Codec<any, any> | undefined,\n resolvedMiddlewares: ReadonlyArray<ResolvedMiddleware.ResolvedMiddleware>,\n): Schema.Codec<any, any> | undefined => {\n const schemas = [\n ...(error !== undefined ? [error] : []),\n ...MiddlewareSpec.errorSchemas(\n resolvedMiddlewares.map(({ middlewareSpec }) => middlewareSpec),\n ),\n ];\n return schemas.length === 0\n ? undefined\n : schemas.length === 1\n ? schemas[0]\n : Schema.Union(schemas);\n};\n\n/**\n * Run the `Effect` as a `Promise`. The error schema acts as an allowlist of\n * failures that may be surfaced to the client as a `ConvexError`:\n *\n * - With a schema: typed errors are schema-encoded and wrapped in a\n * `ConvexError`, then thrown so Convex surfaces the data to the client.\n * `Effect.either` escapes the failure channel before `runPromise` so the\n * thrown `ConvexError` retains its `Symbol.for(\"ConvexError\")` identity\n * instead of being wrapped in Effect's `FiberFailure`.\n * - Without a schema: every failure is converted to a defect via `Effect.orDie`,\n * so nothing—not even a `ConvexError` the handler placed in its error\n * channel—reaches the client as a `ConvexError`. The fiber dies and\n * `runPromise` rejects with a generic failure.\n *\n * Either way, a `ConvexError` _defect_—thrown imperatively rather than placed\n * in the error channel, e.g. the pagination protocol's `InvalidCursor` signal\n * from `QueryStream.paginate`—is rethrown bare so it retains its identity and\n * Convex serializes its `data` to the client, matching how a thrown\n * `ConvexError` behaves in a plain Convex handler.\n *\n * A `scheduler` in `runOptions` must be passed here as a run option rather than\n * provided via `Effect.provideService` inside `effect`: the run option lands in\n * the fiber's root context, while a service provided within `effect` pops\n * before the `orDie`/`catch`/`result` wrappers this function adds. The fiber's\n * op counter survives context pops, so a cooperative yield can fire inside\n * those wrappers—only a root-context scheduler covers them.\n */\nexport const runHandlerPromise =\n (\n errorSchema: Schema.Codec<any, any> | undefined,\n runOptions?: {\n readonly scheduler?: EffectScheduler.Scheduler | undefined;\n },\n ) =>\n <A, E>(effect: Effect.Effect<A, E>): Promise<A> => {\n // A `ConvexError` defect escapes into the (escaped) failure channel so\n // the `throw` below rethrows it with its identity intact.\n const rethrowConvexErrorDefects = Effect.catchDefect(\n (defect: unknown): Effect.Effect<never, ConvexError<any>> =>\n defect instanceof ConvexError\n ? Effect.fail(defect)\n : Effect.die(defect),\n );\n\n const withConvexError =\n errorSchema === undefined\n ? Effect.orDie(effect)\n : effect.pipe(\n Effect.catch((typedError) =>\n pipe(\n Schema.encodeEffect(errorSchema)(typedError),\n Effect.catchTag(\"SchemaError\", Effect.die),\n Effect.andThen((encodedError) =>\n Effect.fail(new ConvexError(encodedError)),\n ),\n ),\n ),\n );\n return Effect.runPromise(\n Effect.result(rethrowConvexErrorDefects(withConvexError)).pipe(\n Effect.provide(ConvexLogger.layer),\n Effect.provideService(Console.Console, globalThis.console),\n ),\n runOptions,\n ).then(\n Result.match({\n onFailure: (error) => {\n throw error;\n },\n onSuccess: (value) => value,\n }),\n );\n };\n\nexport const actionFunctionBase = <\n Schema extends DatabaseSchema.AnyWithProps,\n Args,\n ConvexArgs extends DefaultFunctionArgs,\n Returns,\n ConvexReturns,\n E,\n R,\n>({\n name,\n functionVisibility,\n args,\n returns,\n error,\n handler,\n resolvedMiddlewares = [],\n createLayer,\n scope = IdScope.app,\n}: {\n name: string;\n functionVisibility: FunctionVisibility;\n args: Schema.Codec<Args, ConvexArgs>;\n returns: Schema.Codec<Returns, ConvexReturns>;\n error: Schema.Codec<Error, Value> | undefined;\n handler: (a: Args) => Effect.Effect<Returns, E, R>;\n resolvedMiddlewares?: ReadonlyArray<ResolvedMiddleware.ResolvedMiddleware>;\n createLayer: (\n ctx: GenericActionCtx<DataModel.ToConvex<DataModel.FromSchema<Schema>>>,\n ) => Layer.Layer<R>;\n scope?: IdScope.IdScope;\n}) => ({\n args: compileArgsSchema(args, scope),\n returns: compileReturnsSchema(returns, scope),\n handler: (\n ctx: GenericActionCtx<DataModel.ToConvex<DataModel.FromSchema<Schema>>>,\n actualArgs: ConvexArgs,\n ): Promise<ConvexReturns> =>\n Effect.gen(function* () {\n const decodedArgs = yield* pipe(\n actualArgs,\n Schema.decodeUnknownEffect(args),\n Effect.catchTag(\"SchemaError\", Effect.die),\n );\n const restricted = resolvedMiddlewares.some(\n ({ middlewareSpec }) =>\n middlewareSpec.key === ActionCallSpec.Middleware.key,\n )\n ? restrict(ctx)\n : undefined;\n // oxlint-disable-next-line effecttsgo/any-unknown-in-error-context -- Middleware errors are intentionally erased here and validated by runHandlerPromise against the combined error schema below.\n const decodedReturns = yield* applyMiddleware(\n handler(decodedArgs),\n resolvedMiddlewares,\n {\n name,\n functionType: \"action\",\n functionVisibility,\n args: decodedArgs,\n },\n ).pipe(Effect.provide(createLayer(restricted?.ctx ?? ctx)));\n if (restricted !== undefined) yield* restricted.check;\n return yield* pipe(\n decodedReturns,\n Schema.encodeEffect(returns),\n Effect.catchTag(\"SchemaError\", Effect.die),\n );\n }).pipe(runHandlerPromise(combineErrorSchemas(error, resolvedMiddlewares))),\n});\n\nexport type ActionServices<\n DatabaseSchema_ extends DatabaseSchema.AnyWithProps,\n> = Handler.ActionServices<DatabaseSchema_>;\n\n/**\n * The ctx-backed action services that don't depend on a Confect database\n * schema. {@link actionLayer} adds the schema-typed `VectorSearch` on top; the\n * HTTP API handler uses this base directly.\n */\nexport const baseActionLayer = <ConvexDataModel extends GenericDataModel>(\n ctx: GenericActionCtx<ConvexDataModel>,\n) =>\n Layer.mergeAll(\n Scheduler.layer(ctx.scheduler),\n Auth.layer(ctx.auth),\n ExecutionMetadata.layer(ctx.meta),\n RequestMetadata.layer(ctx.meta),\n Storage.layer(ctx.storage),\n StorageWriter.StorageWriter.layer(ctx.storage),\n StorageActionWriter.StorageActionWriter.layer(ctx.storage),\n QueryRunner.layer(ctx.runQuery.bind(ctx)),\n MutationRunner.layer(ctx.runMutation.bind(ctx)),\n ActionRunner.layer(ctx.runAction.bind(ctx)),\n Layer.succeed(ActionCtx.ActionCtx<ConvexDataModel>(), ctx),\n );\n\nexport const actionLayer = <\n DatabaseSchema_ extends DatabaseSchema.AnyWithProps,\n>(\n databaseSchema: DatabaseSchema_,\n ctx: GenericActionCtx<\n DataModel.ToConvex<DataModel.FromSchema<DatabaseSchema_>>\n >,\n) =>\n Layer.mergeAll(\n Scheduler.layer<DatabaseSchema.Scope<DatabaseSchema_>>(\n ctx.scheduler,\n databaseSchema.target.scope,\n ),\n Auth.layerForTarget<DatabaseSchema_[\"target\"]>(\n databaseSchema.target,\n ctx.auth,\n ),\n ExecutionMetadata.layer(ctx.meta),\n RequestMetadata.layer(ctx.meta),\n storageLayer<DatabaseSchema.Scope<DatabaseSchema_>>(ctx.storage),\n StorageWriter.StorageWriter.layer<DatabaseSchema.Scope<DatabaseSchema_>>(\n ctx.storage,\n databaseSchema.target.scope,\n ),\n StorageActionWriter.StorageActionWriter.layer<\n DatabaseSchema.Scope<DatabaseSchema_>\n >(ctx.storage, databaseSchema.target.scope),\n QueryRunner.layer(ctx.runQuery.bind(ctx)),\n MutationRunner.layer(ctx.runMutation.bind(ctx)),\n ActionRunner.layer(ctx.runAction.bind(ctx)),\n ActionCtx.layer<\n DataModel.ToConvex<DataModel.FromSchema<DatabaseSchema_>>,\n DatabaseSchema.Scope<DatabaseSchema_>\n >(ctx, databaseSchema.target.scope),\n VectorSearch.layer(ctx.vectorSearch.bind(ctx)),\n );\n\n// Scoped readers share the same runtime service and ID strings. Reuse the\n// reader supplied by Storage so both APIs keep the same reader instance.\nexport const storageLayer = <Scope extends IdScope.IdScope>(\n reader: ConvexStorageReader,\n): Layer.Layer<Storage.Storage | StorageReader.ForScope<Scope>> =>\n Storage.layer(reader) as Layer.Layer<\n Storage.Storage | StorageReader.ForScope<Scope>\n >;\n\n/**\n * Shares one dispatch budget across the entire middleware chain.\n */\nconst restrict = <Model extends GenericDataModel>(\n ctx: GenericActionCtx<Model>,\n) => {\n let dispatched = false;\n const claim = () => {\n if (dispatched) throw new ActionCall.ActionCallAlreadyUsed();\n dispatched = true;\n };\n const restricted: GenericActionCtx<Model> = {\n ...ctx,\n scheduler: {\n runAfter: () => {\n throw new ActionCall.SchedulingNotAllowed();\n },\n runAt: () => {\n throw new ActionCall.SchedulingNotAllowed();\n },\n cancel: () => {\n throw new ActionCall.SchedulingNotAllowed();\n },\n },\n runQuery: (...args) => {\n claim();\n return ctx.runQuery(...args);\n },\n runMutation: (...args) => {\n claim();\n return ctx.runMutation(...args);\n },\n runAction: () => {\n throw new ActionCall.NestedActionNotAllowed();\n },\n };\n return {\n ctx: restricted,\n check: Effect.suspend(() =>\n dispatched ? Effect.void : Effect.die(new ActionCall.ActionCallNotUsed()),\n ),\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgJA,MAAa,mBACX,QACA,qBACA,eAC6B;CAC7B,OAAO,oBAAoB,aAExB,SAAS,eAAe;EACvB,MAAM,UACJ,aAAa,WAAW,iBACpB;GAAE,SAAS,WAAW;GAAS;EAAW,IAC1C,EAAE,WAAW;EAEnB,OAAO,WAAW,eAAe,SAAS,OAAO;CACnD,GACA,MACF;AACF;;;;;;;AAQA,MAAa,uBACX,OACA,wBACuC;CACvC,MAAM,UAAU,CACd,GAAI,UAAU,KAAA,IAAY,CAAC,KAAK,IAAI,CAAC,GACrC,GAAG,eAAe,aAChB,oBAAoB,KAAK,EAAE,qBAAqB,cAAc,CAChE,CACF;CACA,OAAO,QAAQ,WAAW,IACtB,KAAA,IACA,QAAQ,WAAW,IACjB,QAAQ,KACR,OAAO,MAAM,OAAO;AAC5B;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAa,qBAET,aACA,gBAIK,WAA4C;CAGjD,MAAM,4BAA4B,OAAO,aACtC,WACC,kBAAkB,cACd,OAAO,KAAK,MAAM,IAClB,OAAO,IAA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AM,IAAIC,qBAAgC;IAC5C;IACA,aAAa;KACX,MAAM,IAAIA,qBAAgC;IAC5C;IACA,cAAc;KACZ,MAAM,IAAIA,qBAAgC;IAC5C;GACF;GACA,WAAW,GAAG,SAAS;IACrB,MAAM;IACN,OAAO,IAAI,SAAS,GAAG,IAAI;GAC7B;GACA,cAAc,GAAG,SAAS;IACxB,MAAM;IACN,OAAO,IAAI,YAAY,GAAG,IAAI;GAChC;GACA,iBAAiB;IACf,MAAM,IAAIC,uBAAkC;GAC9C;EAGc;EACd,OAAO,OAAO,cACZ,aAAa,OAAO,OAAO,OAAO,IAAI,IAAIC,kBAA6B,CAAC,CAC1E;CACF;AACF"}
1
+ {"version":3,"file":"RegisteredFunction.js","names":["ConvexLogger.layer","Scheduler.layer","Auth.layer","ExecutionMetadata.layer","RequestMetadata.layer","Storage.layer","QueryRunner.layer","MutationRunner.layer","ActionRunner.layer","ActionCtx.ActionCtx","Auth.layerForTarget","ActionCtx.layer","VectorSearch.layer","ActionCall.ActionCallAlreadyUsed","ActionCall.SchedulingNotAllowed","ActionCall.NestedActionNotAllowed","ActionCall.ActionCallNotUsed"],"sources":["../src/RegisteredFunction.ts"],"sourcesContent":["import * as ActionCallSpec from \"@confect/core/ActionCall\";\nimport * as ActionCall from \"./ActionCall.js\";\nimport type { FunctionSpec, RuntimeAndFunctionType } from \"@confect/core\";\nimport * as IdScope from \"@confect/core/IdScope\";\nimport type * as FunctionProvenance from \"@confect/core/FunctionProvenance\";\nimport * as MiddlewareSpec from \"@confect/core/MiddlewareSpec\";\nimport {\n compileArgsSchema,\n compileReturnsSchema,\n} from \"@confect/core/SchemaToValidator\";\nimport {\n type DefaultFunctionArgs,\n type FunctionVisibility,\n type GenericActionCtx,\n type GenericDataModel,\n type StorageReader as ConvexStorageReader,\n type RegisteredAction,\n type RegisteredMutation,\n type RegisteredQuery,\n} from \"convex/server\";\nimport type { Value } from \"convex/values\";\nimport { ConvexError } from \"convex/values\";\nimport { pipe } from \"effect/Function\";\nimport * as Cause from \"effect/Cause\";\nimport * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Result from \"effect/Result\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport type * as EffectScheduler from \"effect/Scheduler\";\nimport * as ActionCtx from \"./ActionCtx.js\";\nimport * as ActionRunner from \"./ActionRunner.js\";\nimport * as Auth from \"./Auth.js\";\nimport * as ConvexLogger from \"./ConvexLogger.js\";\nimport type * as DatabaseSchema from \"./DatabaseSchema.js\";\nimport type * as DataModel from \"./DataModel.js\";\nimport * as ExecutionMetadata from \"./ExecutionMetadata.js\";\nimport * as RequestMetadata from \"./RequestMetadata.js\";\nimport * as MutationRunner from \"./MutationRunner.js\";\nimport * as QueryRunner from \"./QueryRunner.js\";\nimport type * as ResolvedMiddleware from \"./ResolvedMiddleware.js\";\nimport * as Scheduler from \"./Scheduler.js\";\nimport * as Storage from \"./Storage.js\";\nimport * as StorageActionWriter from \"./StorageActionWriter.js\";\nimport type * as StorageReader from \"./StorageReader.js\";\nimport * as StorageWriter from \"./StorageWriter.js\";\nimport * as VectorSearch from \"./VectorSearch.js\";\nimport type * as Handler from \"./Handler.js\";\n\nexport type Any =\n | RegisteredQuery<FunctionVisibility, DefaultFunctionArgs, any>\n | RegisteredMutation<FunctionVisibility, DefaultFunctionArgs, any>\n | RegisteredAction<FunctionVisibility, DefaultFunctionArgs, any>;\n\ntype ConfectRegisteredFunction<\n FunctionSpec_ extends FunctionSpec.AnyWithProps,\n> =\n FunctionSpec.EncodedArgs<FunctionSpec_> extends infer Args_ extends\n DefaultFunctionArgs\n ? RuntimeAndFunctionType.GetFunctionType<\n FunctionSpec_[\"runtimeAndFunctionType\"]\n > extends \"query\"\n ? RegisteredQuery<\n FunctionSpec.GetFunctionVisibility<FunctionSpec_>,\n Args_,\n Promise<FunctionSpec.EncodedReturns<FunctionSpec_>>\n >\n : RuntimeAndFunctionType.GetFunctionType<\n FunctionSpec_[\"runtimeAndFunctionType\"]\n > extends \"mutation\"\n ? RegisteredMutation<\n FunctionSpec.GetFunctionVisibility<FunctionSpec_>,\n Args_,\n Promise<FunctionSpec.EncodedReturns<FunctionSpec_>>\n >\n : RuntimeAndFunctionType.GetFunctionType<\n FunctionSpec_[\"runtimeAndFunctionType\"]\n > extends \"action\"\n ? RegisteredAction<\n FunctionSpec.GetFunctionVisibility<FunctionSpec_>,\n Args_,\n Promise<FunctionSpec.EncodedReturns<FunctionSpec_>>\n >\n : never\n : never;\n\nexport type ConvexRegisteredFunction<\n FunctionSpec_ extends FunctionSpec.AnyWithProps,\n> = FunctionSpec_ extends FunctionSpec.AnyWithProps\n ? FunctionSpec.GetFunctionProvenance<FunctionSpec_> extends FunctionProvenance.Convex<\n infer Args_ extends DefaultFunctionArgs,\n infer Returns_\n >\n ? RuntimeAndFunctionType.GetFunctionType<\n FunctionSpec_[\"runtimeAndFunctionType\"]\n > extends \"query\"\n ? RegisteredQuery<\n FunctionSpec.GetFunctionVisibility<FunctionSpec_>,\n Args_,\n Returns_\n >\n : RuntimeAndFunctionType.GetFunctionType<\n FunctionSpec_[\"runtimeAndFunctionType\"]\n > extends \"mutation\"\n ? RegisteredMutation<\n FunctionSpec.GetFunctionVisibility<FunctionSpec_>,\n Args_,\n Returns_\n >\n : RuntimeAndFunctionType.GetFunctionType<\n FunctionSpec_[\"runtimeAndFunctionType\"]\n > extends \"action\"\n ? RegisteredAction<\n FunctionSpec.GetFunctionVisibility<FunctionSpec_>,\n Args_,\n Returns_\n >\n : never\n : never\n : never;\n\nexport type RegisteredFunction<\n FunctionSpec_ extends FunctionSpec.AnyWithProps,\n> =\n FunctionSpec_ extends FunctionSpec.WithFunctionProvenance<\n FunctionSpec_,\n FunctionProvenance.AnyConvex\n >\n ? ConvexRegisteredFunction<FunctionSpec_>\n : FunctionSpec_ extends FunctionSpec.WithFunctionProvenance<\n FunctionSpec_,\n FunctionProvenance.AnyConfect\n >\n ? ConfectRegisteredFunction<FunctionSpec_>\n : never;\n\n/**\n * Wrap a function's handler effect in its resolved middleware chain, per\n * invocation, after args decode. Iterated innermost-first so that the\n * first-attached (group-level, in attachment order) middleware ends up\n * outermost and runs first. Erased types: the public safety story lives at the\n * `MiddlewareSpec.MiddlewareImpl`/`MiddlewareImpl.make` signatures, and the\n * composed effect's error channel is re-accounted by\n * {@link combineErrorSchemas}.\n */\nexport const applyMiddleware = <A, E, R>(\n effect: Effect.Effect<A, E, R>,\n resolvedMiddlewares: ReadonlyArray<ResolvedMiddleware.ResolvedMiddleware>,\n invocation: MiddlewareSpec.MiddlewareOptions[\"invocation\"],\n): Effect.Effect<A, any, R> => {\n return resolvedMiddlewares.reduceRight<Effect.Effect<any, any, any>>(\n // oxlint-disable-next-line effecttsgo/any-unknown-in-error-context -- The erased middleware error remains intact so runHandlerPromise can validate it against the combined error schema.\n (wrapped, middleware) => {\n const context =\n \"options\" in middleware.middlewareSpec\n ? { options: middleware.options, invocation }\n : { invocation };\n // oxlint-disable-next-line effecttsgo/any-unknown-in-error-context -- Resolved middleware is type-erased after its public implementation boundary; its error and service channels are restored by the surrounding function contract.\n return middleware.middlewareImpl(wrapped, context);\n },\n effect,\n );\n};\n\n/**\n * The error-schema allowlist for a function with middleware: the function's own\n * declared `error` schema unioned with every covering middleware's error\n * schema. `undefined` (⇒ every failure dies) only when neither declares\n * one—mirroring the ref-side union clients decode against.\n */\nexport const combineErrorSchemas = (\n error: Schema.Codec<any, any> | undefined,\n resolvedMiddlewares: ReadonlyArray<ResolvedMiddleware.ResolvedMiddleware>,\n): Schema.Codec<any, any> | undefined => {\n const schemas = [\n ...(error !== undefined ? [error] : []),\n ...MiddlewareSpec.errorSchemas(\n resolvedMiddlewares.map(({ middlewareSpec }) => middlewareSpec),\n ),\n ];\n return schemas.length === 0\n ? undefined\n : schemas.length === 1\n ? schemas[0]\n : Schema.Union(schemas);\n};\n\n/**\n * Run the `Effect` as a `Promise`. Inspect the complete `Exit` before encoding\n * a declared error so a typed failure cannot hide a defect.\n *\n * Any `Die` reason takes the defect path. Without a `Die`, the first `Fail` in\n * cause order is schema-encoded and thrown as a `ConvexError` outside the\n * Effect runtime so Convex surfaces its data to the client. Other failures and\n * interruptions alongside that `Fail` are ignored. Without an error schema, the\n * selected failure is treated as a defect.\n *\n * A lone `ConvexError` defect or a selected undeclared `ConvexError` failure is\n * rethrown bare so it keeps Convex's meaning. Pagination and Workpool rely on\n * its data for their control signals. Other causes with a `Die`, interrupt-only\n * or empty causes, and error-encoding failures reject with a plain `Error`\n * whose message renders the complete cause and whose `cause` holds it for\n * server diagnostics.\n *\n * A `scheduler` in `runOptions` must be passed here as a run option rather than\n * provided via `Effect.provideService` inside `effect`: the run option lands in\n * the fiber's root context, while a service provided within `effect` pops\n * before the exit/encoding wrappers this function adds. The fiber's op counter\n * survives context pops, so a cooperative yield can fire inside those wrappers.\n * Only a root-context scheduler covers them.\n */\nexport const runHandlerPromise =\n (\n errorSchema: Schema.Codec<any, any> | undefined,\n runOptions?: {\n readonly scheduler?: EffectScheduler.Scheduler | undefined;\n },\n ) =>\n <A, E>(effect: Effect.Effect<A, E>): Promise<A> => {\n const withConvexError: Effect.Effect<Result.Result<A, ConvexError<any>>> =\n Effect.gen(function* () {\n const exit = yield* Effect.exit(effect);\n if (Exit.isSuccess(exit)) {\n return Result.succeed(exit.value);\n }\n\n const { cause } = exit;\n const reason =\n cause.reasons.find(Cause.isDieReason) ??\n cause.reasons.find(Cause.isFailReason);\n if (\n reason?._tag === \"Die\" &&\n cause.reasons.length === 1 &&\n reason.defect instanceof ConvexError\n ) {\n return Result.fail(reason.defect);\n }\n\n if (reason?._tag === \"Fail\") {\n if (errorSchema === undefined) {\n if (reason.error instanceof ConvexError) {\n return Result.fail(reason.error);\n }\n return yield* Effect.die(reason.error);\n }\n const encoded = yield* Effect.exit(\n Schema.encodeEffect(errorSchema)(reason.error),\n );\n if (Exit.isSuccess(encoded)) {\n return Result.fail(new ConvexError(encoded.value));\n }\n return yield* Effect.die(\n new Error(Cause.pretty(encoded.cause), { cause: encoded.cause }),\n );\n }\n return yield* Effect.die(new Error(Cause.pretty(cause), { cause }));\n });\n return Effect.runPromise(\n withConvexError.pipe(\n Effect.provide(ConvexLogger.layer),\n Effect.provideService(Console.Console, globalThis.console),\n ),\n runOptions,\n ).then(\n Result.match({\n onFailure: (error) => {\n throw error;\n },\n onSuccess: (value) => value,\n }),\n );\n };\n\nexport const actionFunctionBase = <\n Schema extends DatabaseSchema.AnyWithProps,\n Args,\n ConvexArgs extends DefaultFunctionArgs,\n Returns,\n ConvexReturns,\n E,\n R,\n>({\n name,\n functionVisibility,\n args,\n returns,\n error,\n handler,\n resolvedMiddlewares = [],\n createLayer,\n scope = IdScope.app,\n}: {\n name: string;\n functionVisibility: FunctionVisibility;\n args: Schema.Codec<Args, ConvexArgs>;\n returns: Schema.Codec<Returns, ConvexReturns>;\n error: Schema.Codec<Error, Value> | undefined;\n handler: (a: Args) => Effect.Effect<Returns, E, R>;\n resolvedMiddlewares?: ReadonlyArray<ResolvedMiddleware.ResolvedMiddleware>;\n createLayer: (\n ctx: GenericActionCtx<DataModel.ToConvex<DataModel.FromSchema<Schema>>>,\n ) => Layer.Layer<R>;\n scope?: IdScope.IdScope;\n}) => ({\n args: compileArgsSchema(args, scope),\n returns: compileReturnsSchema(returns, scope),\n handler: (\n ctx: GenericActionCtx<DataModel.ToConvex<DataModel.FromSchema<Schema>>>,\n actualArgs: ConvexArgs,\n ): Promise<ConvexReturns> =>\n Effect.gen(function* () {\n const decodedArgs = yield* pipe(\n actualArgs,\n Schema.decodeUnknownEffect(args),\n Effect.catchTag(\"SchemaError\", Effect.die),\n );\n const restricted = resolvedMiddlewares.some(\n ({ middlewareSpec }) =>\n middlewareSpec.key === ActionCallSpec.Middleware.key,\n )\n ? restrict(ctx)\n : undefined;\n // oxlint-disable-next-line effecttsgo/any-unknown-in-error-context -- Middleware errors are intentionally erased here and validated by runHandlerPromise against the combined error schema below.\n const decodedReturns = yield* applyMiddleware(\n handler(decodedArgs),\n resolvedMiddlewares,\n {\n name,\n functionType: \"action\",\n functionVisibility,\n args: decodedArgs,\n },\n ).pipe(Effect.provide(createLayer(restricted?.ctx ?? ctx)));\n if (restricted !== undefined) yield* restricted.check;\n return yield* pipe(\n decodedReturns,\n Schema.encodeEffect(returns),\n Effect.catchTag(\"SchemaError\", Effect.die),\n );\n }).pipe(runHandlerPromise(combineErrorSchemas(error, resolvedMiddlewares))),\n});\n\nexport type ActionServices<\n DatabaseSchema_ extends DatabaseSchema.AnyWithProps,\n> = Handler.ActionServices<DatabaseSchema_>;\n\n/**\n * The ctx-backed action services that don't depend on a Confect database\n * schema. {@link actionLayer} adds the schema-typed `VectorSearch` on top; the\n * HTTP API handler uses this base directly.\n */\nexport const baseActionLayer = <ConvexDataModel extends GenericDataModel>(\n ctx: GenericActionCtx<ConvexDataModel>,\n) =>\n Layer.mergeAll(\n Scheduler.layer(ctx.scheduler),\n Auth.layer(ctx.auth),\n ExecutionMetadata.layer(ctx.meta),\n RequestMetadata.layer(ctx.meta),\n Storage.layer(ctx.storage),\n StorageWriter.StorageWriter.layer(ctx.storage),\n StorageActionWriter.StorageActionWriter.layer(ctx.storage),\n QueryRunner.layer(ctx.runQuery.bind(ctx)),\n MutationRunner.layer(ctx.runMutation.bind(ctx)),\n ActionRunner.layer(ctx.runAction.bind(ctx)),\n Layer.succeed(ActionCtx.ActionCtx<ConvexDataModel>(), ctx),\n );\n\nexport const actionLayer = <\n DatabaseSchema_ extends DatabaseSchema.AnyWithProps,\n>(\n databaseSchema: DatabaseSchema_,\n ctx: GenericActionCtx<\n DataModel.ToConvex<DataModel.FromSchema<DatabaseSchema_>>\n >,\n) =>\n Layer.mergeAll(\n Scheduler.layer<DatabaseSchema.Scope<DatabaseSchema_>>(\n ctx.scheduler,\n databaseSchema.target.scope,\n ),\n Auth.layerForTarget<DatabaseSchema_[\"target\"]>(\n databaseSchema.target,\n ctx.auth,\n ),\n ExecutionMetadata.layer(ctx.meta),\n RequestMetadata.layer(ctx.meta),\n storageLayer<DatabaseSchema.Scope<DatabaseSchema_>>(ctx.storage),\n StorageWriter.StorageWriter.layer<DatabaseSchema.Scope<DatabaseSchema_>>(\n ctx.storage,\n databaseSchema.target.scope,\n ),\n StorageActionWriter.StorageActionWriter.layer<\n DatabaseSchema.Scope<DatabaseSchema_>\n >(ctx.storage, databaseSchema.target.scope),\n QueryRunner.layer(ctx.runQuery.bind(ctx)),\n MutationRunner.layer(ctx.runMutation.bind(ctx)),\n ActionRunner.layer(ctx.runAction.bind(ctx)),\n ActionCtx.layer<\n DataModel.ToConvex<DataModel.FromSchema<DatabaseSchema_>>,\n DatabaseSchema.Scope<DatabaseSchema_>\n >(ctx, databaseSchema.target.scope),\n VectorSearch.layer(ctx.vectorSearch.bind(ctx)),\n );\n\n// Scoped readers share the same runtime service and ID strings. Reuse the\n// reader supplied by Storage so both APIs keep the same reader instance.\nexport const storageLayer = <Scope extends IdScope.IdScope>(\n reader: ConvexStorageReader,\n): Layer.Layer<Storage.Storage | StorageReader.ForScope<Scope>> =>\n Storage.layer(reader) as Layer.Layer<\n Storage.Storage | StorageReader.ForScope<Scope>\n >;\n\n/**\n * Shares one dispatch budget across the entire middleware chain.\n */\nconst restrict = <Model extends GenericDataModel>(\n ctx: GenericActionCtx<Model>,\n) => {\n let dispatched = false;\n const claim = () => {\n if (dispatched) throw new ActionCall.ActionCallAlreadyUsed();\n dispatched = true;\n };\n const restricted: GenericActionCtx<Model> = {\n ...ctx,\n scheduler: {\n runAfter: () => {\n throw new ActionCall.SchedulingNotAllowed();\n },\n runAt: () => {\n throw new ActionCall.SchedulingNotAllowed();\n },\n cancel: () => {\n throw new ActionCall.SchedulingNotAllowed();\n },\n },\n runQuery: (...args) => {\n claim();\n return ctx.runQuery(...args);\n },\n runMutation: (...args) => {\n claim();\n return ctx.runMutation(...args);\n },\n runAction: () => {\n throw new ActionCall.NestedActionNotAllowed();\n },\n };\n return {\n ctx: restricted,\n check: Effect.su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,sBAAiC;EAC3D,aAAa;CACf;CA0BA,OAAO;EACL,KAAK;GAzBL,GAAG;GACH,WAAW;IACT,gBAAgB;KACd,MAAM,IAAIC,qBAAgC;IAC5C;IACA,aAAa;KACX,MAAM,IAAIA,qBAAgC;IAC5C;IACA,cAAc;KACZ,MAAM,IAAIA,qBAAgC;IAC5C;GACF;GACA,WAAW,GAAG,SAAS;IACrB,MAAM;IACN,OAAO,IAAI,SAAS,GAAG,IAAI;GAC7B;GACA,cAAc,GAAG,SAAS;IACxB,MAAM;IACN,OAAO,IAAI,YAAY,GAAG,IAAI;GAChC;GACA,iBAAiB;IACf,MAAM,IAAIC,uBAAkC;GAC9C;EAGc;EACd,OAAO,OAAO,cACZ,aAAa,OAAO,OAAO,OAAO,IAAI,IAAIC,kBAA6B,CAAC,CAC1E;CACF;AACF"}
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "@gaganref/confect-server",
3
- "version": "10.3.1-fork.35",
3
+ "version": "10.3.1-fork.38",
4
4
  "dependencies": {
5
5
  "@effect/ai-openai-compat": "4.0.4",
6
6
  "@effect/ai-openrouter": "4.0.4"
7
7
  },
8
8
  "peerDependencies": {
9
- "@confect/core": "npm:@gaganref/confect-core@10.3.1-fork.35",
10
- "@effect/platform-node": "^4.0.0",
9
+ "@confect/core": "npm:@gaganref/confect-core@10.3.1-fork.38",
10
+ "@effect/platform-node": ">=4.0.0 <4.1.0",
11
11
  "convex": "^1.48.0",
12
- "effect": "^4.0.4"
12
+ "effect": ">=4.0.4 <4.1.0"
13
13
  },
14
14
  "description": "Backend bindings to the Convex platform",
15
15
  "author": "RJ Dellecese",
@@ -21,8 +21,10 @@ import {
21
21
  import type { Value } from "convex/values";
22
22
  import { ConvexError } from "convex/values";
23
23
  import { pipe } from "effect/Function";
24
+ import * as Cause from "effect/Cause";
24
25
  import * as Console from "effect/Console";
25
26
  import * as Effect from "effect/Effect";
27
+ import * as Exit from "effect/Exit";
26
28
  import * as Result from "effect/Result";
27
29
  import * as Layer from "effect/Layer";
28
30
  import * as Schema from "effect/Schema";
@@ -185,31 +187,28 @@ export const combineErrorSchemas = (
185
187
  };
186
188
 
187
189
  /**
188
- * Run the `Effect` as a `Promise`. The error schema acts as an allowlist of
189
- * failures that may be surfaced to the client as a `ConvexError`:
190
+ * Run the `Effect` as a `Promise`. Inspect the complete `Exit` before encoding
191
+ * a declared error so a typed failure cannot hide a defect.
190
192
  *
191
- * - With a schema: typed errors are schema-encoded and wrapped in a
192
- * `ConvexError`, then thrown so Convex surfaces the data to the client.
193
- * `Effect.either` escapes the failure channel before `runPromise` so the
194
- * thrown `ConvexError` retains its `Symbol.for("ConvexError")` identity
195
- * instead of being wrapped in Effect's `FiberFailure`.
196
- * - Without a schema: every failure is converted to a defect via `Effect.orDie`,
197
- * so nothing—not even a `ConvexError` the handler placed in its error
198
- * channel—reaches the client as a `ConvexError`. The fiber dies and
199
- * `runPromise` rejects with a generic failure.
193
+ * Any `Die` reason takes the defect path. Without a `Die`, the first `Fail` in
194
+ * cause order is schema-encoded and thrown as a `ConvexError` outside the
195
+ * Effect runtime so Convex surfaces its data to the client. Other failures and
196
+ * interruptions alongside that `Fail` are ignored. Without an error schema, the
197
+ * selected failure is treated as a defect.
200
198
  *
201
- * Either way, a `ConvexError` _defect_—thrown imperatively rather than placed
202
- * in the error channel, e.g. the pagination protocol's `InvalidCursor` signal
203
- * from `QueryStream.paginate`—is rethrown bare so it retains its identity and
204
- * Convex serializes its `data` to the client, matching how a thrown
205
- * `ConvexError` behaves in a plain Convex handler.
199
+ * A lone `ConvexError` defect or a selected undeclared `ConvexError` failure is
200
+ * rethrown bare so it keeps Convex's meaning. Pagination and Workpool rely on
201
+ * its data for their control signals. Other causes with a `Die`, interrupt-only
202
+ * or empty causes, and error-encoding failures reject with a plain `Error`
203
+ * whose message renders the complete cause and whose `cause` holds it for
204
+ * server diagnostics.
206
205
  *
207
206
  * A `scheduler` in `runOptions` must be passed here as a run option rather than
208
207
  * provided via `Effect.provideService` inside `effect`: the run option lands in
209
208
  * the fiber's root context, while a service provided within `effect` pops
210
- * before the `orDie`/`catch`/`result` wrappers this function adds. The fiber's
211
- * op counter survives context pops, so a cooperative yield can fire inside
212
- * those wrappers—only a root-context scheduler covers them.
209
+ * before the exit/encoding wrappers this function adds. The fiber's op counter
210
+ * survives context pops, so a cooperative yield can fire inside those wrappers.
211
+ * Only a root-context scheduler covers them.
213
212
  */
214
213
  export const runHandlerPromise =
215
214
  (
@@ -219,31 +218,46 @@ export const runHandlerPromise =
219
218
  },
220
219
  ) =>
221
220
  <A, E>(effect: Effect.Effect<A, E>): Promise<A> => {
222
- // A `ConvexError` defect escapes into the (escaped) failure channel so
223
- // the `throw` below rethrows it with its identity intact.
224
- const rethrowConvexErrorDefects = Effect.catchDefect(
225
- (defect: unknown): Effect.Effect<never, ConvexError<any>> =>
226
- defect instanceof ConvexError
227
- ? Effect.fail(defect)
228
- : Effect.die(defect),
229
- );
221
+ const withConvexError: Effect.Effect<Result.Result<A, ConvexError<any>>> =
222
+ Effect.gen(function* () {
223
+ const exit = yield* Effect.exit(effect);
224
+ if (Exit.isSuccess(exit)) {
225
+ return Result.succeed(exit.value);
226
+ }
227
+
228
+ const { cause } = exit;
229
+ const reason =
230
+ cause.reasons.find(Cause.isDieReason) ??
231
+ cause.reasons.find(Cause.isFailReason);
232
+ if (
233
+ reason?._tag === "Die" &&
234
+ cause.reasons.length === 1 &&
235
+ reason.defect instanceof ConvexError
236
+ ) {
237
+ return Result.fail(reason.defect);
238
+ }
230
239
 
231
- const withConvexError =
232
- errorSchema === undefined
233
- ? Effect.orDie(effect)
234
- : effect.pipe(
235
- Effect.catch((typedError) =>
236
- pipe(
237
- Schema.encodeEffect(errorSchema)(typedError),
238
- Effect.catchTag("SchemaError", Effect.die),
239
- Effect.andThen((encodedError) =>
240
- Effect.fail(new ConvexError(encodedError)),
241
- ),
242
- ),
243
- ),
240
+ if (reason?._tag === "Fail") {
241
+ if (errorSchema === undefined) {
242
+ if (reason.error instanceof ConvexError) {
243
+ return Result.fail(reason.error);
244
+ }
245
+ return yield* Effect.die(reason.error);
246
+ }
247
+ const encoded = yield* Effect.exit(
248
+ Schema.encodeEffect(errorSchema)(reason.error),
249
+ );
250
+ if (Exit.isSuccess(encoded)) {
251
+ return Result.fail(new ConvexError(encoded.value));
252
+ }
253
+ return yield* Effect.die(
254
+ new Error(Cause.pretty(encoded.cause), { cause: encoded.cause }),
244
255
  );
256
+ }
257
+ return yield* Effect.die(new Error(Cause.pretty(cause), { cause }));
258
+ });
245
259
  return Effect.runPromise(
246
- Effect.result(rethrowConvexErrorDefects(withConvexError)).pipe(
260
+ withConvexError.pipe(
247
261
  Effect.provide(ConvexLogger.layer),
248
262
  Effect.provideService(Console.Console, globalThis.console),
249
263
  ),