kitcn 0.17.0 → 0.17.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { H as ConvexContext, W as LazyCaller } from "../../procedure-name-Bo5KMcqc.js";
1
+ import { H as ConvexContext, W as LazyCaller } from "../../procedure-name-exVcmr_p.js";
2
2
  import { t as GetTokenOptions } from "../../token-B9Bjcqug.js";
3
3
 
4
4
  //#region src/auth-nextjs/index.d.ts
@@ -4798,12 +4798,21 @@ export function defineMigration(
4798
4798
  }
4799
4799
  `;
4800
4800
  }
4801
+ function renderRuntimeApiTypesImport(entries, importPath) {
4802
+ const specifiers = [];
4803
+ if (entries.some((entry) => !entry.internal)) specifiers.push("api as generatedApi");
4804
+ if (entries.some((entry) => entry.internal)) specifiers.push("internal as generatedInternal");
4805
+ if (specifiers.length === 0) return "";
4806
+ if (specifiers.length === 1) return `import type { ${specifiers[0]} } from '${importPath}';\n`;
4807
+ return `import type {\n${specifiers.map((specifier) => ` ${specifier},\n`).join("")}} from '${importPath}';\n`;
4808
+ }
4801
4809
  function emitGeneratedModuleRuntimeFile(outputFile, functionsDir, moduleName, procedureEntries, runtimeExportNames) {
4802
4810
  const { callerExportName, handlerExportName } = runtimeExportNames?.get(moduleName) ?? getModuleRuntimeExportNames(moduleName);
4803
4811
  const useGeneratedApiTypes = moduleUsesOwnGeneratedRuntime(functionsDir, moduleName);
4804
4812
  const runtimeApiTypesImportPath = useGeneratedApiTypes ? getRuntimeApiTypesImportPath(outputFile, functionsDir) : null;
4805
4813
  const generatedServerImportPath = getGeneratedServerImportPath(outputFile, functionsDir);
4806
4814
  const { callerEntries, handlerEntries } = partitionRuntimeEntriesForEmission(procedureEntries);
4815
+ const runtimeApiTypesImport = runtimeApiTypesImportPath ? renderRuntimeApiTypesImport(callerEntries, runtimeApiTypesImportPath) : "";
4807
4816
  const callerRegistryLines = emitProcedureRegistryEntries(callerEntries, outputFile, functionsDir, moduleName, useGeneratedApiTypes);
4808
4817
  const callerRegistryBody = callerRegistryLines.length > 0 ? `\n${callerRegistryLines.join("\n")}\n` : "\n";
4809
4818
  const hasHandlerRegistry = handlerEntries.length > 0;
@@ -4852,11 +4861,7 @@ import {
4852
4861
  typedProcedureResolver,
4853
4862
  type GeneratedRegistryCallerForContext,${hasHandlerRegistry ? "\n type GeneratedRegistryHandlerForContext," : ""}
4854
4863
  } from 'kitcn/server';
4855
- ${runtimeApiTypesImportPath ? `import type {
4856
- api as generatedApi,
4857
- internal as generatedInternal,
4858
- } from '${runtimeApiTypesImportPath}';
4859
- ` : ""}import type { ActionCtx, MutationCtx, QueryCtx } from '${generatedServerImportPath}';
4864
+ ${runtimeApiTypesImport}import type { ActionCtx, MutationCtx, QueryCtx } from '${generatedServerImportPath}';
4860
4865
  import type { OrmTriggerContext } from 'kitcn/orm';
4861
4866
 
4862
4867
  const procedureRegistry = {${callerRegistryBody}} as const;
@@ -795,46 +795,51 @@ function getApiErrorMessage(cause) {
795
795
  * Convert known framework/library errors into CRPCError.
796
796
  *
797
797
  * Intended for cRPC internals so callers don't need per-endpoint try/catch.
798
+ *
799
+ * Never assign `.stack` on a converted error. The Convex backend only forwards
800
+ * `data` for a thrown error after it reads `__frameData` off it, and
801
+ * `__frameData` is written as a side effect of the runtime's
802
+ * `Error.prepareStackTrace` hook, which V8 runs lazily on the *first* read of
803
+ * `.stack`. Assigning `.stack` satisfies later reads without ever running the
804
+ * hook, so the backend bails out of source mapping and the client receives a
805
+ * bare `Error` with the message redacted to `Server Error` and no `.data` —
806
+ * losing the cRPC `code`, `message`, and custom payload. The original stack
807
+ * stays reachable at `err.cause.stack`. See `error.vitest.ts`.
798
808
  */
799
809
  function toCRPCError(cause) {
800
810
  if (cause instanceof CRPCError) return cause;
801
811
  if (cause instanceof Error && cause.name === "CRPCError") return cause;
802
812
  if (isConvexErrorLike(cause) && isCRPCErrorData(cause.data)) {
803
813
  const { code, message, ...data } = cause.data;
804
- const err = new CRPCError({
814
+ return new CRPCError({
805
815
  code,
806
816
  message,
807
817
  cause,
808
818
  data
809
819
  });
810
- if (cause.stack) err.stack = cause.stack;
811
- return err;
812
- }
813
- if (isOrmNotFoundErrorLike(cause)) {
814
- const err = new CRPCError({
815
- code: "NOT_FOUND",
816
- message: cause.message,
817
- cause
818
- });
819
- if (cause.stack) err.stack = cause.stack;
820
- return err;
821
820
  }
821
+ if (isOrmNotFoundErrorLike(cause)) return new CRPCError({
822
+ code: "NOT_FOUND",
823
+ message: cause.message,
824
+ cause
825
+ });
822
826
  if (isApiErrorLike(cause)) {
823
827
  const status = cause.status;
824
828
  const statusCode = cause.statusCode;
825
- const err = new CRPCError({
829
+ return new CRPCError({
826
830
  code: typeof status === "string" && status in CRPC_ERROR_CODES_BY_KEY ? status : typeof statusCode === "number" ? mapHttpStatusCodeToCRPCCode(statusCode) : "INTERNAL_SERVER_ERROR",
827
831
  message: getApiErrorMessage(cause),
828
832
  cause
829
833
  });
830
- if (cause.stack) err.stack = cause.stack;
831
- return err;
832
834
  }
833
835
  return null;
834
836
  }
835
837
  /**
836
838
  * Wrap unknown error in CRPCError (from tRPC)
837
839
  *
840
+ * The original stack stays reachable at `err.cause.stack`. See the note on
841
+ * `toCRPCError` for why it must not be copied onto the returned error.
842
+ *
838
843
  * @example
839
844
  * ```typescript
