joist-codegen 2.4.0-next.41 → 2.4.0-next.43

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.
package/build/config.cjs CHANGED
@@ -25,8 +25,13 @@ const fieldConfig = zod.z.object({
25
25
  stiType: zod.z.optional(zod.z.union([zod.z.string(), zod.z.array(zod.z.string())])),
26
26
  notNull: zod.z.optional(zod.z.boolean()),
27
27
  hasDefault: zod.z.optional(zod.z.boolean()),
28
- lazy: zod.z.optional(zod.z.boolean())
29
- }).strict();
28
+ lazy: zod.z.optional(zod.z.boolean()),
29
+ /** Mark the entity for read locking whenever the field's value is read. */
30
+ assertUnchanged: zod.z.optional(zod.z.boolean())
31
+ }).strict().refine((field) => !field.assertUnchanged || !field.derived && !field.lazy && !field.ignore, {
32
+ message: "assertUnchanged requires a non-derived, non-lazy, non-ignored field",
33
+ path: ["assertUnchanged"]
34
+ });
30
35
  const relationConfig = zod.z.object({
31
36
  derived: zod.z.optional(zod.z.literal("async")),
32
37
  polymorphic: zod.z.optional(zod.z.union([zod.z.literal("notNull"), zod.z.literal(true)])),
@@ -1 +1 @@
1
- {"version":3,"file":"config.cjs","names":["createFromBuffer","readFileSync","getPath","z","groupBy","getStiEntities","trueIfResolved","getLatestCodemodVersion","sortKeys","parse","join","existsSync","dirname"],"sources":["../src/config.ts"],"sourcesContent":["import { existsSync, promises as fs, readFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\n\nimport { createFromBuffer } from \"@dprint/formatter\";\nimport { getPath } from \"@dprint/json\";\nimport { groupBy } from \"joist-utils\";\nimport { type ParseError, parse } from \"jsonc-parser\";\nimport { z } from \"zod\";\n\nimport { getLatestCodemodVersion } from \"./codemods/index.ts\";\nimport { type DbMetadata, type Entity, type EntityDbMetadata } from \"./EntityDbMetadata.ts\";\nimport { getStiEntities } from \"./inheritance.ts\";\nimport { logger } from \"./logger.ts\";\nimport { fail, sortKeys, trueIfResolved } from \"./utils.ts\";\n\nconst jsonFormatter = createFromBuffer(readFileSync(getPath()));\n\nconst fieldConfig = z\n .object({\n // For getters & ReactiveFields\n derived: z.optional(z.union([z.literal(\"sync\"), z.literal(\"async\")])),\n protected: z.optional(z.boolean()),\n ignore: z.optional(z.boolean()),\n superstruct: z.optional(z.string()),\n zodSchema: z.optional(z.string()),\n type: z.optional(z.string()),\n serde: z.optional(z.string()),\n stiDiscriminator: z.optional(z.record(z.string(), z.string())),\n stiType: z.optional(z.union([z.string(), z.array(z.string())])),\n // Allow subclasses to mark fields as required\n notNull: z.optional(z.boolean()),\n // Allow overriding scanEntities default detection for fields with defaults added by helpers\n hasDefault: z.optional(z.boolean()),\n // Exclude a (large jsonb/text) column from the default SELECT and expose it as a lazy-loaded LazyField\n lazy: z.optional(z.boolean()),\n })\n .strict();\n\nexport type FieldConfig = z.infer<typeof fieldConfig>;\n\nconst relationConfig = z\n .object({\n // For ReactiveReferences\n derived: z.optional(z.literal(\"async\")),\n polymorphic: z.optional(z.union([z.literal(\"notNull\"), z.literal(true)])),\n large: z.optional(z.boolean()),\n orderBy: z.optional(z.string()),\n /**\n * Controls whether this collection's `.get`/`.load` hide soft-deleted entities.\n *\n * Defaults to `\"exclude\"` (soft-deleted entities are hidden); set to `\"include\"` to have\n * this specific o2m/m2m always return soft-deleted entities from `.get`/`.load`.\n */\n softDeletes: z.optional(z.union([z.literal(\"include\"), z.literal(\"exclude\")])),\n // Allow pushing m2o/m2m/o2o relations in a base type (Task) down to a subtype (TaskOld)\n stiType: z.optional(z.union([z.string(), z.array(z.string())])),\n /**\n * Allow specializing a base type relation (SmallPublisher.group: SmallPublisherGroup).\n *\n * Self-referential FKs also support `subType: \"self\"` that means each subtype will point\n * at its own subtype.\n */\n subType: z.optional(z.string()),\n /** Allow skipping self-referential fields getting a `...Recursive` relation. */\n skipRecursiveRelations: z.optional(z.boolean()),\n // Allow marking m2o FKs as required on subclasses\n notNull: z.optional(z.boolean()),\n // Allow overriding scanEntities default detection for fields with defaults added by helpers\n hasDefault: z.optional(z.boolean()),\n })\n .strict();\n\nexport type RelationConfig = z.infer<typeof relationConfig>;\n\nconst uniqueByConfig = z\n .union([z.string(), z.array(z.string()), z.array(z.array(z.string()))])\n .transform(normalizeUniqueByConfig);\n\nconst entityConfig = z\n .object({\n tag: z.string(),\n tableName: z.optional(z.string()),\n fields: z.optional(z.record(z.string(), fieldConfig)),\n relations: z.optional(z.record(z.string(), relationConfig)),\n /** Whether this entity should be abstract, e.g. for inheritance a subtype must be instantiated instead of this type. */\n abstract: z.optional(z.boolean()),\n orderBy: z.optional(z.string()),\n uniqueBy: z.optional(uniqueByConfig),\n })\n .strict();\n\nexport type EntityConfig = z.infer<typeof entityConfig>;\n\nconst timestampConfig = z\n .object({\n /** The names to check for this timestamp, i.e. `created_at` `created`, etc. */\n names: z.array(z.string()),\n /** Whether this timestamp column is required to consider a table an entity, defaults to `false`. */\n required: z.optional(z.boolean()),\n })\n .strict();\n\nexport type TimestampConfig = z.infer<typeof timestampConfig>;\n\nexport const config = z\n .object({\n /** The _build-time_ database URL for reading database metadata. */\n databaseUrl: z.optional(z.string()),\n /** Your application's request-level `Context` type. */\n contextType: z.optional(z.string()),\n /** Your application's database client's `Transaction` type. */\n transactionType: z.optional(z.string()),\n /**\n * Allows the user to specify the `updated_at` / `created_at` column names to look up, and if they're optional.\n *\n * We default to looking for `updated_at`, `updatedAt`, `created_at`, `createdAt`, and optional to true,\n * e.g. tables are not required to have both timestamp columns to be considered entities.\n *\n * These defaults are the most lenient, to facilitate running Joist against an existing schema and\n * seeing all of your entities, regardless of your previous conventions.\n */\n timestampColumns: z.optional(\n z.object({\n createdAt: z.optional(timestampConfig),\n updatedAt: z.optional(timestampConfig),\n deletedAt: z.optional(timestampConfig),\n }),\n ),\n /**\n * Allows the user to have codegen output `Temporal` types instead of the base JS `Date`\n *\n * Additionally, allows for specifying the default time zone for `Temporal` types when converting dates to/from\n * the database.\n */\n temporal: z.optional(z.union([z.boolean(), z.object({ timeZone: z.string() })])),\n /**\n * By default, we create a `flush_database` function for fast testing.\n *\n * However, if you don't want to use this, or you have your own bespoke function like we do\n * that is more application-aware, then you can disable Joist's out-of-the-box one.\n *\n * If you have more than one test database, you can set `createFlushFunction` to the array\n * of test database names, i.e. `mydb_test_1`, `mydb_test_2`, etc.\n */\n createFlushFunction: z.optional(z.union([z.boolean(), z.array(z.string())])),\n entitiesDirectory: z.string().default(\"./src/entities\"),\n codegenPlugins: z.optional(z.array(z.string())),\n entities: z.record(z.string(), entityConfig).default({}),\n ignoredTables: z.optional(z.array(z.string())),\n /** The type of entity `id` fields; defaults to `tagged-string`. */\n idType: z.optional(z.union([z.literal(\"tagged-string\"), z.literal(\"untagged-string\"), z.literal(\"number\")])),\n /** The separator between entity tags and ids; defaults to `:`, and `\"\"` disables the separator. */\n tagDelimiter: z.optional(z.string()),\n /** How we should support non-deferred foreign keys. */\n nonDeferredForeignKeys: z.optional(z.union([z.literal(\"error\"), z.literal(\"warn\"), z.literal(\"ignore\")])),\n /** Enables esm output. */\n esm: z.optional(z.boolean()),\n /** Controls the style of GraphQL pagination scaffolding. */\n paginationStyle: z.optional(z.union([z.literal(\"cursor\"), z.literal(\"limit\")])).default(\"cursor\"),\n /** Enables documentation syncing between .md files and JSDocs. */\n docs: z.optional(z.boolean()),\n /** Installs Joist's bundled Agent Skills into `.claude/skills` and `.agents/skills`; on by default, set `false` to disable. */\n skills: z.optional(z.boolean()),\n /** Output a metadata-docs.ts file with entity/field documentation available at runtime. */\n outputDocs: z.optional(z.boolean()),\n /** Auto-set by probing the project's `tsconfig.json` file. */\n allowImportingTsExtensions: z.optional(z.boolean()),\n /** The latest Joist codemod counter that has been applied to this project. */\n codemodVersion: z.number().int().min(0).default(0),\n\n /** A list of postgres schemas to use for finding tables */\n schemas: z.optional(z.array(z.string())),\n })\n .strict();\n\nexport type Config = z.infer<typeof config> & {\n // We don't persist this, and instead just use it as a cache\n __tableToEntityName?: Record<string, string>;\n};\n\nexport const ormMaintainedFields = [\"createdAt\", \"updatedAt\"];\n\n/** Ensure the user doesn't have any typos in their config. */\nexport function warnInvalidConfigEntries(config: Config, db: DbMetadata): void {\n const entitiesByName = groupBy(db.entities, (e) => e.name);\n for (const [entityName, entityConfig] of Object.entries(config.entities)) {\n const entities = entitiesByName[entityName];\n if (!entities) {\n logger.warn(`Found config for non-existent entity ${entityName}`);\n continue;\n }\n // We don't have keyBy...\n const [entity] = entities;\n\n // Check fields\n const fields = [...entity.primitives, ...entity.enums];\n for (const [name, config] of Object.entries(entityConfig.fields || {})) {\n if (config.ignore) continue;\n let field = fields.find((f) => f.fieldName === name);\n // STI types might be in the base type\n if (!field && entity.stiDiscriminatorField) {\n const stiEntities = getStiEntities(db.entities).get(entity.name)?.subTypes;\n field = stiEntities?.flatMap((st) => [...st.primitives, ...st.enums]).find((f) => f.fieldName === name);\n }\n if (!field) logger.warn(`Found config for non-existent field ${entityName}.${name}`);\n }\n\n // Check relations\n const relations = [\n ...entity.manyToOnes,\n ...entity.oneToManys,\n ...entity.manyToManys,\n ...entity.manyToManyEnums,\n ...entity.oneToOnes,\n ...entity.largeOneToManys,\n ...entity.largeManyToManys,\n ...entity.polymorphics,\n ];\n for (const [name, _] of Object.entries(entityConfig.relations || {})) {\n let relation = relations.find((r) => r.fieldName === name);\n // STI types might be in the subtypes\n if (!relation && entity.stiDiscriminatorField) {\n const stiEntities = getStiEntities(db.entities).get(entity.name)?.subTypes;\n relation = stiEntities\n ?.flatMap((entity) => [\n ...entity.manyToOnes,\n ...entity.oneToManys,\n ...entity.manyToManys,\n ...entity.oneToOnes,\n ...entity.largeOneToManys,\n ...entity.largeManyToManys,\n ...entity.polymorphics,\n ])\n ?.find((f) => f.fieldName === name);\n }\n // CTI subtype specializations (i.e. SmallPublisher.group: SmallPublisherGroup) need to look in the base type\n if (!relation && entity.baseType) {\n const baseType = entity.baseType;\n relation = [\n ...baseType.manyToOnes,\n ...baseType.oneToManys,\n ...baseType.manyToManys,\n ...baseType.oneToOnes,\n ...baseType.largeOneToManys,\n ...baseType.largeManyToManys,\n ...baseType.polymorphics,\n ].find((f) => f.fieldName === name);\n }\n\n if (!relation) logger.warn(`Found config for non-existent relation ${entityName}.${name}`);\n }\n\n const uniqueFields = [\n ...entity.primitives,\n ...entity.enums,\n ...entity.pgEnums,\n ...entity.manyToOnes,\n ...entity.polymorphics,\n ];\n for (const uniqueBy of entityConfig.uniqueBy || []) {\n for (const name of uniqueBy) {\n const field = uniqueFields.find((f) => f.fieldName === name);\n if (!field) {\n logger.warn(`Found uniqueBy for non-existent or non-queryable field ${entityName}.${name}`);\n } else if (field.kind === \"primitive\" && (field.derived || field.customSerde)) {\n logger.warn(`Found uniqueBy for unsupported primitive field ${entityName}.${name}`);\n } else if (field.kind === \"enum\" && (field.derived || field.isArray)) {\n logger.warn(`Found uniqueBy for unsupported enum field ${entityName}.${name}`);\n }\n }\n }\n }\n}\n\nexport function isGetterField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.derived === \"sync\";\n}\n\nexport function isReactiveField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.derived === \"async\";\n}\n\nexport function isReactiveReference(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.derived === \"async\";\n}\n\n/** Returns true if this m2m relation is configured as a ReactiveManyToMany (derived: async). */\nexport function isReactiveManyToMany(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.derived === \"async\";\n}\n\nexport function isProtected(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.protected === true;\n}\n\n/** Whether a column should be excluded from the default SELECT and exposed as a lazy-loaded `LazyField`. */\nexport function isLazyField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.lazy === true;\n}\n\nexport function serdeConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.serde;\n}\n\nexport function superstructConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.superstruct;\n}\n\nexport function zodSchemaConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.zodSchema;\n}\n\nexport function fieldTypeConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.type;\n}\n\nexport function isLargeCollection(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.large === true;\n}\n\n/** Whether a collection should include (or exclude) soft-deleted entities from `.get`/`.load`. */\nexport function softDeletesConfig(\n config: Config,\n entity: Entity,\n fieldName: string,\n): \"include\" | \"exclude\" | undefined {\n return config.entities[entity.name]?.relations?.[fieldName]?.softDeletes;\n}\n\nexport function isFieldIgnored(\n config: Config,\n entity: Entity,\n fieldName: string,\n notNull: boolean = false,\n hasDefault: boolean = false,\n): boolean {\n const ignore = config.entities[entity.name]?.fields?.[fieldName]?.ignore === true;\n if (ignore && notNull && !hasDefault) {\n fail(\n `notNull field ${entity.name}.${fieldName} cannot be ignored. Alter the column to be optional or have a default value prior to ignoring it.`,\n );\n }\n return ignore;\n}\n\nexport function isFieldHasDefault(config: Config, entity: Entity, fieldName: string): boolean {\n const entityConfig = config.entities[entity.name] ?? {};\n const fieldConfig = entityConfig.fields?.[fieldName] ?? entityConfig.relations?.[fieldName] ?? {};\n return fieldConfig.hasDefault === true;\n}\n\nconst configPath = \"./joist-config.json\";\n\nexport async function loadConfig(): Promise<Config> {\n const exists = await trueIfResolved(fs.access(configPath));\n if (exists) {\n const content = await fs.readFile(configPath);\n const result = config.safeParse(stripLegacyConfigKeys(JSON.parse(content.toString())));\n if (!result.success) {\n throw new Error(\n `Invalid joist-config.json: ${result.error.issues\n .map((ze) => `${ze.path.map(String).join(\"/\")} ${ze.message}`)\n .join(\"\\n\")}`,\n );\n }\n result.data.allowImportingTsExtensions ??= projectIsUsingEsmWithImports();\n return result.data;\n }\n // Brand-new projects should not be prompted to run historical codemods.\n const initial = config.parse({ codemodVersion: getLatestCodemodVersion() });\n initial.allowImportingTsExtensions ??= projectIsUsingEsmWithImports();\n return initial;\n}\n\n/**\n * Writes the potentially-updated config entry back to `joist-config.json`.\n *\n * We format the output with prettier so it should both a) look nice and b) be deterministic,\n * such that no changes to the config show up as noops to the scm.\n */\nexport async function writeConfig(config: Config): Promise<void> {\n const sorted: Partial<Config> = sortKeys(config);\n delete sorted.__tableToEntityName;\n delete sorted.allowImportingTsExtensions;\n if (sorted.paginationStyle === \"cursor\") {\n delete sorted.paginationStyle;\n }\n const input = JSON.stringify(sorted);\n const content = jsonFormatter.formatText({ filePath: \"test.json\", fileText: input });\n await fs.writeFile(configPath, content);\n}\n\nexport function stripStiPlaceholders(config: Config, entities: EntityDbMetadata[]): void {\n // Defacto (with today's setup) the config of STI entities lives on the base entity,\n // so don't write confusing subtype-specific entries into the config file.\n // ...hopefully we don't have any code accidentally looking for the STI config...\n for (const entity of entities) {\n if (entity.inheritanceType === \"sti\" && entity.stiDiscriminatorValue) {\n delete config.entities[entity.name];\n }\n }\n}\n\n/** Applies defaults to the timestamp config. */\nexport function getTimestampConfig(config: Config): {\n updatedAtConf: Required<TimestampConfig>;\n createdAtConf: Required<TimestampConfig>;\n deletedAtConf: Required<TimestampConfig>;\n} {\n return {\n createdAtConf: {\n names: [\"created_at\", \"createdAt\"],\n required: false,\n ...config?.timestampColumns?.createdAt,\n },\n updatedAtConf: {\n names: [\"updated_at\", \"updatedAt\"],\n required: false,\n ...config?.timestampColumns?.updatedAt,\n },\n deletedAtConf: {\n names: [\"deleted_at\", \"deletedAt\"],\n required: false,\n ...config?.timestampColumns?.deletedAt,\n },\n };\n}\n\nfunction projectIsUsingEsmWithImports(): boolean {\n // Attempt to find the project's tsconfig.json in the current directory or up the directory hierarchy\n const configPath = findTsConfigFile(process.cwd());\n if (!configPath) {\n return false;\n }\n try {\n // Use jsonc-parser to parse the tsconfig.json file (not the old tsc readConfigFile which was\n // dropped in TypeScript 7), allowing for comments and trailing commas.\n const errors: ParseError[] = [];\n const parsed: unknown = parse(readFileSync(configPath, \"utf8\"), errors, { allowTrailingComma: true });\n if (errors.length > 0 || typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return false;\n const compilerOptions = (parsed as Record<string, unknown>).compilerOptions;\n return (\n typeof compilerOptions === \"object\" &&\n compilerOptions !== null &&\n !Array.isArray(compilerOptions) &&\n (compilerOptions as Record<string, unknown>).allowImportingTsExtensions === true\n );\n } catch {\n return false;\n }\n}\n\n/** Normalizes `uniqueBy` config sugar into runtime identity candidates. */\nfunction normalizeUniqueByConfig(uniqueBy: string | string[] | string[][]): string[][] {\n if (typeof uniqueBy === \"string\") return [[uniqueBy]];\n if (uniqueBy.every((field) => typeof field === \"string\")) return [uniqueBy];\n return uniqueBy;\n}\n\nfunction stripLegacyConfigKeys(raw: unknown): unknown {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) {\n return raw;\n }\n // Accept old configs so the deprecated key disappears on the next write.\n const parsed = { ...(raw as Record<string, unknown>) };\n delete parsed.version;\n return parsed;\n}\n\n/** Finds the nearest `tsconfig.json` in `directory` or one of its ancestors. */\nfunction findTsConfigFile(directory: string): string | undefined {\n while (true) {\n const fileName = join(directory, \"tsconfig.json\");\n if (existsSync(fileName)) return fileName;\n const parent = dirname(directory);\n if (parent === directory) return undefined;\n directory = parent;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,MAAM,iBAAA,GAAgBA,kBAAAA,iBAAAA,EAAAA,GAAiBC,GAAAA,aAAAA,EAAAA,GAAaC,aAAAA,QAAAA,CAAQ,CAAC,CAAC;AAE9D,MAAM,cAAcC,IAAAA,EACjB,OAAO;CAEN,SAASA,IAAAA,EAAE,SAASA,IAAAA,EAAE,MAAM,CAACA,IAAAA,EAAE,QAAQ,MAAM,GAAGA,IAAAA,EAAE,QA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ACpD,IAAI,CAAC,OAAO,OAAO,QAAQ,YAAY,MAAM,QAAQ,GAAG,GACtD,OAAO;CAGT,MAAM,SAAS,EAAE,GAAI,IAAgC;CACrD,OAAO,OAAO;CACd,OAAO;AACT;;AAGA,SAAS,iBAAiB,WAAuC;CAC/D,OAAO,MAAM;EACX,MAAM,YAAA,GAAWS,KAAAA,KAAAA,CAAK,WAAW,eAAe;EAChD,KAAA,GAAIC,GAAAA,WAAAA,CAAW,QAAQ,GAAG,OAAO;EACjC,MAAM,UAAA,GAASC,KAAAA,QAAAA,CAAQ,SAAS;EAChC,IAAI,WAAW,WAAW,OAAO,KAAA;EACjC,YAAY;CACd;AACF"}
1
+ {"version":3,"file":"config.cjs","names":["createFromBuffer","readFileSync","getPath","z","groupBy","getStiEntities","trueIfResolved","getLatestCodemodVersion","sortKeys","parse","join","existsSync","dirname"],"sources":["../src/config.ts"],"sourcesContent":["import { existsSync, promises as fs, readFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\n\nimport { createFromBuffer } from \"@dprint/formatter\";\nimport { getPath } from \"@dprint/json\";\nimport { groupBy } from \"joist-utils\";\nimport { type ParseError, parse } from \"jsonc-parser\";\nimport { z } from \"zod\";\n\nimport { getLatestCodemodVersion } from \"./codemods/index.ts\";\nimport { type DbMetadata, type Entity, type EntityDbMetadata } from \"./EntityDbMetadata.ts\";\nimport { getStiEntities } from \"./inheritance.ts\";\nimport { logger } from \"./logger.ts\";\nimport { fail, sortKeys, trueIfResolved } from \"./utils.ts\";\n\nconst jsonFormatter = createFromBuffer(readFileSync(getPath()));\n\nconst fieldConfig = z\n .object({\n // For getters & ReactiveFields\n derived: z.optional(z.union([z.literal(\"sync\"), z.literal(\"async\")])),\n protected: z.optional(z.boolean()),\n ignore: z.optional(z.boolean()),\n superstruct: z.optional(z.string()),\n zodSchema: z.optional(z.string()),\n type: z.optional(z.string()),\n serde: z.optional(z.string()),\n stiDiscriminator: z.optional(z.record(z.string(), z.string())),\n stiType: z.optional(z.union([z.string(), z.array(z.string())])),\n // Allow subclasses to mark fields as required\n notNull: z.optional(z.boolean()),\n // Allow overriding scanEntities default detection for fields with defaults added by helpers\n hasDefault: z.optional(z.boolean()),\n // Exclude a (large jsonb/text) column from the default SELECT and expose it as a lazy-loaded LazyField\n lazy: z.optional(z.boolean()),\n /** Mark the entity for read locking whenever the field's value is read. */\n assertUnchanged: z.optional(z.boolean()),\n })\n .strict()\n .refine((field) => !field.assertUnchanged || (!field.derived && !field.lazy && !field.ignore), {\n message: \"assertUnchanged requires a non-derived, non-lazy, non-ignored field\",\n path: [\"assertUnchanged\"],\n });\n\nexport type FieldConfig = z.infer<typeof fieldConfig>;\n\nconst relationConfig = z\n .object({\n // For ReactiveReferences\n derived: z.optional(z.literal(\"async\")),\n polymorphic: z.optional(z.union([z.literal(\"notNull\"), z.literal(true)])),\n large: z.optional(z.boolean()),\n orderBy: z.optional(z.string()),\n /**\n * Controls whether this collection's `.get`/`.load` hide soft-deleted entities.\n *\n * Defaults to `\"exclude\"` (soft-deleted entities are hidden); set to `\"include\"` to have\n * this specific o2m/m2m always return soft-deleted entities from `.get`/`.load`.\n */\n softDeletes: z.optional(z.union([z.literal(\"include\"), z.literal(\"exclude\")])),\n // Allow pushing m2o/m2m/o2o relations in a base type (Task) down to a subtype (TaskOld)\n stiType: z.optional(z.union([z.string(), z.array(z.string())])),\n /**\n * Allow specializing a base type relation (SmallPublisher.group: SmallPublisherGroup).\n *\n * Self-referential FKs also support `subType: \"self\"` that means each subtype will point\n * at its own subtype.\n */\n subType: z.optional(z.string()),\n /** Allow skipping self-referential fields getting a `...Recursive` relation. */\n skipRecursiveRelations: z.optional(z.boolean()),\n // Allow marking m2o FKs as required on subclasses\n notNull: z.optional(z.boolean()),\n // Allow overriding scanEntities default detection for fields with defaults added by helpers\n hasDefault: z.optional(z.boolean()),\n })\n .strict();\n\nexport type RelationConfig = z.infer<typeof relationConfig>;\n\nconst uniqueByConfig = z\n .union([z.string(), z.array(z.string()), z.array(z.array(z.string()))])\n .transform(normalizeUniqueByConfig);\n\nconst entityConfig = z\n .object({\n tag: z.string(),\n tableName: z.optional(z.string()),\n fields: z.optional(z.record(z.string(), fieldConfig)),\n relations: z.optional(z.record(z.string(), relationConfig)),\n /** Whether this entity should be abstract, e.g. for inheritance a subtype must be instantiated instead of this type. */\n abstract: z.optional(z.boolean()),\n orderBy: z.optional(z.string()),\n uniqueBy: z.optional(uniqueByConfig),\n })\n .strict();\n\nexport type EntityConfig = z.infer<typeof entityConfig>;\n\nconst timestampConfig = z\n .object({\n /** The names to check for this timestamp, i.e. `created_at` `created`, etc. */\n names: z.array(z.string()),\n /** Whether this timestamp column is required to consider a table an entity, defaults to `false`. */\n required: z.optional(z.boolean()),\n })\n .strict();\n\nexport type TimestampConfig = z.infer<typeof timestampConfig>;\n\nexport const config = z\n .object({\n /** The _build-time_ database URL for reading database metadata. */\n databaseUrl: z.optional(z.string()),\n /** Your application's request-level `Context` type. */\n contextType: z.optional(z.string()),\n /** Your application's database client's `Transaction` type. */\n transactionType: z.optional(z.string()),\n /**\n * Allows the user to specify the `updated_at` / `created_at` column names to look up, and if they're optional.\n *\n * We default to looking for `updated_at`, `updatedAt`, `created_at`, `createdAt`, and optional to true,\n * e.g. tables are not required to have both timestamp columns to be considered entities.\n *\n * These defaults are the most lenient, to facilitate running Joist against an existing schema and\n * seeing all of your entities, regardless of your previous conventions.\n */\n timestampColumns: z.optional(\n z.object({\n createdAt: z.optional(timestampConfig),\n updatedAt: z.optional(timestampConfig),\n deletedAt: z.optional(timestampConfig),\n }),\n ),\n /**\n * Allows the user to have codegen output `Temporal` types instead of the base JS `Date`\n *\n * Additionally, allows for specifying the default time zone for `Temporal` types when converting dates to/from\n * the database.\n */\n temporal: z.optional(z.union([z.boolean(), z.object({ timeZone: z.string() })])),\n /**\n * By default, we create a `flush_database` function for fast testing.\n *\n * However, if you don't want to use this, or you have your own bespoke function like we do\n * that is more application-aware, then you can disable Joist's out-of-the-box one.\n *\n * If you have more than one test database, you can set `createFlushFunction` to the array\n * of test database names, i.e. `mydb_test_1`, `mydb_test_2`, etc.\n */\n createFlushFunction: z.optional(z.union([z.boolean(), z.array(z.string())])),\n entitiesDirectory: z.string().default(\"./src/entities\"),\n codegenPlugins: z.optional(z.array(z.string())),\n entities: z.record(z.string(), entityConfig).default({}),\n ignoredTables: z.optional(z.array(z.string())),\n /** The type of entity `id` fields; defaults to `tagged-string`. */\n idType: z.optional(z.union([z.literal(\"tagged-string\"), z.literal(\"untagged-string\"), z.literal(\"number\")])),\n /** The separator between entity tags and ids; defaults to `:`, and `\"\"` disables the separator. */\n tagDelimiter: z.optional(z.string()),\n /** How we should support non-deferred foreign keys. */\n nonDeferredForeignKeys: z.optional(z.union([z.literal(\"error\"), z.literal(\"warn\"), z.literal(\"ignore\")])),\n /** Enables esm output. */\n esm: z.optional(z.boolean()),\n /** Controls the style of GraphQL pagination scaffolding. */\n paginationStyle: z.optional(z.union([z.literal(\"cursor\"), z.literal(\"limit\")])).default(\"cursor\"),\n /** Enables documentation syncing between .md files and JSDocs. */\n docs: z.optional(z.boolean()),\n /** Installs Joist's bundled Agent Skills into `.claude/skills` and `.agents/skills`; on by default, set `false` to disable. */\n skills: z.optional(z.boolean()),\n /** Output a metadata-docs.ts file with entity/field documentation available at runtime. */\n outputDocs: z.optional(z.boolean()),\n /** Auto-set by probing the project's `tsconfig.json` file. */\n allowImportingTsExtensions: z.optional(z.boolean()),\n /** The latest Joist codemod counter that has been applied to this project. */\n codemodVersion: z.number().int().min(0).default(0),\n\n /** A list of postgres schemas to use for finding tables */\n schemas: z.optional(z.array(z.string())),\n })\n .strict();\n\nexport type Config = z.infer<typeof config> & {\n // We don't persist this, and instead just use it as a cache\n __tableToEntityName?: Record<string, string>;\n};\n\nexport const ormMaintainedFields = [\"createdAt\", \"updatedAt\"];\n\n/** Ensure the user doesn't have any typos in their config. */\nexport function warnInvalidConfigEntries(config: Config, db: DbMetadata): void {\n const entitiesByName = groupBy(db.entities, (e) => e.name);\n for (const [entityName, entityConfig] of Object.entries(config.entities)) {\n const entities = entitiesByName[entityName];\n if (!entities) {\n logger.warn(`Found config for non-existent entity ${entityName}`);\n continue;\n }\n // We don't have keyBy...\n const [entity] = entities;\n\n // Check fields\n const fields = [...entity.primitives, ...entity.enums];\n for (const [name, config] of Object.entries(entityConfig.fields || {})) {\n if (config.ignore) continue;\n let field = fields.find((f) => f.fieldName === name);\n // STI types might be in the base type\n if (!field && entity.stiDiscriminatorField) {\n const stiEntities = getStiEntities(db.entities).get(entity.name)?.subTypes;\n field = stiEntities?.flatMap((st) => [...st.primitives, ...st.enums]).find((f) => f.fieldName === name);\n }\n if (!field) logger.warn(`Found config for non-existent field ${entityName}.${name}`);\n }\n\n // Check relations\n const relations = [\n ...entity.manyToOnes,\n ...entity.oneToManys,\n ...entity.manyToManys,\n ...entity.manyToManyEnums,\n ...entity.oneToOnes,\n ...entity.largeOneToManys,\n ...entity.largeManyToManys,\n ...entity.polymorphics,\n ];\n for (const [name, _] of Object.entries(entityConfig.relations || {})) {\n let relation = relations.find((r) => r.fieldName === name);\n // STI types might be in the subtypes\n if (!relation && entity.stiDiscriminatorField) {\n const stiEntities = getStiEntities(db.entities).get(entity.name)?.subTypes;\n relation = stiEntities\n ?.flatMap((entity) => [\n ...entity.manyToOnes,\n ...entity.oneToManys,\n ...entity.manyToManys,\n ...entity.oneToOnes,\n ...entity.largeOneToManys,\n ...entity.largeManyToManys,\n ...entity.polymorphics,\n ])\n ?.find((f) => f.fieldName === name);\n }\n // CTI subtype specializations (i.e. SmallPublisher.group: SmallPublisherGroup) need to look in the base type\n if (!relation && entity.baseType) {\n const baseType = entity.baseType;\n relation = [\n ...baseType.manyToOnes,\n ...baseType.oneToManys,\n ...baseType.manyToManys,\n ...baseType.oneToOnes,\n ...baseType.largeOneToManys,\n ...baseType.largeManyToManys,\n ...baseType.polymorphics,\n ].find((f) => f.fieldName === name);\n }\n\n if (!relation) logger.warn(`Found config for non-existent relation ${entityName}.${name}`);\n }\n\n const uniqueFields = [\n ...entity.primitives,\n ...entity.enums,\n ...entity.pgEnums,\n ...entity.manyToOnes,\n ...entity.polymorphics,\n ];\n for (const uniqueBy of entityConfig.uniqueBy || []) {\n for (const name of uniqueBy) {\n const field = uniqueFields.find((f) => f.fieldName === name);\n if (!field) {\n logger.warn(`Found uniqueBy for non-existent or non-queryable field ${entityName}.${name}`);\n } else if (field.kind === \"primitive\" && (field.derived || field.customSerde)) {\n logger.warn(`Found uniqueBy for unsupported primitive field ${entityName}.${name}`);\n } else if (field.kind === \"enum\" && (field.derived || field.isArray)) {\n logger.warn(`Found uniqueBy for unsupported enum field ${entityName}.${name}`);\n }\n }\n }\n }\n}\n\nexport function isGetterField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.derived === \"sync\";\n}\n\nexport function isReactiveField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.derived === \"async\";\n}\n\nexport function isReactiveReference(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.derived === \"async\";\n}\n\n/** Returns true if this m2m relation is configured as a ReactiveManyToMany (derived: async). */\nexport function isReactiveManyToMany(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.derived === \"async\";\n}\n\nexport function isProtected(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.protected === true;\n}\n\n/** Whether a column should be excluded from the default SELECT and exposed as a lazy-loaded `LazyField`. */\nexport function isLazyField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.lazy === true;\n}\n\nexport function serdeConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.serde;\n}\n\nexport function superstructConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.superstruct;\n}\n\nexport function zodSchemaConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.zodSchema;\n}\n\nexport function fieldTypeConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.type;\n}\n\nexport function isLargeCollection(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.large === true;\n}\n\n/** Whether a collection should include (or exclude) soft-deleted entities from `.get`/`.load`. */\nexport function softDeletesConfig(\n config: Config,\n entity: Entity,\n fieldName: string,\n): \"include\" | \"exclude\" | undefined {\n return config.entities[entity.name]?.relations?.[fieldName]?.softDeletes;\n}\n\nexport function isFieldIgnored(\n config: Config,\n entity: Entity,\n fieldName: string,\n notNull: boolean = false,\n hasDefault: boolean = false,\n): boolean {\n const ignore = config.entities[entity.name]?.fields?.[fieldName]?.ignore === true;\n if (ignore && notNull && !hasDefault) {\n fail(\n `notNull field ${entity.name}.${fieldName} cannot be ignored. Alter the column to be optional or have a default value prior to ignoring it.`,\n );\n }\n return ignore;\n}\n\nexport function isFieldHasDefault(config: Config, entity: Entity, fieldName: string): boolean {\n const entityConfig = config.entities[entity.name] ?? {};\n const fieldConfig = entityConfig.fields?.[fieldName] ?? entityConfig.relations?.[fieldName] ?? {};\n return fieldConfig.hasDefault === true;\n}\n\nconst configPath = \"./joist-config.json\";\n\nexport async function loadConfig(): Promise<Config> {\n const exists = await trueIfResolved(fs.access(configPath));\n if (exists) {\n const content = await fs.readFile(configPath);\n const result = config.safeParse(stripLegacyConfigKeys(JSON.parse(content.toString())));\n if (!result.success) {\n throw new Error(\n `Invalid joist-config.json: ${result.error.issues\n .map((ze) => `${ze.path.map(String).join(\"/\")} ${ze.message}`)\n .join(\"\\n\")}`,\n );\n }\n result.data.allowImportingTsExtensions ??= projectIsUsingEsmWithImports();\n return result.data;\n }\n // Brand-new projects should not be prompted to run historical codemods.\n const initial = config.parse({ codemodVersion: getLatestCodemodVersion() });\n initial.allowImportingTsExtensions ??= projectIsUsingEsmWithImports();\n return initial;\n}\n\n/**\n * Writes the potentially-updated config entry back to `joist-config.json`.\n *\n * We format the output with prettier so it should both a) look nice and b) be deterministic,\n * such that no changes to the config show up as noops to the scm.\n */\nexport async function writeConfig(config: Config): Promise<void> {\n const sorted: Partial<Config> = sortKeys(config);\n delete sorted.__tableToEntityName;\n delete sorted.allowImportingTsExtensions;\n if (sorted.paginationStyle === \"cursor\") {\n delete sorted.paginationStyle;\n }\n const input = JSON.stringify(sorted);\n const content = jsonFormatter.formatText({ filePath: \"test.json\", fileText: input });\n await fs.writeFile(configPath, content);\n}\n\nexport function stripStiPlaceholders(config: Config, entities: EntityDbMetadata[]): void {\n // Defacto (with today's setup) the config of STI entities lives on the base entity,\n // so don't write confusing subtype-specific entries into the config file.\n // ...hopefully we don't have any code accidentally looking for the STI config...\n for (const entity of entities) {\n if (entity.inheritanceType === \"sti\" && entity.stiDiscriminatorValue) {\n delete config.entities[entity.name];\n }\n }\n}\n\n/** Applies defaults to the timestamp config. */\nexport function getTimestampConfig(config: Config): {\n updatedAtConf: Required<TimestampConfig>;\n createdAtConf: Required<TimestampConfig>;\n deletedAtConf: Required<TimestampConfig>;\n} {\n return {\n createdAtConf: {\n names: [\"created_at\", \"createdAt\"],\n required: false,\n ...config?.timestampColumns?.createdAt,\n },\n updatedAtConf: {\n names: [\"updated_at\", \"updatedAt\"],\n required: false,\n ...config?.timestampColumns?.updatedAt,\n },\n deletedAtConf: {\n names: [\"deleted_at\", \"deletedAt\"],\n required: false,\n ...config?.timestampColumns?.deletedAt,\n },\n };\n}\n\nfunction projectIsUsingEsmWithImports(): boolean {\n // Attempt to find the project's tsconfig.json in the current directory or up the directory hierarchy\n const configPath = findTsConfigFile(process.cwd());\n if (!configPath) {\n return false;\n }\n try {\n // Use jsonc-parser to parse the tsconfig.json file (not the old tsc readConfigFile which was\n // dropped in TypeScript 7), allowing for comments and trailing commas.\n const errors: ParseError[] = [];\n const parsed: unknown = parse(readFileSync(configPath, \"utf8\"), errors, { allowTrailingComma: true });\n if (errors.length > 0 || typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return false;\n const compilerOptions = (parsed as Record<string, unknown>).compilerOptions;\n return (\n typeof compilerOptions === \"object\" &&\n compilerOptions !== null &&\n !Array.isArray(compilerOptions) &&\n (compilerOptions as Record<string, unknown>).allowImportingTsExtensions === true\n );\n } catch {\n return false;\n }\n}\n\n/** Normalizes `uniqueBy` config sugar into runtime identity candidates. */\nfunction normalizeUniqueByConfig(uniqueBy: string | string[] | string[][]): string[][] {\n if (typeof uniqueBy === \"string\") return [[uniqueBy]];\n if (uniqueBy.every((field) => typeof field === \"string\")) return [uniqueBy];\n return uniqueBy;\n}\n\nfunction stripLegacyConfigKeys(raw: unknown): unknown {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) {\n return raw;\n }\n // Accept old configs so the deprecated key disappears on the next write.\n const parsed = { ...(raw as Record<string, unknown>) };\n delete parsed.version;\n return parsed;\n}\n\n/** Finds the nearest `tsconfig.json` in `directory` or one of its ancestors. */\nfunction findTsConfigFile(directory: string): string | undefined {\n while (true) {\n const fileName = join(directory, \"tsconfig.json\");\n if (existsSync(fileName)) return fileName;\n const parent = dirname(directory);\n if (parent === directory) return undefined;\n directory = parent;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAeA,MAAM,iBAAA,GAAgBA,kBAAAA,iBAAAA,EAAAA,GAAiBC,GAAAA,aAAAA,EAAAA,GAAaC,aAAAA,QAAAA,CAAQ,CAAC,CAAC;AAE9D,MAAM,cAAcC,IAAAA,EACjB,OAAO;CAEN,SAASA,IAAAA,EAAE,SAASA,IAAAA,EAAE,MAAM,CAACA,IAAAA,EAAE,QAAQ,MAAM,GAAGA,IAAAA,EAAE,QAAQ,OAAO,CAAC,CAAC,CAAC;CACpE,WAAWA,IAAAA,EAAE,SAASA,IAAAA,EAAE,QAAQ,CAAC;CACjC,QAAQA,IAAAA,EAAE,SA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UAAU,OAAO,UAAU,QAAQ,GAAG,OAAO,CAAC,QAAQ;CAC1E,OAAO;AACT;AAEA,SAAS,sBAAsB,KAAuB;CACpD,IAAI,CAAC,OAAO,OAAO,QAAQ,YAAY,MAAM,QAAQ,GAAG,GACtD,OAAO;CAGT,MAAM,SAAS,EAAE,GAAI,IAAgC;CACrD,OAAO,OAAO;CACd,OAAO;AACT;;AAGA,SAAS,iBAAiB,WAAuC;CAC/D,OAAO,MAAM;EACX,MAAM,YAAA,GAAWS,KAAAA,KAAAA,CAAK,WAAW,eAAe;EAChD,KAAA,GAAIC,GAAAA,WAAAA,CAAW,QAAQ,GAAG,OAAO;EACjC,MAAM,UAAA,GAASC,KAAAA,QAAAA,CAAQ,SAAS;EAChC,IAAI,WAAW,WAAW,OAAO,KAAA;EACjC,YAAY;CACd;AACF"}
@@ -14,6 +14,7 @@ declare const fieldConfig: z.ZodObject<{
14
14
  notNull: z.ZodOptional<z.ZodBoolean>;
15
15
  hasDefault: z.ZodOptional<z.ZodBoolean>;
16
16
  lazy: z.ZodOptional<z.ZodBoolean>;
17
+ assertUnchanged: z.ZodOptional<z.ZodBoolean>;
17
18
  }, z.core.$strict>;
18
19
  export type FieldConfig = z.infer<typeof fieldConfig>;
19
20
  declare const relationConfig: z.ZodObject<{
@@ -45,6 +46,7 @@ declare const entityConfig: z.ZodObject<{
45
46
  notNull: z.ZodOptional<z.ZodBoolean>;
46
47
  hasDefault: z.ZodOptional<z.ZodBoolean>;
47
48
  lazy: z.ZodOptional<z.ZodBoolean>;
49
+ assertUnchanged: z.ZodOptional<z.ZodBoolean>;
48
50
  }, z.core.$strict>>>;
49
51
  relations: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
50
52
  derived: z.ZodOptional<z.ZodLiteral<"async">>;
@@ -108,6 +110,7 @@ export declare const config: z.ZodObject<{
108
110
  notNull: z.ZodOptional<z.ZodBoolean>;
109
111
  hasDefault: z.ZodOptional<z.ZodBoolean>;
110
112
  lazy: z.ZodOptional<z.ZodBoolean>;
113
+ assertUnchanged: z.ZodOptional<z.ZodBoolean>;
111
114
  }, z.core.$strict>>>;
112
115
  relations: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
113
116
  derived: z.ZodOptional<z.ZodLiteral<"async">>;
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.cts","names":[],"sources":["../src/config.ts"],"mappings":";;;cAiBM,aAAW,EAAA;;;;;;;;;;;;;GAmBN,EAAA,KAAA;YAEC,cAAc,EAAE,aAAa;cAEnC,gBAAc,EAAA;;;;;;;;;;;GA8BT,EAAA,KAAA;YAEC,iBAAiB,EAAE,aAAa;cAMtC,cAAY,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAWP,EAAA,KAAA;YAEC,eAAe,EAAE,aAAa;cAEpC,iBAAe,EAAA;;;GAOV,EAAA,KAAA;YAEC,kBAAkB,EAAE,aAAa;qBAEhC,QAAM,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqER,EAAA,KAAA;YAEC,SAAS,EAAE,aAAa;EAElC,sBAAsB;;qBAGX;;wBAGG,yBAAyB,QAAQ,QAAQ,IAAI;wBA2F7C,cAAc,QAAQ,QAAQ,QAAQ,QAAQ;wBAI9C,gBAAgB,QAAQ,QAAQ,QAAQ,QAAQ;wBAIhD,oBAAoB,QAAQ,QAAQ,QAAQ,QAAQ;;wBAKpD,qBAAqB,QAAQ,QAAQ,QAAQ,QAAQ;wBAIrD,YAAY,QAAQ,QAAQ,QAAQ,QAAQ;;wBAK5C,YAAY,QAAQ,QAAQ,QAAQ,QAAQ;wBAI5C,YAAY,QAAQ,QAAQ,QAAQ,QAAQ;wBAI5C,kBAAkB,QAAQ,QAAQ,QAAQ,QAAQ;wBAIlD,gBAAgB,QAAQ,QAAQ,QAAQ,QAAQ;wBAIhD,gBAAgB,QAAQ,QAAQ,QAAQ,QAAQ;wBAIhD,k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,QAAQ,QAAQ;wBAI5C,kBAAkB,QAAQ,QAAQ,QAAQ,QAAQ;wBAIlD,gBAAgB,QAAQ,QAAQ,QAAQ,QAAQ;wBAIhD,gBAAgB,QAAQ,QAAQ,QAAQ,QAAQ;wBAIhD,kBAAkB,QAAQ,QAAQ,QAAQ,QAAQ;;wBAKlD,kBACd,QAAQ,QACR,QAAQ,QACR;wBAKc,eACd,QAAQ,QACR,QAAQ,QACR,mBACA,mBACA;wBAWc,kBAAkB,QAAQ,QAAQ,QAAQ,QAAQ;wBAQ5C,cAAc,QAAQ;;;;;;;wBA2BtB,YAAY,QAAQ,SAAS;wBAYnC,qBAAqB,QAAQ,QAAQ,UAAU;;wBAY/C,mBAAmB,QAAQ;EACzC,eAAe,SAAS;EACxB,eAAe,SAAS;EACxB,eAAe,SAAS"}
@@ -14,6 +14,7 @@ declare const fieldConfig: z.ZodObject<{
14
14
  notNull: z.ZodOptional<z.ZodBoolean>;
15
15
  hasDefault: z.ZodOptional<z.ZodBoolean>;
16
16
  lazy: z.ZodOptional<z.ZodBoolean>;
17
+ assertUnchanged: z.ZodOptional<z.ZodBoolean>;
17
18
  }, z.core.$strict>;
18
19
  export type FieldConfig = z.infer<typeof fieldConfig>;
19
20
  declare const relationConfig: z.ZodObject<{
@@ -45,6 +46,7 @@ declare const entityConfig: z.ZodObject<{
45
46
  notNull: z.ZodOptional<z.ZodBoolean>;
46
47
  hasDefault: z.ZodOptional<z.ZodBoolean>;
47
48
  lazy: z.ZodOptional<z.ZodBoolean>;
49
+ assertUnchanged: z.ZodOptional<z.ZodBoolean>;
48
50
  }, z.core.$strict>>>;
49
51
  relations: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
50
52
  derived: z.ZodOptional<z.ZodLiteral<"async">>;
@@ -108,6 +110,7 @@ export declare const config: z.ZodObject<{
108
110
  notNull: z.ZodOptional<z.ZodBoolean>;
109
111
  hasDefault: z.ZodOptional<z.ZodBoolean>;
110
112
  lazy: z.ZodOptional<z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QAAQ;wBAI5C,kBAAkB,QAAQ,QAAQ,QAAQ,QAAQ;wBAIlD,gBAAgB,QAAQ,QAAQ,QAAQ,QAAQ;wBAIhD,gBAAgB,QAAQ,QAAQ,QAAQ,QAAQ;wBAIhD,kBAAkB,QAAQ,QAAQ,QAAQ,QAAQ;;wBAKlD,kBACd,QAAQ,QACR,QAAQ,QACR;wBAKc,eACd,QAAQ,QACR,QAAQ,QACR,mBACA,mBACA;wBAWc,kBAAkB,QAAQ,QAAQ,QAAQ,QAAQ;wBAQ5C,cAAc,QAAQ;;;;;;;wBA2BtB,YAAY,QAAQ,SAAS;wBAYnC,qBAAqB,QAAQ,QAAQ,UAAU;;wBAY/C,mBAAmB,QAAQ;EACzC,eAAe,SAAS;EACxB,eAAe,SAAS;EACxB,eAAe,SAAS"}
package/build/config.js CHANGED
@@ -24,8 +24,13 @@ const fieldConfig = z.object({
24
24
  stiType: z.optional(z.union([z.string(), z.array(z.string())])),
25
25
  notNull: z.optional(z.boolean()),
26
26
  hasDefault: z.optional(z.boolean()),
27
- lazy: z.optional(z.boolean())
28
- }).strict();
27
+ lazy: z.optional(z.boolean()),
28
+ /** Mark the entity for read locking whenever the field's value is read. */
29
+ assertUnchanged: z.optional(z.boolean())
30
+ }).strict().refine((field) => !field.assertUnchanged || !field.derived && !field.lazy && !field.ignore, {
31
+ message: "assertUnchanged requires a non-derived, non-lazy, non-ignored field",
32
+ path: ["assertUnchanged"]
33
+ });
29
34
  const relationConfig = z.object({
30
35
  derived: z.optional(z.literal("async")),
31
36
  polymorphic: z.optional(z.union([z.literal("notNull"), z.literal(true)])),
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","names":["fs"],"sources":["../src/config.ts"],"sourcesContent":["import { existsSync, promises as fs, readFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\n\nimport { createFromBuffer } from \"@dprint/formatter\";\nimport { getPath } from \"@dprint/json\";\nimport { groupBy } from \"joist-utils\";\nimport { type ParseError, parse } from \"jsonc-parser\";\nimport { z } from \"zod\";\n\nimport { getLatestCodemodVersion } from \"./codemods/index.ts\";\nimport { type DbMetadata, type Entity, type EntityDbMetadata } from \"./EntityDbMetadata.ts\";\nimport { getStiEntities } from \"./inheritance.ts\";\nimport { logger } from \"./logger.ts\";\nimport { fail, sortKeys, trueIfResolved } from \"./utils.ts\";\n\nconst jsonFormatter = createFromBuffer(readFileSync(getPath()));\n\nconst fieldConfig = z\n .object({\n // For getters & ReactiveFields\n derived: z.optional(z.union([z.literal(\"sync\"), z.literal(\"async\")])),\n protected: z.optional(z.boolean()),\n ignore: z.optional(z.boolean()),\n superstruct: z.optional(z.string()),\n zodSchema: z.optional(z.string()),\n type: z.optional(z.string()),\n serde: z.optional(z.string()),\n stiDiscriminator: z.optional(z.record(z.string(), z.string())),\n stiType: z.optional(z.union([z.string(), z.array(z.string())])),\n // Allow subclasses to mark fields as required\n notNull: z.optional(z.boolean()),\n // Allow overriding scanEntities default detection for fields with defaults added by helpers\n hasDefault: z.optional(z.boolean()),\n // Exclude a (large jsonb/text) column from the default SELECT and expose it as a lazy-loaded LazyField\n lazy: z.optional(z.boolean()),\n })\n .strict();\n\nexport type FieldConfig = z.infer<typeof fieldConfig>;\n\nconst relationConfig = z\n .object({\n // For ReactiveReferences\n derived: z.optional(z.literal(\"async\")),\n polymorphic: z.optional(z.union([z.literal(\"notNull\"), z.literal(true)])),\n large: z.optional(z.boolean()),\n orderBy: z.optional(z.string()),\n /**\n * Controls whether this collection's `.get`/`.load` hide soft-deleted entities.\n *\n * Defaults to `\"exclude\"` (soft-deleted entities are hidden); set to `\"include\"` to have\n * this specific o2m/m2m always return soft-deleted entities from `.get`/`.load`.\n */\n softDeletes: z.optional(z.union([z.literal(\"include\"), z.literal(\"exclude\")])),\n // Allow pushing m2o/m2m/o2o relations in a base type (Task) down to a subtype (TaskOld)\n stiType: z.optional(z.union([z.string(), z.array(z.string())])),\n /**\n * Allow specializing a base type relation (SmallPublisher.group: SmallPublisherGroup).\n *\n * Self-referential FKs also support `subType: \"self\"` that means each subtype will point\n * at its own subtype.\n */\n subType: z.optional(z.string()),\n /** Allow skipping self-referential fields getting a `...Recursive` relation. */\n skipRecursiveRelations: z.optional(z.boolean()),\n // Allow marking m2o FKs as required on subclasses\n notNull: z.optional(z.boolean()),\n // Allow overriding scanEntities default detection for fields with defaults added by helpers\n hasDefault: z.optional(z.boolean()),\n })\n .strict();\n\nexport type RelationConfig = z.infer<typeof relationConfig>;\n\nconst uniqueByConfig = z\n .union([z.string(), z.array(z.string()), z.array(z.array(z.string()))])\n .transform(normalizeUniqueByConfig);\n\nconst entityConfig = z\n .object({\n tag: z.string(),\n tableName: z.optional(z.string()),\n fields: z.optional(z.record(z.string(), fieldConfig)),\n relations: z.optional(z.record(z.string(), relationConfig)),\n /** Whether this entity should be abstract, e.g. for inheritance a subtype must be instantiated instead of this type. */\n abstract: z.optional(z.boolean()),\n orderBy: z.optional(z.string()),\n uniqueBy: z.optional(uniqueByConfig),\n })\n .strict();\n\nexport type EntityConfig = z.infer<typeof entityConfig>;\n\nconst timestampConfig = z\n .object({\n /** The names to check for this timestamp, i.e. `created_at` `created`, etc. */\n names: z.array(z.string()),\n /** Whether this timestamp column is required to consider a table an entity, defaults to `false`. */\n required: z.optional(z.boolean()),\n })\n .strict();\n\nexport type TimestampConfig = z.infer<typeof timestampConfig>;\n\nexport const config = z\n .object({\n /** The _build-time_ database URL for reading database metadata. */\n databaseUrl: z.optional(z.string()),\n /** Your application's request-level `Context` type. */\n contextType: z.optional(z.string()),\n /** Your application's database client's `Transaction` type. */\n transactionType: z.optional(z.string()),\n /**\n * Allows the user to specify the `updated_at` / `created_at` column names to look up, and if they're optional.\n *\n * We default to looking for `updated_at`, `updatedAt`, `created_at`, `createdAt`, and optional to true,\n * e.g. tables are not required to have both timestamp columns to be considered entities.\n *\n * These defaults are the most lenient, to facilitate running Joist against an existing schema and\n * seeing all of your entities, regardless of your previous conventions.\n */\n timestampColumns: z.optional(\n z.object({\n createdAt: z.optional(timestampConfig),\n updatedAt: z.optional(timestampConfig),\n deletedAt: z.optional(timestampConfig),\n }),\n ),\n /**\n * Allows the user to have codegen output `Temporal` types instead of the base JS `Date`\n *\n * Additionally, allows for specifying the default time zone for `Temporal` types when converting dates to/from\n * the database.\n */\n temporal: z.optional(z.union([z.boolean(), z.object({ timeZone: z.string() })])),\n /**\n * By default, we create a `flush_database` function for fast testing.\n *\n * However, if you don't want to use this, or you have your own bespoke function like we do\n * that is more application-aware, then you can disable Joist's out-of-the-box one.\n *\n * If you have more than one test database, you can set `createFlushFunction` to the array\n * of test database names, i.e. `mydb_test_1`, `mydb_test_2`, etc.\n */\n createFlushFunction: z.optional(z.union([z.boolean(), z.array(z.string())])),\n entitiesDirectory: z.string().default(\"./src/entities\"),\n codegenPlugins: z.optional(z.array(z.string())),\n entities: z.record(z.string(), entityConfig).default({}),\n ignoredTables: z.optional(z.array(z.string())),\n /** The type of entity `id` fields; defaults to `tagged-string`. */\n idType: z.optional(z.union([z.literal(\"tagged-string\"), z.literal(\"untagged-string\"), z.literal(\"number\")])),\n /** The separator between entity tags and ids; defaults to `:`, and `\"\"` disables the separator. */\n tagDelimiter: z.optional(z.string()),\n /** How we should support non-deferred foreign keys. */\n nonDeferredForeignKeys: z.optional(z.union([z.literal(\"error\"), z.literal(\"warn\"), z.literal(\"ignore\")])),\n /** Enables esm output. */\n esm: z.optional(z.boolean()),\n /** Controls the style of GraphQL pagination scaffolding. */\n paginationStyle: z.optional(z.union([z.literal(\"cursor\"), z.literal(\"limit\")])).default(\"cursor\"),\n /** Enables documentation syncing between .md files and JSDocs. */\n docs: z.optional(z.boolean()),\n /** Installs Joist's bundled Agent Skills into `.claude/skills` and `.agents/skills`; on by default, set `false` to disable. */\n skills: z.optional(z.boolean()),\n /** Output a metadata-docs.ts file with entity/field documentation available at runtime. */\n outputDocs: z.optional(z.boolean()),\n /** Auto-set by probing the project's `tsconfig.json` file. */\n allowImportingTsExtensions: z.optional(z.boolean()),\n /** The latest Joist codemod counter that has been applied to this project. */\n codemodVersion: z.number().int().min(0).default(0),\n\n /** A list of postgres schemas to use for finding tables */\n schemas: z.optional(z.array(z.string())),\n })\n .strict();\n\nexport type Config = z.infer<typeof config> & {\n // We don't persist this, and instead just use it as a cache\n __tableToEntityName?: Record<string, string>;\n};\n\nexport const ormMaintainedFields = [\"createdAt\", \"updatedAt\"];\n\n/** Ensure the user doesn't have any typos in their config. */\nexport function warnInvalidConfigEntries(config: Config, db: DbMetadata): void {\n const entitiesByName = groupBy(db.entities, (e) => e.name);\n for (const [entityName, entityConfig] of Object.entries(config.entities)) {\n const entities = entitiesByName[entityName];\n if (!entities) {\n logger.warn(`Found config for non-existent entity ${entityName}`);\n continue;\n }\n // We don't have keyBy...\n const [entity] = entities;\n\n // Check fields\n const fields = [...entity.primitives, ...entity.enums];\n for (const [name, config] of Object.entries(entityConfig.fields || {})) {\n if (config.ignore) continue;\n let field = fields.find((f) => f.fieldName === name);\n // STI types might be in the base type\n if (!field && entity.stiDiscriminatorField) {\n const stiEntities = getStiEntities(db.entities).get(entity.name)?.subTypes;\n field = stiEntities?.flatMap((st) => [...st.primitives, ...st.enums]).find((f) => f.fieldName === name);\n }\n if (!field) logger.warn(`Found config for non-existent field ${entityName}.${name}`);\n }\n\n // Check relations\n const relations = [\n ...entity.manyToOnes,\n ...entity.oneToManys,\n ...entity.manyToManys,\n ...entity.manyToManyEnums,\n ...entity.oneToOnes,\n ...entity.largeOneToManys,\n ...entity.largeManyToManys,\n ...entity.polymorphics,\n ];\n for (const [name, _] of Object.entries(entityConfig.relations || {})) {\n let relation = relations.find((r) => r.fieldName === name);\n // STI types might be in the subtypes\n if (!relation && entity.stiDiscriminatorField) {\n const stiEntities = getStiEntities(db.entities).get(entity.name)?.subTypes;\n relation = stiEntities\n ?.flatMap((entity) => [\n ...entity.manyToOnes,\n ...entity.oneToManys,\n ...entity.manyToManys,\n ...entity.oneToOnes,\n ...entity.largeOneToManys,\n ...entity.largeManyToManys,\n ...entity.polymorphics,\n ])\n ?.find((f) => f.fieldName === name);\n }\n // CTI subtype specializations (i.e. SmallPublisher.group: SmallPublisherGroup) need to look in the base type\n if (!relation && entity.baseType) {\n const baseType = entity.baseType;\n relation = [\n ...baseType.manyToOnes,\n ...baseType.oneToManys,\n ...baseType.manyToManys,\n ...baseType.oneToOnes,\n ...baseType.largeOneToManys,\n ...baseType.largeManyToManys,\n ...baseType.polymorphics,\n ].find((f) => f.fieldName === name);\n }\n\n if (!relation) logger.warn(`Found config for non-existent relation ${entityName}.${name}`);\n }\n\n const uniqueFields = [\n ...entity.primitives,\n ...entity.enums,\n ...entity.pgEnums,\n ...entity.manyToOnes,\n ...entity.polymorphics,\n ];\n for (const uniqueBy of entityConfig.uniqueBy || []) {\n for (const name of uniqueBy) {\n const field = uniqueFields.find((f) => f.fieldName === name);\n if (!field) {\n logger.warn(`Found uniqueBy for non-existent or non-queryable field ${entityName}.${name}`);\n } else if (field.kind === \"primitive\" && (field.derived || field.customSerde)) {\n logger.warn(`Found uniqueBy for unsupported primitive field ${entityName}.${name}`);\n } else if (field.kind === \"enum\" && (field.derived || field.isArray)) {\n logger.warn(`Found uniqueBy for unsupported enum field ${entityName}.${name}`);\n }\n }\n }\n }\n}\n\nexport function isGetterField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.derived === \"sync\";\n}\n\nexport function isReactiveField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.derived === \"async\";\n}\n\nexport function isReactiveReference(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.derived === \"async\";\n}\n\n/** Returns true if this m2m relation is configured as a ReactiveManyToMany (derived: async). */\nexport function isReactiveManyToMany(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.derived === \"async\";\n}\n\nexport function isProtected(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.protected === true;\n}\n\n/** Whether a column should be excluded from the default SELECT and exposed as a lazy-loaded `LazyField`. */\nexport function isLazyField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.lazy === true;\n}\n\nexport function serdeConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.serde;\n}\n\nexport function superstructConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.superstruct;\n}\n\nexport function zodSchemaConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.zodSchema;\n}\n\nexport function fieldTypeConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.type;\n}\n\nexport function isLargeCollection(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.large === true;\n}\n\n/** Whether a collection should include (or exclude) soft-deleted entities from `.get`/`.load`. */\nexport function softDeletesConfig(\n config: Config,\n entity: Entity,\n fieldName: string,\n): \"include\" | \"exclude\" | undefined {\n return config.entities[entity.name]?.relations?.[fieldName]?.softDeletes;\n}\n\nexport function isFieldIgnored(\n config: Config,\n entity: Entity,\n fieldName: string,\n notNull: boolean = false,\n hasDefault: boolean = false,\n): boolean {\n const ignore = config.entities[entity.name]?.fields?.[fieldName]?.ignore === true;\n if (ignore && notNull && !hasDefault) {\n fail(\n `notNull field ${entity.name}.${fieldName} cannot be ignored. Alter the column to be optional or have a default value prior to ignoring it.`,\n );\n }\n return ignore;\n}\n\nexport function isFieldHasDefault(config: Config, entity: Entity, fieldName: string): boolean {\n const entityConfig = config.entities[entity.name] ?? {};\n const fieldConfig = entityConfig.fields?.[fieldName] ?? entityConfig.relations?.[fieldName] ?? {};\n return fieldConfig.hasDefault === true;\n}\n\nconst configPath = \"./joist-config.json\";\n\nexport async function loadConfig(): Promise<Config> {\n const exists = await trueIfResolved(fs.access(configPath));\n if (exists) {\n const content = await fs.readFile(configPath);\n const result = config.safeParse(stripLegacyConfigKeys(JSON.parse(content.toString())));\n if (!result.success) {\n throw new Error(\n `Invalid joist-config.json: ${result.error.issues\n .map((ze) => `${ze.path.map(String).join(\"/\")} ${ze.message}`)\n .join(\"\\n\")}`,\n );\n }\n result.data.allowImportingTsExtensions ??= projectIsUsingEsmWithImports();\n return result.data;\n }\n // Brand-new projects should not be prompted to run historical codemods.\n const initial = config.parse({ codemodVersion: getLatestCodemodVersion() });\n initial.allowImportingTsExtensions ??= projectIsUsingEsmWithImports();\n return initial;\n}\n\n/**\n * Writes the potentially-updated config entry back to `joist-config.json`.\n *\n * We format the output with prettier so it should both a) look nice and b) be deterministic,\n * such that no changes to the config show up as noops to the scm.\n */\nexport async function writeConfig(config: Config): Promise<void> {\n const sorted: Partial<Config> = sortKeys(config);\n delete sorted.__tableToEntityName;\n delete sorted.allowImportingTsExtensions;\n if (sorted.paginationStyle === \"cursor\") {\n delete sorted.paginationStyle;\n }\n const input = JSON.stringify(sorted);\n const content = jsonFormatter.formatText({ filePath: \"test.json\", fileText: input });\n await fs.writeFile(configPath, content);\n}\n\nexport function stripStiPlaceholders(config: Config, entities: EntityDbMetadata[]): void {\n // Defacto (with today's setup) the config of STI entities lives on the base entity,\n // so don't write confusing subtype-specific entries into the config file.\n // ...hopefully we don't have any code accidentally looking for the STI config...\n for (const entity of entities) {\n if (entity.inheritanceType === \"sti\" && entity.stiDiscriminatorValue) {\n delete config.entities[entity.name];\n }\n }\n}\n\n/** Applies defaults to the timestamp config. */\nexport function getTimestampConfig(config: Config): {\n updatedAtConf: Required<TimestampConfig>;\n createdAtConf: Required<TimestampConfig>;\n deletedAtConf: Required<TimestampConfig>;\n} {\n return {\n createdAtConf: {\n names: [\"created_at\", \"createdAt\"],\n required: false,\n ...config?.timestampColumns?.createdAt,\n },\n updatedAtConf: {\n names: [\"updated_at\", \"updatedAt\"],\n required: false,\n ...config?.timestampColumns?.updatedAt,\n },\n deletedAtConf: {\n names: [\"deleted_at\", \"deletedAt\"],\n required: false,\n ...config?.timestampColumns?.deletedAt,\n },\n };\n}\n\nfunction projectIsUsingEsmWithImports(): boolean {\n // Attempt to find the project's tsconfig.json in the current directory or up the directory hierarchy\n const configPath = findTsConfigFile(process.cwd());\n if (!configPath) {\n return false;\n }\n try {\n // Use jsonc-parser to parse the tsconfig.json file (not the old tsc readConfigFile which was\n // dropped in TypeScript 7), allowing for comments and trailing commas.\n const errors: ParseError[] = [];\n const parsed: unknown = parse(readFileSync(configPath, \"utf8\"), errors, { allowTrailingComma: true });\n if (errors.length > 0 || typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return false;\n const compilerOptions = (parsed as Record<string, unknown>).compilerOptions;\n return (\n typeof compilerOptions === \"object\" &&\n compilerOptions !== null &&\n !Array.isArray(compilerOptions) &&\n (compilerOptions as Record<string, unknown>).allowImportingTsExtensions === true\n );\n } catch {\n return false;\n }\n}\n\n/** Normalizes `uniqueBy` config sugar into runtime identity candidates. */\nfunction normalizeUniqueByConfig(uniqueBy: string | string[] | string[][]): string[][] {\n if (typeof uniqueBy === \"string\") return [[uniqueBy]];\n if (uniqueBy.every((field) => typeof field === \"string\")) return [uniqueBy];\n return uniqueBy;\n}\n\nfunction stripLegacyConfigKeys(raw: unknown): unknown {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) {\n return raw;\n }\n // Accept old configs so the deprecated key disappears on the next write.\n const parsed = { ...(raw as Record<string, unknown>) };\n delete parsed.version;\n return parsed;\n}\n\n/** Finds the nearest `tsconfig.json` in `directory` or one of its ancestors. */\nfunction findTsConfigFile(directory: string): string | undefined {\n while (true) {\n const fileName = join(directory, \"tsconfig.json\");\n if (existsSync(fileName)) return fileName;\n const parent = dirname(directory);\n if (parent === directory) return undefined;\n directory = parent;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,MAAM,gBAAgB,iBAAiB,aAAa,QAAQ,CAAC,CAAC;AAE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C1E,OAAO;AACT;AAEA,SAAS,sBAAsB,KAAuB;CACpD,IAAI,CAAC,OAAO,OAAO,QAAQ,YAAY,MAAM,QAAQ,GAAG,GACtD,OAAO;CAGT,MAAM,SAAS,EAAE,GAAI,IAAgC;CACrD,OAAO,OAAO;CACd,OAAO;AACT;;AAGA,SAAS,iBAAiB,WAAuC;CAC/D,OAAO,MAAM;EACX,MAAM,WAAW,KAAK,WAAW,eAAe;EAChD,IAAI,WAAW,QAAQ,GAAG,OAAO;EACjC,MAAM,SAAS,QAAQ,SAAS;EAChC,IAAI,WAAW,WAAW,OAAO,KAAA;EACjC,YAAY;CACd;AACF"}
1
+ {"version":3,"file":"config.js","names":["fs"],"sources":["../src/config.ts"],"sourcesContent":["import { existsSync, promises as fs, readFileSync } from \"fs\";\nimport { dirname, join } from \"path\";\n\nimport { createFromBuffer } from \"@dprint/formatter\";\nimport { getPath } from \"@dprint/json\";\nimport { groupBy } from \"joist-utils\";\nimport { type ParseError, parse } from \"jsonc-parser\";\nimport { z } from \"zod\";\n\nimport { getLatestCodemodVersion } from \"./codemods/index.ts\";\nimport { type DbMetadata, type Entity, type EntityDbMetadata } from \"./EntityDbMetadata.ts\";\nimport { getStiEntities } from \"./inheritance.ts\";\nimport { logger } from \"./logger.ts\";\nimport { fail, sortKeys, trueIfResolved } from \"./utils.ts\";\n\nconst jsonFormatter = createFromBuffer(readFileSync(getPath()));\n\nconst fieldConfig = z\n .object({\n // For getters & ReactiveFields\n derived: z.optional(z.union([z.literal(\"sync\"), z.literal(\"async\")])),\n protected: z.optional(z.boolean()),\n ignore: z.optional(z.boolean()),\n superstruct: z.optional(z.string()),\n zodSchema: z.optional(z.string()),\n type: z.optional(z.string()),\n serde: z.optional(z.string()),\n stiDiscriminator: z.optional(z.record(z.string(), z.string())),\n stiType: z.optional(z.union([z.string(), z.array(z.string())])),\n // Allow subclasses to mark fields as required\n notNull: z.optional(z.boolean()),\n // Allow overriding scanEntities default detection for fields with defaults added by helpers\n hasDefault: z.optional(z.boolean()),\n // Exclude a (large jsonb/text) column from the default SELECT and expose it as a lazy-loaded LazyField\n lazy: z.optional(z.boolean()),\n /** Mark the entity for read locking whenever the field's value is read. */\n assertUnchanged: z.optional(z.boolean()),\n })\n .strict()\n .refine((field) => !field.assertUnchanged || (!field.derived && !field.lazy && !field.ignore), {\n message: \"assertUnchanged requires a non-derived, non-lazy, non-ignored field\",\n path: [\"assertUnchanged\"],\n });\n\nexport type FieldConfig = z.infer<typeof fieldConfig>;\n\nconst relationConfig = z\n .object({\n // For ReactiveReferences\n derived: z.optional(z.literal(\"async\")),\n polymorphic: z.optional(z.union([z.literal(\"notNull\"), z.literal(true)])),\n large: z.optional(z.boolean()),\n orderBy: z.optional(z.string()),\n /**\n * Controls whether this collection's `.get`/`.load` hide soft-deleted entities.\n *\n * Defaults to `\"exclude\"` (soft-deleted entities are hidden); set to `\"include\"` to have\n * this specific o2m/m2m always return soft-deleted entities from `.get`/`.load`.\n */\n softDeletes: z.optional(z.union([z.literal(\"include\"), z.literal(\"exclude\")])),\n // Allow pushing m2o/m2m/o2o relations in a base type (Task) down to a subtype (TaskOld)\n stiType: z.optional(z.union([z.string(), z.array(z.string())])),\n /**\n * Allow specializing a base type relation (SmallPublisher.group: SmallPublisherGroup).\n *\n * Self-referential FKs also support `subType: \"self\"` that means each subtype will point\n * at its own subtype.\n */\n subType: z.optional(z.string()),\n /** Allow skipping self-referential fields getting a `...Recursive` relation. */\n skipRecursiveRelations: z.optional(z.boolean()),\n // Allow marking m2o FKs as required on subclasses\n notNull: z.optional(z.boolean()),\n // Allow overriding scanEntities default detection for fields with defaults added by helpers\n hasDefault: z.optional(z.boolean()),\n })\n .strict();\n\nexport type RelationConfig = z.infer<typeof relationConfig>;\n\nconst uniqueByConfig = z\n .union([z.string(), z.array(z.string()), z.array(z.array(z.string()))])\n .transform(normalizeUniqueByConfig);\n\nconst entityConfig = z\n .object({\n tag: z.string(),\n tableName: z.optional(z.string()),\n fields: z.optional(z.record(z.string(), fieldConfig)),\n relations: z.optional(z.record(z.string(), relationConfig)),\n /** Whether this entity should be abstract, e.g. for inheritance a subtype must be instantiated instead of this type. */\n abstract: z.optional(z.boolean()),\n orderBy: z.optional(z.string()),\n uniqueBy: z.optional(uniqueByConfig),\n })\n .strict();\n\nexport type EntityConfig = z.infer<typeof entityConfig>;\n\nconst timestampConfig = z\n .object({\n /** The names to check for this timestamp, i.e. `created_at` `created`, etc. */\n names: z.array(z.string()),\n /** Whether this timestamp column is required to consider a table an entity, defaults to `false`. */\n required: z.optional(z.boolean()),\n })\n .strict();\n\nexport type TimestampConfig = z.infer<typeof timestampConfig>;\n\nexport const config = z\n .object({\n /** The _build-time_ database URL for reading database metadata. */\n databaseUrl: z.optional(z.string()),\n /** Your application's request-level `Context` type. */\n contextType: z.optional(z.string()),\n /** Your application's database client's `Transaction` type. */\n transactionType: z.optional(z.string()),\n /**\n * Allows the user to specify the `updated_at` / `created_at` column names to look up, and if they're optional.\n *\n * We default to looking for `updated_at`, `updatedAt`, `created_at`, `createdAt`, and optional to true,\n * e.g. tables are not required to have both timestamp columns to be considered entities.\n *\n * These defaults are the most lenient, to facilitate running Joist against an existing schema and\n * seeing all of your entities, regardless of your previous conventions.\n */\n timestampColumns: z.optional(\n z.object({\n createdAt: z.optional(timestampConfig),\n updatedAt: z.optional(timestampConfig),\n deletedAt: z.optional(timestampConfig),\n }),\n ),\n /**\n * Allows the user to have codegen output `Temporal` types instead of the base JS `Date`\n *\n * Additionally, allows for specifying the default time zone for `Temporal` types when converting dates to/from\n * the database.\n */\n temporal: z.optional(z.union([z.boolean(), z.object({ timeZone: z.string() })])),\n /**\n * By default, we create a `flush_database` function for fast testing.\n *\n * However, if you don't want to use this, or you have your own bespoke function like we do\n * that is more application-aware, then you can disable Joist's out-of-the-box one.\n *\n * If you have more than one test database, you can set `createFlushFunction` to the array\n * of test database names, i.e. `mydb_test_1`, `mydb_test_2`, etc.\n */\n createFlushFunction: z.optional(z.union([z.boolean(), z.array(z.string())])),\n entitiesDirectory: z.string().default(\"./src/entities\"),\n codegenPlugins: z.optional(z.array(z.string())),\n entities: z.record(z.string(), entityConfig).default({}),\n ignoredTables: z.optional(z.array(z.string())),\n /** The type of entity `id` fields; defaults to `tagged-string`. */\n idType: z.optional(z.union([z.literal(\"tagged-string\"), z.literal(\"untagged-string\"), z.literal(\"number\")])),\n /** The separator between entity tags and ids; defaults to `:`, and `\"\"` disables the separator. */\n tagDelimiter: z.optional(z.string()),\n /** How we should support non-deferred foreign keys. */\n nonDeferredForeignKeys: z.optional(z.union([z.literal(\"error\"), z.literal(\"warn\"), z.literal(\"ignore\")])),\n /** Enables esm output. */\n esm: z.optional(z.boolean()),\n /** Controls the style of GraphQL pagination scaffolding. */\n paginationStyle: z.optional(z.union([z.literal(\"cursor\"), z.literal(\"limit\")])).default(\"cursor\"),\n /** Enables documentation syncing between .md files and JSDocs. */\n docs: z.optional(z.boolean()),\n /** Installs Joist's bundled Agent Skills into `.claude/skills` and `.agents/skills`; on by default, set `false` to disable. */\n skills: z.optional(z.boolean()),\n /** Output a metadata-docs.ts file with entity/field documentation available at runtime. */\n outputDocs: z.optional(z.boolean()),\n /** Auto-set by probing the project's `tsconfig.json` file. */\n allowImportingTsExtensions: z.optional(z.boolean()),\n /** The latest Joist codemod counter that has been applied to this project. */\n codemodVersion: z.number().int().min(0).default(0),\n\n /** A list of postgres schemas to use for finding tables */\n schemas: z.optional(z.array(z.string())),\n })\n .strict();\n\nexport type Config = z.infer<typeof config> & {\n // We don't persist this, and instead just use it as a cache\n __tableToEntityName?: Record<string, string>;\n};\n\nexport const ormMaintainedFields = [\"createdAt\", \"updatedAt\"];\n\n/** Ensure the user doesn't have any typos in their config. */\nexport function warnInvalidConfigEntries(config: Config, db: DbMetadata): void {\n const entitiesByName = groupBy(db.entities, (e) => e.name);\n for (const [entityName, entityConfig] of Object.entries(config.entities)) {\n const entities = entitiesByName[entityName];\n if (!entities) {\n logger.warn(`Found config for non-existent entity ${entityName}`);\n continue;\n }\n // We don't have keyBy...\n const [entity] = entities;\n\n // Check fields\n const fields = [...entity.primitives, ...entity.enums];\n for (const [name, config] of Object.entries(entityConfig.fields || {})) {\n if (config.ignore) continue;\n let field = fields.find((f) => f.fieldName === name);\n // STI types might be in the base type\n if (!field && entity.stiDiscriminatorField) {\n const stiEntities = getStiEntities(db.entities).get(entity.name)?.subTypes;\n field = stiEntities?.flatMap((st) => [...st.primitives, ...st.enums]).find((f) => f.fieldName === name);\n }\n if (!field) logger.warn(`Found config for non-existent field ${entityName}.${name}`);\n }\n\n // Check relations\n const relations = [\n ...entity.manyToOnes,\n ...entity.oneToManys,\n ...entity.manyToManys,\n ...entity.manyToManyEnums,\n ...entity.oneToOnes,\n ...entity.largeOneToManys,\n ...entity.largeManyToManys,\n ...entity.polymorphics,\n ];\n for (const [name, _] of Object.entries(entityConfig.relations || {})) {\n let relation = relations.find((r) => r.fieldName === name);\n // STI types might be in the subtypes\n if (!relation && entity.stiDiscriminatorField) {\n const stiEntities = getStiEntities(db.entities).get(entity.name)?.subTypes;\n relation = stiEntities\n ?.flatMap((entity) => [\n ...entity.manyToOnes,\n ...entity.oneToManys,\n ...entity.manyToManys,\n ...entity.oneToOnes,\n ...entity.largeOneToManys,\n ...entity.largeManyToManys,\n ...entity.polymorphics,\n ])\n ?.find((f) => f.fieldName === name);\n }\n // CTI subtype specializations (i.e. SmallPublisher.group: SmallPublisherGroup) need to look in the base type\n if (!relation && entity.baseType) {\n const baseType = entity.baseType;\n relation = [\n ...baseType.manyToOnes,\n ...baseType.oneToManys,\n ...baseType.manyToManys,\n ...baseType.oneToOnes,\n ...baseType.largeOneToManys,\n ...baseType.largeManyToManys,\n ...baseType.polymorphics,\n ].find((f) => f.fieldName === name);\n }\n\n if (!relation) logger.warn(`Found config for non-existent relation ${entityName}.${name}`);\n }\n\n const uniqueFields = [\n ...entity.primitives,\n ...entity.enums,\n ...entity.pgEnums,\n ...entity.manyToOnes,\n ...entity.polymorphics,\n ];\n for (const uniqueBy of entityConfig.uniqueBy || []) {\n for (const name of uniqueBy) {\n const field = uniqueFields.find((f) => f.fieldName === name);\n if (!field) {\n logger.warn(`Found uniqueBy for non-existent or non-queryable field ${entityName}.${name}`);\n } else if (field.kind === \"primitive\" && (field.derived || field.customSerde)) {\n logger.warn(`Found uniqueBy for unsupported primitive field ${entityName}.${name}`);\n } else if (field.kind === \"enum\" && (field.derived || field.isArray)) {\n logger.warn(`Found uniqueBy for unsupported enum field ${entityName}.${name}`);\n }\n }\n }\n }\n}\n\nexport function isGetterField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.derived === \"sync\";\n}\n\nexport function isReactiveField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.derived === \"async\";\n}\n\nexport function isReactiveReference(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.derived === \"async\";\n}\n\n/** Returns true if this m2m relation is configured as a ReactiveManyToMany (derived: async). */\nexport function isReactiveManyToMany(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.derived === \"async\";\n}\n\nexport function isProtected(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.protected === true;\n}\n\n/** Whether a column should be excluded from the default SELECT and exposed as a lazy-loaded `LazyField`. */\nexport function isLazyField(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.fields?.[fieldName]?.lazy === true;\n}\n\nexport function serdeConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.serde;\n}\n\nexport function superstructConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.superstruct;\n}\n\nexport function zodSchemaConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.zodSchema;\n}\n\nexport function fieldTypeConfig(config: Config, entity: Entity, fieldName: string): string | undefined {\n return config.entities[entity.name]?.fields?.[fieldName]?.type;\n}\n\nexport function isLargeCollection(config: Config, entity: Entity, fieldName: string): boolean {\n return config.entities[entity.name]?.relations?.[fieldName]?.large === true;\n}\n\n/** Whether a collection should include (or exclude) soft-deleted entities from `.get`/`.load`. */\nexport function softDeletesConfig(\n config: Config,\n entity: Entity,\n fieldName: string,\n): \"include\" | \"exclude\" | undefined {\n return config.entities[entity.name]?.relations?.[fieldName]?.softDeletes;\n}\n\nexport function isFieldIgnored(\n config: Config,\n entity: Entity,\n fieldName: string,\n notNull: boolean = false,\n hasDefault: boolean = false,\n): boolean {\n const ignore = config.entities[entity.name]?.fields?.[fieldName]?.ignore === true;\n if (ignore && notNull && !hasDefault) {\n fail(\n `notNull field ${entity.name}.${fieldName} cannot be ignored. Alter the column to be optional or have a default value prior to ignoring it.`,\n );\n }\n return ignore;\n}\n\nexport function isFieldHasDefault(config: Config, entity: Entity, fieldName: string): boolean {\n const entityConfig = config.entities[entity.name] ?? {};\n const fieldConfig = entityConfig.fields?.[fieldName] ?? entityConfig.relations?.[fieldName] ?? {};\n return fieldConfig.hasDefault === true;\n}\n\nconst configPath = \"./joist-config.json\";\n\nexport async function loadConfig(): Promise<Config> {\n const exists = await trueIfResolved(fs.access(configPath));\n if (exists) {\n const content = await fs.readFile(configPath);\n const result = config.safeParse(stripLegacyConfigKeys(JSON.parse(content.toString())));\n if (!result.success) {\n throw new Error(\n `Invalid joist-config.json: ${result.error.issues\n .map((ze) => `${ze.path.map(String).join(\"/\")} ${ze.message}`)\n .join(\"\\n\")}`,\n );\n }\n result.data.allowImportingTsExtensions ??= projectIsUsingEsmWithImports();\n return result.data;\n }\n // Brand-new projects should not be prompted to run historical codemods.\n const initial = config.parse({ codemodVersion: getLatestCodemodVersion() });\n initial.allowImportingTsExtensions ??= projectIsUsingEsmWithImports();\n return initial;\n}\n\n/**\n * Writes the potentially-updated config entry back to `joist-config.json`.\n *\n * We format the output with prettier so it should both a) look nice and b) be deterministic,\n * such that no changes to the config show up as noops to the scm.\n */\nexport async function writeConfig(config: Config): Promise<void> {\n const sorted: Partial<Config> = sortKeys(config);\n delete sorted.__tableToEntityName;\n delete sorted.allowImportingTsExtensions;\n if (sorted.paginationStyle === \"cursor\") {\n delete sorted.paginationStyle;\n }\n const input = JSON.stringify(sorted);\n const content = jsonFormatter.formatText({ filePath: \"test.json\", fileText: input });\n await fs.writeFile(configPath, content);\n}\n\nexport function stripStiPlaceholders(config: Config, entities: EntityDbMetadata[]): void {\n // Defacto (with today's setup) the config of STI entities lives on the base entity,\n // so don't write confusing subtype-specific entries into the config file.\n // ...hopefully we don't have any code accidentally looking for the STI config...\n for (const entity of entities) {\n if (entity.inheritanceType === \"sti\" && entity.stiDiscriminatorValue) {\n delete config.entities[entity.name];\n }\n }\n}\n\n/** Applies defaults to the timestamp config. */\nexport function getTimestampConfig(config: Config): {\n updatedAtConf: Required<TimestampConfig>;\n createdAtConf: Required<TimestampConfig>;\n deletedAtConf: Required<TimestampConfig>;\n} {\n return {\n createdAtConf: {\n names: [\"created_at\", \"createdAt\"],\n required: false,\n ...config?.timestampColumns?.createdAt,\n },\n updatedAtConf: {\n names: [\"updated_at\", \"updatedAt\"],\n required: false,\n ...config?.timestampColumns?.updatedAt,\n },\n deletedAtConf: {\n names: [\"deleted_at\", \"deletedAt\"],\n required: false,\n ...config?.timestampColumns?.deletedAt,\n },\n };\n}\n\nfunction projectIsUsingEsmWithImports(): boolean {\n // Attempt to find the project's tsconfig.json in the current directory or up the directory hierarchy\n const configPath = findTsConfigFile(process.cwd());\n if (!configPath) {\n return false;\n }\n try {\n // Use jsonc-parser to parse the tsconfig.json file (not the old tsc readConfigFile which was\n // dropped in TypeScript 7), allowing for comments and trailing commas.\n const errors: ParseError[] = [];\n const parsed: unknown = parse(readFileSync(configPath, \"utf8\"), errors, { allowTrailingComma: true });\n if (errors.length > 0 || typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) return false;\n const compilerOptions = (parsed as Record<string, unknown>).compilerOptions;\n return (\n typeof compilerOptions === \"object\" &&\n compilerOptions !== null &&\n !Array.isArray(compilerOptions) &&\n (compilerOptions as Record<string, unknown>).allowImportingTsExtensions === true\n );\n } catch {\n return false;\n }\n}\n\n/** Normalizes `uniqueBy` config sugar into runtime identity candidates. */\nfunction normalizeUniqueByConfig(uniqueBy: string | string[] | string[][]): string[][] {\n if (typeof uniqueBy === \"string\") return [[uniqueBy]];\n if (uniqueBy.every((field) => typeof field === \"string\")) return [uniqueBy];\n return uniqueBy;\n}\n\nfunction stripLegacyConfigKeys(raw: unknown): unknown {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) {\n return raw;\n }\n // Accept old configs so the deprecated key disappears on the next write.\n const parsed = { ...(raw as Record<string, unknown>) };\n delete parsed.version;\n return parsed;\n}\n\n/** Finds the nearest `tsconfig.json` in `directory` or one of its ancestors. */\nfunction findTsConfigFile(directory: string): string | undefined {\n while (true) {\n const fileName = join(directory, \"tsconfig.json\");\n if (existsSync(fileName)) return fileName;\n const parent = dirname(directory);\n if (parent === directory) return undefined;\n directory = parent;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAeA,MAAM,gBAAgB,iBAAiB,aAAa,QAAQ,CAAC,CAAC;AAE9D,MAAM,cAAc,EACjB,OAAO;CAEN,SAAS,EAAE,SAAS,EAAE,MAAM,CAAC,EAAE,QAAQ,MAAM,GAAG,EAAE,QAAQ,OAAO,CAAC,CAAC,CAAC;CACpE,WAAW,EAAE,SAAS,EAAE,QAAQ,CAAC;CACjC,QAAQ,EAAE,SAAS,EAAE,QAAQ,CAAC;CAC9B,aAAa,EAAE,SAAS,EAAE,OAAO,CAAC;CAClC,WAAW,EAAE,SAAS,EAAE,OAAO,CAAC;CAChC,MAAM,EAAE,SAAS,EAAE,OAAO,CAAC;CAC3B,OAAO,EAAE,SAAS,EAAE,OAAO,CAAC;CAC5B,kBAAkB,EAAE,SAAS,EAAE,OAAO,EA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M;EACX,MAAM,WAAW,KAAK,WAAW,eAAe;EAChD,IAAI,WAAW,QAAQ,GAAG,OAAO;EACjC,MAAM,SAAS,QAAQ,SAAS;EAChC,IAAI,WAAW,WAAW,OAAO,KAAA;EACjC,YAAY;CACd;AACF"}
@@ -8,6 +8,7 @@ let ts_poet = require("ts-poet");
8
8
  //#region src/generateMetadataFile.ts
9
9
  function generateMetadataFile(config, dbMeta, meta) {
10
10
  const { entity, createdAt, updatedAt, deletedAt } = meta;
11
+ validateAssertUnchangedFields(config, meta);
11
12
  const fields = generateFields(config, dbMeta, meta, columnReference);
12
13
  Object.values(fields).forEach((code) => code.asOneline());
13
14
  const maybeBaseType = meta.baseClassName ? `"${meta.baseClassName}"` : void 0;
@@ -90,6 +91,7 @@ function generateFields(config, dbMeta, dbMetadata, columnRef) {
90
91
  serde: new ${require_symbols.SimpleFieldSerde}("${fieldName}", ${columnRef(p, serde, column)}),
91
92
  immutable: false,
92
93
  ${p.lazy ? ts_poet.code`lazy: true,` : ""}
94
+ ${maybeAssertUnchanged(config, dbMetadata, fieldName)}
93
95
  ${extras}
94
96
  ${maybeDefault(p)}
95
97
  ${maybeSanitize(config, p)}
@@ -108,6 +110,7 @@ function generateFields(config, dbMeta, dbMetadata, columnRef) {
108
110
  type: "string",
109
111
  serde: new ${require_symbols.SimpleFieldSerde}("${fieldName}", ${columnRef(p, ts_poet.code`new ${require_symbols.PrimitiveSerde}("${dbType}")`, columnArgs(p, dbMetadata))}),
110
112
  immutable: false,
113
+ ${maybeAssertUnchanged(config, dbMetadata, fieldName)}
111
114
  ${maybeDefault(p)}
112
115
  }`;
113
116
  });
@@ -126,6 +129,7 @@ function generateFields(config, dbMeta, dbMetadata, columnRef) {
126
129
  enumType: ${enumType},
127
130
  serde: new ${require_symbols.SimpleFieldSerde}("${fieldName}", ${columnRef(field, ts_poet.code`new ${serdeType}("${columnTypeWithArray}", ${enumDetailType})`, columnArgs(field, dbMetadata))}),
128
131
  immutable: false,
132
+ ${maybeAssertUnchanged(config, dbMetadata, fieldName)}
129
133
  ${maybeDefault(field)}
130
134
  }
131
135
  `;
@@ -310,6 +314,29 @@ function primitiveColumnCodec(config, column) {
310
314
  else serdeType = require_symbols.PrimitiveSerde;
311
315
  return isArray ? ts_poet.code`new ${serdeType}( "${columnType}[]", true)` : ts_poet.code`new ${serdeType}( "${columnType}")`;
312
316
  }
317
+ /** Emits read protection only for configured fields, leaving ordinary reads on the default path. */
318
+ function maybeAssertUnchanged(config, meta, fieldName) {
319
+ return config.entities[meta.name]?.fields?.[fieldName]?.assertUnchanged ? ts_poet.code`assertUnchanged: true,` : "";
320
+ }
321
+ /**
322
+ * Reject configurations whose field reads cannot provide the promised protection.
323
+ *
324
+ * A misspelled or inherited field must not silently disable an invariant's read drift check.
325
+ */
326
+ function validateAssertUnchangedFields(config, meta) {
327
+ for (const [fieldName, field] of Object.entries(config.entities[meta.name]?.fields ?? {})) {
328
+ if (!field.assertUnchanged) continue;
329
+ const scalar = [
330
+ ...meta.primitives,
331
+ ...meta.enums,
332
+ ...meta.pgEnums
333
+ ].find((f) => f.fieldName === fieldName);
334
+ if (!scalar || "derived" in scalar && (scalar.derived === "sync" || scalar.derived === "async") || "lazy" in scalar && scalar.lazy) throw new Error(`assertUnchanged on ${meta.name}.${fieldName} requires a stored scalar field declared on this entity`);
335
+ let base = meta;
336
+ while (base.baseType) base = base.baseType;
337
+ if (!base.updatedAt) throw new Error(`assertUnchanged on ${meta.name}.${fieldName} requires an updatedAt version field`);
338
+ }
339
+ }
313
340
  //#endregion
314
341
  exports.generateColumnDeclarations = generateColumnDeclarations;
315
342
  exports.generateMetadataFile = generateMetadataFile;
@@ -1 +1 @@
1
- {"version":3,"file":"generateMetadataFile.cjs","names":["q","EntityMetadata","imp","SimpleFieldSerde","KeySerde","PrimitiveSerde","EnumArrayFieldSerde","EnumFieldSerde","polymorphicField","PolyComponent","camelCase","Column","ColumnDescriptors","mapSimpleDbTypeToTypescriptType","CustomSerdeAdapter","SuperstructSerde","ZodSerde","DecimalToNumberSerde","JsonSerde","VectorSerde","BigIntSerde","PlainDateSerde","DateSerde","PlainDateTimeSerde","ZonedDateTimeSerde","PlainTimeSerde"],"sources":["../src/generateMetadataFile.ts"],"sourcesContent":["import { camelCase } from \"change-case\";\nimport { type Code, type Import, code, imp } from \"ts-poet\";\n\nimport { type Config } from \"./config.ts\";\nimport {\n type DatabaseColumnType,\n type DbMetadata,\n type EntityDbMetadata,\n type OneToManyField,\n type PrimitiveField,\n} from \"./EntityDbMetadata.ts\";\nimport {\n BigIntSerde,\n Column,\n ColumnDescriptors,\n CustomSerdeAdapter,\n DateSerde,\n DecimalToNumberSerde,\n EntityMetadata,\n EnumArrayFieldSerde,\n EnumFieldSerde,\n JsonSerde,\n KeySerde,\n PlainDateSerde,\n PlainDateTimeSerde,\n PlainTimeSerde,\n PolyComponent,\n PrimitiveSerde,\n SimpleFieldSerde,\n SuperstructSerde,\n VectorSerde,\n ZodSerde,\n ZonedDateTimeSerde,\n polymorphicField,\n} from \"./symbols.ts\";\nimport { mapSimpleDbTypeToTypescriptType, q } from \"./utils.ts\";\n\nexport function generateMetadataFile(config: Config, dbMeta: DbMetadata, meta: EntityDbMetadata): Code {\n const { entity, createdAt, updatedAt, deletedAt } = meta;\n\n const fields = generateFields(config, dbMeta, meta, columnReference);\n\n Object.values(fields).forEach((code) => code.asOneline());\n\n const maybeBaseType = meta.baseClassName ? `\"${meta.baseClassName}\"` : undefined;\n // We want to put inheritanceType: sti/cti onto base classes as well\n const maybeInheritanceType = meta.inheritanceType ? `inheritanceType: \"${meta.inheritanceType}\",` : \"\";\n const maybeStiColumn = meta.stiDiscriminatorField ? `stiDiscriminatorField: \"${meta.stiDiscriminatorField}\",` : \"\";\n const maybeStiValue = meta.stiDiscriminatorValue ? `stiDiscriminatorValue: ${meta.stiDiscriminatorValue},` : \"\";\n const maybeCtiAbstract = meta.abstract ? `ctiAbstract: ${meta.abstract},` : \"\";\n // Force subtype `timestampFields` to be `undefined` to ensure all runtime code is reading from the baseMeta values.\n // Force subtype `timestampFields` to be `undefined` to ensure all runtime code is reading from the baseMeta values.\n const maybeTimestampConfig = meta.baseClassName\n ? code`undefined`\n : code`\n {\n createdAt: ${q(createdAt?.fieldName)},\n updatedAt: ${q(updatedAt?.fieldName)},\n deletedAt: ${q(deletedAt?.fieldName)},\n }\n `;\n const maybeInsertionOrder = meta.nonDeferredFkOrder !== 0 ? `nonDeferredFkOrder: ${meta.nonDeferredFkOrder},` : ``;\n const uniqueBy = getUniqueBy(config, meta);\n const maybeUniqueBy = uniqueBy.length > 0 ? code`uniqueBy: ${JSON.stringify(uniqueBy)},` : code``;\n\n return code`\n export const ${entity.metaName}: ${EntityMetadata}<${entity.name}> = {\n cstr: ${entity.typeForMetadataFile},\n type: \"${entity.name}\",\n baseType: ${maybeBaseType}, ${maybeInheritanceType} ${maybeStiColumn} ${maybeStiValue} ${maybeCtiAbstract}\n idType: \"${config.idType ?? \"tagged-string\"}\",\n idDbType: \"${meta.primaryKey.columnType}\",\n tagName: \"${meta.tagName}\",\n tableName: \"${meta.tableName}\",\n supportsEmExecute: ${!meta.inheritanceType && meta.supportsEmExecute === true},\n fields: ${fields},\n columns: ${meta.primaryKey.columnOwner.metaName}Columns,\n allFields: {},\n orderBy: ${q(config.entities[meta.name]?.orderBy)},\n timestampFields: ${maybeTimestampConfig},\n config: ${entity.configConst},\n factory: ${imp(`new${entity.name}@./entities.ts`)},\n baseTypes: [],\n subTypes: [], ${maybeInsertionOrder} ${maybeUniqueBy}\n };\n\n (${entity.typeForMetadataFile} as any).metadata = ${entity.metaName};\n `;\n}\n\n/** Returns configured identities plus conservative database-backed unique identities. */\nfunction getUniqueBy(config: Config, meta: EntityDbMetadata): string[][] {\n const uniqueBy = config.entities[meta.name]?.uniqueBy ?? [];\n const seen = new Set<string>();\n return [...uniqueBy, ...(meta.uniqueConstraints ?? [])].filter((fields) => {\n const key = fields.join(\"\\u0000\");\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\n/** Emits fields that bind the already-declared physical columns. */\nfunction generateFields(\n config: Config,\n dbMeta: DbMetadata,\n dbMetadata: EntityDbMetadata,\n columnRef: (column: Pick<PrimitiveField, \"columnName\" | \"columnOwner\">, codec?: Code, args?: Code) => Code,\n): Record<string, Code> {\n const fields: Record<string, Code> = {};\n\n fields[\"id\"] = code`\n {\n kind: \"primaryKey\",\n fieldName: \"id\",\n fieldIdName: undefined,\n required: true,\n serde: new ${SimpleFieldSerde}(\"id\", ${columnRef(dbMetadata.primaryKey, code`new ${KeySerde}(\"${dbMetadata.tagName}\", \"${dbMetadata.primaryKey.columnType}\")`, columnArgs(dbMetadata.primaryKey, dbMetadata, code`() => ${dbMetadata.entity.metaName}`))}),\n immutable: true,\n }\n `;\n\n dbMetadata.primitives.forEach((p) => {\n const { fieldName, derived, columnType } = p;\n const column = columnArgs(p, dbMetadata);\n const serde = primitiveColumnCodec(config, p);\n const extras = columnType === \"citext\" ? code`citext: true,` : \"\";\n fields[fieldName] = code`\n {\n kind: \"primitive\",\n fieldName: \"${fieldName}\",\n fieldIdName: undefined,\n derived: ${!derived ? false : `\"${derived}\"`},\n required: ${!derived && p.notNull},\n protected: ${p.protected},\n type: ${typeof p.rawFieldType === \"string\" ? `\"${p.rawFieldType}\"` : p.rawFieldType},\n serde: new ${SimpleFieldSerde}(\"${fieldName}\", ${columnRef(p, serde, column)}),\n immutable: false,\n ${p.lazy ? code`lazy: true,` : \"\"}\n ${extras}\n ${maybeDefault(p)}\n ${maybeSanitize(config, p)}\n }`;\n });\n\n // Treat native enums as primitives\n dbMetadata.pgEnums.forEach((p) => {\n const { fieldName, notNull, dbType } = p;\n fields[fieldName] = code`\n {\n kind: \"primitive\",\n fieldName: \"${fieldName}\",\n fieldIdName: undefined,\n derived: false,\n required: ${notNull},\n protected: false,\n type: \"string\",\n serde: new ${SimpleFieldSerde}(\"${fieldName}\", ${columnRef(p, code`new ${PrimitiveSerde}(\"${dbType}\")`, columnArgs(p, dbMetadata))}),\n immutable: false,\n ${maybeDefault(p)}\n }`;\n });\n\n dbMetadata.enums.forEach((field) => {\n const { fieldName, enumDetailType, enumType, notNull, isArray, columnType, derived } = field;\n const serdeType = isArray ? EnumArrayFieldSerde : EnumFieldSerde;\n const columnTypeWithArray = `${columnType}${isArray ? \"[]\" : \"\"}`;\n fields[fieldName] = code`\n {\n kind: \"enum\",\n fieldName: \"${fieldName}\",\n fieldIdName: undefined,\n required: ${notNull},\n derived: ${!derived ? false : `\"${derived}\"`},\n enumDetailType: ${enumDetailType},\n enumType: ${enumType},\n serde: new ${SimpleFieldSerde}(\"${fieldName}\", ${columnRef(field, code`new ${serdeType}(\"${columnTypeWithArray}\", ${enumDetailType})`, columnArgs(field, dbMetadata))}),\n immutable: false,\n ${maybeDefault(field)}\n }\n `;\n });\n\n dbMetadata.manyToOnes.forEach((m2o) => {\n const { fieldName, columnName, notNull, otherEntity, otherFieldName, derived, dbType } = m2o;\n const otherTagName = config.entities[otherEntity.name].tag;\n const physical = (dbMetadata.physicalMetadata ?? dbMetadata).manyToOnes.find(\n (field) => field.columnName === columnName,\n );\n const otherMetadata =\n physical?.otherEntity.name === otherEntity.name\n ? code`${columnRef(m2o)}.idMetadata!`\n : code`() => ${otherEntity.metaName}`;\n fields[fieldName] = code`\n {\n kind: \"m2o\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${fieldName}Id\",\n derived: ${!derived ? false : `\"${derived}\"`},\n required: ${notNull},\n otherMetadata: ${otherMetadata},\n otherFieldName: \"${otherFieldName}\",\n serde: new ${SimpleFieldSerde}(\"${fieldName}\", ${columnRef(m2o, code`new ${KeySerde}(\"${otherTagName}\", \"${dbType}\")`, columnArgs(m2o, dbMetadata, code`() => ${otherEntity.metaName}`))}),\n immutable: false,\n ${maybeDefault(m2o)}\n }\n `;\n });\n\n dbMetadata.oneToManys.forEach((o2m) => {\n const { fieldName, singularName, otherEntity, otherFieldName, otherColumnName } = o2m;\n fields[fieldName] = code`\n {\n kind: \"o2m\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${singularName}Ids\",\n required: false,\n otherMetadata: () => ${otherEntity.metaName},\n otherFieldName: \"${otherFieldName}\",\n otherColumnName: \"${otherColumnName}\",\n serde: undefined,\n immutable: false,\n ${maybeOrderBy(o2m)}\n ${maybeSoftDeletes(o2m)}\n }\n `;\n });\n\n dbMetadata.largeOneToManys.forEach((o2m) => {\n const { fieldName, singularName, otherEntity, otherFieldName, otherColumnName } = o2m;\n fields[fieldName] = code`\n {\n kind: \"lo2m\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${singularName}Ids\",\n required: false,\n otherMetadata: () => ${otherEntity.metaName},\n otherFieldName: \"${otherFieldName}\",\n otherColumnName: \"${otherColumnName}\",\n serde: undefined,\n immutable: false,\n }\n `;\n });\n\n dbMetadata.manyToManys.forEach((m2m) => {\n const { fieldName, singularName, otherEntity, otherFieldName, derived } = m2m;\n fields[fieldName] = code`\n {\n kind: \"m2m\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${singularName}Ids\",\n required: false,\n derived: ${derived === \"async\" ? `\"async\"` : derived === \"otherSide\" ? `\"otherSide\"` : \"false\"},\n otherMetadata: () => ${otherEntity.metaName},\n otherFieldName: \"${otherFieldName}\",\n serde: undefined,\n immutable: false,\n joinTableName: \"${m2m.joinTableName}\",\n columnNames: [\"${m2m.columnName}\", \"${m2m.otherColumnName}\"],\n hasJoinTableId: ${m2m.hasJoinTableId},\n ${maybeSoftDeletes(m2m)}\n }\n `;\n });\n\n dbMetadata.manyToManyEnums.forEach((m2m) => {\n const { fieldName, enumDetailType } = m2m;\n fields[fieldName] = code`\n {\n kind: \"m2mEnum\",\n fieldName: \"${fieldName}\",\n fieldIdName: undefined,\n required: false,\n derived: false,\n enumDetailType: ${enumDetailType},\n serde: undefined,\n immutable: false,\n joinTableName: \"${m2m.joinTableName}\",\n columnNames: [\"${m2m.columnName}\", \"${m2m.otherColumnName}\"],\n hasJoinTableId: ${m2m.hasJoinTableId},\n }\n `;\n });\n\n dbMetadata.oneToOnes.forEach((o2o) => {\n const { fieldName, otherEntity, otherFieldName, otherColumnName } = o2o;\n fields[fieldName] = code`\n {\n kind: \"o2o\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${fieldName}Id\",\n required: false,\n otherMetadata: () => ${otherEntity.metaName},\n otherFieldName: \"${otherFieldName}\",\n otherColumnName: \"${otherColumnName}\",\n serde: undefined,\n immutable: false,\n }\n `;\n });\n\n dbMetadata.polymorphics.forEach((p) => {\n const { fieldName, notNull, components } = p;\n components.forEach((component) =>\n columnRef(\n component,\n code`new ${KeySerde}(\"${config.entities[component.otherEntity.name].tag}\", \"${dbMeta.entitiesByName[component.otherEntity.name].primaryKey.columnType}\")`,\n code`true, false, false, false, false, () => ${component.otherEntity.metaName}`,\n ),\n );\n fields[fieldName] = code`\n ${polymorphicField}(\"${fieldName}\", ${notNull}, [${components.map((component) => {\n const owner = dbMeta.entitiesByName[component.columnOwner.name];\n const physical = (owner.physicalMetadata ?? owner).polymorphics\n .flatMap((field) => field.components)\n .find((c) => c.columnName === component.columnName)!;\n const target =\n physical.otherEntity.name === component.otherEntity.name\n ? \"\"\n : code`, () => ${component.otherEntity.metaName}`;\n return code`new ${PolyComponent}(${columnRef(component)}, ${q(component.otherFieldName)}${target}),`;\n })}])\n `;\n });\n\n return fields;\n}\n\n/** Emits constructor arguments using codegen's existing column facts. */\nfunction columnArgs(\n column: Pick<PrimitiveField, \"columnNotNull\" | \"columnGenerated\"> & Partial<Pick<PrimitiveField, \"columnDefault\">>,\n meta: EntityDbMetadata,\n idMetadata?: Code,\n): Code {\n const insertOptional = column === meta.createdAt || column === meta.updatedAt;\n return code`${!column.columnNotNull}, ${column.columnDefault != null && !column.columnGenerated}, ${column.columnGenerated}, ${insertOptional}, true, ${idMetadata ?? \"undefined\"}`;\n}\n\n/** Declares all physical codecs by their SQL API names before any domain metadata; ID targets remain lazy. */\nexport function generateColumnDeclarations(config: Config, dbMeta: DbMetadata, meta: EntityDbMetadata): Code {\n if (meta.inheritanceType === \"sti\" && meta.baseClassName) return code``;\n const columns: Record<string, Code> = {};\n generateFields(config, dbMeta, meta.physicalMetadata ?? meta, (column, codec, args) => {\n const columnName = column.columnName;\n const apiName = camelCase(columnName);\n if (codec) columns[apiName] = code`new ${Column}(${q(columnName)}, ${args}, ${codec})`.asOneline();\n return code`${meta.entity.metaName}Columns[${q(apiName)}]`;\n });\n for (const column of (meta.physicalMetadata ?? meta).ignoredColumns) {\n const apiName = camelCase(column.columnName);\n columns[apiName] =\n code`new ${Column}(${q(column.columnName)}, ${columnArgs(column, meta)}, ${primitiveColumnCodec(config, column)})`.asOneline();\n }\n return code`const ${meta.entity.metaName}Columns = ${columns} satisfies ${ColumnDescriptors};`;\n}\n\n/** Emits a direct reference to a descriptor by its SQL API name. */\nfunction columnReference(column: Pick<PrimitiveField, \"columnName\" | \"columnOwner\">): Code {\n return code`${column.columnOwner.metaName}Columns[${q(camelCase(column.columnName))}]`;\n}\n\nfunction maybeDefault(f: { hasConfigDefault: boolean; columnDefault?: number | boolean | string | null }): Code | \"\" {\n return f.hasConfigDefault ? code`default: \"config\",` : f.columnDefault != null ? code`default: \"schema\",` : \"\";\n}\n\nfunction maybeOrderBy(f: OneToManyField): Code | \"\" {\n return f.orderBy ? code`orderBy: { field: \"${f.orderBy.field}\", direction: \"${f.orderBy.direction}\" },` : \"\";\n}\n\n/** Emits the `softDeletes` config, i.e. `softDeletes: \"include\",`, for relations that opt out of hiding soft-deletes. */\nfunction maybeSoftDeletes(f: { softDeletes: \"include\" | \"exclude\" | undefined }): Code | \"\" {\n return f.softDeletes ? code`softDeletes: \"${f.softDeletes}\",` : \"\";\n}\n\n/** We sanitize/cleanStringValue all varchars, unless opted out by the column default/arrays/custom serdes. */\nfunction maybeSanitize(\n config: Config,\n f: { columnType: DatabaseColumnType; columnDefault?: any; isArray: boolean; customSerde: any },\n): Code | \"\" {\n // Only strings need to maybe turn off their cleanStringValue sanitization, if the default=\"\" or its an array\n return isString(config, f.columnType) && (f.columnDefault === \"''\" || f.isArray || f.customSerde)\n ? code`sanitize: false,`\n : \"\";\n}\n\nfunction isString(config: Config, columnType: DatabaseColumnType): boolean {\n return mapSimpleDbTypeToTypescriptType(config, columnType) === \"string\";\n}\n\n/** Uses domain codecs for modeled fields and the same native conversions for unmodeled columns. */\nfunction primitiveColumnCodec(config: Config, column: PrimitiveField): Code {\n const { columnType, customSerde, superstruct, zodSchema, isArray } = column;\n if (customSerde) {\n return isArray\n ? code`new ${CustomSerdeAdapter}( \"${columnType}[]\", ${customSerde}, true)`\n : code`new ${CustomSerdeAdapter}( \"${columnType}\", ${customSerde})`;\n }\n if (superstruct) return code`new ${SuperstructSerde}( ${superstruct})`;\n if (zodSchema) return code`new ${ZodSerde}( ${zodSchema})`;\n if (columnType === \"numeric\" || columnType === \"decimal\") {\n return isArray ? code`new ${DecimalToNumberSerde}(true)` : code`new ${DecimalToNumberSerde}()`;\n }\n if (columnType === \"jsonb\") return code`new ${JsonSerde}()`;\n if (columnType === \"vector\") return code`new ${VectorSerde}()`;\n if (column.rawFieldType === \"bigint\") {\n return isArray ? code`new ${BigIntSerde}(true)` : code`new ${BigIntSerde}()`;\n }\n\n let serdeType: Import;\n if (columnType === \"date\") {\n serdeType = config.temporal ? PlainDateSerde : DateSerde;\n } else if (columnType === \"timestamp without time zone\") {\n serdeType = config.temporal ? PlainDateTimeSerde : DateSerde;\n } else if (columnType === \"timestamp with time zone\") {\n serdeType = config.temporal ? ZonedDateTimeSerde : DateSerde;\n } else if (columnType === \"time without time zone\") {\n serdeType = config.temporal ? PlainTimeSerde : PrimitiveSerde;\n } else {\n serdeType = PrimitiveSerde;\n }\n return isArray ? code`new ${serdeType}( \"${columnType}[]\", true)` : code`new ${serdeType}( \"${columnType}\")`;\n}\n"],"mappings":";;;;;;;;AAqCA,SAAgB,qBAAqB,QAAgB,QAAoB,MAA8B;CACrG,MAAM,EAAE,QAAQ,WAAW,WAAW,cAAc;CAEpD,MAAM,SAA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7F,IAAI,eAAe,SAAS,OAAO,QAAA,IAAI,OAAOC,gBAAAA,UAAU;CACxD,IAAI,eAAe,UAAU,OAAO,QAAA,IAAI,OAAOC,gBAAAA,YAAY;CAC3D,IAAI,OAAO,iBAAiB,UAC1B,OAAO,UAAU,QAAA,IAAI,OAAOC,gBAAAA,YAAY,UAAU,QAAA,IAAI,OAAOA,gBAAAA,YAAY;CAG3E,IAAI;CACJ,IAAI,eAAe,QACjB,YAAY,OAAO,WAAWC,gBAAAA,iBAAiBC,gBAAAA;MAC1C,IAAI,eAAe,+BACxB,YAAY,OAAO,WAAWC,gBAAAA,qBAAqBD,gBAAAA;MAC9C,IAAI,eAAe,4BACxB,YAAY,OAAO,WAAWE,gBAAAA,qBAAqBF,gBAAAA;MAC9C,IAAI,eAAe,0BACxB,YAAY,OAAO,WAAWG,gBAAAA,iBAAiBpB,gBAAAA;MAE/C,YAAYA,gBAAAA;CAEd,OAAO,UAAU,QAAA,IAAI,OAAO,UAAU,KAAK,WAAW,cAAc,QAAA,IAAI,OAAO,UAAU,KAAK,WAAW;AAC3G"}
1
+ {"version":3,"file":"generateMetadataFile.cjs","names":["q","EntityMetadata","imp","SimpleFieldSerde","KeySerde","PrimitiveSerde","EnumArrayFieldSerde","EnumFieldSerde","polymorphicField","PolyComponent","camelCase","Column","ColumnDescriptors","mapSimpleDbTypeToTypescriptType","CustomSerdeAdapter","SuperstructSerde","ZodSerde","DecimalToNumberSerde","JsonSerde","VectorSerde","BigIntSerde","PlainDateSerde","DateSerde","PlainDateTimeSerde","ZonedDateTimeSerde","PlainTimeSerde"],"sources":["../src/generateMetadataFile.ts"],"sourcesContent":["import { camelCase } from \"change-case\";\nimport { type Code, type Import, code, imp } from \"ts-poet\";\n\nimport { type Config } from \"./config.ts\";\nimport {\n type DatabaseColumnType,\n type DbMetadata,\n type EntityDbMetadata,\n type OneToManyField,\n type PrimitiveField,\n} from \"./EntityDbMetadata.ts\";\nimport {\n BigIntSerde,\n Column,\n ColumnDescriptors,\n CustomSerdeAdapter,\n DateSerde,\n DecimalToNumberSerde,\n EntityMetadata,\n EnumArrayFieldSerde,\n EnumFieldSerde,\n JsonSerde,\n KeySerde,\n PlainDateSerde,\n PlainDateTimeSerde,\n PlainTimeSerde,\n PolyComponent,\n PrimitiveSerde,\n SimpleFieldSerde,\n SuperstructSerde,\n VectorSerde,\n ZodSerde,\n ZonedDateTimeSerde,\n polymorphicField,\n} from \"./symbols.ts\";\nimport { mapSimpleDbTypeToTypescriptType, q } from \"./utils.ts\";\n\nexport function generateMetadataFile(config: Config, dbMeta: DbMetadata, meta: EntityDbMetadata): Code {\n const { entity, createdAt, updatedAt, deletedAt } = meta;\n\n validateAssertUnchangedFields(config, meta);\n const fields = generateFields(config, dbMeta, meta, columnReference);\n\n Object.values(fields).forEach((code) => code.asOneline());\n\n const maybeBaseType = meta.baseClassName ? `\"${meta.baseClassName}\"` : undefined;\n // We want to put inheritanceType: sti/cti onto base classes as well\n const maybeInheritanceType = meta.inheritanceType ? `inheritanceType: \"${meta.inheritanceType}\",` : \"\";\n const maybeStiColumn = meta.stiDiscriminatorField ? `stiDiscriminatorField: \"${meta.stiDiscriminatorField}\",` : \"\";\n const maybeStiValue = meta.stiDiscriminatorValue ? `stiDiscriminatorValue: ${meta.stiDiscriminatorValue},` : \"\";\n const maybeCtiAbstract = meta.abstract ? `ctiAbstract: ${meta.abstract},` : \"\";\n // Force subtype `timestampFields` to be `undefined` to ensure all runtime code is reading from the baseMeta values.\n // Force subtype `timestampFields` to be `undefined` to ensure all runtime code is reading from the baseMeta values.\n const maybeTimestampConfig = meta.baseClassName\n ? code`undefined`\n : code`\n {\n createdAt: ${q(createdAt?.fieldName)},\n updatedAt: ${q(updatedAt?.fieldName)},\n deletedAt: ${q(deletedAt?.fieldName)},\n }\n `;\n const maybeInsertionOrder = meta.nonDeferredFkOrder !== 0 ? `nonDeferredFkOrder: ${meta.nonDeferredFkOrder},` : ``;\n const uniqueBy = getUniqueBy(config, meta);\n const maybeUniqueBy = uniqueBy.length > 0 ? code`uniqueBy: ${JSON.stringify(uniqueBy)},` : code``;\n\n return code`\n export const ${entity.metaName}: ${EntityMetadata}<${entity.name}> = {\n cstr: ${entity.typeForMetadataFile},\n type: \"${entity.name}\",\n baseType: ${maybeBaseType}, ${maybeInheritanceType} ${maybeStiColumn} ${maybeStiValue} ${maybeCtiAbstract}\n idType: \"${config.idType ?? \"tagged-string\"}\",\n idDbType: \"${meta.primaryKey.columnType}\",\n tagName: \"${meta.tagName}\",\n tableName: \"${meta.tableName}\",\n supportsEmExecute: ${!meta.inheritanceType && meta.supportsEmExecute === true},\n fields: ${fields},\n columns: ${meta.primaryKey.columnOwner.metaName}Columns,\n allFields: {},\n orderBy: ${q(config.entities[meta.name]?.orderBy)},\n timestampFields: ${maybeTimestampConfig},\n config: ${entity.configConst},\n factory: ${imp(`new${entity.name}@./entities.ts`)},\n baseTypes: [],\n subTypes: [], ${maybeInsertionOrder} ${maybeUniqueBy}\n };\n\n (${entity.typeForMetadataFile} as any).metadata = ${entity.metaName};\n `;\n}\n\n/** Returns configured identities plus conservative database-backed unique identities. */\nfunction getUniqueBy(config: Config, meta: EntityDbMetadata): string[][] {\n const uniqueBy = config.entities[meta.name]?.uniqueBy ?? [];\n const seen = new Set<string>();\n return [...uniqueBy, ...(meta.uniqueConstraints ?? [])].filter((fields) => {\n const key = fields.join(\"\\u0000\");\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\n/** Emits fields that bind the already-declared physical columns. */\nfunction generateFields(\n config: Config,\n dbMeta: DbMetadata,\n dbMetadata: EntityDbMetadata,\n columnRef: (column: Pick<PrimitiveField, \"columnName\" | \"columnOwner\">, codec?: Code, args?: Code) => Code,\n): Record<string, Code> {\n const fields: Record<string, Code> = {};\n\n fields[\"id\"] = code`\n {\n kind: \"primaryKey\",\n fieldName: \"id\",\n fieldIdName: undefined,\n required: true,\n serde: new ${SimpleFieldSerde}(\"id\", ${columnRef(dbMetadata.primaryKey, code`new ${KeySerde}(\"${dbMetadata.tagName}\", \"${dbMetadata.primaryKey.columnType}\")`, columnArgs(dbMetadata.primaryKey, dbMetadata, code`() => ${dbMetadata.entity.metaName}`))}),\n immutable: true,\n }\n `;\n\n dbMetadata.primitives.forEach((p) => {\n const { fieldName, derived, columnType } = p;\n const column = columnArgs(p, dbMetadata);\n const serde = primitiveColumnCodec(config, p);\n const extras = columnType === \"citext\" ? code`citext: true,` : \"\";\n fields[fieldName] = code`\n {\n kind: \"primitive\",\n fieldName: \"${fieldName}\",\n fieldIdName: undefined,\n derived: ${!derived ? false : `\"${derived}\"`},\n required: ${!derived && p.notNull},\n protected: ${p.protected},\n type: ${typeof p.rawFieldType === \"string\" ? `\"${p.rawFieldType}\"` : p.rawFieldType},\n serde: new ${SimpleFieldSerde}(\"${fieldName}\", ${columnRef(p, serde, column)}),\n immutable: false,\n ${p.lazy ? code`lazy: true,` : \"\"}\n ${maybeAssertUnchanged(config, dbMetadata, fieldName)}\n ${extras}\n ${maybeDefault(p)}\n ${maybeSanitize(config, p)}\n }`;\n });\n\n // Treat native enums as primitives\n dbMetadata.pgEnums.forEach((p) => {\n const { fieldName, notNull, dbType } = p;\n fields[fieldName] = code`\n {\n kind: \"primitive\",\n fieldName: \"${fieldName}\",\n fieldIdName: undefined,\n derived: false,\n required: ${notNull},\n protected: false,\n type: \"string\",\n serde: new ${SimpleFieldSerde}(\"${fieldName}\", ${columnRef(p, code`new ${PrimitiveSerde}(\"${dbType}\")`, columnArgs(p, dbMetadata))}),\n immutable: false,\n ${maybeAssertUnchanged(config, dbMetadata, fieldName)}\n ${maybeDefault(p)}\n }`;\n });\n\n dbMetadata.enums.forEach((field) => {\n const { fieldName, enumDetailType, enumType, notNull, isArray, columnType, derived } = field;\n const serdeType = isArray ? EnumArrayFieldSerde : EnumFieldSerde;\n const columnTypeWithArray = `${columnType}${isArray ? \"[]\" : \"\"}`;\n fields[fieldName] = code`\n {\n kind: \"enum\",\n fieldName: \"${fieldName}\",\n fieldIdName: undefined,\n required: ${notNull},\n derived: ${!derived ? false : `\"${derived}\"`},\n enumDetailType: ${enumDetailType},\n enumType: ${enumType},\n serde: new ${SimpleFieldSerde}(\"${fieldName}\", ${columnRef(field, code`new ${serdeType}(\"${columnTypeWithArray}\", ${enumDetailType})`, columnArgs(field, dbMetadata))}),\n immutable: false,\n ${maybeAssertUnchanged(config, dbMetadata, fieldName)}\n ${maybeDefault(field)}\n }\n `;\n });\n\n dbMetadata.manyToOnes.forEach((m2o) => {\n const { fieldName, columnName, notNull, otherEntity, otherFieldName, derived, dbType } = m2o;\n const otherTagName = config.entities[otherEntity.name].tag;\n const physical = (dbMetadata.physicalMetadata ?? dbMetadata).manyToOnes.find(\n (field) => field.columnName === columnName,\n );\n const otherMetadata =\n physical?.otherEntity.name === otherEntity.name\n ? code`${columnRef(m2o)}.idMetadata!`\n : code`() => ${otherEntity.metaName}`;\n fields[fieldName] = code`\n {\n kind: \"m2o\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${fieldName}Id\",\n derived: ${!derived ? false : `\"${derived}\"`},\n required: ${notNull},\n otherMetadata: ${otherMetadata},\n otherFieldName: \"${otherFieldName}\",\n serde: new ${SimpleFieldSerde}(\"${fieldName}\", ${columnRef(m2o, code`new ${KeySerde}(\"${otherTagName}\", \"${dbType}\")`, columnArgs(m2o, dbMetadata, code`() => ${otherEntity.metaName}`))}),\n immutable: false,\n ${maybeDefault(m2o)}\n }\n `;\n });\n\n dbMetadata.oneToManys.forEach((o2m) => {\n const { fieldName, singularName, otherEntity, otherFieldName, otherColumnName } = o2m;\n fields[fieldName] = code`\n {\n kind: \"o2m\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${singularName}Ids\",\n required: false,\n otherMetadata: () => ${otherEntity.metaName},\n otherFieldName: \"${otherFieldName}\",\n otherColumnName: \"${otherColumnName}\",\n serde: undefined,\n immutable: false,\n ${maybeOrderBy(o2m)}\n ${maybeSoftDeletes(o2m)}\n }\n `;\n });\n\n dbMetadata.largeOneToManys.forEach((o2m) => {\n const { fieldName, singularName, otherEntity, otherFieldName, otherColumnName } = o2m;\n fields[fieldName] = code`\n {\n kind: \"lo2m\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${singularName}Ids\",\n required: false,\n otherMetadata: () => ${otherEntity.metaName},\n otherFieldName: \"${otherFieldName}\",\n otherColumnName: \"${otherColumnName}\",\n serde: undefined,\n immutable: false,\n }\n `;\n });\n\n dbMetadata.manyToManys.forEach((m2m) => {\n const { fieldName, singularName, otherEntity, otherFieldName, derived } = m2m;\n fields[fieldName] = code`\n {\n kind: \"m2m\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${singularName}Ids\",\n required: false,\n derived: ${derived === \"async\" ? `\"async\"` : derived === \"otherSide\" ? `\"otherSide\"` : \"false\"},\n otherMetadata: () => ${otherEntity.metaName},\n otherFieldName: \"${otherFieldName}\",\n serde: undefined,\n immutable: false,\n joinTableName: \"${m2m.joinTableName}\",\n columnNames: [\"${m2m.columnName}\", \"${m2m.otherColumnName}\"],\n hasJoinTableId: ${m2m.hasJoinTableId},\n ${maybeSoftDeletes(m2m)}\n }\n `;\n });\n\n dbMetadata.manyToManyEnums.forEach((m2m) => {\n const { fieldName, enumDetailType } = m2m;\n fields[fieldName] = code`\n {\n kind: \"m2mEnum\",\n fieldName: \"${fieldName}\",\n fieldIdName: undefined,\n required: false,\n derived: false,\n enumDetailType: ${enumDetailType},\n serde: undefined,\n immutable: false,\n joinTableName: \"${m2m.joinTableName}\",\n columnNames: [\"${m2m.columnName}\", \"${m2m.otherColumnName}\"],\n hasJoinTableId: ${m2m.hasJoinTableId},\n }\n `;\n });\n\n dbMetadata.oneToOnes.forEach((o2o) => {\n const { fieldName, otherEntity, otherFieldName, otherColumnName } = o2o;\n fields[fieldName] = code`\n {\n kind: \"o2o\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${fieldName}Id\",\n required: false,\n otherMetadata: () => ${otherEntity.metaName},\n otherFieldName: \"${otherFieldName}\",\n otherColumnName: \"${otherColumnName}\",\n serde: undefined,\n immutable: false,\n }\n `;\n });\n\n dbMetadata.polymorphics.forEach((p) => {\n const { fieldName, notNull, components } = p;\n components.forEach((component) =>\n columnRef(\n component,\n code`new ${KeySerde}(\"${config.entities[component.otherEntity.name].tag}\", \"${dbMeta.entitiesByName[component.otherEntity.name].primaryKey.columnType}\")`,\n code`true, false, false, false, false, () => ${component.otherEntity.metaName}`,\n ),\n );\n fields[fieldName] = code`\n ${polymorphicField}(\"${fieldName}\", ${notNull}, [${components.map((component) => {\n const owner = dbMeta.entitiesByName[component.columnOwner.name];\n const physical = (owner.physicalMetadata ?? owner).polymorphics\n .flatMap((field) => field.components)\n .find((c) => c.columnName === component.columnName)!;\n const target =\n physical.otherEntity.name === component.otherEntity.name\n ? \"\"\n : code`, () => ${component.otherEntity.metaName}`;\n return code`new ${PolyComponent}(${columnRef(component)}, ${q(component.otherFieldName)}${target}),`;\n })}])\n `;\n });\n\n return fields;\n}\n\n/** Emits constructor arguments using codegen's existing column facts. */\nfunction columnArgs(\n column: Pick<PrimitiveField, \"columnNotNull\" | \"columnGenerated\"> & Partial<Pick<PrimitiveField, \"columnDefault\">>,\n meta: EntityDbMetadata,\n idMetadata?: Code,\n): Code {\n const insertOptional = column === meta.createdAt || column === meta.updatedAt;\n return code`${!column.columnNotNull}, ${column.columnDefault != null && !column.columnGenerated}, ${column.columnGenerated}, ${insertOptional}, true, ${idMetadata ?? \"undefined\"}`;\n}\n\n/** Declares all physical codecs by their SQL API names before any domain metadata; ID targets remain lazy. */\nexport function generateColumnDeclarations(config: Config, dbMeta: DbMetadata, meta: EntityDbMetadata): Code {\n if (meta.inheritanceType === \"sti\" && meta.baseClassName) return code``;\n const columns: Record<string, Code> = {};\n generateFields(config, dbMeta, meta.physicalMetadata ?? meta, (column, codec, args) => {\n const columnName = column.columnName;\n const apiName = camelCase(columnName);\n if (codec) columns[apiName] = code`new ${Column}(${q(columnName)}, ${args}, ${codec})`.asOneline();\n return code`${meta.entity.metaName}Columns[${q(apiName)}]`;\n });\n for (const column of (meta.physicalMetadata ?? meta).ignoredColumns) {\n const apiName = camelCase(column.columnName);\n columns[apiName] =\n code`new ${Column}(${q(column.columnName)}, ${columnArgs(column, meta)}, ${primitiveColumnCodec(config, column)})`.asOneline();\n }\n return code`const ${meta.entity.metaName}Columns = ${columns} satisfies ${ColumnDescriptors};`;\n}\n\n/** Emits a direct reference to a descriptor by its SQL API name. */\nfunction columnReference(column: Pick<PrimitiveField, \"columnName\" | \"columnOwner\">): Code {\n return code`${column.columnOwner.metaName}Columns[${q(camelCase(column.columnName))}]`;\n}\n\nfunction maybeDefault(f: { hasConfigDefault: boolean; columnDefault?: number | boolean | string | null }): Code | \"\" {\n return f.hasConfigDefault ? code`default: \"config\",` : f.columnDefault != null ? code`default: \"schema\",` : \"\";\n}\n\nfunction maybeOrderBy(f: OneToManyField): Code | \"\" {\n return f.orderBy ? code`orderBy: { field: \"${f.orderBy.field}\", direction: \"${f.orderBy.direction}\" },` : \"\";\n}\n\n/** Emits the `softDeletes` config, i.e. `softDeletes: \"include\",`, for relations that opt out of hiding soft-deletes. */\nfunction maybeSoftDeletes(f: { softDeletes: \"include\" | \"exclude\" | undefined }): Code | \"\" {\n return f.softDeletes ? code`softDeletes: \"${f.softDeletes}\",` : \"\";\n}\n\n/** We sanitize/cleanStringValue all varchars, unless opted out by the column default/arrays/custom serdes. */\nfunction maybeSanitize(\n config: Config,\n f: { columnType: DatabaseColumnType; columnDefault?: any; isArray: boolean; customSerde: any },\n): Code | \"\" {\n // Only strings need to maybe turn off their cleanStringValue sanitization, if the default=\"\" or its an array\n return isString(config, f.columnType) && (f.columnDefault === \"''\" || f.isArray || f.customSerde)\n ? code`sanitize: false,`\n : \"\";\n}\n\nfunction isString(config: Config, columnType: DatabaseColumnType): boolean {\n return mapSimpleDbTypeToTypescriptType(config, columnType) === \"string\";\n}\n\n/** Uses domain codecs for modeled fields and the same native conversions for unmodeled columns. */\nfunction primitiveColumnCodec(config: Config, column: PrimitiveField): Code {\n const { columnType, customSerde, superstruct, zodSchema, isArray } = column;\n if (customSerde) {\n return isArray\n ? code`new ${CustomSerdeAdapter}( \"${columnType}[]\", ${customSerde}, true)`\n : code`new ${CustomSerdeAdapter}( \"${columnType}\", ${customSerde})`;\n }\n if (superstruct) return code`new ${SuperstructSerde}( ${superstruct})`;\n if (zodSchema) return code`new ${ZodSerde}( ${zodSchema})`;\n if (columnType === \"numeric\" || columnType === \"decimal\") {\n return isArray ? code`new ${DecimalToNumberSerde}(true)` : code`new ${DecimalToNumberSerde}()`;\n }\n if (columnType === \"jsonb\") return code`new ${JsonSerde}()`;\n if (columnType === \"vector\") return code`new ${VectorSerde}()`;\n if (column.rawFieldType === \"bigint\") {\n return isArray ? code`new ${BigIntSerde}(true)` : code`new ${BigIntSerde}()`;\n }\n\n let serdeType: Import;\n if (columnType === \"date\") {\n serdeType = config.temporal ? PlainDateSerde : DateSerde;\n } else if (columnType === \"timestamp without time zone\") {\n serdeType = config.temporal ? PlainDateTimeSerde : DateSerde;\n } else if (columnType === \"timestamp with time zone\") {\n serdeType = config.temporal ? ZonedDateTimeSerde : DateSerde;\n } else if (columnType === \"time without time zone\") {\n serdeType = config.temporal ? PlainTimeSerde : PrimitiveSerde;\n } else {\n serdeType = PrimitiveSerde;\n }\n return isArray ? code`new ${serdeType}( \"${columnType}[]\", true)` : code`new ${serdeType}( \"${columnType}\")`;\n}\n\n/** Emits read protection only for configured fields, leaving ordinary reads on the default path. */\nfunction maybeAssertUnchanged(config: Config, meta: EntityDbMetadata, fieldName: string): Code | \"\" {\n return config.entities[meta.name]?.fields?.[fieldName]?.assertUnchanged ? code`assertUnchanged: true,` : \"\";\n}\n\n/**\n * Reject configurations whose field reads cannot provide the promised protection.\n *\n * A misspelled or inherited field must not silently disable an invariant's read drift check.\n */\nfunction validateAssertUnchangedFields(config: Config, meta: EntityDbMetadata): void {\n for (const [fieldName, field] of Object.entries(config.entities[meta.name]?.fields ?? {})) {\n if (!field.assertUnchanged) continue;\n\n const scalar = [...meta.primitives, ...meta.enums, ...meta.pgEnums].find((f) => f.fieldName === fieldName);\n if (\n !scalar ||\n (\"derived\" in scalar && (scalar.derived === \"sync\" || scalar.derived === \"async\")) ||\n (\"lazy\" in scalar && scalar.lazy)\n ) {\n throw new Error(\n `assertUnchanged on ${meta.name}.${fieldName} requires a stored scalar field declared on this entity`,\n );\n }\n\n let base = meta;\n while (base.baseType) base = base.baseType;\n if (!base.updatedAt) {\n throw new Error(`assertUnchanged on ${meta.name}.${fieldName} requires an updatedAt version field`);\n }\n }\n}\n"],"mappings":";;;;;;;;AAqCA,SAAgB,qBAAqB,QAAgB,QAAoB,MAA8B;CACrG,MAAM,EAAE,QAAQ,WAAW,WAAW,cAAc;CAEpD,8BAA8B,QAAQ,IAAI;CAC1C,MAAM,SAAS,eAAe,QAAQ,QAAQ,MAAM,eAAe;CAEnE,OAAO,OAAO,MAAM,CAAC,CAAC,SAAS,SAAS,KAAK,UAAU,CAAC;CAExD,MAAM,gBAAgB,KAAK,gBAAgB,IAAI,KAAK,cAAc,KAAK,KAAA;CAEvE,MAAM,uBAAuB,KAAK,kBAAkB,qBAAqB,KAAK,gBAAgB,MAAM;CACpG,MAAM,iBAAiB,KAAK,wBAAwB,2BAA2B,KAAK,sBAAsB,MAAM;CAChH,MAAM,gBAAgB,KAAK,wBAAwB,0BAA0B,KAAK,sBAAsB,KAAK;CAC7G,MAAM,mBAAmB,KAAK,WAAW,gBAAgB,KAAK,SAAS,KAAK;CAG5E,MAAM,uBAAuB,KAAK,gBAC9B,QAAA,IAAI,cACJ,QAAA,IAAI;;mBAESA,cAAAA,EAAE,WAAW,SAAS,EAAE;mBACxBA,cAAAA,EAAE,WAAW,SAAS,EAAE;mBACxBA,cAAAA,EAAE,WAAW,SAAS,EAAE;;;CAGzC,MAAM,sBAAsB,KAAK,uBAAuB,IAAI,uBAAuB,KAAK,mBAAmB,KAAK;CAChH,MAAM,WAAW,YAAY,QAAQ,IAAI;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I,OAAO,UAAU,KAAK,WAAW,cAAc,QAAA,IAAI,OAAO,UAAU,KAAK,WAAW;AAC3G;;AAGA,SAAS,qBAAqB,QAAgB,MAAwB,WAA8B;CAClG,OAAO,OAAO,SAAS,KAAK,KAAK,EAAE,SAAS,UAAU,EAAE,kBAAkB,QAAA,IAAI,2BAA2B;AAC3G;;;;;;AAOA,SAAS,8BAA8B,QAAgB,MAA8B;CACnF,KAAK,MAAM,CAAC,WAAW,UAAU,OAAO,QAAQ,OAAO,SAAS,KAAK,KAAK,EAAE,UAAU,CAAC,CAAC,GAAG;EACzF,IAAI,CAAC,MAAM,iBAAiB;EAE5B,MAAM,SAAS;GAAC,GAAG,KAAK;GAAY,GAAG,KAAK;GAAO,GAAG,KAAK;EAAO,CAAC,CAAC,MAAM,MAAM,EAAE,cAAc,SAAS;EACzG,IACE,CAAC,UACA,aAAa,WAAW,OAAO,YAAY,UAAU,OAAO,YAAY,YACxE,UAAU,UAAU,OAAO,MAE5B,MAAM,IAAI,MACR,sBAAsB,KAAK,KAAK,GAAG,UAAU,wDAC/C;EAGF,IAAI,OAAO;EACX,OAAO,KAAK,UAAU,OAAO,KAAK;EAClC,IAAI,CAAC,KAAK,WACR,MAAM,IAAI,MAAM,sBAAsB,KAAK,KAAK,GAAG,UAAU,qCAAqC;CAEtG;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"generateMetadataFile.d.cts","names":[],"sources":["../src/generateMetadataFile.ts"],"mappings":";;;;wBAqCgB,qBAAqB,QAAQ,QAAQ,QAAQ,YAAY,MAAM,mBAAmB;;wBA+SlF,2BAA2B,QAAQ,QAAQ,QAAQ,YAAY,MAAM,mBAAmB"}
1
+ {"version":3,"file":"generateMetadataFile.d.cts","names":[],"sources":["../src/generateMetadataFile.ts"],"mappings":";;;;wBAqCgB,qBAAqB,QAAQ,QAAQ,QAAQ,YAAY,MAAM,mBAAmB;;wBAmTlF,2BAA2B,QAAQ,QAAQ,QAAQ,YAAY,MAAM,mBAAmB"}
@@ -1 +1 @@
1
- {"version":3,"file":"generateMetadataFile.d.mts","names":[],"sources":["../src/generateMetadataFile.ts"],"mappings":";;;;wBAqCgB,qBAAqB,QAAQ,QAAQ,QAAQ,YAAY,MAAM,mBAAmB;;wBA+SlF,2BAA2B,QAAQ,QAAQ,QAAQ,YAAY,MAAM,mBAAmB"}
1
+ {"version":3,"file":"generateMetadataFile.d.mts","names":[],"sources":["../src/generateMetadataFile.ts"],"mappings":";;;;wBAqCgB,qBAAqB,QAAQ,QAAQ,QAAQ,YAAY,MAAM,mBAAmB;;wBAmTlF,2BAA2B,QAAQ,QAAQ,QAAQ,YAAY,MAAM,mBAAmB"}
@@ -7,6 +7,7 @@ import { code, imp } from "ts-poet";
7
7
  //#region src/generateMetadataFile.ts
8
8
  function generateMetadataFile(config, dbMeta, meta) {
9
9
  const { entity, createdAt, updatedAt, deletedAt } = meta;
10
+ validateAssertUnchangedFields(config, meta);
10
11
  const fields = generateFields(config, dbMeta, meta, columnReference);
11
12
  Object.values(fields).forEach((code) => code.asOneline());
12
13
  const maybeBaseType = meta.baseClassName ? `"${meta.baseClassName}"` : void 0;
@@ -89,6 +90,7 @@ function generateFields(config, dbMeta, dbMetadata, columnRef) {
89
90
  serde: new ${SimpleFieldSerde}("${fieldName}", ${columnRef(p, serde, column)}),
90
91
  immutable: false,
91
92
  ${p.lazy ? code`lazy: true,` : ""}
93
+ ${maybeAssertUnchanged(config, dbMetadata, fieldName)}
92
94
  ${extras}
93
95
  ${maybeDefault(p)}
94
96
  ${maybeSanitize(config, p)}
@@ -107,6 +109,7 @@ function generateFields(config, dbMeta, dbMetadata, columnRef) {
107
109
  type: "string",
108
110
  serde: new ${SimpleFieldSerde}("${fieldName}", ${columnRef(p, code`new ${PrimitiveSerde}("${dbType}")`, columnArgs(p, dbMetadata))}),
109
111
  immutable: false,
112
+ ${maybeAssertUnchanged(config, dbMetadata, fieldName)}
110
113
  ${maybeDefault(p)}
111
114
  }`;
112
115
  });
@@ -125,6 +128,7 @@ function generateFields(config, dbMeta, dbMetadata, columnRef) {
125
128
  enumType: ${enumType},
126
129
  serde: new ${SimpleFieldSerde}("${fieldName}", ${columnRef(field, code`new ${serdeType}("${columnTypeWithArray}", ${enumDetailType})`, columnArgs(field, dbMetadata))}),
127
130
  immutable: false,
131
+ ${maybeAssertUnchanged(config, dbMetadata, fieldName)}
128
132
  ${maybeDefault(field)}
129
133
  }
130
134
  `;
@@ -309,6 +313,29 @@ function primitiveColumnCodec(config, column) {
309
313
  else serdeType = PrimitiveSerde;
310
314
  return isArray ? code`new ${serdeType}( "${columnType}[]", true)` : code`new ${serdeType}( "${columnType}")`;
311
315
  }
316
+ /** Emits read protection only for configured fields, leaving ordinary reads on the default path. */
317
+ function maybeAssertUnchanged(config, meta, fieldName) {
318
+ return config.entities[meta.name]?.fields?.[fieldName]?.assertUnchanged ? code`assertUnchanged: true,` : "";
319
+ }
320
+ /**
321
+ * Reject configurations whose field reads cannot provide the promised protection.
322
+ *
323
+ * A misspelled or inherited field must not silently disable an invariant's read drift check.
324
+ */
325
+ function validateAssertUnchangedFields(config, meta) {
326
+ for (const [fieldName, field] of Object.entries(config.entities[meta.name]?.fields ?? {})) {
327
+ if (!field.assertUnchanged) continue;
328
+ const scalar = [
329
+ ...meta.primitives,
330
+ ...meta.enums,
331
+ ...meta.pgEnums
332
+ ].find((f) => f.fieldName === fieldName);
333
+ if (!scalar || "derived" in scalar && (scalar.derived === "sync" || scalar.derived === "async") || "lazy" in scalar && scalar.lazy) throw new Error(`assertUnchanged on ${meta.name}.${fieldName} requires a stored scalar field declared on this entity`);
334
+ let base = meta;
335
+ while (base.baseType) base = base.baseType;
336
+ if (!base.updatedAt) throw new Error(`assertUnchanged on ${meta.name}.${fieldName} requires an updatedAt version field`);
337
+ }
338
+ }
312
339
  //#endregion
313
340
  export { generateColumnDeclarations, generateMetadataFile };
314
341
 
@@ -1 +1 @@
1
- {"version":3,"file":"generateMetadataFile.js","names":[],"sources":["../src/generateMetadataFile.ts"],"sourcesContent":["import { camelCase } from \"change-case\";\nimport { type Code, type Import, code, imp } from \"ts-poet\";\n\nimport { type Config } from \"./config.ts\";\nimport {\n type DatabaseColumnType,\n type DbMetadata,\n type EntityDbMetadata,\n type OneToManyField,\n type PrimitiveField,\n} from \"./EntityDbMetadata.ts\";\nimport {\n BigIntSerde,\n Column,\n ColumnDescriptors,\n CustomSerdeAdapter,\n DateSerde,\n DecimalToNumberSerde,\n EntityMetadata,\n EnumArrayFieldSerde,\n EnumFieldSerde,\n JsonSerde,\n KeySerde,\n PlainDateSerde,\n PlainDateTimeSerde,\n PlainTimeSerde,\n PolyComponent,\n PrimitiveSerde,\n SimpleFieldSerde,\n SuperstructSerde,\n VectorSerde,\n ZodSerde,\n ZonedDateTimeSerde,\n polymorphicField,\n} from \"./symbols.ts\";\nimport { mapSimpleDbTypeToTypescriptType, q } from \"./utils.ts\";\n\nexport function generateMetadataFile(config: Config, dbMeta: DbMetadata, meta: EntityDbMetadata): Code {\n const { entity, createdAt, updatedAt, deletedAt } = meta;\n\n const fields = generateFields(config, dbMeta, meta, columnReference);\n\n Object.values(fields).forEach((code) => code.asOneline());\n\n const maybeBaseType = meta.baseClassName ? `\"${meta.baseClassName}\"` : undefined;\n // We want to put inheritanceType: sti/cti onto base classes as well\n const maybeInheritanceType = meta.inheritanceType ? `inheritanceType: \"${meta.inheritanceType}\",` : \"\";\n const maybeStiColumn = meta.stiDiscriminatorField ? `stiDiscriminatorField: \"${meta.stiDiscriminatorField}\",` : \"\";\n const maybeStiValue = meta.stiDiscriminatorValue ? `stiDiscriminatorValue: ${meta.stiDiscriminatorValue},` : \"\";\n const maybeCtiAbstract = meta.abstract ? `ctiAbstract: ${meta.abstract},` : \"\";\n // Force subtype `timestampFields` to be `undefined` to ensure all runtime code is reading from the baseMeta values.\n // Force subtype `timestampFields` to be `undefined` to ensure all runtime code is reading from the baseMeta values.\n const maybeTimestampConfig = meta.baseClassName\n ? code`undefined`\n : code`\n {\n createdAt: ${q(createdAt?.fieldName)},\n updatedAt: ${q(updatedAt?.fieldName)},\n deletedAt: ${q(deletedAt?.fieldName)},\n }\n `;\n const maybeInsertionOrder = meta.nonDeferredFkOrder !== 0 ? `nonDeferredFkOrder: ${meta.nonDeferredFkOrder},` : ``;\n const uniqueBy = getUniqueBy(config, meta);\n const maybeUniqueBy = uniqueBy.length > 0 ? code`uniqueBy: ${JSON.stringify(uniqueBy)},` : code``;\n\n return code`\n export const ${entity.metaName}: ${EntityMetadata}<${entity.name}> = {\n cstr: ${entity.typeForMetadataFile},\n type: \"${entity.name}\",\n baseType: ${maybeBaseType}, ${maybeInheritanceType} ${maybeStiColumn} ${maybeStiValue} ${maybeCtiAbstract}\n idType: \"${config.idType ?? \"tagged-string\"}\",\n idDbType: \"${meta.primaryKey.columnType}\",\n tagName: \"${meta.tagName}\",\n tableName: \"${meta.tableName}\",\n supportsEmExecute: ${!meta.inheritanceType && meta.supportsEmExecute === true},\n fields: ${fields},\n columns: ${meta.primaryKey.columnOwner.metaName}Columns,\n allFields: {},\n orderBy: ${q(config.entities[meta.name]?.orderBy)},\n timestampFields: ${maybeTimestampConfig},\n config: ${entity.configConst},\n factory: ${imp(`new${entity.name}@./entities.ts`)},\n baseTypes: [],\n subTypes: [], ${maybeInsertionOrder} ${maybeUniqueBy}\n };\n\n (${entity.typeForMetadataFile} as any).metadata = ${entity.metaName};\n `;\n}\n\n/** Returns configured identities plus conservative database-backed unique identities. */\nfunction getUniqueBy(config: Config, meta: EntityDbMetadata): string[][] {\n const uniqueBy = config.entities[meta.name]?.uniqueBy ?? [];\n const seen = new Set<string>();\n return [...uniqueBy, ...(meta.uniqueConstraints ?? [])].filter((fields) => {\n const key = fields.join(\"\\u0000\");\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\n/** Emits fields that bind the already-declared physical columns. */\nfunction generateFields(\n config: Config,\n dbMeta: DbMetadata,\n dbMetadata: EntityDbMetadata,\n columnRef: (column: Pick<PrimitiveField, \"columnName\" | \"columnOwner\">, codec?: Code, args?: Code) => Code,\n): Record<string, Code> {\n const fields: Record<string, Code> = {};\n\n fields[\"id\"] = code`\n {\n kind: \"primaryKey\",\n fieldName: \"id\",\n fieldIdName: undefined,\n required: true,\n serde: new ${SimpleFieldSerde}(\"id\", ${columnRef(dbMetadata.primaryKey, code`new ${KeySerde}(\"${dbMetadata.tagName}\", \"${dbMetadata.primaryKey.columnType}\")`, columnArgs(dbMetadata.primaryKey, dbMetadata, code`() => ${dbMetadata.entity.metaName}`))}),\n immutable: true,\n }\n `;\n\n dbMetadata.primitives.forEach((p) => {\n const { fieldName, derived, columnType } = p;\n const column = columnArgs(p, dbMetadata);\n const serde = primitiveColumnCodec(config, p);\n const extras = columnType === \"citext\" ? code`citext: true,` : \"\";\n fields[fieldName] = code`\n {\n kind: \"primitive\",\n fieldName: \"${fieldName}\",\n fieldIdName: undefined,\n derived: ${!derived ? false : `\"${derived}\"`},\n required: ${!derived && p.notNull},\n protected: ${p.protected},\n type: ${typeof p.rawFieldType === \"string\" ? `\"${p.rawFieldType}\"` : p.rawFieldType},\n serde: new ${SimpleFieldSerde}(\"${fieldName}\", ${columnRef(p, serde, column)}),\n immutable: false,\n ${p.lazy ? code`lazy: true,` : \"\"}\n ${extras}\n ${maybeDefault(p)}\n ${maybeSanitize(config, p)}\n }`;\n });\n\n // Treat native enums as primitives\n dbMetadata.pgEnums.forEach((p) => {\n const { fieldName, notNull, dbType } = p;\n fields[fieldName] = code`\n {\n kind: \"primitive\",\n fieldName: \"${fieldName}\",\n fieldIdName: undefined,\n derived: false,\n required: ${notNull},\n protected: false,\n type: \"string\",\n serde: new ${SimpleFieldSerde}(\"${fieldName}\", ${columnRef(p, code`new ${PrimitiveSerde}(\"${dbType}\")`, columnArgs(p, dbMetadata))}),\n immutable: false,\n ${maybeDefault(p)}\n }`;\n });\n\n dbMetadata.enums.forEach((field) => {\n const { fieldName, enumDetailType, enumType, notNull, isArray, columnType, derived } = field;\n const serdeType = isArray ? EnumArrayFieldSerde : EnumFieldSerde;\n const columnTypeWithArray = `${columnType}${isArray ? \"[]\" : \"\"}`;\n fields[fieldName] = code`\n {\n kind: \"enum\",\n fieldName: \"${fieldName}\",\n fieldIdName: undefined,\n required: ${notNull},\n derived: ${!derived ? false : `\"${derived}\"`},\n enumDetailType: ${enumDetailType},\n enumType: ${enumType},\n serde: new ${SimpleFieldSerde}(\"${fieldName}\", ${columnRef(field, code`new ${serdeType}(\"${columnTypeWithArray}\", ${enumDetailType})`, columnArgs(field, dbMetadata))}),\n immutable: false,\n ${maybeDefault(field)}\n }\n `;\n });\n\n dbMetadata.manyToOnes.forEach((m2o) => {\n const { fieldName, columnName, notNull, otherEntity, otherFieldName, derived, dbType } = m2o;\n const otherTagName = config.entities[otherEntity.name].tag;\n const physical = (dbMetadata.physicalMetadata ?? dbMetadata).manyToOnes.find(\n (field) => field.columnName === columnName,\n );\n const otherMetadata =\n physical?.otherEntity.name === otherEntity.name\n ? code`${columnRef(m2o)}.idMetadata!`\n : code`() => ${otherEntity.metaName}`;\n fields[fieldName] = code`\n {\n kind: \"m2o\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${fieldName}Id\",\n derived: ${!derived ? false : `\"${derived}\"`},\n required: ${notNull},\n otherMetadata: ${otherMetadata},\n otherFieldName: \"${otherFieldName}\",\n serde: new ${SimpleFieldSerde}(\"${fieldName}\", ${columnRef(m2o, code`new ${KeySerde}(\"${otherTagName}\", \"${dbType}\")`, columnArgs(m2o, dbMetadata, code`() => ${otherEntity.metaName}`))}),\n immutable: false,\n ${maybeDefault(m2o)}\n }\n `;\n });\n\n dbMetadata.oneToManys.forEach((o2m) => {\n const { fieldName, singularName, otherEntity, otherFieldName, otherColumnName } = o2m;\n fields[fieldName] = code`\n {\n kind: \"o2m\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${singularName}Ids\",\n required: false,\n otherMetadata: () => ${otherEntity.metaName},\n otherFieldName: \"${otherFieldName}\",\n otherColumnName: \"${otherColumnName}\",\n serde: undefined,\n immutable: false,\n ${maybeOrderBy(o2m)}\n ${maybeSoftDeletes(o2m)}\n }\n `;\n });\n\n dbMetadata.largeOneToManys.forEach((o2m) => {\n const { fieldName, singularName, otherEntity, otherFieldName, otherColumnName } = o2m;\n fields[fieldName] = code`\n {\n kind: \"lo2m\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${singularName}Ids\",\n required: false,\n otherMetadata: () => ${otherEntity.metaName},\n otherFieldName: \"${otherFieldName}\",\n otherColumnName: \"${otherColumnName}\",\n serde: undefined,\n immutable: false,\n }\n `;\n });\n\n dbMetadata.manyToManys.forEach((m2m) => {\n const { fieldName, singularName, otherEntity, otherFieldName, derived } = m2m;\n fields[fieldName] = code`\n {\n kind: \"m2m\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${singularName}Ids\",\n required: false,\n derived: ${derived === \"async\" ? `\"async\"` : derived === \"otherSide\" ? `\"otherSide\"` : \"false\"},\n otherMetadata: () => ${otherEntity.metaName},\n otherFieldName: \"${otherFieldName}\",\n serde: undefined,\n immutable: false,\n joinTableName: \"${m2m.joinTableName}\",\n columnNames: [\"${m2m.columnName}\", \"${m2m.otherColumnName}\"],\n hasJoinTableId: ${m2m.hasJoinTableId},\n ${maybeSoftDeletes(m2m)}\n }\n `;\n });\n\n dbMetadata.manyToManyEnums.forEach((m2m) => {\n const { fieldName, enumDetailType } = m2m;\n fields[fieldName] = code`\n {\n kind: \"m2mEnum\",\n fieldName: \"${fieldName}\",\n fieldIdName: undefined,\n required: false,\n derived: false,\n enumDetailType: ${enumDetailType},\n serde: undefined,\n immutable: false,\n joinTableName: \"${m2m.joinTableName}\",\n columnNames: [\"${m2m.columnName}\", \"${m2m.otherColumnName}\"],\n hasJoinTableId: ${m2m.hasJoinTableId},\n }\n `;\n });\n\n dbMetadata.oneToOnes.forEach((o2o) => {\n const { fieldName, otherEntity, otherFieldName, otherColumnName } = o2o;\n fields[fieldName] = code`\n {\n kind: \"o2o\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${fieldName}Id\",\n required: false,\n otherMetadata: () => ${otherEntity.metaName},\n otherFieldName: \"${otherFieldName}\",\n otherColumnName: \"${otherColumnName}\",\n serde: undefined,\n immutable: false,\n }\n `;\n });\n\n dbMetadata.polymorphics.forEach((p) => {\n const { fieldName, notNull, components } = p;\n components.forEach((component) =>\n columnRef(\n component,\n code`new ${KeySerde}(\"${config.entities[component.otherEntity.name].tag}\", \"${dbMeta.entitiesByName[component.otherEntity.name].primaryKey.columnType}\")`,\n code`true, false, false, false, false, () => ${component.otherEntity.metaName}`,\n ),\n );\n fields[fieldName] = code`\n ${polymorphicField}(\"${fieldName}\", ${notNull}, [${components.map((component) => {\n const owner = dbMeta.entitiesByName[component.columnOwner.name];\n const physical = (owner.physicalMetadata ?? owner).polymorphics\n .flatMap((field) => field.components)\n .find((c) => c.columnName === component.columnName)!;\n const target =\n physical.otherEntity.name === component.otherEntity.name\n ? \"\"\n : code`, () => ${component.otherEntity.metaName}`;\n return code`new ${PolyComponent}(${columnRef(component)}, ${q(component.otherFieldName)}${target}),`;\n })}])\n `;\n });\n\n return fields;\n}\n\n/** Emits constructor arguments using codegen's existing column facts. */\nfunction columnArgs(\n column: Pick<PrimitiveField, \"columnNotNull\" | \"columnGenerated\"> & Partial<Pick<PrimitiveField, \"columnDefault\">>,\n meta: EntityDbMetadata,\n idMetadata?: Code,\n): Code {\n const insertOptional = column === meta.createdAt || column === meta.updatedAt;\n return code`${!column.columnNotNull}, ${column.columnDefault != null && !column.columnGenerated}, ${column.columnGenerated}, ${insertOptional}, true, ${idMetadata ?? \"undefined\"}`;\n}\n\n/** Declares all physical codecs by their SQL API names before any domain metadata; ID targets remain lazy. */\nexport function generateColumnDeclarations(config: Config, dbMeta: DbMetadata, meta: EntityDbMetadata): Code {\n if (meta.inheritanceType === \"sti\" && meta.baseClassName) return code``;\n const columns: Record<string, Code> = {};\n generateFields(config, dbMeta, meta.physicalMetadata ?? meta, (column, codec, args) => {\n const columnName = column.columnName;\n const apiName = camelCase(columnName);\n if (codec) columns[apiName] = code`new ${Column}(${q(columnName)}, ${args}, ${codec})`.asOneline();\n return code`${meta.entity.metaName}Columns[${q(apiName)}]`;\n });\n for (const column of (meta.physicalMetadata ?? meta).ignoredColumns) {\n const apiName = camelCase(column.columnName);\n columns[apiName] =\n code`new ${Column}(${q(column.columnName)}, ${columnArgs(column, meta)}, ${primitiveColumnCodec(config, column)})`.asOneline();\n }\n return code`const ${meta.entity.metaName}Columns = ${columns} satisfies ${ColumnDescriptors};`;\n}\n\n/** Emits a direct reference to a descriptor by its SQL API name. */\nfunction columnReference(column: Pick<PrimitiveField, \"columnName\" | \"columnOwner\">): Code {\n return code`${column.columnOwner.metaName}Columns[${q(camelCase(column.columnName))}]`;\n}\n\nfunction maybeDefault(f: { hasConfigDefault: boolean; columnDefault?: number | boolean | string | null }): Code | \"\" {\n return f.hasConfigDefault ? code`default: \"config\",` : f.columnDefault != null ? code`default: \"schema\",` : \"\";\n}\n\nfunction maybeOrderBy(f: OneToManyField): Code | \"\" {\n return f.orderBy ? code`orderBy: { field: \"${f.orderBy.field}\", direction: \"${f.orderBy.direction}\" },` : \"\";\n}\n\n/** Emits the `softDeletes` config, i.e. `softDeletes: \"include\",`, for relations that opt out of hiding soft-deletes. */\nfunction maybeSoftDeletes(f: { softDeletes: \"include\" | \"exclude\" | undefined }): Code | \"\" {\n return f.softDeletes ? code`softDeletes: \"${f.softDeletes}\",` : \"\";\n}\n\n/** We sanitize/cleanStringValue all varchars, unless opted out by the column default/arrays/custom serdes. */\nfunction maybeSanitize(\n config: Config,\n f: { columnType: DatabaseColumnType; columnDefault?: any; isArray: boolean; customSerde: any },\n): Code | \"\" {\n // Only strings need to maybe turn off their cleanStringValue sanitization, if the default=\"\" or its an array\n return isString(config, f.columnType) && (f.columnDefault === \"''\" || f.isArray || f.customSerde)\n ? code`sanitize: false,`\n : \"\";\n}\n\nfunction isString(config: Config, columnType: DatabaseColumnType): boolean {\n return mapSimpleDbTypeToTypescriptType(config, columnType) === \"string\";\n}\n\n/** Uses domain codecs for modeled fields and the same native conversions for unmodeled columns. */\nfunction primitiveColumnCodec(config: Config, column: PrimitiveField): Code {\n const { columnType, customSerde, superstruct, zodSchema, isArray } = column;\n if (customSerde) {\n return isArray\n ? code`new ${CustomSerdeAdapter}( \"${columnType}[]\", ${customSerde}, true)`\n : code`new ${CustomSerdeAdapter}( \"${columnType}\", ${customSerde})`;\n }\n if (superstruct) return code`new ${SuperstructSerde}( ${superstruct})`;\n if (zodSchema) return code`new ${ZodSerde}( ${zodSchema})`;\n if (columnType === \"numeric\" || columnType === \"decimal\") {\n return isArray ? code`new ${DecimalToNumberSerde}(true)` : code`new ${DecimalToNumberSerde}()`;\n }\n if (columnType === \"jsonb\") return code`new ${JsonSerde}()`;\n if (columnType === \"vector\") return code`new ${VectorSerde}()`;\n if (column.rawFieldType === \"bigint\") {\n return isArray ? code`new ${BigIntSerde}(true)` : code`new ${BigIntSerde}()`;\n }\n\n let serdeType: Import;\n if (columnType === \"date\") {\n serdeType = config.temporal ? PlainDateSerde : DateSerde;\n } else if (columnType === \"timestamp without time zone\") {\n serdeType = config.temporal ? PlainDateTimeSerde : DateSerde;\n } else if (columnType === \"timestamp with time zone\") {\n serdeType = config.temporal ? ZonedDateTimeSerde : DateSerde;\n } else if (columnType === \"time without time zone\") {\n serdeType = config.temporal ? PlainTimeSerde : PrimitiveSerde;\n } else {\n serdeType = PrimitiveSerde;\n }\n return isArray ? code`new ${serdeType}( \"${columnType}[]\", true)` : code`new ${serdeType}( \"${columnType}\")`;\n}\n"],"mappings":";;;;;;;AAqCA,SAAgB,qBAAqB,QAAgB,QAAoB,MAA8B;CACrG,MAAM,EAAE,QAAQ,WAAW,WAAW,cAAc;CAEpD,MAAM,SAAS,eAAe,QAAQ,QAAQ,MAAM,eAAe;CAEnE,OAAO,OAAO,MAAM,CAAC,CAAC,SAAS,SAAS,KAAK,UAAU,CAAC;CAExD,MAAM,gBAAgB,KAAK,gBAAgB,IA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S,qBAAqB,QAAgB,QAA8B;CAC1E,MAAM,EAAE,YAAY,aAAa,aAAa,WAAW,YAAY;CACrE,IAAI,aACF,OAAO,UACH,IAAI,OAAO,mBAAmB,KAAK,WAAW,OAAO,YAAY,WACjE,IAAI,OAAO,mBAAmB,KAAK,WAAW,KAAK,YAAY;CAErE,IAAI,aAAa,OAAO,IAAI,OAAO,iBAAiB,IAAI,YAAY;CACpE,IAAI,WAAW,OAAO,IAAI,OAAO,SAAS,IAAI,UAAU;CACxD,IAAI,eAAe,aAAa,eAAe,WAC7C,OAAO,UAAU,IAAI,OAAO,qBAAqB,UAAU,IAAI,OAAO,qBAAqB;CAE7F,IAAI,eAAe,SAAS,OAAO,IAAI,OAAO,UAAU;CACxD,IAAI,eAAe,UAAU,OAAO,IAAI,OAAO,YAAY;CAC3D,IAAI,OAAO,iBAAiB,UAC1B,OAAO,UAAU,IAAI,OAAO,YAAY,UAAU,IAAI,OAAO,YAAY;CAG3E,IAAI;CACJ,IAAI,eAAe,QACjB,YAAY,OAAO,WAAW,iBAAiB;MAC1C,IAAI,eAAe,+BACxB,YAAY,OAAO,WAAW,qBAAqB;MAC9C,IAAI,eAAe,4BACxB,YAAY,OAAO,WAAW,qBAAqB;MAC9C,IAAI,eAAe,0BACxB,YAAY,OAAO,WAAW,iBAAiB;MAE/C,YAAY;CAEd,OAAO,UAAU,IAAI,OAAO,UAAU,KAAK,WAAW,cAAc,IAAI,OAAO,UAAU,KAAK,WAAW;AAC3G"}
1
+ {"version":3,"file":"generateMetadataFile.js","names":[],"sources":["../src/generateMetadataFile.ts"],"sourcesContent":["import { camelCase } from \"change-case\";\nimport { type Code, type Import, code, imp } from \"ts-poet\";\n\nimport { type Config } from \"./config.ts\";\nimport {\n type DatabaseColumnType,\n type DbMetadata,\n type EntityDbMetadata,\n type OneToManyField,\n type PrimitiveField,\n} from \"./EntityDbMetadata.ts\";\nimport {\n BigIntSerde,\n Column,\n ColumnDescriptors,\n CustomSerdeAdapter,\n DateSerde,\n DecimalToNumberSerde,\n EntityMetadata,\n EnumArrayFieldSerde,\n EnumFieldSerde,\n JsonSerde,\n KeySerde,\n PlainDateSerde,\n PlainDateTimeSerde,\n PlainTimeSerde,\n PolyComponent,\n PrimitiveSerde,\n SimpleFieldSerde,\n SuperstructSerde,\n VectorSerde,\n ZodSerde,\n ZonedDateTimeSerde,\n polymorphicField,\n} from \"./symbols.ts\";\nimport { mapSimpleDbTypeToTypescriptType, q } from \"./utils.ts\";\n\nexport function generateMetadataFile(config: Config, dbMeta: DbMetadata, meta: EntityDbMetadata): Code {\n const { entity, createdAt, updatedAt, deletedAt } = meta;\n\n validateAssertUnchangedFields(config, meta);\n const fields = generateFields(config, dbMeta, meta, columnReference);\n\n Object.values(fields).forEach((code) => code.asOneline());\n\n const maybeBaseType = meta.baseClassName ? `\"${meta.baseClassName}\"` : undefined;\n // We want to put inheritanceType: sti/cti onto base classes as well\n const maybeInheritanceType = meta.inheritanceType ? `inheritanceType: \"${meta.inheritanceType}\",` : \"\";\n const maybeStiColumn = meta.stiDiscriminatorField ? `stiDiscriminatorField: \"${meta.stiDiscriminatorField}\",` : \"\";\n const maybeStiValue = meta.stiDiscriminatorValue ? `stiDiscriminatorValue: ${meta.stiDiscriminatorValue},` : \"\";\n const maybeCtiAbstract = meta.abstract ? `ctiAbstract: ${meta.abstract},` : \"\";\n // Force subtype `timestampFields` to be `undefined` to ensure all runtime code is reading from the baseMeta values.\n // Force subtype `timestampFields` to be `undefined` to ensure all runtime code is reading from the baseMeta values.\n const maybeTimestampConfig = meta.baseClassName\n ? code`undefined`\n : code`\n {\n createdAt: ${q(createdAt?.fieldName)},\n updatedAt: ${q(updatedAt?.fieldName)},\n deletedAt: ${q(deletedAt?.fieldName)},\n }\n `;\n const maybeInsertionOrder = meta.nonDeferredFkOrder !== 0 ? `nonDeferredFkOrder: ${meta.nonDeferredFkOrder},` : ``;\n const uniqueBy = getUniqueBy(config, meta);\n const maybeUniqueBy = uniqueBy.length > 0 ? code`uniqueBy: ${JSON.stringify(uniqueBy)},` : code``;\n\n return code`\n export const ${entity.metaName}: ${EntityMetadata}<${entity.name}> = {\n cstr: ${entity.typeForMetadataFile},\n type: \"${entity.name}\",\n baseType: ${maybeBaseType}, ${maybeInheritanceType} ${maybeStiColumn} ${maybeStiValue} ${maybeCtiAbstract}\n idType: \"${config.idType ?? \"tagged-string\"}\",\n idDbType: \"${meta.primaryKey.columnType}\",\n tagName: \"${meta.tagName}\",\n tableName: \"${meta.tableName}\",\n supportsEmExecute: ${!meta.inheritanceType && meta.supportsEmExecute === true},\n fields: ${fields},\n columns: ${meta.primaryKey.columnOwner.metaName}Columns,\n allFields: {},\n orderBy: ${q(config.entities[meta.name]?.orderBy)},\n timestampFields: ${maybeTimestampConfig},\n config: ${entity.configConst},\n factory: ${imp(`new${entity.name}@./entities.ts`)},\n baseTypes: [],\n subTypes: [], ${maybeInsertionOrder} ${maybeUniqueBy}\n };\n\n (${entity.typeForMetadataFile} as any).metadata = ${entity.metaName};\n `;\n}\n\n/** Returns configured identities plus conservative database-backed unique identities. */\nfunction getUniqueBy(config: Config, meta: EntityDbMetadata): string[][] {\n const uniqueBy = config.entities[meta.name]?.uniqueBy ?? [];\n const seen = new Set<string>();\n return [...uniqueBy, ...(meta.uniqueConstraints ?? [])].filter((fields) => {\n const key = fields.join(\"\\u0000\");\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\n/** Emits fields that bind the already-declared physical columns. */\nfunction generateFields(\n config: Config,\n dbMeta: DbMetadata,\n dbMetadata: EntityDbMetadata,\n columnRef: (column: Pick<PrimitiveField, \"columnName\" | \"columnOwner\">, codec?: Code, args?: Code) => Code,\n): Record<string, Code> {\n const fields: Record<string, Code> = {};\n\n fields[\"id\"] = code`\n {\n kind: \"primaryKey\",\n fieldName: \"id\",\n fieldIdName: undefined,\n required: true,\n serde: new ${SimpleFieldSerde}(\"id\", ${columnRef(dbMetadata.primaryKey, code`new ${KeySerde}(\"${dbMetadata.tagName}\", \"${dbMetadata.primaryKey.columnType}\")`, columnArgs(dbMetadata.primaryKey, dbMetadata, code`() => ${dbMetadata.entity.metaName}`))}),\n immutable: true,\n }\n `;\n\n dbMetadata.primitives.forEach((p) => {\n const { fieldName, derived, columnType } = p;\n const column = columnArgs(p, dbMetadata);\n const serde = primitiveColumnCodec(config, p);\n const extras = columnType === \"citext\" ? code`citext: true,` : \"\";\n fields[fieldName] = code`\n {\n kind: \"primitive\",\n fieldName: \"${fieldName}\",\n fieldIdName: undefined,\n derived: ${!derived ? false : `\"${derived}\"`},\n required: ${!derived && p.notNull},\n protected: ${p.protected},\n type: ${typeof p.rawFieldType === \"string\" ? `\"${p.rawFieldType}\"` : p.rawFieldType},\n serde: new ${SimpleFieldSerde}(\"${fieldName}\", ${columnRef(p, serde, column)}),\n immutable: false,\n ${p.lazy ? code`lazy: true,` : \"\"}\n ${maybeAssertUnchanged(config, dbMetadata, fieldName)}\n ${extras}\n ${maybeDefault(p)}\n ${maybeSanitize(config, p)}\n }`;\n });\n\n // Treat native enums as primitives\n dbMetadata.pgEnums.forEach((p) => {\n const { fieldName, notNull, dbType } = p;\n fields[fieldName] = code`\n {\n kind: \"primitive\",\n fieldName: \"${fieldName}\",\n fieldIdName: undefined,\n derived: false,\n required: ${notNull},\n protected: false,\n type: \"string\",\n serde: new ${SimpleFieldSerde}(\"${fieldName}\", ${columnRef(p, code`new ${PrimitiveSerde}(\"${dbType}\")`, columnArgs(p, dbMetadata))}),\n immutable: false,\n ${maybeAssertUnchanged(config, dbMetadata, fieldName)}\n ${maybeDefault(p)}\n }`;\n });\n\n dbMetadata.enums.forEach((field) => {\n const { fieldName, enumDetailType, enumType, notNull, isArray, columnType, derived } = field;\n const serdeType = isArray ? EnumArrayFieldSerde : EnumFieldSerde;\n const columnTypeWithArray = `${columnType}${isArray ? \"[]\" : \"\"}`;\n fields[fieldName] = code`\n {\n kind: \"enum\",\n fieldName: \"${fieldName}\",\n fieldIdName: undefined,\n required: ${notNull},\n derived: ${!derived ? false : `\"${derived}\"`},\n enumDetailType: ${enumDetailType},\n enumType: ${enumType},\n serde: new ${SimpleFieldSerde}(\"${fieldName}\", ${columnRef(field, code`new ${serdeType}(\"${columnTypeWithArray}\", ${enumDetailType})`, columnArgs(field, dbMetadata))}),\n immutable: false,\n ${maybeAssertUnchanged(config, dbMetadata, fieldName)}\n ${maybeDefault(field)}\n }\n `;\n });\n\n dbMetadata.manyToOnes.forEach((m2o) => {\n const { fieldName, columnName, notNull, otherEntity, otherFieldName, derived, dbType } = m2o;\n const otherTagName = config.entities[otherEntity.name].tag;\n const physical = (dbMetadata.physicalMetadata ?? dbMetadata).manyToOnes.find(\n (field) => field.columnName === columnName,\n );\n const otherMetadata =\n physical?.otherEntity.name === otherEntity.name\n ? code`${columnRef(m2o)}.idMetadata!`\n : code`() => ${otherEntity.metaName}`;\n fields[fieldName] = code`\n {\n kind: \"m2o\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${fieldName}Id\",\n derived: ${!derived ? false : `\"${derived}\"`},\n required: ${notNull},\n otherMetadata: ${otherMetadata},\n otherFieldName: \"${otherFieldName}\",\n serde: new ${SimpleFieldSerde}(\"${fieldName}\", ${columnRef(m2o, code`new ${KeySerde}(\"${otherTagName}\", \"${dbType}\")`, columnArgs(m2o, dbMetadata, code`() => ${otherEntity.metaName}`))}),\n immutable: false,\n ${maybeDefault(m2o)}\n }\n `;\n });\n\n dbMetadata.oneToManys.forEach((o2m) => {\n const { fieldName, singularName, otherEntity, otherFieldName, otherColumnName } = o2m;\n fields[fieldName] = code`\n {\n kind: \"o2m\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${singularName}Ids\",\n required: false,\n otherMetadata: () => ${otherEntity.metaName},\n otherFieldName: \"${otherFieldName}\",\n otherColumnName: \"${otherColumnName}\",\n serde: undefined,\n immutable: false,\n ${maybeOrderBy(o2m)}\n ${maybeSoftDeletes(o2m)}\n }\n `;\n });\n\n dbMetadata.largeOneToManys.forEach((o2m) => {\n const { fieldName, singularName, otherEntity, otherFieldName, otherColumnName } = o2m;\n fields[fieldName] = code`\n {\n kind: \"lo2m\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${singularName}Ids\",\n required: false,\n otherMetadata: () => ${otherEntity.metaName},\n otherFieldName: \"${otherFieldName}\",\n otherColumnName: \"${otherColumnName}\",\n serde: undefined,\n immutable: false,\n }\n `;\n });\n\n dbMetadata.manyToManys.forEach((m2m) => {\n const { fieldName, singularName, otherEntity, otherFieldName, derived } = m2m;\n fields[fieldName] = code`\n {\n kind: \"m2m\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${singularName}Ids\",\n required: false,\n derived: ${derived === \"async\" ? `\"async\"` : derived === \"otherSide\" ? `\"otherSide\"` : \"false\"},\n otherMetadata: () => ${otherEntity.metaName},\n otherFieldName: \"${otherFieldName}\",\n serde: undefined,\n immutable: false,\n joinTableName: \"${m2m.joinTableName}\",\n columnNames: [\"${m2m.columnName}\", \"${m2m.otherColumnName}\"],\n hasJoinTableId: ${m2m.hasJoinTableId},\n ${maybeSoftDeletes(m2m)}\n }\n `;\n });\n\n dbMetadata.manyToManyEnums.forEach((m2m) => {\n const { fieldName, enumDetailType } = m2m;\n fields[fieldName] = code`\n {\n kind: \"m2mEnum\",\n fieldName: \"${fieldName}\",\n fieldIdName: undefined,\n required: false,\n derived: false,\n enumDetailType: ${enumDetailType},\n serde: undefined,\n immutable: false,\n joinTableName: \"${m2m.joinTableName}\",\n columnNames: [\"${m2m.columnName}\", \"${m2m.otherColumnName}\"],\n hasJoinTableId: ${m2m.hasJoinTableId},\n }\n `;\n });\n\n dbMetadata.oneToOnes.forEach((o2o) => {\n const { fieldName, otherEntity, otherFieldName, otherColumnName } = o2o;\n fields[fieldName] = code`\n {\n kind: \"o2o\",\n fieldName: \"${fieldName}\",\n fieldIdName: \"${fieldName}Id\",\n required: false,\n otherMetadata: () => ${otherEntity.metaName},\n otherFieldName: \"${otherFieldName}\",\n otherColumnName: \"${otherColumnName}\",\n serde: undefined,\n immutable: false,\n }\n `;\n });\n\n dbMetadata.polymorphics.forEach((p) => {\n const { fieldName, notNull, components } = p;\n components.forEach((component) =>\n columnRef(\n component,\n code`new ${KeySerde}(\"${config.entities[component.otherEntity.name].tag}\", \"${dbMeta.entitiesByName[component.otherEntity.name].primaryKey.columnType}\")`,\n code`true, false, false, false, false, () => ${component.otherEntity.metaName}`,\n ),\n );\n fields[fieldName] = code`\n ${polymorphicField}(\"${fieldName}\", ${notNull}, [${components.map((component) => {\n const owner = dbMeta.entitiesByName[component.columnOwner.name];\n const physical = (owner.physicalMetadata ?? owner).polymorphics\n .flatMap((field) => field.components)\n .find((c) => c.columnName === component.columnName)!;\n const target =\n physical.otherEntity.name === component.otherEntity.name\n ? \"\"\n : code`, () => ${component.otherEntity.metaName}`;\n return code`new ${PolyComponent}(${columnRef(component)}, ${q(component.otherFieldName)}${target}),`;\n })}])\n `;\n });\n\n return fields;\n}\n\n/** Emits constructor arguments using codegen's existing column facts. */\nfunction columnArgs(\n column: Pick<PrimitiveField, \"columnNotNull\" | \"columnGenerated\"> & Partial<Pick<PrimitiveField, \"columnDefault\">>,\n meta: EntityDbMetadata,\n idMetadata?: Code,\n): Code {\n const insertOptional = column === meta.createdAt || column === meta.updatedAt;\n return code`${!column.columnNotNull}, ${column.columnDefault != null && !column.columnGenerated}, ${column.columnGenerated}, ${insertOptional}, true, ${idMetadata ?? \"undefined\"}`;\n}\n\n/** Declares all physical codecs by their SQL API names before any domain metadata; ID targets remain lazy. */\nexport function generateColumnDeclarations(config: Config, dbMeta: DbMetadata, meta: EntityDbMetadata): Code {\n if (meta.inheritanceType === \"sti\" && meta.baseClassName) return code``;\n const columns: Record<string, Code> = {};\n generateFields(config, dbMeta, meta.physicalMetadata ?? meta, (column, codec, args) => {\n const columnName = column.columnName;\n const apiName = camelCase(columnName);\n if (codec) columns[apiName] = code`new ${Column}(${q(columnName)}, ${args}, ${codec})`.asOneline();\n return code`${meta.entity.metaName}Columns[${q(apiName)}]`;\n });\n for (const column of (meta.physicalMetadata ?? meta).ignoredColumns) {\n const apiName = camelCase(column.columnName);\n columns[apiName] =\n code`new ${Column}(${q(column.columnName)}, ${columnArgs(column, meta)}, ${primitiveColumnCodec(config, column)})`.asOneline();\n }\n return code`const ${meta.entity.metaName}Columns = ${columns} satisfies ${ColumnDescriptors};`;\n}\n\n/** Emits a direct reference to a descriptor by its SQL API name. */\nfunction columnReference(column: Pick<PrimitiveField, \"columnName\" | \"columnOwner\">): Code {\n return code`${column.columnOwner.metaName}Columns[${q(camelCase(column.columnName))}]`;\n}\n\nfunction maybeDefault(f: { hasConfigDefault: boolean; columnDefault?: number | boolean | string | null }): Code | \"\" {\n return f.hasConfigDefault ? code`default: \"config\",` : f.columnDefault != null ? code`default: \"schema\",` : \"\";\n}\n\nfunction maybeOrderBy(f: OneToManyField): Code | \"\" {\n return f.orderBy ? code`orderBy: { field: \"${f.orderBy.field}\", direction: \"${f.orderBy.direction}\" },` : \"\";\n}\n\n/** Emits the `softDeletes` config, i.e. `softDeletes: \"include\",`, for relations that opt out of hiding soft-deletes. */\nfunction maybeSoftDeletes(f: { softDeletes: \"include\" | \"exclude\" | undefined }): Code | \"\" {\n return f.softDeletes ? code`softDeletes: \"${f.softDeletes}\",` : \"\";\n}\n\n/** We sanitize/cleanStringValue all varchars, unless opted out by the column default/arrays/custom serdes. */\nfunction maybeSanitize(\n config: Config,\n f: { columnType: DatabaseColumnType; columnDefault?: any; isArray: boolean; customSerde: any },\n): Code | \"\" {\n // Only strings need to maybe turn off their cleanStringValue sanitization, if the default=\"\" or its an array\n return isString(config, f.columnType) && (f.columnDefault === \"''\" || f.isArray || f.customSerde)\n ? code`sanitize: false,`\n : \"\";\n}\n\nfunction isString(config: Config, columnType: DatabaseColumnType): boolean {\n return mapSimpleDbTypeToTypescriptType(config, columnType) === \"string\";\n}\n\n/** Uses domain codecs for modeled fields and the same native conversions for unmodeled columns. */\nfunction primitiveColumnCodec(config: Config, column: PrimitiveField): Code {\n const { columnType, customSerde, superstruct, zodSchema, isArray } = column;\n if (customSerde) {\n return isArray\n ? code`new ${CustomSerdeAdapter}( \"${columnType}[]\", ${customSerde}, true)`\n : code`new ${CustomSerdeAdapter}( \"${columnType}\", ${customSerde})`;\n }\n if (superstruct) return code`new ${SuperstructSerde}( ${superstruct})`;\n if (zodSchema) return code`new ${ZodSerde}( ${zodSchema})`;\n if (columnType === \"numeric\" || columnType === \"decimal\") {\n return isArray ? code`new ${DecimalToNumberSerde}(true)` : code`new ${DecimalToNumberSerde}()`;\n }\n if (columnType === \"jsonb\") return code`new ${JsonSerde}()`;\n if (columnType === \"vector\") return code`new ${VectorSerde}()`;\n if (column.rawFieldType === \"bigint\") {\n return isArray ? code`new ${BigIntSerde}(true)` : code`new ${BigIntSerde}()`;\n }\n\n let serdeType: Import;\n if (columnType === \"date\") {\n serdeType = config.temporal ? PlainDateSerde : DateSerde;\n } else if (columnType === \"timestamp without time zone\") {\n serdeType = config.temporal ? PlainDateTimeSerde : DateSerde;\n } else if (columnType === \"timestamp with time zone\") {\n serdeType = config.temporal ? ZonedDateTimeSerde : DateSerde;\n } else if (columnType === \"time without time zone\") {\n serdeType = config.temporal ? PlainTimeSerde : PrimitiveSerde;\n } else {\n serdeType = PrimitiveSerde;\n }\n return isArray ? code`new ${serdeType}( \"${columnType}[]\", true)` : code`new ${serdeType}( \"${columnType}\")`;\n}\n\n/** Emits read protection only for configured fields, leaving ordinary reads on the default path. */\nfunction maybeAssertUnchanged(config: Config, meta: EntityDbMetadata, fieldName: string): Code | \"\" {\n return config.entities[meta.name]?.fields?.[fieldName]?.assertUnchanged ? code`assertUnchanged: true,` : \"\";\n}\n\n/**\n * Reject configurations whose field reads cannot provide the promised protection.\n *\n * A misspelled or inherited field must not silently disable an invariant's read drift check.\n */\nfunction validateAssertUnchangedFields(config: Config, meta: EntityDbMetadata): void {\n for (const [fieldName, field] of Object.entries(config.entities[meta.name]?.fields ?? {})) {\n if (!field.assertUnchanged) continue;\n\n const scalar = [...meta.primitives, ...meta.enums, ...meta.pgEnums].find((f) => f.fieldName === fieldName);\n if (\n !scalar ||\n (\"derived\" in scalar && (scalar.derived === \"sync\" || scalar.derived === \"async\")) ||\n (\"lazy\" in scalar && scalar.lazy)\n ) {\n throw new Error(\n `assertUnchanged on ${meta.name}.${fieldName} requires a stored scalar field declared on this entity`,\n );\n }\n\n let base = meta;\n while (base.baseType) base = base.baseType;\n if (!base.updatedAt) {\n throw new Error(`assertUnchanged on ${meta.name}.${fieldName} requires an updatedAt version field`);\n }\n }\n}\n"],"mappings":";;;;;;;AAqCA,SAAgB,qBAAqB,QAAgB,QAAoB,MAA8B;CACrG,MAAM,EAAE,QAAQ,WAAW,WAAW,cAAc;CAEpD,8BAA8B,QAAQ,IAAI;CAC1C,MAAM,SAAS,eAAe,QAAQ,QAAQ,MAAM,eAAe;CAEnE,OAAO,OAAO,MAAM,CAAC,CAAC,SAAS,SAAS,KAAK,UAAU,CAAC;CAExD,MAAM,gBAAgB,KAAK,gBAAgB,IAAI,KAAK,cAAc,KAAK,KAAA;CAEvE,MAAM,uBAAuB,KAAK,kBAAkB,qBAAqB,KAAK,gBAAgB,MAAM;CACpG,MAAM,iBAAiB,KAAK,wBAAwB,2BAA2B,KAAK,sBAAsB,MAAM;CAChH,MAAM,gBAAgB,KAAK,wBAAwB,0BAA0B,KAAK,sBAAsB,KAAK;CAC7G,MAAM,mBAAmB,KAAK,WAAW,gBAAgB,KAAK,SAAS,KAAK;CAG5E,MAAM,uBAAuB,KAAK,gBAC9B,IAAI,cACJ,IAAI;;mBAES,EAAE,WAAW,SAAS,EAAE;mBACxB,EAAE,WAAW,SAAS,EAAE;mBACxB,EAAE,WAAW,SAAS,EAAE;;;CAGzC,MAAM,sBAAsB,KAAK,uBAAuB,IAAI,uBAAuB,KAAK,mBAAmB,KAAK;CAChH,MAAM,WAAW,YAAY,QAAQ,IAAI;CACzC,MAAM,gBAAgB,SAAS,SAAS,IAAI,IAAI,aAAa,KAAK,UAAU,QAAQ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3
- "version": "2.4.0-next.41",
3
+ "version": "2.4.0-next.43",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {
@@ -48,12 +48,12 @@
48
48
  "skills"
49
49
  ],
50
50
  "peerDependencies": {
51
- "joist-utils": "2.4.0-next.41",
51
+ "joist-utils": "2.4.0-next.43",
52
52
  "knex": "^3.1.0",
53
53
  "pg": "^8.23.0"
54
54
  },
55
55
  "dependencies": {
56
- "@dprint/formatter": "^0.5.1",
56
+ "@dprint/formatter": "^0.6.0",
57
57
  "@dprint/json": "^0.25.2",
58
58
  "@inquirer/prompts": "^8.7.3",
59
59
  "@types/jscodeshift": "^17.3.0",
@@ -65,7 +65,7 @@
65
65
  "pluralize": "^8.0.0",
66
66
  "prettier": "^3.9.10",
67
67
  "ts-poet": "^6.12.0",
68
- "zod": "^4.6.5"
68
+ "zod": "^4.6.7"
69
69
  },
70
70
  "devDependencies": {
71
71
  "@swc/jest": "^0.2.39",