kitcn 0.25.1 → 0.25.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,5 +1,5 @@
1
1
  import { Bn as ConvexTextBuilderInitial, Xt as ConvexTableWithColumns } from "../capabilities-Bem7xvGK.js";
2
- import { C as ConvexNumberBuilderInitial, E as ConvexIdBuilderInitial, N as ConvexCustomBuilderInitial } from "../where-clause-compiler-Dmq4HMrK.js";
2
+ import { C as ConvexNumberBuilderInitial, E as ConvexIdBuilderInitial, N as ConvexCustomBuilderInitial } from "../where-clause-compiler-TMNQB6US.js";
3
3
  import * as convex_values0 from "convex/values";
4
4
  import { GenericId, Infer, Value } from "convex/values";
5
5
  import { DocumentByName, GenericDataModel, GenericDatabaseReader, GenericDatabaseWriter, TableNamesInDataModel } from "convex/server";
@@ -1,4 +1,4 @@
1
- import { H as ConvexContext, W as LazyCaller } from "../../procedure-name-Bjw1JDIS.js";
1
+ import { H as ConvexContext, W as LazyCaller } from "../../procedure-name-l2YusEZI.js";
2
2
  import { t as GetTokenOptions } from "../../token-kQaqFby4.js";
3
3
 
4
4
  //#region src/auth-nextjs/index.d.ts
@@ -3,8 +3,8 @@ import { n as customCtx, t as NoOp } from "./customFunctions-ivbc6-_g.js";
3
3
  import { s as getTransformer } from "./transformer-D8wO-kEj.js";
4
4
  import { ConvexError, v } from "convex/values";
5
5
  import { HttpRouter, actionGeneric, httpActionGeneric, internalActionGeneric, internalMutationGeneric, internalQueryGeneric, mutationGeneric, queryGeneric } from "convex/server";
6
- import { z } from "zod";
7
- import * as z$1 from "zod/v4";
6
+ import * as z$1 from "zod";
7
+ import * as z$2 from "zod/v4";
8
8
  import * as zCore from "zod/v4/core";
9
9
 
10
10
  //#region src/internal/upstream/server/zod4.ts