840
845
  * try {
@@ -847,12 +852,10 @@ function toCRPCError(cause) {
847
852
  function getCRPCErrorFromUnknown(cause) {
848
853
  const handled = toCRPCError(cause);
849
854
  if (handled) return handled;
850
- const error = new CRPCError({
855
+ return new CRPCError({
851
856
  code: "INTERNAL_SERVER_ERROR",
852
857
  cause
853
858
  });
854
- if (cause instanceof Error && cause.stack) error.stack = cause.stack;
855
- return error;
856
859
  }
857
860
  /**
858
861
  * Get HTTP status code from CRPCError
package/dist/cli.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { $ as promptForScaffoldTemplateSelection, A as resolveCodegenTrimSegments, B as runConfiguredCodegen, C as isEntryPoint, Ct as formatDependencyInstallCommand, D as parseInitCommandArgs, E as parseBackendRunJson, Et as stripConvexCommandNoise, F as resolveRunDeps, G as runMigrationFlow, H as runDevSchemaBackfillIfNeeded, I as runAfterScaffoldScript, J as withWorkingDirectory, K as trackProcess, L as runAggregateBackfillFlow, M as resolveDocTopic, N as resolveInitProjectDir, O as readPackageVersions, P as resolveMigrationConfig, Q as promptForPluginSelection, R as runAggregatePruneFlow, S as isConvexDevPreRunConflictFlag, St as detectPackageManager, T as parseArgs, Tt as serializeEnvValue, U as runInitCommandFlow, V as runConvexInitIfNeeded, W as runMigrationCreate, X as collectPluginScaffoldTemplates, Y as createSpinner, Z as filterScaffoldTemplatePathMap, _ as formatInfoOutput, _t as applyPlanningDependencyInstall, a as cleanup, at as getPluginCatalogEntry, b as getDevAggregateBackfillStatePath, bt as resolveSupportedDependencyWarnings, c as createCommandEnv, ct as buildPluginInstallPlan, d as extractBackfillCliOptions, dt as collectInstalledPluginKeys, et as resolveAddTemplateDefaults, f as extractConcaveRunTargetArgs, ft as getPluginLockfilePath, g as formatDocsOutput, gt as applyDependencyHintsInstall, h as extractResetCliOptions, ht as resolveSchemaInstalledPlugins, i as buildInitializationPlan, it as resolveTemplatesByIdOrThrow, j as resolveConfiguredBackend, jt as highlighter, k as resolveBackfillConfig, kt as logger, l as ensureConvexGitignoreEntry, lt as resolvePluginScaffoldRoots, m as extractMigrationDownOptions, mt as readPluginLockfile, n as applyPluginInstallPlanFiles, nt as resolvePresetScaffoldTemplates, o as createBackendAdapter, ot as getSupportedPluginKeys, p as extractMigrationCliOptions, pt as getSchemaFilePath, q as withLocalCodegenEnv, r as assertNoRemovedDevPreRunFlag, rt as resolveTemplateSelectionSource, s as createBackendCommandEnv, st as isSupportedPluginKey, t as applyDependencyInstallPlan, tt as resolvePluginPreset, u as extractBackendRunTargetArgs, ut as assertSchemaFileExists, v as getAggregateBackfillDeploymentKey, vt as applyPluginDependencyInstall, w as isInitialized, wt as resolveAuthEnvState, x as hasRemoteConvexDeploymentEnv, xt as resolveProjectScaffoldContext, y as getConvexDeploymentCommandEnv, yt as inspectPluginDependencyInstall, z as runBackendFunction } from "./backend-core-BsKP1LVg.mjs";
2
+ import { $ as promptForScaffoldTemplateSelection, A as resolveCodegenTrimSegments, B as runConfiguredCodegen, C as isEntryPoint, Ct as formatDependencyInstallCommand, D as parseInitCommandArgs, E as parseBackendRunJson, Et as stripConvexCommandNoise, F as resolveRunDeps, G as runMigrationFlow, H as runDevSchemaBackfillIfNeeded, I as runAfterScaffoldScript, J as withWorkingDirectory, K as trackProcess, L as runAggregateBackfillFlow, M as resolveDocTopic, N as resolveInitProjectDir, O as readPackageVersions, P as resolveMigrationConfig, Q as promptForPluginSelection, R as runAggregatePruneFlow, S as isConvexDevPreRunConflictFlag, St as detectPackageManager, T as parseArgs, Tt as serializeEnvValue, U as runInitCommandFlow, V as runConvexInitIfNeeded, W as runMigrationCreate, X as collectPluginScaffoldTemplates, Y as createSpinner, Z as filterScaffoldTemplatePathMap, _ as formatInfoOutput, _t as applyPlanningDependencyInstall, a as cleanup, at as getPluginCatalogEntry, b as getDevAggregateBackfillStatePath, bt as resolveSupportedDependencyWarnings, c as createCommandEnv, ct as buildPluginInstallPlan, d as extractBackfillCliOptions, dt as collectInstalledPluginKeys, et as resolveAddTemplateDefaults, f as extractConcaveRunTargetArgs, ft as getPluginLockfilePath, g as formatDocsOutput, gt as applyDependencyHintsInstall, h as extractResetCliOptions, ht as resolveSchemaInstalledPlugins, i as buildInitializationPlan, it as resolveTemplatesByIdOrThrow, j as resolveConfiguredBackend, jt as highlighter, k as resolveBackfillConfig, kt as logger, l as ensureConvexGitignoreEntry, lt as resolvePluginScaffoldRoots, m as extractMigrationDownOptions, mt as readPluginLockfile, n as applyPluginInstallPlanFiles, nt as resolvePresetScaffoldTemplates, o as createBackendAdapter, ot as getSupportedPluginKeys, p as extractMigrationCliOptions, pt as getSchemaFilePath, q as withLocalCodegenEnv, r as assertNoRemovedDevPreRunFlag, rt as resolveTemplateSelectionSource, s as createBackendCommandEnv, st as isSupportedPluginKey, t as applyDependencyInstallPlan, tt as resolvePluginPreset, u as extractBackendRunTargetArgs, ut as assertSchemaFileExists, v as getAggregateBackfillDeploymentKey, vt as applyPluginDependencyInstall, w as isInitialized, wt as resolveAuthEnvState, x as hasRemoteConvexDeploymentEnv, xt as resolveProjectScaffoldContext, y as getConvexDeploymentCommandEnv, yt as inspectPluginDependencyInstall, z as runBackendFunction } from "./backend-core-KwJ5FZgj.mjs";
3
3
  import fs, { existsSync, readFileSync } from "node:fs";
4
4
  import path, { delimiter, dirname, join, relative, resolve } from "node:path";
5
5
  import { fileURLToPath } from "node:url";
@@ -1,4 +1,4 @@
1
- import { a as createMiddlewareFactory } from "./builder-f4F_NRvK.js";
1
+ import { a as createMiddlewareFactory } from "./builder-Dwy6D2QA.js";
2
2
 
3
3
  //#region src/plugins/middleware.ts
4
4
  const PLUGIN_CONFIG_RESOLVERS = Symbol.for("kitcn:PluginConfigResolvers");
@@ -1,3 +1,3 @@
1
- import { n as resolvePluginOptions, t as definePlugin } from "../middleware-Cgrv2jIu.js";
1
+ import { n as resolvePluginOptions, t as definePlugin } from "../middleware-qzHEHaDy.js";
2
2
 
3
3
  export { definePlugin, resolvePluginOptions };
@@ -1,5 +1,5 @@
1
1
  import { i as decodeWire, o as encodeWire } from "./transformer-C6pGVHqx.js";
2
- import { _ as CRPCError } from "./builder-f4F_NRvK.js";
2
+ import { _ as CRPCError } from "./builder-Dwy6D2QA.js";
3
3
  import { z } from "zod";
4
4
 
5
5
  //#region src/server/env.ts
@@ -1184,11 +1184,24 @@ declare class CRPCError<TData extends Record<string, Value$1 | undefined> = Reco
1184
1184
  * Convert known framework/library errors into CRPCError.
1185
1185
  *
1186
1186
  * Intended for cRPC internals so callers don't need per-endpoint try/catch.
1187
+ *
1188
+ * Never assign `.stack` on a converted error. The Convex backend only forwards
1189
+ * `data` for a thrown error after it reads `__frameData` off it, and
1190
+ * `__frameData` is written as a side effect of the runtime's
1191
+ * `Error.prepareStackTrace` hook, which V8 runs lazily on the *first* read of
1192
+ * `.stack`. Assigning `.stack` satisfies later reads without ever running the
1193
+ * hook, so the backend bails out of source mapping and the client receives a
1194
+ * bare `Error` with the message redacted to `Server Error` and no `.data` —
1195
+ * losing the cRPC `code`, `message`, and custom payload. The original stack
1196
+ * stays reachable at `err.cause.stack`. See `error.vitest.ts`.
1187
1197
  */
1188
1198
  declare function toCRPCError(cause: unknown): CRPCError | null;
1189
1199
  /**
1190
1200
  * Wrap unknown error in CRPCError (from tRPC)
1191
1201
  *
1202
+ * The original stack stays reachable at `err.cause.stack`. See the note on
1203
+ * `toCRPCError` for why it must not be copied onto the returned error.
1204
+ *
1192
1205
  * @example
1193
1206
  * ```typescript
1194
1207
  * try {
@@ -1,6 +1,6 @@
1
1
  import { u as requireMutationCtx } from "../api-entry-N3nBOlI2.js";
2
- import { _ as CRPCError } from "../builder-f4F_NRvK.js";
3
- import { t as definePlugin } from "../middleware-Cgrv2jIu.js";
2
+ import { _ as CRPCError } from "../builder-Dwy6D2QA.js";
3
+ import { t as definePlugin } from "../middleware-qzHEHaDy.js";
4
4
  import { v } from "convex/values";
5
5
  import { mutationGeneric, queryGeneric } from "convex/server";
6
6
 
@@ -1,4 +1,4 @@
1
- import { $ as ActionProcedureBuilder, A as CRPCError, B as RuntimeEnv, C as createProcedureHandlerFactory, Ct as zCustomQuery, D as WithHttpRouter, Dt as zodToConvex, E as typedProcedureResolver, Et as zodOutputToConvexFields, F as getCRPCErrorFromUnknown, G as createLazyCaller, H as ConvexContext, I as getHTTPStatusCodeFromError, J as ServerCaller, K as CallerMeta, L as isCRPCError, M as CRPCErrorData, N as CRPC_ERROR_CODES_BY_KEY, O as inferApiInputs, Ot as zodToConvexFields, P as CRPC_ERROR_CODE_TO_HTTP, Q as getGeneratedValue, R as toCRPCError, S as createProcedureCallerFactory, St as zCustomMutation, T as getGeneratedFunctionReference, Tt as zodOutputToConvex, U as createCallerFactory, V as createEnv, W as LazyCaller, X as createApiLeaf, Y as createServerCaller, Z as createGeneratedFunctionReference, _ as ProcedureSchedulableCallerFromRegistry, _t as ZodValidatorFromConvex, a as CreateProcedureCallerFactoryOptions, at as initCRPC, b as createGenericCallerFactory, bt as withSystemFields, c as GeneratedRegistryCallerFactory, ct as extractPathParams, d as GeneratedRegistryHandlerForContext, dt as ConvexValidatorFromZod, et as CRPCFunctionTypeHint, f as ProcedureActionCallerFromRegistry, ft as ConvexValidatorFromZodOutput, g as ProcedureFromFunctionReference, gt as ZodFromValidatorBase, h as ProcedureDefinition, ht as Zid, i as registerProcedureNameLookup, it as createMiddlewareFactory, j as CRPCErrorCode, k as inferApiOutputs, l as GeneratedRegistryCallerForContext, lt as handleHttpError, m as ProcedureCallerFromRegistry, mt as ZCustomCtx, n as ProcedureNameLookup, nt as ProcedureBuilder, o as GeneratedProcedureRegistry, ot as HttpProcedureBuilder, p as ProcedureCaller, pt as CustomBuilder, q as CallerOpts, r as inferProcedureNameFromCallsite, rt as QueryProcedureBuilder, s as GeneratedProcedureRegistryEntry, st as createHttpProcedureBuilder, t as ProcedureNameEntry, tt as MutationProcedureBuilder, u as GeneratedRegistryHandlerFactory, ut as matchPathParams, v as ProcedureScheduleCallerFromRegistry, vt as convexToZod, w as defineProcedure, wt as zid, x as createGenericHandlerFactory, xt as zCustomAction, y as createGeneratedRegistryRuntime, yt as convexToZodFields, z as CreateEnvOptions } from "../procedure-name-Bo5KMcqc.js";
1
+ import { $ as ActionProcedureBuilder, A as CRPCError, B as RuntimeEnv, C as createProcedureHandlerFactory, Ct as zCustomQuery, D as WithHttpRouter, Dt as zodToConvex, E as typedProcedureResolver, Et as zodOutputToConvexFields, F as getCRPCErrorFromUnknown, G as createLazyCaller, H as ConvexContext, I as getHTTPStatusCodeFromError, J as ServerCaller, K as CallerMeta, L as isCRPCError, M as CRPCErrorData, N as CRPC_ERROR_CODES_BY_KEY, O as inferApiInputs, Ot as zodToConvexFields, P as CRPC_ERROR_CODE_TO_HTTP, Q as getGeneratedValue, R as toCRPCError, S as createProcedureCallerFactory, St as zCustomMutation, T as getGeneratedFunctionReference, Tt as zodOutputToConvex, U as createCallerFactory, V as createEnv, W as LazyCaller, X as createApiLeaf, Y as createServerCaller, Z as createGeneratedFunctionReference, _ as ProcedureSchedulableCallerFromRegistry, _t as ZodValidatorFromConvex, a as CreateProcedureCallerFactoryOptions, at as initCRPC, b as createGenericCallerFactory, bt as withSystemFields, c as GeneratedRegistryCallerFactory, ct as extractPathParams, d as GeneratedRegistryHandlerForContext, dt as ConvexValidatorFromZod, et as CRPCFunctionTypeHint, f as ProcedureActionCallerFromRegistry, ft as ConvexValidatorFromZodOutput, g as ProcedureFromFunctionReference, gt as ZodFromValidatorBase, h as ProcedureDefinition, ht as Zid, i as registerProcedureNameLookup, it as createMiddlewareFactory, j as CRPCErrorCode, k as inferApiOutputs, l as GeneratedRegistryCallerForContext, lt as handleHttpError, m as ProcedureCallerFromRegistry, mt as ZCustomCtx, n as ProcedureNameLookup, nt as ProcedureBuilder, o as GeneratedProcedureRegistry, ot as HttpProcedureBuilder, p as ProcedureCaller, pt as CustomBuilder, q as CallerOpts, r as inferProcedureNameFromCallsite, rt as QueryProcedureBuilder, s as GeneratedProcedureRegistryEntry, st as createHttpProcedureBuilder, t as ProcedureNameEntry, tt as MutationProcedureBuilder, u as GeneratedRegistryHandlerFactory, ut as matchPathParams, v as ProcedureScheduleCallerFromRegistry, vt as convexToZod, w as defineProcedure, wt as zid, x as createGenericHandlerFactory, xt as zCustomAction, y as createGeneratedRegistryRuntime, yt as convexToZodFields, z as CreateEnvOptions } from "../procedure-name-exVcmr_p.js";
2
2
  import { C as HttpProcedure, D as ProcedureMeta, E as InferHttpInput, S as HttpMethod, T as HttpRouteDefinition, _ as extractRouteMap, b as HttpActionHandler, d as CRPCHttpRouter, f as HttpRouterDef, g as createHttpRouterFactory, h as createHttpRouter, m as HttpRouterWithHono, p as HttpRouterRecord, v as CRPCHonoHandler, w as HttpProcedureBuilderDef, x as HttpHandlerOpts, y as HttpActionConstructor } from "../http-types-zsMHb_QN.js";
3
3
  import { a as MergeZodObjects, c as MiddlewareMarker, d as MiddlewareProcedureType, f as MiddlewareResult, g as UnsetMarker, h as Simplify, i as IntersectIfDefined, l as MiddlewareNext, m as ResolveIfSet, n as AnyMiddlewareBuilder, o as MiddlewareBuilder, p as Overwrite, r as GetRawInputFn, s as MiddlewareFunction, t as AnyMiddleware, u as MiddlewareProcedureInfo } from "../types-CnTpHR1F.js";
4
4
  import { a as isMutationCtx, c as isSchedulerCtx, d as requireQueryCtx, f as requireRunMutationCtx, i as isActionCtx, l as requireActionCtx, n as RunMutationCtx, o as isQueryCtx, p as requireSchedulerCtx, r as SchedulerCtx, s as isRunMutationCtx, t as GenericCtx, u as requireMutationCtx } from "../context-utils-BBUtBqjN.js";
@@ -1,6 +1,6 @@
1
1
  import { a as isMutationCtx, c as isSchedulerCtx, d as requireQueryCtx, f as requireRunMutationCtx, i as isActionCtx, l as requireActionCtx, n as createGeneratedFunctionReference, o as isQueryCtx, p as requireSchedulerCtx, r as getGeneratedValue, s as isRunMutationCtx, t as createApiLeaf, u as requireMutationCtx } from "../api-entry-N3nBOlI2.js";
2
2
  import { n as createLazyCaller, r as createServerCaller, t as createCallerFactory } from "../caller-factory-DHywSoGZ.js";
3
- import { A as zid, C as toCRPCError, D as zCustomAction, E as withSystemFields, M as zodOutputToConvexFields, N as zodToConvex, O as zCustomMutation, P as zodToConvexFields, S as isCRPCError, T as convexToZodFields, _ as CRPCError, a as createMiddlewareFactory, b as getCRPCErrorFromUnknown, c as registerProcedureNameLookup, d as createHttpRouterFactory, f as extractRouteMap, g as matchPathParams, h as handleHttpError, i as QueryProcedureBuilder, j as zodOutputToConvex, k as zCustomQuery, l as HttpRouterWithHono, m as extractPathParams, n as MutationProcedureBuilder, o as initCRPC, p as createHttpProcedureBuilder, r as ProcedureBuilder, s as inferProcedureNameFromCallsite, t as ActionProcedureBuilder, u as createHttpRouter, v as CRPC_ERROR_CODES_BY_KEY, w as convexToZod, x as getHTTPStatusCodeFromError, y as CRPC_ERROR_CODE_TO_HTTP } from "../builder-f4F_NRvK.js";
4
- import { a as createProcedureHandlerFactory, c as typedProcedureResolver, i as createProcedureCallerFactory, l as createEnv, n as createGenericCallerFactory, o as defineProcedure, r as createGenericHandlerFactory, s as getGeneratedFunctionReference, t as createGeneratedRegistryRuntime } from "../procedure-caller-Rj6z3ai7.js";
3
+ import { A as zid, C as toCRPCError, D as zCustomAction, E as withSystemFields, M as zodOutputToConvexFields, N as zodToConvex, O as zCustomMutation, P as zodToConvexFields, S as isCRPCError, T as convexToZodFields, _ as CRPCError, a as createMiddlewareFactory, b as getCRPCErrorFromUnknown, c as registerProcedureNameLookup, d as createHttpRouterFactory, f as extractRouteMap, g as matchPathParams, h as handleHttpError, i as QueryProcedureBuilder, j as zodOutputToConvex, k as zCustomQuery, l as HttpRouterWithHono, m as extractPathParams, n as MutationProcedureBuilder, o as initCRPC, p as createHttpProcedureBuilder, r as ProcedureBuilder, s as inferProcedureNameFromCallsite, t as ActionProcedureBuilder, u as createHttpRouter, v as CRPC_ERROR_CODES_BY_KEY, w as convexToZod, x as getHTTPStatusCodeFromError, y as CRPC_ERROR_CODE_TO_HTTP } from "../builder-Dwy6D2QA.js";
4
+ import { a as createProcedureHandlerFactory, c as typedProcedureResolver, i as createProcedureCallerFactory, l as createEnv, n as createGenericCallerFactory, o as defineProcedure, r as createGenericHandlerFactory, s as getGeneratedFunctionReference, t as createGeneratedRegistryRuntime } from "../procedure-caller-JB9kjYsy.js";
5
5
 
6
6
  export { ActionProcedureBuilder, CRPCError, CRPC_ERROR_CODES_BY_KEY, CRPC_ERROR_CODE_TO_HTTP, HttpRouterWithHono, MutationProcedureBuilder, ProcedureBuilder, QueryProcedureBuilder, convexToZod, convexToZodFields, createApiLeaf, createCallerFactory, createEnv, createGeneratedFunctionReference, createGeneratedRegistryRuntime, createGenericCallerFactory, createGenericHandlerFactory, createHttpProcedureBuilder, createHttpRouter, createHttpRouterFactory, createLazyCaller, createMiddlewareFactory, createProcedureCallerFactory, createProcedureHandlerFactory, createServerCaller, defineProcedure, extractPathParams, extractRouteMap, getCRPCErrorFromUnknown, getGeneratedFunctionReference, getGeneratedValue, getHTTPStatusCodeFromError, handleHttpError, inferProcedureNameFromCallsite, initCRPC, isActionCtx, isCRPCError, isMutationCtx, isQueryCtx, isRunMutationCtx, isSchedulerCtx, matchPathParams, registerProcedureNameLookup, requireActionCtx, requireMutationCtx, requireQueryCtx, requireRunMutationCtx, requireSchedulerCtx, toCRPCError, typedProcedureResolver, withSystemFields, zCustomAction, zCustomMutation, zCustomQuery, zid, zodOutputToConvex, zodOutputToConvexFields, zodToConvex, zodToConvexFields };
@@ -1,10 +1,10 @@
1
1
  import { getFunctionName } from "convex/server";
2
- import { Show, createContext, createEffect, createMemo, createSignal, on, onCleanup, onMount, useContext } from "solid-js";
2
+ import { Show, createComputed, createContext, createEffect, createMemo, createRenderEffect, createSignal, on, onCleanup, onMount, useContext } from "solid-js";
3
3
  import { createComponent, memo } from "solid-js/web";
4
4
  import { createStore } from "solid-js/store";
5
- import { notifyManager, skipToken, useQueries, useQueryClient } from "@tanstack/solid-query";
5
+ import { notifyManager, skipToken, useQueryClient } from "@tanstack/solid-query";
6
6
  import { ConvexClient, ConvexHttpClient } from "convex/browser";
7
- import { hashKey } from "@tanstack/query-core";
7
+ import { QueriesObserver, hashKey } from "@tanstack/query-core";
8
8
  import { convexToJson } from "convex/values";
9
9
 
10
10
  //#region src/crpc/error.ts
@@ -2504,6 +2504,42 @@ const getConvexQueryClientSingleton = ({ authStore, convex, queryClient, symbolK
2504
2504
  //#region src/internal/pagination.ts
2505
2505
  const shouldSplitPaginationPage = (page, initialNumItems) => Boolean(page.splitCursor) && (page.pageStatus === "SplitRecommended" || page.pageStatus === "SplitRequired" || initialNumItems !== void 0 && page.page.length > initialNumItems * 2);
2506
2506
 
2507
+ //#endregion
2508
+ //#region src/solid/create-queries-results.ts
2509
+ /**
2510
+ * Subscribe a reactive list of queries and expose the raw observer results.
2511
+ *
2512
+ * Solid Query's `useQueries` cannot back an aggregate result: it feeds the
2513
+ * `combine` output straight into `createStore` and then calls `.map()` on it,
2514
+ * so any non-array aggregate throws `state.map is not a function` while the
2515
+ * component is still setting up. It also routes `.data` through
2516
+ * `createResource`, which suspends the nearest boundary for as long as a query
2517
+ * is in flight.
2518
+ *
2519
+ * Driving `QueriesObserver` directly keeps every entry a plain
2520
+ * `QueryObserverResult` - the same value the React port aggregates - and leaves
2521
+ * aggregation to the caller.
2522
+ *
2523
+ * @param queries Reactive list of query options.
2524
+ * @returns Accessor for the raw observer results, in query order.
2525
+ */
2526
+ function createQueriesResults(queries) {
2527
+ const queryClient = useQueryClient();
2528
+ const defaulted = () => queries().map((options) => ({
2529
+ ...queryClient.defaultQueryOptions(options),
2530
+ _optimisticResults: "optimistic"
2531
+ }));
2532
+ const observer = new QueriesObserver(queryClient, defaulted());
2533
+ const [results, setResults] = createSignal(observer.getCurrentResult(), { equals: false });
2534
+ createComputed(() => {
2535
+ const next = defaulted();
2536
+ observer.setQueries(next);
2537
+ setResults(observer.getOptimisticResult(next, void 0)[0]);
2538
+ });
2539
+ onCleanup(observer.subscribe((next) => setResults(next)));
2540
+ return results;
2541
+ }
2542
+
2507
2543
  //#endregion
2508
2544
  //#region src/solid/use-infinite-query.ts
2509
2545
  const PAGINATION_KEY_PREFIX = "__pagination__";
@@ -2516,6 +2552,59 @@ const getOrCreatePaginationId = (storeKey) => {
2516
2552
  paginationIdStore.set(storeKey, newId);
2517
2553
  return newId;
2518
2554
  };
2555
+ /** Read the identity of a Convex document, tolerating `id` and `_id` shapes */
2556
+ const getItemId = (item) => {
2557
+ const doc = item;
2558
+ return doc?._id || doc?.id;
2559
+ };
2560
+ /**
2561
+ * Fold the per-page observer results into one pagination-shaped aggregate.
2562
+ * Pure: same inputs always produce the same output, so it is safe to re-run
2563
+ * inside a reactive derivation.
2564
+ */
2565
+ const aggregatePages = (results, hasPlaceholderData) => {
2566
+ const allItems = [];
2567
+ const pages = [];
2568
+ const seenIds = /* @__PURE__ */ new Set();
2569
+ let lastPage;
2570
+ let status = "LoadingFirstPage";
2571
+ for (let i = 0; i < results.length; i++) {
2572
+ const pageQuery = results[i];
2573
+ if (pageQuery.isLoading || pageQuery.data === void 0) {
2574
+ status = i === 0 ? "LoadingFirstPage" : "LoadingMore";
2575
+ break;
2576
+ }
2577
+ const page = pageQuery.data;
2578
+ lastPage = page;
2579
+ pages.push(page.page);
2580
+ for (const item of page.page) {
2581
+ const id = getItemId(item);
2582
+ if (id && seenIds.has(id)) continue;
2583
+ if (id) seenIds.add(id);
2584
+ allItems.push(item);
2585
+ }
2586
+ status = page.isDone ? "Exhausted" : "CanLoadMore";
2587
+ }
2588
+ const firstPage = results.length > 0 ? results[0] : void 0;
2589
+ const isPlaceholderData = firstPage ? firstPage.isPlaceholderData : hasPlaceholderData;
2590
+ const isFetching = results.some((r) => r.isFetching);
2591
+ const error = results.find((r) => r.isError)?.error ?? null;
2592
+ return {
2593
+ data: allItems,
2594
+ dataUpdatedAt: Math.max(...results.map((r) => r.dataUpdatedAt)),
2595
+ error,
2596
+ failureReason: error,
2597
+ isError: results.some((r) => r.isError),
2598
+ isFetchNextPageError: results.length > 1 && (results.at(-1)?.isError ?? false),
2599
+ isFetching,
2600
+ isLoading: status === "LoadingFirstPage",
2601
+ isPlaceholderData,
2602
+ isRefetching: isFetching && allItems.length > 0 && !isPlaceholderData,
2603
+ lastPage,
2604
+ pages,
2605
+ status
2606
+ };
2607
+ };
2519
2608
  /** Build a unique key for recovery attempt detection */
2520
2609
  const buildRecoveryKey = (pageKeys, page0Cursor, page0UpdatedAt) => JSON.stringify({
2521
2610
  pageKeys,
@@ -2531,26 +2620,27 @@ const buildRecoveryKey = (pageKeys, page0Cursor, page0UpdatedAt) => JSON.stringi
2531
2620
  * This hook detects this pattern and creates a recovery page that fetches
2532
2621
  * enough items to cover the lost pages, preserving the user's scroll position.
2533
2622
  */
2534
- const useStaleCursorRecovery = ({ argsObject, combined, limit, setState, state }) => {
2623
+ const useStaleCursorRecovery = ({ argsObject, combined, limit, pageResults, setState, state }) => {
2535
2624
  createEffect(on([
2536
2625
  () => combined.isFetchNextPageError,
2537
- () => combined._rawResults,
2626
+ pageResults,
2538
2627
  () => state().pageKeys,
2539
2628
  () => state().queries,
2540
2629
  () => state().autoRecoveryAttempted,
2541
2630
  argsObject
2542
2631
  ], () => {
2543
2632
  if (!combined.isFetchNextPageError) return;
2544
- const page0Result = combined._rawResults[0];
2633
+ const results = pageResults();
2634
+ const page0Result = results[0];
2545
2635
  const page0Data = page0Result?.data;
2546
2636
  const page0UpdatedAt = page0Result?.dataUpdatedAt ?? 0;
2547
2637
  const hasPage0Data = page0Data !== void 0 && !page0Result?.isError;
2548
- const hasSubsequentErrors = combined._rawResults.slice(1).some((q) => q?.isError && !q?.isFetching);
2638
+ const hasSubsequentErrors = results.slice(1).some((q) => q?.isError && !q?.isFetching);
2549
2639
  if (!hasPage0Data || !hasSubsequentErrors || !page0Data?.continueCursor) return;
2550
2640
  const currentState = state();
2551
2641
  const recoveryKey = buildRecoveryKey(currentState.pageKeys, page0Data.continueCursor, page0UpdatedAt);
2552
2642
  if (currentState.autoRecoveryAttempted === recoveryKey) return;
2553
- const erroredPageKeys = currentState.pageKeys.filter((_, i) => i > 0 && combined._rawResults[i]?.isError);
2643
+ const erroredPageKeys = currentState.pageKeys.filter((_, i) => i > 0 && results[i]?.isError);
2554
2644
  const itemsToRecover = erroredPageKeys.reduce((sum, key) => {
2555
2645
  return sum + (currentState.queries[key]?.args?.limit ?? limit ?? 20);
2556
2646
  }, 0);
@@ -2711,66 +2801,27 @@ const useInfiniteQueryInternal = (query, args, options) => {
2711
2801
  } } : {}
2712
2802
  };
2713
2803
  }));
2714
- const combined = useQueries(() => ({
2715
- queries: tanstackQueries(),
2716
- combine: (results) => {
2717
- const allItems = [];
2718
- const pages = [];
2719
- const seenIds = /* @__PURE__ */ new Set();
2720
- let lastPage;
2721
- let paginationStatus = "LoadingFirstPage";
2722
- for (let i = 0; i < results.length; i++) {
2723
- const pageQuery = results[i];
2724
- if (pageQuery.isLoading || pageQuery.data === void 0) {
2725
- paginationStatus = i === 0 ? "LoadingFirstPage" : "LoadingMore";
2726
- break;
2727
- }
2728
- const page = pageQuery.data;
2729
- lastPage = page;
2730
- pages.push(page.page);
2731
- for (const item of page.page) {
2732
- const id = item._id || item.id;
2733
- if (id && seenIds.has(id)) continue;
2734
- if (id) seenIds.add(id);
2735
- allItems.push(item);
2736
- }
2737
- paginationStatus = page.isDone ? "Exhausted" : "CanLoadMore";
2738
- }
2739
- const isPlaceholderData = results[0]?.isPlaceholderData ?? !!placeholderData;
2740
- const isFetching = results.some((r) => r.isFetching);
2741
- return {
2742
- data: allItems,
2743
- dataUpdatedAt: Math.max(...results.map((r) => r.dataUpdatedAt ?? 0)),
2744
- lastPage,
2745
- pages,
2746
- status: paginationStatus,
2747
- error: results.find((r) => r.isError)?.error ?? null,
2748
- isError: results.some((r) => r.isError),
2749
- isFetching,
2750
- isFetchNextPageError: results.length > 1 && (results.at(-1)?.isError ?? false),
2751
- isPlaceholderData,
2752
- isRefetching: isFetching && allItems.length > 0 && !isPlaceholderData,
2753
- isLoading: paginationStatus === "LoadingFirstPage",
2754
- failureReason: results.find((r) => r.isError)?.error ?? null,
2755
- _rawResults: results
2756
- };
2757
- }
2758
- }));
2804
+ const pageResults = createQueriesResults(() => tanstackQueries());
2805
+ const derive = () => aggregatePages(pageResults(), !!placeholderData);
2806
+ const [combined, setCombined] = createStore(derive());
2807
+ createRenderEffect(() => setCombined(derive()));
2759
2808
  useStaleCursorRecovery({
2760
2809
  argsObject,
2761
2810
  combined,
2762
2811
  limit,
2812
+ pageResults,
2763
2813
  setState,
2764
2814
  state
2765
2815
  });
2766
2816
  createEffect(on([
2767
- () => combined._rawResults,
2817
+ pageResults,
2768
2818
  () => state().pageKeys,
2769
2819
  () => state().queries,
2770
2820
  argsObject
2771
2821
  ], () => {
2772
- for (let i = 0; i < combined._rawResults.length; i++) {
2773
- const pageQuery = combined._rawResults[i];
2822
+ const results = pageResults();
2823
+ for (let i = 0; i < results.length; i++) {
2824
+ const pageQuery = results[i];
2774
2825
  if (pageQuery.data) {
2775
2826
  const page = pageQuery.data;
2776
2827
  const pageKey = state().pageKeys[i];
package/dist/watcher.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { At as PARSE_SNAPSHOT_SUFFIX, Dt as generateMeta, F as resolveRunDeps, Ot as getConvexConfig, j as resolveConfiguredBackend, kt as logger, q as withLocalCodegenEnv } from "./backend-core-BsKP1LVg.mjs";
2
+ import { At as PARSE_SNAPSHOT_SUFFIX, Dt as generateMeta, F as resolveRunDeps, Ot as getConvexConfig, j as resolveConfiguredBackend, kt as logger, q as withLocalCodegenEnv } from "./backend-core-KwJ5FZgj.mjs";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kitcn",
3
- "version": "0.17.0",
3
+ "version": "0.17.2",
4
4
  "description": "kitcn - React Query integration and CLI tools for Convex",
5
5
  "keywords": [
6
6
  "convex",