@@ -190,7 +190,7 @@ function zCustomAction(action, customization) {
190
190
  * @returns A Zod schema representing a Convex `Id`
191
191
  */
192
192
  const zid = (tableName) => {
193
- const result = z$1.custom((val) => typeof val === "string");
193
+ const result = z$2.custom((val) => typeof val === "string");
194
194
  _zidRegistry.add(result, { tableName });
195
195
  return result;
196
196
  };
@@ -413,35 +413,35 @@ function convexToZod(convexValidator) {
413
413
  zodValidator = zid(convexValidator.tableName);
414
414
  break;
415
415
  case "string":
416
- zodValidator = z$1.string();
416
+ zodValidator = z$2.string();
417
417
  break;
418
418
  case "float64":
419
- zodValidator = z$1.number();
419
+ zodValidator = z$2.number();
420
420
  break;
421
421
  case "int64":
422
- zodValidator = z$1.bigint();
422
+ zodValidator = z$2.bigint();
423
423
  break;
424
424
  case "commitTs":
425
- zodValidator = z$1.union([z$1.bigint(), z$1.custom(isCommitTsPlaceholder)]);
425
+ zodValidator = z$2.union([z$2.bigint(), z$2.custom(isCommitTsPlaceholder)]);
426
426
  break;
427
427
  case "boolean":
428
- zodValidator = z$1.boolean();
428
+ zodValidator = z$2.boolean();
429
429
  break;
430
430
  case "null":
431
- zodValidator = z$1.null();
431
+ zodValidator = z$2.null();
432
432
  break;
433
433
  case "any":
434
- zodValidator = z$1.any();
434
+ zodValidator = z$2.any();
435
435
  break;
436
436
  case "array":
437
- zodValidator = z$1.array(convexToZod(convexValidator.element));
437
+ zodValidator = z$2.array(convexToZod(convexValidator.element));
438
438
  break;
439
439
  case "object":
440
- zodValidator = z$1.object(convexToZodFields(convexValidator.fields));
440
+ zodValidator = z$2.object(convexToZodFields(convexValidator.fields));
441
441
  break;
442
442
  case "union": {
443
443
  if (convexValidator.members.length === 0) {
444
- zodValidator = z$1.never();
444
+ zodValidator = z$2.never();
445
445
  break;
446
446
  }
447
447
  if (convexValidator.members.length === 1) {
@@ -449,21 +449,21 @@ function convexToZod(convexValidator) {
449
449
  break;
450
450
  }
451
451
  const memberValidators = convexValidator.members.map((member) => convexToZod(member));
452
- zodValidator = z$1.union([...memberValidators]);
452
+ zodValidator = z$2.union([...memberValidators]);
453
453
  break;
454
454
  }
455
455
  case "literal": {
456
456
  const literalValidator = convexValidator;
457
- zodValidator = z$1.literal(literalValidator.value);
457
+ zodValidator = z$2.literal(literalValidator.value);
458
458
  break;
459
459
  }
460
460
  case "record":
461
- zodValidator = z$1.record(convexToZod(convexValidator.key), convexToZod(convexValidator.value));
461
+ zodValidator = z$2.record(convexToZod(convexValidator.key), convexToZod(convexValidator.value));
462
462
  break;
463
463
  case "bytes": throw new Error("v.bytes() is not supported");
464
464
  default: throw new Error(`Unknown convex validator type: ${kind}`);
465
465
  }
466
- return isOptional ? z$1.optional(zodValidator) : zodValidator;
466
+ return isOptional ? z$2.optional(zodValidator) : zodValidator;
467
467
  }
468
468
  /**
469
469
  * Like {@link convexToZod}, but it takes in a bare object, as expected by Convex
@@ -503,7 +503,7 @@ function withSystemFields(tableName, zObject) {
503
503
  return {
504
504
  ...zObject,
505
505
  _id: zid(tableName),
506
- _creationTime: z$1.number()
506
+ _creationTime: z$2.number()
507
507
  };
508
508
  }
509
509
  /**
@@ -523,7 +523,7 @@ function customFnBuilder(builder, customization) {
523
523
  const inputArgs = customization.args ?? NoOp.args;
524
524
  return function customBuilder(fn) {
525
525
  const { args, handler = fn, skipConvexValidation = false, skipZodReturnsValidation = false, returns: maybeObject, ...extra } = fn;
526
- const returns = maybeObject && !(maybeObject instanceof zCore.$ZodType) ? z$1.object(maybeObject) : maybeObject;
526
+ const returns = maybeObject && !(maybeObject instanceof zCore.$ZodType) ? z$2.object(maybeObject) : maybeObject;
527
527
  const returnValidator = returns && !skipConvexValidation ? { returns: zodOutputToConvex(returns) } : null;
528
528
  const parseReturns = returns && !skipZodReturnsValidation ? (value) => returns.parseAsync(value === void 0 ? null : value) : null;
529
529
  if (args) {
@@ -541,7 +541,7 @@ function customFnBuilder(builder, customization) {
541
541
  handler: async (ctx, allArgs) => {
542
542
  const added = await customInput(ctx, inputArgKeys.length === 0 ? {} : pickKeys(allArgs, inputArgKeySet), extra);
543
543
  const rawArgs = pickKeys(allArgs, argKeySet);
544
- argsSchema ??= z$1.object(argsValidator);
544
+ argsSchema ??= z$2.object(argsValidator);
545
545
  const parsed = await argsSchema.safeParseAsync(rawArgs);
546
546
  if (!parsed.success) throw new ConvexError({ ZodError: JSON.parse(JSON.stringify(parsed.error.issues, null, 2)) });
547
547
  const args = parsed.data;
@@ -990,8 +990,8 @@ async function readFormDataBody(request) {
990
990
  }
991
991
  }
992
992
  function getBaseSchema(schema) {
993
- if (schema instanceof z.ZodOptional || schema instanceof z.ZodNullable) return getBaseSchema(schema.unwrap());
994
- if (schema instanceof z.ZodDefault) return getBaseSchema(schema._def.innerType);
993
+ if (schema instanceof z$1.ZodOptional || schema instanceof z$1.ZodNullable) return getBaseSchema(schema.unwrap());
994
+ if (schema instanceof z$1.ZodDefault) return getBaseSchema(schema._def.innerType);
995
995
  return schema;
996
996
  }
997
997
  /**
@@ -1007,12 +1007,12 @@ function getBaseSchema(schema) {
1007
1007
  */
1008
1008
  function buildQueryCoercion(schema) {
1009
1009
  const coercion = /* @__PURE__ */ new Map();
1010
- if (!(schema instanceof z.ZodObject)) return coercion;
1010
+ if (!(schema instanceof z$1.ZodObject)) return coercion;
1011
1011
  for (const [key, fieldSchema] of Object.entries(schema.shape)) {
1012
1012
  const base = getBaseSchema(fieldSchema);
1013
- if (base instanceof z.ZodArray) coercion.set(key, "array");
1014
- else if (base instanceof z.ZodNumber) coercion.set(key, "number");
1015
- else if (base instanceof z.ZodBoolean) coercion.set(key, "boolean");
1013
+ if (base instanceof z$1.ZodArray) coercion.set(key, "array");
1014
+ else if (base instanceof z$1.ZodNumber) coercion.set(key, "number");
1015
+ else if (base instanceof z$1.ZodBoolean) coercion.set(key, "boolean");
1016
1016
  }
1017
1017
  return coercion;
1018
1018
  }
@@ -1083,7 +1083,7 @@ function createProcedure(def, handler, _type) {
1083
1083
  if (def.paramsSchema) try {
1084
1084
  parsedParams = def.paramsSchema.parse(pathParams);
1085
1085
  } catch (error) {
1086
- if (error instanceof z.ZodError) throw new CRPCError({
1086
+ if (error instanceof z$1.ZodError) throw new CRPCError({
1087
1087
  code: "BAD_REQUEST",
1088
1088
  message: "Invalid path params",
1089
1089
  cause: error
@@ -1096,7 +1096,7 @@ function createProcedure(def, handler, _type) {
1096
1096
  try {
1097
1097
  parsedQuery = def.querySchema.parse(queryParams);
1098
1098
  } catch (error) {
1099
- if (error instanceof z.ZodError) throw new CRPCError({
1099
+ if (error instanceof z$1.ZodError) throw new CRPCError({
1100
1100
  code: "BAD_REQUEST",
1101
1101
  message: "Invalid query params",
1102
1102
  cause: error
@@ -1116,7 +1116,7 @@ function createProcedure(def, handler, _type) {
1116
1116
  try {
1117
1117
  parsedInput = def.inputSchema.parse(def.functionConfig.transformer.input.deserialize(body));
1118
1118
  } catch (error) {
1119
- if (error instanceof z.ZodError) throw new CRPCError({
1119
+ if (error instanceof z$1.ZodError) throw new CRPCError({
1120
1120
  code: "BAD_REQUEST",
1121
1121
  message: "Invalid input",
1122
1122
  cause: error
@@ -1132,7 +1132,7 @@ function createProcedure(def, handler, _type) {
1132
1132
  try {
1133
1133
  parsedForm = def.formSchema.parse(formObj);
1134
1134
  } catch (error) {
1135
- if (error instanceof z.ZodError) throw new CRPCError({
1135
+ if (error instanceof z$1.ZodError) throw new CRPCError({
1136
1136
  code: "BAD_REQUEST",
1137
1137
  message: "Invalid form data",
1138
1138
  cause: error
@@ -1598,13 +1598,13 @@ function inferProcedureNameFromCallsite() {
1598
1598
  *
1599
1599
  * Core library - no project-specific dependencies
1600
1600
  */
1601
- z.object({
1602
- cursor: z.union([z.string(), z.null()]),
1603
- limit: z.number()
1601
+ z$1.object({
1602
+ cursor: z$1.union([z$1.string(), z$1.null()]),
1603
+ limit: z$1.number()
1604
1604
  });
1605
- z.object({
1606
- cursor: z.union([z.string(), z.null()]).optional(),
1607
- limit: z.number().optional()
1605
+ z$1.object({
1606
+ cursor: z$1.union([z$1.string(), z$1.null()]).optional(),
1607
+ limit: z$1.number().optional()
1608
1608
  });
1609
1609
  /**
1610
1610
  * Create a middleware factory for building reusable middleware chains
@@ -1731,32 +1731,32 @@ const withConvexSafeRunners = (ctx) => {
1731
1731
  return changed ? wrappedContext : contextObject;
1732
1732
  };
1733
1733
  const replaceUnencodableOutputTypes = (schema) => {
1734
- if (schema instanceof z.ZodDate) return z.any();
1735
- if (schema instanceof z.ZodArray) return z.array(replaceUnencodableOutputTypes(schema.element));
1736
- if (schema instanceof z.ZodObject) {
1734
+ if (schema instanceof z$1.ZodDate) return z$1.any();
1735
+ if (schema instanceof z$1.ZodArray) return z$1.array(replaceUnencodableOutputTypes(schema.element));
1736
+ if (schema instanceof z$1.ZodObject) {
1737
1737
  const nextShape = {};
1738
1738
  for (const [key, value] of Object.entries(schema.shape)) nextShape[key] = replaceUnencodableOutputTypes(value);
1739
- return z.object(nextShape);
1739
+ return z$1.object(nextShape);
1740
1740
  }
1741
- if (schema instanceof z.ZodUnion) return z.union(schema.options.map((option) => replaceUnencodableOutputTypes(option)));
1742
- if (schema instanceof z.ZodOptional) return replaceUnencodableOutputTypes(schema.unwrap()).optional();
1743
- if (schema instanceof z.ZodNullable) return replaceUnencodableOutputTypes(schema.unwrap()).nullable();
1744
- if (schema instanceof z.ZodRecord) return z.record(schema.keyType, replaceUnencodableOutputTypes(schema.valueType));
1741
+ if (schema instanceof z$1.ZodUnion) return z$1.union(schema.options.map((option) => replaceUnencodableOutputTypes(option)));
1742
+ if (schema instanceof z$1.ZodOptional) return replaceUnencodableOutputTypes(schema.unwrap()).optional();
1743
+ if (schema instanceof z$1.ZodNullable) return replaceUnencodableOutputTypes(schema.unwrap()).nullable();
1744
+ if (schema instanceof z$1.ZodRecord) return z$1.record(schema.keyType, replaceUnencodableOutputTypes(schema.valueType));
1745
1745
  return schema;
1746
1746
  };
1747
1747
  const replaceUnencodableInputTypes = (schema) => {
1748
- if (schema instanceof z.ZodDate) return z.any();
1749
- if (schema instanceof z.ZodArray) return z.array(replaceUnencodableInputTypes(schema.element));
1750
- if (schema instanceof z.ZodObject) {
1748
+ if (schema instanceof z$1.ZodDate) return z$1.any();
1749
+ if (schema instanceof z$1.ZodArray) return z$1.array(replaceUnencodableInputTypes(schema.element));
1750
+ if (schema instanceof z$1.ZodObject) {
1751
1751
  const nextShape = {};
1752
1752
  for (const [key, value] of Object.entries(schema.shape)) nextShape[key] = replaceUnencodableInputTypes(value);
1753
- return z.object(nextShape);
1753
+ return z$1.object(nextShape);
1754
1754
  }
1755
- if (schema instanceof z.ZodUnion) return z.union(schema.options.map((option) => replaceUnencodableInputTypes(option)));
1756
- if (schema instanceof z.ZodOptional) return replaceUnencodableInputTypes(schema.unwrap()).optional();
1757
- if (schema instanceof z.ZodNullable) return replaceUnencodableInputTypes(schema.unwrap()).nullable();
1758
- if (schema instanceof z.ZodRecord) return z.record(schema.keyType, replaceUnencodableInputTypes(schema.valueType));
1759
- if (schema instanceof z.ZodDefault) return replaceUnencodableInputTypes(schema.removeDefault());
1755
+ if (schema instanceof z$1.ZodUnion) return z$1.union(schema.options.map((option) => replaceUnencodableInputTypes(option)));
1756
+ if (schema instanceof z$1.ZodOptional) return replaceUnencodableInputTypes(schema.unwrap()).optional();
1757
+ if (schema instanceof z$1.ZodNullable) return replaceUnencodableInputTypes(schema.unwrap()).nullable();
1758
+ if (schema instanceof z$1.ZodRecord) return z$1.record(schema.keyType, replaceUnencodableInputTypes(schema.valueType));
1759
+ if (schema instanceof z$1.ZodDefault) return replaceUnencodableInputTypes(schema.removeDefault());
1760
1760
  return schema;
1761
1761
  };
1762
1762
  /**
@@ -1776,11 +1776,11 @@ const resolveConvexArgsShape = (inputShape) => {
1776
1776
  try {
1777
1777
  return toWireShape(inputShape);
1778
1778
  } catch {
1779
- const compatibleSchema = replaceUnencodableInputTypes(z.object(inputShape));
1779
+ const compatibleSchema = replaceUnencodableInputTypes(z$1.object(inputShape));
1780
1780
  try {
1781
1781
  return toWireShape(compatibleSchema.shape);
1782
1782
  } catch {
1783
- return Object.fromEntries(Object.keys(inputShape).map((key) => [key, z.any()]));
1783
+ return Object.fromEntries(Object.keys(inputShape).map((key) => [key, z$1.any()]));
1784
1784
  }
1785
1785
  }
1786
1786
  };
@@ -1795,7 +1795,7 @@ const resolveConvexArgsShape = (inputShape) => {
1795
1795
  const relaxSupersededKeys = (schema, superseded) => {
1796
1796
  if (superseded.length === 0) return schema;
1797
1797
  try {
1798
- return schema.safeExtend(Object.fromEntries(superseded.map((key) => [key, z.any()])));
1798
+ return schema.safeExtend(Object.fromEntries(superseded.map((key) => [key, z$1.any()])));
1799
1799
  } catch {
1800
1800
  return schema;
1801
1801
  }
@@ -1852,7 +1852,7 @@ const parseInput = (plan, value) => {
1852
1852
  }
1853
1853
  return parsed;
1854
1854
  } catch (cause) {
1855
- if (cause instanceof z.ZodError) throw new ConvexError({ ZodError: JSON.parse(JSON.stringify(cause.issues, null, 2)) });
1855
+ if (cause instanceof z$1.ZodError) throw new ConvexError({ ZodError: JSON.parse(JSON.stringify(cause.issues, null, 2)) });
1856
1856
  throw cause;
1857
1857
  }
1858
1858
  };
@@ -2011,14 +2011,14 @@ var QueryProcedureBuilder = class QueryProcedureBuilder extends ProcedureBuilder
2011
2011
  * @param opts.item - Zod schema for each item in the page array
2012
2012
  */
2013
2013
  paginated(opts) {
2014
- const paginationSchemaWithDefault = z.object({
2015
- cursor: z.union([z.string(), z.null()]).default(null),
2016
- limit: z.number().default(opts.limit).transform((n) => Math.min(n, opts.limit))
2014
+ const paginationSchemaWithDefault = z$1.object({
2015
+ cursor: z$1.union([z$1.string(), z$1.null()]).default(null),
2016
+ limit: z$1.number().default(opts.limit).transform((n) => Math.min(n, opts.limit))
2017
2017
  });
2018
- const outputSchema = z.object({
2019
- continueCursor: z.union([z.string(), z.null()]),
2020
- isDone: z.boolean(),
2021
- page: z.array(opts.item)
2018
+ const outputSchema = z$1.object({
2019
+ continueCursor: z$1.union([z$1.string(), z$1.null()]),
2020
+ isDone: z$1.boolean(),
2021
+ page: z$1.array(opts.item)
2022
2022
  });
2023
2023
  return new QueryProcedureBuilder({
2024
2024
  ...this._def,
package/dist/cli.mjs CHANGED
@@ -6,12 +6,46 @@ import path, { basename, delimiter, dirname, extname, isAbsolute, join, posix, r
6
6
  import { fileURLToPath } from "node:url";
7
7
  import { createHash, randomBytes } from "node:crypto";
8
8
  import { execa } from "execa";
9
- import { createInterface } from "node:readline/promises";
10
9
  import os from "node:os";
10
+ import { createInterface } from "node:readline/promises";
11
11
  import { diffWords, structuredPatch } from "diff";
12
12
  import { parseEnv } from "node:util";
13
13
  import { createServer } from "node:http";
14
14
 
15
+ //#region src/internal/concurrency.ts
16
+ /**
17
+ * Bounded-concurrency fan-out, shared by the ORM write path, relation loading
18
+ * and the CLI's entry-point analyzer.
19
+ *
20
+ * Deliberately dependency-free: ORM callers reach it from a Convex function
21
+ * entry, and Convex bundles every static import of an entry.
22
+ */
23
+ /**
24
+ * Runs `worker` over `items` with at most `limit` in flight. Results keep input
25
+ * order, so callers can rely on a stable mapping back to `items`.
26
+ *
27
+ * Unbounded `Promise.all` is not an option for the ORM caller: a fan-out is
28
+ * bounded only by `mutationMaxRows` (10,000), and that many simultaneous
29
+ * in-flight syscalls is its own failure mode.
30
+ */
31
+ async function mapWithConcurrency(items, limit, worker) {
32
+ if (items.length === 0) return [];
33
+ const width = Math.max(1, Math.min(limit, items.length));
34
+ const results = new Array(items.length);
35
+ let nextIndex = 0;
36
+ const runWorker = async () => {
37
+ while (true) {
38
+ const index = nextIndex;
39
+ nextIndex += 1;
40
+ if (index >= items.length) return;
41
+ results[index] = await worker(items[index], index);
42
+ }
43
+ };
44
+ await Promise.all(Array.from({ length: width }, () => runWorker()));
45
+ return results;
46
+ }
47
+
48
+ //#endregion
15
49
  //#region src/orm/mutation-utils.ts
16
50
  const UTF8_ENCODER = new TextEncoder();
17
51
  function getTableName(table) {
@@ -830,20 +864,32 @@ const collectAnalyzeEntrySelection = async (roots, options) => {
830
864
  handlerExportsByEntry
831
865
  };
832
866
  };
867
+ const MAX_ANALYZE_CONCURRENCY = 8;
868
+ /**
869
+ * esbuild bundles are independent, so the entry sweep runs through a bounded
870
+ * pool instead of one build at a time. The cap stays low enough to avoid
871
+ * oversubscribing esbuild's worker pool on small machines.
872
+ */
873
+ const resolveAnalyzeConcurrency = (taskCount) => {
874
+ if (taskCount <= 1) return 1;
875
+ const cpuCount = os.cpus().length || 1;
876
+ return Math.max(1, Math.min(MAX_ANALYZE_CONCURRENCY, cpuCount - 1, taskCount));
877
+ };
833
878
  const collectHotspotRows = async (roots, options, includeDeepData) => {
834
879
  const { isolateEntries, generatedEntries, entryPoints, handlerExportsByEntry } = await collectAnalyzeEntrySelection(roots, options);
835
- const rows = [];
836
- for (const entryPoint of entryPoints) try {
837
- rows.push({
838
- ...await analyzeHotspotEntry(entryPoint, roots.projectRoot, includeDeepData),
839
- handlerExports: handlerExportsByEntry.get(entryPoint) ?? []
840
- });
841
- } catch (error) {
842
- rows.push({
843
- entry: path.relative(roots.projectRoot, entryPoint),
844
- error: error instanceof Error ? error.message : String(error)
845
- });
846
- }
880
+ const rows = await mapWithConcurrency(entryPoints, resolveAnalyzeConcurrency(entryPoints.length), async (entryPoint) => {
881
+ try {
882
+ return {
883
+ ...await analyzeHotspotEntry(entryPoint, roots.projectRoot, includeDeepData),
884
+ handlerExports: handlerExportsByEntry.get(entryPoint) ?? []
885
+ };
886
+ } catch (error) {
887
+ return {
888
+ entry: path.relative(roots.projectRoot, entryPoint),
889
+ error: error instanceof Error ? error.message : String(error)
890
+ };
891
+ }
892
+ });
847
893
  return {
848
894
  isolateEntries,
849
895
  generatedEntries,
@@ -3270,7 +3316,7 @@ const upsertReadOptionalRuntimeEnvOption = (source, keys) => {
3270
3316
  const renderEnvHelperContent = (envFields, existingContent) => {
3271
3317
  const fields = resolveBootstrapEnvFields(envFields);
3272
3318
  const readOptionalRuntimeEnvKeys = resolveReadOptionalRuntimeEnvKeys(fields);
3273
- if (!existingContent) return `import { createEnv } from 'kitcn/server';\nimport { z } from 'zod';\n\nconst envSchema = z.object({\n${fields.map((field) => ` ${field.key}: ${field.schema},`).join("\n")}\n});\n\nexport const getEnv = createEnv({\n${renderReadOptionalRuntimeEnvOption(readOptionalRuntimeEnvKeys)} schema: envSchema,\n});\n`;
3319
+ if (!existingContent) return `import { createEnv } from 'kitcn/server';\nimport * as z from 'zod';\n\nconst envSchema = z.object({\n${fields.map((field) => ` ${field.key}: ${field.schema},`).join("\n")}\n});\n\nexport const getEnv = createEnv({\n${renderReadOptionalRuntimeEnvOption(readOptionalRuntimeEnvKeys)} schema: envSchema,\n});\n`;
3274
3320
  const match = existingContent.match(ENV_SCHEMA_RE);
3275
3321
  if (!match) throw new Error("Expected env helper to define `const envSchema = z.object({ ... });`.");
3276
3322
  const existingBody = match[2];
@@ -6782,7 +6828,7 @@ const authRegistryItem = defineInternalRegistryItem({
6782
6828
  //#region src/cli/registry/items/ratelimit/ratelimit-functions.template.ts
6783
6829
  const PROJECT_CRPC_IMPORT_PLACEHOLDER$3 = "__KITCN_PROJECT_CRPC_IMPORT__";
6784
6830
  const RATELIMIT_FUNCTIONS_TEMPLATE = `import { cleanupRatelimitState } from "kitcn/ratelimit";
6785
- import { z } from "zod";
6831
+ import * as z from "zod";
6786
6832
  import { privateMutation } from "${PROJECT_CRPC_IMPORT_PLACEHOLDER$3}";
6787
6833
 
6788
6834
  const DEFAULT_BATCH_SIZE = 500;
@@ -7098,7 +7144,7 @@ import {
7098
7144
  Text,
7099
7145
  } from '@react-email/components';
7100
7146
  import { render } from '@react-email/render';
7101
- import { z } from 'zod';
7147
+ import * as z from 'zod';
7102
7148
  import { privateAction } from '${PROJECT_CRPC_IMPORT_PLACEHOLDER$2}';
7103
7149
  ${PROJECT_GET_ENV_IMPORT_PLACEHOLDER$1}
7104
7150
  import { createResendCaller } from '${FUNCTIONS_DIR_IMPORT_PLACEHOLDER$2}/generated/plugins/resend.runtime';
@@ -7218,7 +7264,7 @@ const RESEND_FUNCTIONS_TEMPLATE = `import {
7218
7264
  shouldRetry,
7219
7265
  } from '@kitcn/resend';
7220
7266
  import { eq, inArray } from 'kitcn/orm';
7221
- import { z } from 'zod';
7267
+ import * as z from 'zod';
7222
7268
  import { privateAction, privateMutation, privateQuery } from '${PROJECT_CRPC_IMPORT_PLACEHOLDER$1}';
7223
7269
  import { resend } from '${PLUGIN_CONFIG_IMPORT_PLACEHOLDER}';
7224
7270
  import {
@@ -8916,7 +8962,7 @@ function renderInitNextEnvLocalTemplate(source) {
8916
8962
  //#endregion
8917
8963
  //#region src/cli/registry/init/next/init-next-messages.template.ts
8918
8964
  const resolveCrpcImportPath = (functionsDirRelative) => functionsDirRelative === "convex" ? "./lib/crpc" : "../lib/crpc";
8919
- const renderInitNextMessagesTemplate = (functionsDirRelative = "convex/functions") => `import { z } from 'zod';
8965
+ const renderInitNextMessagesTemplate = (functionsDirRelative = "convex/functions") => `import * as z from 'zod';
8920
8966
 
8921
8967
  import { publicMutation, publicQuery } from '${resolveCrpcImportPath(functionsDirRelative)}';
8922
8968
 
@@ -14368,6 +14414,54 @@ const assertRawConvexAuthDeploymentReady = () => {
14368
14414
  const convexUrl = localEnv[projectContext.convexUrlEnvKey]?.trim();
14369
14415
  if (!deployment || !convexUrl) throw new Error(RAW_CONVEX_AUTH_DEPLOYMENT_ERROR);
14370
14416
  };
14417
+ const runDependencyInstallStage = async (installPlan, stage, execaFn) => {
14418
+ try {
14419
+ await applyDependencyInstallPlan(installPlan, execaFn);
14420
+ } catch (error) {
14421
+ throw new Error(`${stage}: ${error instanceof Error ? error.message : String(error)}`);
14422
+ }
14423
+ };
14424
+ /**
14425
+ * The baseline install and the plugin package install run back to back with no
14426
+ * code between them, so they collapse into a single package-manager call.
14427
+ * Merging only happens when both legs target the same package.json with the
14428
+ * same package manager; otherwise each leg runs on its own.
14429
+ */
14430
+ const mergeBaselineAndPluginInstall = (baseline, plugin) => {
14431
+ if (!baseline) return null;
14432
+ if (plugin.skipped || !(plugin.packageName && plugin.packageJsonPath)) return null;
14433
+ if (resolve(baseline.cwd) !== resolve(dirname(plugin.packageJsonPath))) return null;
14434
+ if (detectPackageManager(baseline.cwd) !== baseline.packageManager) return null;
14435
+ const pluginSpec = plugin.packageSpec ?? plugin.packageName;
14436
+ const packages = [...baseline.packages, pluginSpec];
14437
+ const { args, command } = resolveDependencyInstallCommand(baseline.packageManager, packages);
14438
+ return {
14439
+ ...baseline,
14440
+ args,
14441
+ command,
14442
+ packages
14443
+ };
14444
+ };
14445
+ const installBaselineAndPluginDependencies = async (params) => {
14446
+ const { baseline, plugin, pluginKey, execaFn } = params;
14447
+ const merged = mergeBaselineAndPluginInstall(baseline, plugin);
14448
+ if (merged) {
14449
+ await runDependencyInstallStage(merged, `Installing baseline dependencies and the ${pluginKey} package`, execaFn);
14450
+ return {
14451
+ packageName: plugin.packageName,
14452
+ packageSpec: plugin.packageSpec ?? plugin.packageName,
14453
+ packageJsonPath: plugin.packageJsonPath,
14454
+ installed: true,
14455
+ skipped: false
14456
+ };
14457
+ }
14458
+ await runDependencyInstallStage(baseline, "Installing baseline dependencies", execaFn);
14459
+ try {
14460
+ return await applyPluginDependencyInstall(plugin, execaFn);
14461
+ } catch (error) {
14462
+ throw new Error(`Installing the ${pluginKey} package: ${error instanceof Error ? error.message : String(error)}`);
14463
+ }
14464
+ };
14371
14465
  const handleAddCommand = async (argv, deps = {}) => {
14372
14466
  const parsed = parseArgs(argv);
14373
14467
  if (HELP_FLAGS$10.has(argv[0] ?? "") || HELP_FLAGS$10.has(parsed.restArgs[0] ?? "")) {
@@ -14481,8 +14575,12 @@ const handleAddCommand = async (argv, deps = {}) => {
14481
14575
  yes: addArgs.yes,
14482
14576
  promptAdapter
14483
14577
  });
14484
- await applyDependencyInstallPlan(initializationPlan?.dependencyInstall ?? null, execaFn);
14485
- const dependencyInstall = await applyPluginDependencyInstall(plan.dependency, execaFn);
14578
+ const dependencyInstall = await installBaselineAndPluginDependencies({
14579
+ baseline: initializationPlan?.dependencyInstall ?? null,
14580
+ plugin: plan.dependency,
14581
+ pluginKey: selectedPlugin,
14582
+ execaFn
14583
+ });
14486
14584
  const installedDependencyHints = await applyDependencyHintsInstall(plan.dependencyHints, execaFn);
14487
14585
  const payload = {
14488
14586
  command: "add",
@@ -1,4 +1,4 @@
1
- import { a as createMiddlewareFactory } from "./builder-C6JSHkRK.js";
1
+ import { a as createMiddlewareFactory } from "./builder-DoeyW4Vq.js";
2
2
 
3
3
  //#region src/plugins/middleware.ts
4
4
  const PLUGIN_CONFIG_RESOLVERS = Symbol.for("kitcn:PluginConfigResolvers");
@@ -1,6 +1,6 @@
1
1
  import { t as DirectAggregate } from "../../runtime-BdqTbgKh.js";
2
2
  import { a as Columns } from "../../table-CX2lnX7e.js";
3
- import { Y as normalizeTemporalComparableValue, _t as usesSystemCreatedAtAlias, c as AGGREGATE_ERROR, f as createError, gt as PUBLIC_CREATED_AT_FIELD, ht as INTERNAL_CREATION_TIME_FIELD, i as AGGREGATE_STATE_TABLE, it as mapWithConcurrency, l as COUNT_ERROR, n as AGGREGATE_EXTREMA_TABLE, o as getAggregateIndexDefinitions, r as AGGREGATE_MEMBER_TABLE, s as getRankIndexDefinitions, t as AGGREGATE_BUCKET_TABLE } from "../../schema-BQd2Xrfb.js";
3
+ import { Y as normalizeTemporalComparableValue, _t as PUBLIC_CREATED_AT_FIELD, c as AGGREGATE_ERROR, f as createError, gt as INTERNAL_CREATION_TIME_FIELD, i as AGGREGATE_STATE_TABLE, l as COUNT_ERROR, n as AGGREGATE_EXTREMA_TABLE, o as getAggregateIndexDefinitions, ot as mapWithConcurrency, r as AGGREGATE_MEMBER_TABLE, s as getRankIndexDefinitions, t as AGGREGATE_BUCKET_TABLE, vt as usesSystemCreatedAtAlias } from "../../schema-D8sVYuYO.js";
4
4
 
5
5
  //#region src/orm/aggregate-index/runtime.ts
6
6
  const UNDEFINED_SENTINEL = "__kitcnUndefined";
@@ -1,5 +1,5 @@
1
1
  import { $n as BinaryExpression, $t as OrmLifecycleOperation, A as DatabaseWithMutations, An as ConvexCheckConfig, Ar as AnyColumn, At as VectorQueryConfig, B as RlsContext, Bn as ConvexTextBuilderInitial, Br as IsUnique, Bt as RelationsBuilderColumnConfig, C as MigrationTableName, Cn as aggregateIndex, Cr as notBetween, Ct as OrderDirection, D as defineMigrationSet, Dn as uniqueIndex, Dt as ReturningResult, E as defineMigration, En as searchIndex, Er as startsWith, Et as ReturningAll, Fn as ConvexUniqueConstraintConfig, Fr as ColumnBuilderWithTableName, Ft as ExtractTablesWithRelations, Gt as defineRelations, H as EdgeMetadata, In as check, Ir as ColumnDataType, It as ManyConfig, Jt as ConvexDeletionConfig, Kt as defineRelationsPart, Ln as foreignKey, Lr as DrizzleEntity, Lt as OneConfig, M as OrmReader$1, Mn as ConvexForeignKeyConfig, Mr as ColumnBuilderBaseConfig, Mt as unsetToken, N as OrmWriter$1, Nn as ConvexUniqueConstraintBuilder, Nr as ColumnBuilderRuntimeConfig, O as detectMigrationDrift, On as vectorIndex, Or as SystemFields, Ot as ReturningSelection, Pn as ConvexUniqueConstraintBuilderOn, Pr as ColumnBuilderTypeConfig, Pt as ExtractTablesFromSchema, Qn as TableName, Qt as OrmLifecycleChange, Rn as unique, Rr as HasDefault, Rt as RelationsBuilder, S as MigrationStep, Sn as ConvexVectorIndexConfig, Sr as not, St as OrderByClause, T as buildMigrationPlan, Tn as rankIndex, Tr as or, Tt as PredicateWhereIndexConfig, U as extractRelationsConfig, Un as Brand, Ut as TableRelationalConfig, V as RlsMode, Vn as text, Vr as NotNull, Wn as Columns, Wt as TablesRelationalConfig, Xn as OrmSchemaRelations, Xt as ConvexTableWithColumns, Yn as OrmSchemaExtensions, Yt as ConvexTable, Zn as OrmSchemaTriggers, Zt as DiscriminatorBuilderConfig, _ as MigrationMigrateOne, _n as ConvexSearchIndexBuilder, _r as isNull, _t as MutationPaginateConfig, an as RlsPolicyConfig, ar as and, at as CountConfig, b as MigrationSet, bn as ConvexVectorIndexBuilder, br as lte, bt as MutationReturning, cn as RlsRole, cr as endsWith, ct as FilterOperators, d as MigrationDefinition, dn as ConvexAggregateIndexBuilder, dr as gt, dt as InferModelFromColumns, en as TableConfig, er as ExpressionVisitor, et as AggregateConfig, f as MigrationDirection, fn as ConvexAggregateIndexBuilderOn, fr as gte, ft as InferSelectModel, g as MigrationManifestEntry, gn as ConvexRankIndexBuilderOn, gr as isNotNull, gt as MutationExecutionMode, h as MigrationDriftIssue, hn as ConvexRankIndexBuilder, hr as isFieldReference, ht as MutationExecuteResult, i as OrmMigrationCapability, in as RlsPolicy, ir as UnaryExpression, it as BuildRelationResult, j as DatabaseWithQuery, jn as ConvexForeignKeyBuilder, jr as ColumnBuilder, jt as VectorSearchProvider, kn as ConvexCheckBuilder, kt as UpdateSet, ln as RlsRoleConfig, lr as eq, lt as GetColumnData, m as MigrationDocContext, mn as ConvexIndexBuilderOn, mr as inArray, mt as MutationExecuteConfig, n as OrmCapabilities, nn as deletion, nr as FilterExpression, nt as AggregateResult, on as RlsPolicyToOption, or as between, ot as CountResult, p as MigrationDoc, pn as ConvexIndexBuilder, pr as ilike, pt as InsertValue, qn as OrmSchemaExtensionTables, qt as ConvexDeletionBuilder, r as OrmCapability, rn as discriminator, rr as LogicalExpression, rt as BuildQueryResult, sn as rlsPolicy, sr as contains, st as DBQueryConfig, t as OrmAggregateCapability, tn as convexTable, tr as FieldReference, tt as AggregateFieldValue, u as MigrationAppliedState, un as rlsRole, ur as fieldRef, ut as InferInsertModel, v as MigrationPlan, vn as ConvexSearchIndexBuilderOn, vr as like, vt as MutationPaginatedResult, w as MigrationWriteMode, wn as index, wr as notInArray, wt as PaginatedResult, x as MigrationStateMap, xn as ConvexVectorIndexBuilderOn, xr as ne, xt as MutationRunMode, y as MigrationRunStatus, yn as ConvexSearchIndexConfig, yr as lt, yt as MutationResult, zn as ConvexTextBuilder, zr as IsPrimaryKey, zt as RelationsBuilderColumnBase } from "../capabilities-Bem7xvGK.js";
2
- import { $ as OrmClientWithApi$1, A as ConvexDateMode, B as ConvexBytesBuilderInitial, C as ConvexNumberBuilderInitial, D as id, E as ConvexIdBuilderInitial, F as custom, G as ConvexBigIntBuilder, H as ConvexBooleanBuilder, I as json, J as CreateOrmOptions, K as ConvexBigIntBuilderInitial, L as objectOf, M as ConvexCustomBuilder, N as ConvexCustomBuilderInitial, O as ConvexDateBuilder, P as arrayOf, Q as OrmClientBase$1, R as unionOf, S as ConvexNumberBuilder, St as defineTriggers, T as ConvexIdBuilder, U as ConvexBooleanBuilderInitial, V as bytes, W as boolean, X as GenericOrmCtx$1, Y as GenericOrm$1, Z as OrmApiResult, _ as ConvexTimestampMode, _t as OrmBeforeResult, a as requireSchemaRelations, at as ScheduledMutationBatchArgs, b as ConvexTextEnumBuilderInitial, bt as OrmTriggerContext, c as TableConfigResult, ct as scheduledDeleteFactory, d as OrmNotFoundError, et as OrmFunctions, f as ConvexVectorBuilder, g as ConvexTimestampBuilderInitial, gt as defineSchemaExtension, h as ConvexTimestampBuilder, ht as SchemaExtension, i as getSchemaTriggers, it as createOrm, j as date, k as ConvexDateBuilderInitial, l as getTableColumns, m as vector, n as defineSchema, nt as OrmWriterCtx, o as asc, ot as scheduledMutationBatchFactory, p as ConvexVectorBuilderInitial, q as bigint, r as getSchemaRelations, rt as ResolveOrmSchema, s as desc, st as ScheduledDeleteArgs, t as WhereClauseResult, tt as OrmReaderCtx, u as getTableConfig, v as timestamp, vt as OrmTableTriggers, w as integer, x as textEnum, xt as OrmTriggers, y as ConvexTextEnumBuilder, yt as OrmTriggerChange, z as ConvexBytesBuilder } from "../where-clause-compiler-Dmq4HMrK.js";
2
+ import { $ as OrmClientWithApi$1, A as ConvexDateMode, B as ConvexBytesBuilderInitial, C as ConvexNumberBuilderInitial, D as id, E as ConvexIdBuilderInitial, F as custom, G as ConvexBigIntBuilder, H as ConvexBooleanBuilder, I as json, J as CreateOrmOptions, K as ConvexBigIntBuilderInitial, L as objectOf, M as ConvexCustomBuilder, N as ConvexCustomBuilderInitial, O as ConvexDateBuilder, P as arrayOf, Q as OrmClientBase$1, R as unionOf, S as ConvexNumberBuilder, St as defineTriggers, T as ConvexIdBuilder, U as ConvexBooleanBuilderInitial, V as bytes, W as boolean, X as GenericOrmCtx$1, Y as GenericOrm$1, Z as OrmApiResult, _ as ConvexTimestampMode, _t as OrmBeforeResult, a as requireSchemaRelations, at as ScheduledMutationBatchArgs, b as ConvexTextEnumBuilderInitial, bt as OrmTriggerContext, c as TableConfigResult, ct as scheduledDeleteFactory, d as OrmNotFoundError, et as OrmFunctions, f as ConvexVectorBuilder, g as ConvexTimestampBuilderInitial, gt as defineSchemaExtension, h as ConvexTimestampBuilder, ht as SchemaExtension, i as getSchemaTriggers, it as createOrm, j as date, k as ConvexDateBuilderInitial, l as getTableColumns, m as vector, n as defineSchema, nt as OrmWriterCtx, o as asc, ot as scheduledMutationBatchFactory, p as ConvexVectorBuilderInitial, q as bigint, r as getSchemaRelations, rt as ResolveOrmSchema, s as desc, st as ScheduledDeleteArgs, t as WhereClauseResult, tt as OrmReaderCtx, u as getTableConfig, v as timestamp, vt as OrmTableTriggers, w as integer, x as textEnum, xt as OrmTriggers, y as ConvexTextEnumBuilder, yt as OrmTriggerChange, z as ConvexBytesBuilder } from "../where-clause-compiler-TMNQB6US.js";
3
3
  import { i as pretendRequired, n as deprecated, r as pretend } from "../validators-wOIjhkfN.js";
4
4
  import { a as QueryCtxWithPreferredOrmQueryTable, i as QueryCtxWithOrmQueryTable, n as LookupByIdResultByCtx, o as getByIdWithOrmQueryFallback, r as QueryCtxWithOptionalOrmQueryTable, t as DocByCtx } from "../query-context-DJONf8X5.js";
5
5
  import { DefineSchemaOptions, GenericDatabaseReader, GenericDatabaseWriter, GenericSchema, SchemaDefinition } from "convex/server";
package/dist/orm/index.js CHANGED
@@ -4,7 +4,7 @@ import { a as pretendRequired, i as pretend, n as deprecated } from "../validato
4
4
  import { t as id } from "../id-CuSfWa5q.js";
5
5
  import { A as or, C as matchLikePattern, D as notIlike, E as notBetween, O as notInArray, S as lte, T as not, _ as isFieldReference, a as between, b as like, c as endsWith, d as filterValueInList, f as filterValuesEqual, g as inArray, h as ilike, i as arrayOverlaps, j as startsWith, k as notLike, l as eq, m as gte, n as arrayContained, o as column, p as gt, r as arrayContains, s as contains, t as and, u as fieldRef, v as isNotNull, w as ne, x as lt, y as isNull } from "../filter-expression-Dydt8wS0.js";
6
6
  import { a as indexKeyWithinBounds, c as streamIndexRange, i as getIndexFields, l as isUnsetToken, n as EmptyStream, o as mergedStream, r as QueryStream, s as stream, t as getByIdWithOrmQueryFallback, u as unsetToken } from "../query-context-DOm5Xm3H.js";
7
- import { $ as serializeFilterExpression, A as ensureNonNullValues, B as getMutationExecutionMode, C as deserializeFilterExpression, D as enforcePolymorphicWrite, E as enforceForeignKeys, F as getChecks, G as getUniqueIndexes, H as getTableColumns$2, I as getColumnName$1, J as normalizeDateFieldsForWrite, K as hardDeleteRow, L as getForeignKeys, M as evaluateCheckConstraintTriState, N as evaluateFilter, O as enforceUniqueIndexes, P as extractPrimaryIdLookup, Q as selectReturningRowWithHydration, R as getMutationAsyncDelayMs, S as decodeUndefinedDeep, T as enforceCheckConstraints, U as getTableDeleteConfig, V as getOrmContext, W as getTableName, X as patchReferencingRows, Y as normalizeTemporalComparableValue, Z as resolveOrmRuntimeDefaults, _ as applyIncomingForeignKeyActionsOnUpdate, _t as usesSystemCreatedAtAlias, a as aggregateExtension, at as markLifecycleHookedTables, b as collectMutationRowsBounded, c as AGGREGATE_ERROR, ct as findSearchIndexByName, d as createCountError, dt as getIndexes, et as softDeleteRow, ft as getRankIndexes, g as applyIncomingForeignKeyActionsOnDelete, gt as PUBLIC_CREATED_AT_FIELD, h as applyDefaults, ht as INTERNAL_CREATION_TIME_FIELD, it as mapWithConcurrency, j as ensureNullableColumns, k as ensureDefaultColumns, l as COUNT_ERROR, lt as findVectorIndexByName, m as ensureCountAllowedForRls, mt as CREATED_AT_MIGRATION_MESSAGE, nt as takeRowsWithinByteBudget, o as getAggregateIndexDefinitions, ot as findIndexForColumns, p as ensureAggregateAllowedForRls, pt as resolveIndexOrderPushdown, q as hydrateDateFieldsForRead, rt as toConvexFilter, s as getRankIndexDefinitions, st as findRelationIndex, tt as splitReturningSelection, u as createAggregateError, ut as getAggregateIndexes, v as buildForeignKeyGraph, w as encodeUndefinedDeep, x as collectPrimaryIdLookupRows, y as canUsePrimaryIdLookupCursor, z as getMutationCollectionLimits } from "../schema-BQd2Xrfb.js";
7
+ import { $ as serializeFilterExpression, A as ensureNonNullValues, B as getMutationExecutionMode, C as deserializeFilterExpression, D as enforcePolymorphicWrite, E as enforceForeignKeys, F as getChecks, G as getUniqueIndexes, H as getTableColumns$2, I as getColumnName$1, J as normalizeDateFieldsForWrite, K as hardDeleteRow, L as getForeignKeys, M as evaluateCheckConstraintTriState, N as evaluateFilter, O as enforceUniqueIndexes, P as extractPrimaryIdLookup, Q as selectReturningRowWithHydration, R as getMutationAsyncDelayMs, S as decodeUndefinedDeep, T as enforceCheckConstraints, U as getTableDeleteConfig, V as getOrmContext, W as getTableName, X as patchReferencingRows, Y as normalizeTemporalComparableValue, Z as resolveOrmRuntimeDefaults, _ as applyIncomingForeignKeyActionsOnUpdate, _t as PUBLIC_CREATED_AT_FIELD, a as aggregateExtension, at as markLifecycleHookedTables, b as collectMutationRowsBounded, c as AGGREGATE_ERROR, ct as findRelationIndex, d as createCountError, dt as getAggregateIndexes, et as softDeleteRow, ft as getIndexes, g as applyIncomingForeignKeyActionsOnDelete, gt as INTERNAL_CREATION_TIME_FIELD, h as applyDefaults, ht as CREATED_AT_MIGRATION_MESSAGE, it as hasLifecycleHooks, j as ensureNullableColumns, k as ensureDefaultColumns, l as COUNT_ERROR, lt as findSearchIndexByName, m as ensureCountAllowedForRls, mt as resolveIndexOrderPushdown, nt as takeRowsWithinByteBudget, o as getAggregateIndexDefinitions, ot as mapWithConcurrency, p as ensureAggregateAllowedForRls, pt as getRankIndexes, q as hydrateDateFieldsForRead, rt as toConvexFilter, s as getRankIndexDefinitions, st as findIndexForColumns, tt as splitReturningSelection, u as createAggregateError, ut as findVectorIndexByName, v as buildForeignKeyGraph, vt as usesSystemCreatedAtAlias, w as encodeUndefinedDeep, x as collectPrimaryIdLookupRows, y as canUsePrimaryIdLookupCursor, z as getMutationCollectionLimits } from "../schema-D8sVYuYO.js";
8
8
  import { t as defineSchemaExtension } from "../extensions-Blzsyekm.js";
9
9
  import { compareValues, v } from "convex/values";
10
10
  import { defineSchema as defineSchema$1, internalActionGeneric, internalMutationGeneric } from "convex/server";
@@ -6703,11 +6703,43 @@ var ConvexUpdateBuilder = class extends QueryPromise {
6703
6703
  callCap: scheduleCallCap
6704
6704
  };
6705
6705
  const fkBatchSize = isPaginated ? pagination.limit : batchSize;
6706
+ const changedFields = new Set(Object.keys(writeSet));
6707
+ const incomingForeignKeys = foreignKeyGraph.incomingByTable.get(tableName) ?? [];
6708
+ const hooksCanWriteMidLoop = hasLifecycleHooks(this.db, tableName) || incomingForeignKeys.some((foreignKey) => hasLifecycleHooks(this.db, foreignKey.sourceTableName));
6709
+ const cascadeTargetsThisTable = incomingForeignKeys.some((foreignKey) => foreignKey.sourceTableName === tableName);
6710
+ const canDerivePostImage = !(hooksCanWriteMidLoop || cascadeTargetsThisTable);
6711
+ const unsetFields = Object.keys(writeSet).filter((field) => writeSet[field] === void 0);
6712
+ const derivePostImage = (candidate) => {
6713
+ if (unsetFields.length === 0) return candidate;
6714
+ const postImage = { ...candidate };
6715
+ for (const field of unsetFields) delete postImage[field];
6716
+ return postImage;
6717
+ };
6718
+ /**
6719
+ * A single-column `references()` FK to `_id` whose column is supplied by
6720
+ * `set()` probes a byte-identical id on every row, and nothing in this loop
6721
+ * can delete that document. Probe it once, then hide those columns from
6722
+ * `enforceForeignKeys` so the remaining keys still get their per-row check.
6723
+ * Composite FKs read columns off `row`, so they genuinely vary.
6724
+ */
6725
+ const memoizedFkColumns = /* @__PURE__ */ new Set();
6726
+ const perRowFkColumns = /* @__PURE__ */ new Set();
6727
+ for (const foreignKey of getForeignKeys(this.table)) {
6728
+ if (!hooksCanWriteMidLoop && foreignKey.columns.length === 1 && foreignKey.foreignColumns.length === 1 && foreignKey.foreignColumns[0] === "_id" && changedFields.has(foreignKey.columns[0])) {
6729
+ memoizedFkColumns.add(foreignKey.columns[0]);
6730
+ continue;
6731
+ }
6732
+ for (const column of foreignKey.columns) perRowFkColumns.add(column);
6733
+ }
6734
+ for (const column of perRowFkColumns) memoizedFkColumns.delete(column);
6735
+ const residualChangedFields = memoizedFkColumns.size === 0 ? changedFields : new Set([...changedFields].filter((field) => !memoizedFkColumns.has(field)));
6736
+ let foreignKeysProbed = false;
6706
6737
  for (const { row, updatedRow, decision } of updates) {
6707
6738
  if (!decision.allowed) continue;
6708
- enforcePolymorphicWrite(this.table, updatedRow, { changedFields: new Set(Object.keys(writeSet)) });
6739
+ enforcePolymorphicWrite(this.table, updatedRow, { changedFields });
6709
6740
  enforceCheckConstraints(this.table, updatedRow);
6710
- await enforceForeignKeys(this.db, this.table, updatedRow, { changedFields: new Set(Object.keys(writeSet)) });
6741
+ await enforceForeignKeys(this.db, this.table, updatedRow, { changedFields: foreignKeysProbed ? residualChangedFields : changedFields });
6742
+ foreignKeysProbed = true;
6711
6743
  await applyIncomingForeignKeyActionsOnUpdate(this.db, this.table, row, updatedRow, {
6712
6744
  graph: foreignKeyGraph,
6713
6745
  batchSize: fkBatchSize,
@@ -6724,12 +6756,12 @@ var ConvexUpdateBuilder = class extends QueryPromise {
6724
6756
  });
6725
6757
  await enforceUniqueIndexes(this.db, this.table, updatedRow, {
6726
6758
  currentId: row._id,
6727
- changedFields: new Set(Object.keys(writeSet))
6759
+ changedFields
6728
6760
  });
6729
6761
  await this.db.patch(tableName, row._id, writeSet);
6730
6762
  numAffected++;
6731
6763
  if (!this.returningFields) continue;
6732
- const updated = await this.db.get(row._id);
6764
+ const updated = canDerivePostImage ? derivePostImage(updatedRow) : await this.db.get(row._id);
6733
6765
  if (!updated) continue;
6734
6766
  if (this.returningFields === true) results.push(hydrateDateFieldsForRead(this.table, updated));
6735
6767
  else {
@@ -1,3 +1,3 @@
1
1
  import { C as MigrationTableName, D as defineMigrationSet, E as defineMigration, O as detectMigrationDrift, S as MigrationStep, T as buildMigrationPlan, _ as MigrationMigrateOne, a as MigrationCancelArgs, b as MigrationSet, c as MigrationStatusArgs, d as MigrationDefinition, f as MigrationDirection, g as MigrationManifestEntry, h as MigrationDriftIssue, l as createMigrationHandlers, m as MigrationDocContext, o as MigrationRunArgs, p as MigrationDoc, s as MigrationRunChunkArgs, u as MigrationAppliedState, v as MigrationPlan, w as MigrationWriteMode, x as MigrationStateMap, y as MigrationRunStatus } from "../../capabilities-Bem7xvGK.js";
2
- import { Ct as migrationCapability, dt as MIGRATION_STORAGE_TABLE_NAMES, ft as injectMigrationStorageTables, lt as MIGRATION_RUN_TABLE, mt as migrationStorageTables, pt as migrationExtension, ut as MIGRATION_STATE_TABLE } from "../../where-clause-compiler-Dmq4HMrK.js";
2
+ import { Ct as migrationCapability, dt as MIGRATION_STORAGE_TABLE_NAMES, ft as injectMigrationStorageTables, lt as MIGRATION_RUN_TABLE, mt as migrationStorageTables, pt as migrationExtension, ut as MIGRATION_STATE_TABLE } from "../../where-clause-compiler-TMNQB6US.js";
3
3
  export { MIGRATION_RUN_TABLE, MIGRATION_STATE_TABLE, MIGRATION_STORAGE_TABLE_NAMES, type MigrationAppliedState, type MigrationCancelArgs, type MigrationDefinition, type MigrationDirection, type MigrationDoc, type MigrationDocContext, type MigrationDriftIssue, type MigrationManifestEntry, type MigrationMigrateOne, type MigrationPlan, type MigrationRunArgs, type MigrationRunChunkArgs, type MigrationRunStatus, type MigrationSet, type MigrationStateMap, type MigrationStatusArgs, type MigrationStep, type MigrationTableName, type MigrationWriteMode, buildMigrationPlan, createMigrationHandlers, defineMigration, defineMigrationSet, detectMigrationDrift, injectMigrationStorageTables, migrationCapability, migrationExtension, migrationStorageTables };