joist-core 2.3.0-next.81 → 2.3.0-next.83

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.
@@ -41,7 +41,7 @@ function addInserts(ops, todo, fixups) {
41
41
  const meta = todo.metadata;
42
42
  if (meta.subTypes.length > 0) {
43
43
  if (meta.inheritanceType === "cti") for (const [meta, group] of groupEntitiesByTable(todo.inserts)) ops.inserts.push(newInsertOp(meta, group, fixups));
44
- else if (meta.inheritanceType === "sti") ops.inserts.push(newStiInsertOp(meta, todo.inserts, fixups));
44
+ else if (meta.inheritanceType === "sti") for (const group of require_utils.groupBy(todo.inserts, (e) => require_EntityMetadata.getMetadata(e)).values()) ops.inserts.push(newStiInsertOp(meta, group, fixups));
45
45
  else throw new Error(`Found ${meta.tableName} subTypes without a known inheritanceType ${meta.inheritanceType}`);
46
46
  } else ops.inserts.push(newInsertOp(meta, todo.inserts, fixups));
47
47
  }
@@ -56,11 +56,7 @@ function newInsertOp(meta, entities, fixups) {
56
56
  };
57
57
  }
58
58
  function newStiInsertOp(root, entities, fixups) {
59
- const subTypes = /* @__PURE__ */ new Set();
60
- for (const e of entities) subTypes.add(require_EntityMetadata.getMetadata(e));
61
- const fields = Object.values(root.fields);
62
- for (const st of subTypes) for (const f of Object.values(st.fields)) if (!fields.some((f2) => f2.fieldName === f.fieldName)) fields.push(f);
63
- const columns = fields.filter(require_fieldSerde.hasSerde).flatMap((f) => f.serde.columns);
59
+ const columns = Object.values(require_EntityMetadata.getMetadata(entities[0]).allFields).filter(require_fieldSerde.hasSerde).flatMap((f) => f.serde.columns);
64
60
  const columnValues = collectBindings(entities, root.tableName, columns, fixups);
65
61
  return {
66
62
  tableName: root.tableName,
@@ -1 +1 @@
1
- {"version":3,"file":"EntityWriter.cjs","names":["hasSerde","getMetadata","getInstanceData","isChangeableField","getBaseSelfAndSubMetas","keyToNumber","getBaseAndSelfMetas"],"sources":["../../src/drivers/EntityWriter.ts"],"sourcesContent":["import { getInstanceData } from \"../BaseEntity.ts\";\nimport { type Entity } from \"../Entity.ts\";\nimport {\n type EntityMetadata,\n type Field,\n type PrimitiveField,\n getBaseAndSelfMetas,\n getBaseSelfAndSubMetas,\n getMetadata,\n} from \"../EntityMetadata.ts\";\nimport { getField, isChangeableField } from \"../fields.ts\";\nimport { type FieldColumn, type TimestampSerde, hasSerde } from \"../fieldSerde.ts\";\nimport { keyToNumber } from \"../keys.ts\";\nimport { type Todo } from \"../Todo.ts\";\nimport { groupBy } from \"../utils.ts\";\n\n/** A simplified view of columns, with only the keys necessary to create SQL statements. */\nexport type OpColumn = { columnName: string; dbType: string; isNullableArray?: boolean };\nexport type InsertOp = { tableName: string; columns: OpColumn[]; columnValues: any[][] };\n/**\n * A logical `update` operation.\n *\n * If we're using op locks, `columns` will include both the new `updatedAt` value (as bumped\n * by the `EntityManager` on mutate), as well as an extra/last \"original updated at\" column\n * (with respective pre-update values in the `rows` data), for including in the conditional\n * update clause.\n */\nexport type UpdateOp = {\n tableName: string;\n columns: OpColumn[];\n columnValues: any[][];\n updatedAt: string | undefined;\n};\nexport type DeleteOp = { tableName: string; ids: any[] };\n\ntype Ops = { inserts: InsertOp[]; updates: UpdateOp[]; deletes: DeleteOp[] };\n\n/**\n * In schemas with entity FK cycles, we may insert a dummy/null value, and later fix it up\n * before the transaction commits.\n *\n * I.e. `INSERT author.favorite_book_id` as `NULL` and then later do an `UPDATE author\n * SET favorite_book_id = 1` after the book has been inserted/we have the id.\n */\nexport type InsertFixup = {\n entity: Entity;\n tableName: string;\n column: OpColumn;\n value: any;\n};\n\n/**\n * Builds AST-ish `Ops` for the inserts/updates/deletes in `todos`.\n *\n * This helps decouple the database-specific driver/library from the knowledge\n * of turning entities into table operations, i.e. so they can be unaware of\n * complexities like field -> column mapping, oplocks, and class table inheritance.\n *\n * We still assume Postgres b/c we assume all ids have been pre-assigned for INSERTs,\n * and don't do any topological sorting of cross-row FK dependencies.\n *\n * But this should let us experiment with knex vs. raw client/etc.\n */\nexport function generateOps(todos: Record<string, Todo>): Ops {\n const ops: Ops = { inserts: [], updates: [], deletes: [] };\n const fixups: InsertFixup[] = [];\n // Would be nice to conditionally sort\n const sorted = Object.values(todos).sort(\n (a, b) => (a.metadata.nonDeferredFkOrder ?? 0) - (b.metadata.nonDeferredFkOrder ?? 0),\n );\n for (const todo of sorted) {\n addInserts(ops, todo, fixups);\n addUpdates(ops, todo);\n addDeletes(ops, todo);\n }\n if (fixups.length > 0) translateFixupsIntoUpdates(ops, fixups);\n return ops;\n}\n\nfunction addInserts(ops: Ops, todo: Todo, fixups: InsertFixup[]): void {\n if (todo.inserts.length > 0) {\n // If we have subtypes, this todo.metadata will always be the base type\n const meta = todo.metadata;\n if (meta.subTypes.length > 0) {\n if (meta.inheritanceType === \"cti\") {\n // Insert into each of the CTI tables\n for (const [meta, group] of groupEntitiesByTable(todo.inserts)) {\n ops.inserts.push(newInsertOp(meta, group, fixups));\n }\n } else if (meta.inheritanceType === \"sti\") {\n ops.inserts.push(newStiInsertOp(meta, todo.inserts, fixups));\n } else {\n throw new Error(`Found ${meta.tableName} subTypes without a known inheritanceType ${meta.inheritanceType}`);\n }\n } else {\n ops.inserts.push(newInsertOp(meta, todo.inserts, fixups));\n }\n }\n}\n\nfunction newInsertOp(meta: EntityMetadata, entities: Entity[], fixups: InsertFixup[]): InsertOp {\n // Purposefully use `meta.fields` instead of `allFields` b/c each CTI table has its own `InsertOp`\n const columns = Object.values(meta.fields)\n .filter(hasSerde)\n .flatMap((f) => f.serde.columns);\n const columnValues = collectBindings(entities, meta.tableName, columns, fixups);\n return { tableName: meta.tableName, columns, columnValues };\n}\n\nfunction newStiInsertOp(root: EntityMetadata, entities: Entity[], fixups: InsertFixup[]): InsertOp {\n // Get the unique set of subtypes\n const subTypes = new Set<EntityMetadata>();\n for (const e of entities) subTypes.add(getMetadata(e));\n // All the root fields (including id)\n const fields: Field[] = Object.values(root.fields);\n // Then the subtype fields that haven't been seen yet (subtypes have the root fields + can share non-root fields)\n for (const st of subTypes) {\n for (const f of Object.values(st.fields)) {\n if (!fields.some((f2) => f2.fieldName === f.fieldName)) {\n fields.push(f);\n }\n }\n }\n const columns = fields.filter(hasSerde).flatMap((f) => f.serde.columns);\n // And then collect the same bindings across each STI\n const columnValues = collectBindings(entities, root.tableName, columns, fixups);\n return { tableName: root.tableName, columns, columnValues };\n}\n\nfunction addUpdates(ops: Ops, todo: Todo): void {\n if (todo.updates.length > 0) {\n const meta = todo.metadata;\n if (meta.subTypes.length > 0) {\n if (meta.inheritanceType === \"cti\") {\n for (const [meta, group] of groupEntitiesByTable(todo.updates)) {\n const op = newUpdateOp(meta, group);\n if (op) ops.updates.push(op);\n addLazyUpdates(ops, meta, group);\n }\n } else if (meta.inheritanceType === \"sti\") {\n const op = newUpdateOp(meta, todo.updates);\n if (op) ops.updates.push(op);\n addLazyUpdates(ops, meta, todo.updates);\n } else {\n throw new Error(`Found ${meta.tableName} subTypes without a known inheritanceType ${meta.inheritanceType}`);\n }\n } else {\n const op = newUpdateOp(meta, todo.updates);\n if (op) ops.updates.push(op);\n addLazyUpdates(ops, meta, todo.updates);\n }\n }\n}\n\n/**\n * Writes changed `lazy` columns via a targeted `UPDATE table SET lazy_col = ... WHERE id in (...)`.\n *\n * Lazy columns are excluded from the main batch UPDATE (which spans the batch's union of changed fields),\n * so that entities in the batch that never loaded a lazy column keep their existing db value instead of\n * being overwritten with null. Here we write each lazy column only for the entities that actually changed it.\n */\nfunction addLazyUpdates(ops: Ops, meta: EntityMetadata, entities: Entity[]): void {\n const idColumn = meta.fields[\"id\"].serde!.columns[0];\n for (const fieldName of meta.lazyFieldNames!) {\n const field = meta.fields[fieldName];\n if (!hasSerde(field)) continue;\n const changed = entities.filter((e) => fieldName in getInstanceData(e).changedData);\n if (changed.length === 0) continue;\n const columns: BindingColumn[] = [idColumn, ...field.serde.columns];\n const columnValues = collectBindings(changed, meta.tableName, columns, undefined);\n ops.updates.push({ tableName: meta.tableName, columns, columnValues, updatedAt: undefined });\n }\n}\n\nfunction newUpdateOp(meta: EntityMetadata, entities: Entity[]): UpdateOp | undefined {\n // We only include changed fields in our `UPDATE`--maybe we could change this\n // to always use the same fields, to take advantage of Prepared Statements.\n const changedFields = new Set<string>();\n for (const entity of entities) {\n for (const fieldName in getInstanceData(entity).changedData) changedFields.add(fieldName);\n }\n // Sometimes with derived fields, an instance will be marked as an update, but if the derived field hasn't\n // actually changed, it'll be a noop, so just short-circuit if it looks like that happened. Unless touched.\n if (changedFields.size === 0 && !entities.some((e) => getInstanceData(e).isTouched)) {\n return undefined;\n }\n\n // We may have loaded a1 and a2, and changed a1.firstName, and a2.lastName, but either one\n // might be missing the other's changed fields in it's lazy-initialized data field...\n // (Use `?` because subtypes won't have the updatedAt, and it will be handled by the base type\n // `newUpdateUp`--except STI where we're doing it all in one go, probably needs checked here.)\n const updatedAt = meta.timestampFields?.updatedAt;\n changedFields.add(\"id\");\n if (updatedAt) changedFields.add(updatedAt);\n // `lazy` columns are deliberately excluded from the batch UPDATE and written by `addLazyUpdates`; an\n // entity that never loaded a lazy column isn't in `row`, so forcing `getField` here would clobber it to null.\n const lazyFieldNames = meta.lazyFieldNames!;\n for (const entity of entities) {\n const { data } = getInstanceData(entity);\n for (const key of changedFields) {\n // Check isChangeableField because we might be updating the base `publishers` table\n // and `originalData` might have fields from a subclass `large_publishers` table.\n if (!(key in data) && isChangeableField(entity, key) && !lazyFieldNames.has(key)) {\n getField(entity, key);\n }\n }\n }\n\n const columns: Array<BindingColumn> = (\n meta.inheritanceType === \"sti\"\n ? // Hack this one handling of STI into here...\n getBaseSelfAndSubMetas(meta).flatMap((meta) =>\n meta.stiDiscriminatorField\n ? Object.values(meta.fields)\n : Object.values(meta.fields).filter((f) => f.fieldName !== \"id\"),\n )\n : Object.values(meta.fields)\n )\n .filter((f) => changedFields.has(f.fieldName))\n .filter((f) => !lazyFieldNames.has(f.fieldName))\n .filter(hasSerde)\n .flatMap((f) => f.serde.columns);\n\n // If we're using class table inheritance, base/child tables may not have any columns to update\n if (columns.length === 1) {\n return undefined;\n }\n\n // We already have the bumped updated_at column, but also include the original updated_at for the data CTE\n if (updatedAt) {\n const serde = meta.fields[updatedAt].serde as TimestampSerde<unknown>;\n columns.push({\n columnName: \"__original_updated_at\",\n dbType: \"timestamptz\",\n dbValue: (_, entity) => serde.dbValue(getInstanceData(entity).originalData),\n });\n }\n\n const columnValues = collectBindings(entities, meta.tableName, columns, []);\n const updatedAtColumn = updatedAt ? (meta.fields[updatedAt] as PrimitiveField).serde.columns[0] : undefined;\n return { tableName: meta.tableName, columns, updatedAt: updatedAtColumn?.columnName, columnValues };\n}\n\nfunction addDeletes(ops: Ops, todo: Todo): void {\n if (todo.deletes.length > 0) {\n const meta = todo.metadata;\n const ids = todo.deletes.map((e) => keyToNumber(meta, e.idTagged!).toString());\n if (meta.subTypes.length > 0) {\n getBaseSelfAndSubMetas(meta).forEach((meta) => {\n ops.deletes.push({ tableName: meta.tableName, ids });\n });\n } else {\n ops.deletes.push({ tableName: meta.tableName, ids });\n }\n }\n}\n\nfunction groupEntitiesByTable(entities: Entity[]): Array<[EntityMetadata, Entity[]]> {\n const entitiesByType: Map<EntityMetadata, Entity[]> = new Map();\n for (const e of entities) {\n for (const m of getBaseAndSelfMetas(getMetadata(e))) {\n let list = entitiesByType.get(m);\n if (!list) {\n list = [];\n entitiesByType.set(m, list);\n }\n list.push(e);\n }\n }\n return [...entitiesByType.entries()];\n}\n\ntype BindingColumn = OpColumn & Pick<FieldColumn, \"dbValue\">;\ntype EntityWithData = Entity & { __data: { data: Record<string, unknown> } };\n\n/**\n * Builds a *columnar* array of bindings for the given `entities` and `columns`.\n *\n * We use a columnar approach, instead of `rows[]`, to best match the unnest-based\n * column operations in our `batchInsert` / `batchUpdate` SQL statements.\n */\nfunction collectBindings(\n entities: Entity[],\n tableName: string,\n columns: BindingColumn[],\n fixups: InsertFixup[] | undefined,\n): any[][] {\n const entityCount = entities.length;\n const bindings: any[][] = new Array(columns.length);\n const entitiesWithData = entities as EntityWithData[];\n // Cache data separately; this benchmarks faster than `entities[i].__data.data` in the inner loop.\n const entityData = new Array(entityCount);\n for (let i = 0; i < entityCount; i++) entityData[i] = entitiesWithData[i].__data.data;\n for (let columnIndex = 0; columnIndex < columns.length; columnIndex++) {\n const column = columns[columnIndex];\n const columnValues: any[] = new Array(entityCount);\n for (let entityIndex = 0; entityIndex < entityCount; entityIndex++) {\n columnValues[entityIndex] =\n column.dbValue(entityData[entityIndex], entities[entityIndex], tableName, fixups) ?? null;\n }\n bindings[columnIndex] = columnValues;\n }\n return bindings;\n}\n/**\n * Given `fixups` that indicate where we inserted `NULL` into non-deferred FKs, create `UPDATE`s\n * that insert the value now that the FK check will succeed.\n */\nfunction translateFixupsIntoUpdates(ops: Ops, fixups: InsertFixup[]): void {\n // Create a single `UPDATE` for the N fixups we might have for each table/column combination\n groupBy(fixups, (f) => `${f.tableName}.${f.column.columnName}`).forEach((fixups) => {\n const { tableName, entity, column } = fixups[0];\n ops.updates.push({\n tableName,\n columns: [getMetadata(entity).fields[\"id\"].serde!.columns[0], column],\n columnValues: [\n // Make 1 column of ids, and 1 column of values\n fixups.map((fixup) => fixup.entity.id),\n fixups.map((fixup) => fixup.value),\n ],\n updatedAt: undefined,\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA+DA,SAAgB,YAAY,OAAkC;CAC5D,MAAM,MAAW;EAAE,SAAS,CAAC;EAAG,SAAS,CAAC;EAAG,SAAS,CAAC;CAAE;CACzD,MAAM,SAAwB,CAAC;CAE/B,MAAM,SAAS,OAAO,OAAO,KAAK,CAAC,CAAC,MACjC,GAAG,OAAO,EAAE,SAAS,sBAAsB,MAAM,EAAE,SAAS,sBAAsB,EACrF;CACA,KAAK,MAAM,QAAQ,QAAQ;EACzB,WAAW,KAAK,MAAM,MAAM;EAC5B,WAAW,KAAK,IAAI;EACpB,WAAW,KAAK,IAAI;CACtB;CACA,IAAI,OAAO,SAAS,GAAG,2BAA2B,KAAK,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P,UACA,WACA,SACA,QACS;CACT,MAAM,cAAc,SAAS;CAC7B,MAAM,WAAoB,IAAI,MAAM,QAAQ,MAAM;CAClD,MAAM,mBAAmB;CAEzB,MAAM,aAAa,IAAI,MAAM,WAAW;CACxC,KAAK,IAAI,IAAI,GAAG,IAAI,aAAa,KAAK,WAAW,KAAK,iBAAiB,EAAE,CAAC,OAAO;CACjF,KAAK,IAAI,cAAc,GAAG,cAAc,QAAQ,QAAQ,eAAe;EACrE,MAAM,SAAS,QAAQ;EACvB,MAAM,eAAsB,IAAI,MAAM,WAAW;EACjD,KAAK,IAAI,cAAc,GAAG,cAAc,aAAa,eACnD,aAAa,eACX,OAAO,QAAQ,WAAW,cAAc,SAAS,cAAc,WAAW,MAAM,KAAK;EAEzF,SAAS,eAAe;CAC1B;CACA,OAAO;AACT;;;;;AAKA,SAAS,2BAA2B,KAAU,QAA6B;CAEzE,cAAA,QAAQ,SAAS,MAAM,GAAG,EAAE,UAAU,GAAG,EAAE,OAAO,YAAY,CAAC,CAAC,SAAS,WAAW;EAClF,MAAM,EAAE,WAAW,QAAQ,WAAW,OAAO;EAC7C,IAAI,QAAQ,KAAK;GACf;GACA,SAAS,CAACA,uBAAAA,YAAY,MAAM,CAAC,CAAC,OAAO,KAAK,CAAC,MAAO,QAAQ,IAAI,MAAM;GACpE,cAAc,CAEZ,OAAO,KAAK,UAAU,MAAM,OAAO,EAAE,GACrC,OAAO,KAAK,UAAU,MAAM,KAAK,CACnC;GACA,WAAW,KAAA;EACb,CAAC;CACH,CAAC;AACH"}
1
+ {"version":3,"file":"EntityWriter.cjs","names":["groupBy","getMetadata","hasSerde","getInstanceData","isChangeableField","getBaseSelfAndSubMetas","keyToNumber","getBaseAndSelfMetas"],"sources":["../../src/drivers/EntityWriter.ts"],"sourcesContent":["import { getInstanceData } from \"../BaseEntity.ts\";\nimport { type Entity } from \"../Entity.ts\";\nimport {\n type EntityMetadata,\n type Field,\n type PrimitiveField,\n getBaseAndSelfMetas,\n getBaseSelfAndSubMetas,\n getMetadata,\n} from \"../EntityMetadata.ts\";\nimport { getField, isChangeableField } from \"../fields.ts\";\nimport { type FieldColumn, type TimestampSerde, hasSerde } from \"../fieldSerde.ts\";\nimport { keyToNumber } from \"../keys.ts\";\nimport { type Todo } from \"../Todo.ts\";\nimport { groupBy } from \"../utils.ts\";\n\n/** A simplified view of columns, with only the keys necessary to create SQL statements. */\nexport type OpColumn = { columnName: string; dbType: string; isNullableArray?: boolean };\nexport type InsertOp = { tableName: string; columns: OpColumn[]; columnValues: any[][] };\n/**\n * A logical `update` operation.\n *\n * If we're using op locks, `columns` will include both the new `updatedAt` value (as bumped\n * by the `EntityManager` on mutate), as well as an extra/last \"original updated at\" column\n * (with respective pre-update values in the `rows` data), for including in the conditional\n * update clause.\n */\nexport type UpdateOp = {\n tableName: string;\n columns: OpColumn[];\n columnValues: any[][];\n updatedAt: string | undefined;\n};\nexport type DeleteOp = { tableName: string; ids: any[] };\n\ntype Ops = { inserts: InsertOp[]; updates: UpdateOp[]; deletes: DeleteOp[] };\n\n/**\n * In schemas with entity FK cycles, we may insert a dummy/null value, and later fix it up\n * before the transaction commits.\n *\n * I.e. `INSERT author.favorite_book_id` as `NULL` and then later do an `UPDATE author\n * SET favorite_book_id = 1` after the book has been inserted/we have the id.\n */\nexport type InsertFixup = {\n entity: Entity;\n tableName: string;\n column: OpColumn;\n value: any;\n};\n\n/**\n * Builds AST-ish `Ops` for the inserts/updates/deletes in `todos`.\n *\n * This helps decouple the database-specific driver/library from the knowledge\n * of turning entities into table operations, i.e. so they can be unaware of\n * complexities like field -> column mapping, oplocks, and class table inheritance.\n *\n * We still assume Postgres b/c we assume all ids have been pre-assigned for INSERTs,\n * and don't do any topological sorting of cross-row FK dependencies.\n *\n * But this should let us experiment with knex vs. raw client/etc.\n */\nexport function generateOps(todos: Record<string, Todo>): Ops {\n const ops: Ops = { inserts: [], updates: [], deletes: [] };\n const fixups: InsertFixup[] = [];\n // Would be nice to conditionally sort\n const sorted = Object.values(todos).sort(\n (a, b) => (a.metadata.nonDeferredFkOrder ?? 0) - (b.metadata.nonDeferredFkOrder ?? 0),\n );\n for (const todo of sorted) {\n addInserts(ops, todo, fixups);\n addUpdates(ops, todo);\n addDeletes(ops, todo);\n }\n if (fixups.length > 0) translateFixupsIntoUpdates(ops, fixups);\n return ops;\n}\n\nfunction addInserts(ops: Ops, todo: Todo, fixups: InsertFixup[]): void {\n if (todo.inserts.length > 0) {\n // If we have subtypes, this todo.metadata will always be the base type\n const meta = todo.metadata;\n if (meta.subTypes.length > 0) {\n if (meta.inheritanceType === \"cti\") {\n // Insert into each of the CTI tables\n for (const [meta, group] of groupEntitiesByTable(todo.inserts)) {\n ops.inserts.push(newInsertOp(meta, group, fixups));\n }\n } else if (meta.inheritanceType === \"sti\") {\n // One INSERT per subtype, so each statement's column list spans exactly what that subtype can\n // set. A single statement across subtypes has to bind NULL for the other subtypes' columns,\n // which defeats their database defaults, and outright fails for notNull ones.\n for (const group of groupBy(todo.inserts, (e) => getMetadata(e)).values()) {\n ops.inserts.push(newStiInsertOp(meta, group, fixups));\n }\n } else {\n throw new Error(`Found ${meta.tableName} subTypes without a known inheritanceType ${meta.inheritanceType}`);\n }\n } else {\n ops.inserts.push(newInsertOp(meta, todo.inserts, fixups));\n }\n }\n}\n\nfunction newInsertOp(meta: EntityMetadata, entities: Entity[], fixups: InsertFixup[]): InsertOp {\n // Purposefully use `meta.fields` instead of `allFields` b/c each CTI table has its own `InsertOp`\n const columns = Object.values(meta.fields)\n .filter(hasSerde)\n .flatMap((f) => f.serde.columns);\n const columnValues = collectBindings(entities, meta.tableName, columns, fixups);\n return { tableName: meta.tableName, columns, columnValues };\n}\n\nfunction newStiInsertOp(root: EntityMetadata, entities: Entity[], fixups: InsertFixup[]): InsertOp {\n // `allFields` is the base's fields plus this subtype's own, i.e. everything this subtype can write.\n // Anything it can't write is left out of the statement entirely, so the database applies its default.\n const fields: Field[] = Object.values(getMetadata(entities[0]).allFields);\n const columns = fields.filter(hasSerde).flatMap((f) => f.serde.columns);\n const columnValues = collectBindings(entities, root.tableName, columns, fixups);\n return { tableName: root.tableName, columns, columnValues };\n}\n\nfunction addUpdates(ops: Ops, todo: Todo): void {\n if (todo.updates.length > 0) {\n const meta = todo.metadata;\n if (meta.subTypes.length > 0) {\n if (meta.inheritanceType === \"cti\") {\n for (const [meta, group] of groupEntitiesByTable(todo.updates)) {\n const op = newUpdateOp(meta, group);\n if (op) ops.updates.push(op);\n addLazyUpdates(ops, meta, group);\n }\n } else if (meta.inheritanceType === \"sti\") {\n const op = newUpdateOp(meta, todo.updates);\n if (op) ops.updates.push(op);\n addLazyUpdates(ops, meta, todo.updates);\n } else {\n throw new Error(`Found ${meta.tableName} subTypes without a known inheritanceType ${meta.inheritanceType}`);\n }\n } else {\n const op = newUpdateOp(meta, todo.updates);\n if (op) ops.updates.push(op);\n addLazyUpdates(ops, meta, todo.updates);\n }\n }\n}\n\n/**\n * Writes changed `lazy` columns via a targeted `UPDATE table SET lazy_col = ... WHERE id in (...)`.\n *\n * Lazy columns are excluded from the main batch UPDATE (which spans the batch's union of changed fields),\n * so that entities in the batch that never loaded a lazy column keep their existing db value instead of\n * being overwritten with null. Here we write each lazy column only for the entities that actually changed it.\n */\nfunction addLazyUpdates(ops: Ops, meta: EntityMetadata, entities: Entity[]): void {\n const idColumn = meta.fields[\"id\"].serde!.columns[0];\n for (const fieldName of meta.lazyFieldNames!) {\n const field = meta.fields[fieldName];\n if (!hasSerde(field)) continue;\n const changed = entities.filter((e) => fieldName in getInstanceData(e).changedData);\n if (changed.length === 0) continue;\n const columns: BindingColumn[] = [idColumn, ...field.serde.columns];\n const columnValues = collectBindings(changed, meta.tableName, columns, undefined);\n ops.updates.push({ tableName: meta.tableName, columns, columnValues, updatedAt: undefined });\n }\n}\n\nfunction newUpdateOp(meta: EntityMetadata, entities: Entity[]): UpdateOp | undefined {\n // We only include changed fields in our `UPDATE`--maybe we could change this\n // to always use the same fields, to take advantage of Prepared Statements.\n const changedFields = new Set<string>();\n for (const entity of entities) {\n for (const fieldName in getInstanceData(entity).changedData) changedFields.add(fieldName);\n }\n // Sometimes with derived fields, an instance will be marked as an update, but if the derived field hasn't\n // actually changed, it'll be a noop, so just short-circuit if it looks like that happened. Unless touched.\n if (changedFields.size === 0 && !entities.some((e) => getInstanceData(e).isTouched)) {\n return undefined;\n }\n\n // We may have loaded a1 and a2, and changed a1.firstName, and a2.lastName, but either one\n // might be missing the other's changed fields in it's lazy-initialized data field...\n // (Use `?` because subtypes won't have the updatedAt, and it will be handled by the base type\n // `newUpdateUp`--except STI where we're doing it all in one go, probably needs checked here.)\n const updatedAt = meta.timestampFields?.updatedAt;\n changedFields.add(\"id\");\n if (updatedAt) changedFields.add(updatedAt);\n // `lazy` columns are deliberately excluded from the batch UPDATE and written by `addLazyUpdates`; an\n // entity that never loaded a lazy column isn't in `row`, so forcing `getField` here would clobber it to null.\n const lazyFieldNames = meta.lazyFieldNames!;\n for (const entity of entities) {\n const { data } = getInstanceData(entity);\n for (const key of changedFields) {\n // Check isChangeableField because we might be updating the base `publishers` table\n // and `originalData` might have fields from a subclass `large_publishers` table.\n if (!(key in data) && isChangeableField(entity, key) && !lazyFieldNames.has(key)) {\n getField(entity, key);\n }\n }\n }\n\n const columns: Array<BindingColumn> = (\n meta.inheritanceType === \"sti\"\n ? // Hack this one handling of STI into here...\n getBaseSelfAndSubMetas(meta).flatMap((meta) =>\n meta.stiDiscriminatorField\n ? Object.values(meta.fields)\n : Object.values(meta.fields).filter((f) => f.fieldName !== \"id\"),\n )\n : Object.values(meta.fields)\n )\n .filter((f) => changedFields.has(f.fieldName))\n .filter((f) => !lazyFieldNames.has(f.fieldName))\n .filter(hasSerde)\n .flatMap((f) => f.serde.columns);\n\n // If we're using class table inheritance, base/child tables may not have any columns to update\n if (columns.length === 1) {\n return undefined;\n }\n\n // We already have the bumped updated_at column, but also include the original updated_at for the data CTE\n if (updatedAt) {\n const serde = meta.fields[updatedAt].serde as TimestampSerde<unknown>;\n columns.push({\n columnName: \"__original_updated_at\",\n dbType: \"timestamptz\",\n dbValue: (_, entity) => serde.dbValue(getInstanceData(entity).originalData),\n });\n }\n\n const columnValues = collectBindings(entities, meta.tableName, columns, []);\n const updatedAtColumn = updatedAt ? (meta.fields[updatedAt] as PrimitiveField).serde.columns[0] : undefined;\n return { tableName: meta.tableName, columns, updatedAt: updatedAtColumn?.columnName, columnValues };\n}\n\nfunction addDeletes(ops: Ops, todo: Todo): void {\n if (todo.deletes.length > 0) {\n const meta = todo.metadata;\n const ids = todo.deletes.map((e) => keyToNumber(meta, e.idTagged!).toString());\n if (meta.subTypes.length > 0) {\n getBaseSelfAndSubMetas(meta).forEach((meta) => {\n ops.deletes.push({ tableName: meta.tableName, ids });\n });\n } else {\n ops.deletes.push({ tableName: meta.tableName, ids });\n }\n }\n}\n\nfunction groupEntitiesByTable(entities: Entity[]): Array<[EntityMetadata, Entity[]]> {\n const entitiesByType: Map<EntityMetadata, Entity[]> = new Map();\n for (const e of entities) {\n for (const m of getBaseAndSelfMetas(getMetadata(e))) {\n let list = entitiesByType.get(m);\n if (!list) {\n list = [];\n entitiesByType.set(m, list);\n }\n list.push(e);\n }\n }\n return [...entitiesByType.entries()];\n}\n\ntype BindingColumn = OpColumn & Pick<FieldColumn, \"dbValue\">;\ntype EntityWithData = Entity & { __data: { data: Record<string, unknown> } };\n\n/**\n * Builds a *columnar* array of bindings for the given `entities` and `columns`.\n *\n * We use a columnar approach, instead of `rows[]`, to best match the unnest-based\n * column operations in our `batchInsert` / `batchUpdate` SQL statements.\n */\nfunction collectBindings(\n entities: Entity[],\n tableName: string,\n columns: BindingColumn[],\n fixups: InsertFixup[] | undefined,\n): any[][] {\n const entityCount = entities.length;\n const bindings: any[][] = new Array(columns.length);\n const entitiesWithData = entities as EntityWithData[];\n // Cache data separately; this benchmarks faster than `entities[i].__data.data` in the inner loop.\n const entityData = new Array(entityCount);\n for (let i = 0; i < entityCount; i++) entityData[i] = entitiesWithData[i].__data.data;\n for (let columnIndex = 0; columnIndex < columns.length; columnIndex++) {\n const column = columns[columnIndex];\n const columnValues: any[] = new Array(entityCount);\n for (let entityIndex = 0; entityIndex < entityCount; entityIndex++) {\n columnValues[entityIndex] =\n column.dbValue(entityData[entityIndex], entities[entityIndex], tableName, fixups) ?? null;\n }\n bindings[columnIndex] = columnValues;\n }\n return bindings;\n}\n/**\n * Given `fixups` that indicate where we inserted `NULL` into non-deferred FKs, create `UPDATE`s\n * that insert the value now that the FK check will succeed.\n */\nfunction translateFixupsIntoUpdates(ops: Ops, fixups: InsertFixup[]): void {\n // Create a single `UPDATE` for the N fixups we might have for each table/column combination\n groupBy(fixups, (f) => `${f.tableName}.${f.column.columnName}`).forEach((fixups) => {\n const { tableName, entity, column } = fixups[0];\n ops.updates.push({\n tableName,\n columns: [getMetadata(entity).fields[\"id\"].serde!.columns[0], column],\n columnValues: [\n // Make 1 column of ids, and 1 column of values\n fixups.map((fixup) => fixup.entity.id),\n fixups.map((fixup) => fixup.value),\n ],\n updatedAt: undefined,\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA+DA,SAAgB,YAAY,OAAkC;CAC5D,MAAM,MAAW;EAAE,SAAS,CAAC;EAAG,SAAS,CAAC;EAAG,SAAS,CAAC;CAAE;CACzD,MAAM,SAAwB,CAAC;CAE/B,MAAM,SAAS,OAAO,OAAO,KAAK,CAAC,CAAC,MACjC,GAAG,OAAO,EAAE,SAAS,sBAAsB,MAAM,EAAE,SAAS,sBAAsB,EACrF;CACA,KAAK,MAAM,QAAQ,QAAQ;EACzB,WAAW,KAAK,MAAM,MAAM;EAC5B,WAAW,KAAK,IAAI;EACpB,WAAW,KAAK,IAAI;CACtB;CACA,IAAI,OAAO,SAAS,GAAG,2BAA2B,KAAK,MAAM;CAC7D,OAAO;AACT;AAEA,SAAS,WAAW,KAAU,MAAY,QAA6B;CACrE,IAAI,KAAK,QAAQ,SAAS,GAAG;EAE3B,MAAM,OAAO,KAAK;EAClB,IA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Q,QAAQ,eAAe;EACrE,MAAM,SAAS,QAAQ;EACvB,MAAM,eAAsB,IAAI,MAAM,WAAW;EACjD,KAAK,IAAI,cAAc,GAAG,cAAc,aAAa,eACnD,aAAa,eACX,OAAO,QAAQ,WAAW,cAAc,SAAS,cAAc,WAAW,MAAM,KAAK;EAEzF,SAAS,eAAe;CAC1B;CACA,OAAO;AACT;;;;;AAKA,SAAS,2BAA2B,KAAU,QAA6B;CAEzE,cAAA,QAAQ,SAAS,MAAM,GAAG,EAAE,UAAU,GAAG,EAAE,OAAO,YAAY,CAAC,CAAC,SAAS,WAAW;EAClF,MAAM,EAAE,WAAW,QAAQ,WAAW,OAAO;EAC7C,IAAI,QAAQ,KAAK;GACf;GACA,SAAS,CAACA,uBAAAA,YAAY,MAAM,CAAC,CAAC,OAAO,KAAK,CAAC,MAAO,QAAQ,IAAI,MAAM;GACpE,cAAc,CAEZ,OAAO,KAAK,UAAU,MAAM,OAAO,EAAE,GACrC,OAAO,KAAK,UAAU,MAAM,KAAK,CACnC;GACA,WAAW,KAAA;EACb,CAAC;CACH,CAAC;AACH"}
@@ -40,7 +40,7 @@ function addInserts(ops, todo, fixups) {
40
40
  const meta = todo.metadata;
41
41
  if (meta.subTypes.length > 0) {
42
42
  if (meta.inheritanceType === "cti") for (const [meta, group] of groupEntitiesByTable(todo.inserts)) ops.inserts.push(newInsertOp(meta, group, fixups));
43
- else if (meta.inheritanceType === "sti") ops.inserts.push(newStiInsertOp(meta, todo.inserts, fixups));
43
+ else if (meta.inheritanceType === "sti") for (const group of groupBy(todo.inserts, (e) => getMetadata(e)).values()) ops.inserts.push(newStiInsertOp(meta, group, fixups));
44
44
  else throw new Error(`Found ${meta.tableName} subTypes without a known inheritanceType ${meta.inheritanceType}`);
45
45
  } else ops.inserts.push(newInsertOp(meta, todo.inserts, fixups));
46
46
  }
@@ -55,11 +55,7 @@ function newInsertOp(meta, entities, fixups) {
55
55
  };
56
56
  }
57
57
  function newStiInsertOp(root, entities, fixups) {
58
- const subTypes = /* @__PURE__ */ new Set();
59
- for (const e of entities) subTypes.add(getMetadata(e));
60
- const fields = Object.values(root.fields);
61
- for (const st of subTypes) for (const f of Object.values(st.fields)) if (!fields.some((f2) => f2.fieldName === f.fieldName)) fields.push(f);
62
- const columns = fields.filter(hasSerde).flatMap((f) => f.serde.columns);
58
+ const columns = Object.values(getMetadata(entities[0]).allFields).filter(hasSerde).flatMap((f) => f.serde.columns);
63
59
  const columnValues = collectBindings(entities, root.tableName, columns, fixups);
64
60
  return {
65
61
  tableName: root.tableName,
@@ -1 +1 @@
1
- {"version":3,"file":"EntityWriter.js","names":[],"sources":["../../src/drivers/EntityWriter.ts"],"sourcesContent":["import { getInstanceData } from \"../BaseEntity.ts\";\nimport { type Entity } from \"../Entity.ts\";\nimport {\n type EntityMetadata,\n type Field,\n type PrimitiveField,\n getBaseAndSelfMetas,\n getBaseSelfAndSubMetas,\n getMetadata,\n} from \"../EntityMetadata.ts\";\nimport { getField, isChangeableField } from \"../fields.ts\";\nimport { type FieldColumn, type TimestampSerde, hasSerde } from \"../fieldSerde.ts\";\nimport { keyToNumber } from \"../keys.ts\";\nimport { type Todo } from \"../Todo.ts\";\nimport { groupBy } from \"../utils.ts\";\n\n/** A simplified view of columns, with only the keys necessary to create SQL statements. */\nexport type OpColumn = { columnName: string; dbType: string; isNullableArray?: boolean };\nexport type InsertOp = { tableName: string; columns: OpColumn[]; columnValues: any[][] };\n/**\n * A logical `update` operation.\n *\n * If we're using op locks, `columns` will include both the new `updatedAt` value (as bumped\n * by the `EntityManager` on mutate), as well as an extra/last \"original updated at\" column\n * (with respective pre-update values in the `rows` data), for including in the conditional\n * update clause.\n */\nexport type UpdateOp = {\n tableName: string;\n columns: OpColumn[];\n columnValues: any[][];\n updatedAt: string | undefined;\n};\nexport type DeleteOp = { tableName: string; ids: any[] };\n\ntype Ops = { inserts: InsertOp[]; updates: UpdateOp[]; deletes: DeleteOp[] };\n\n/**\n * In schemas with entity FK cycles, we may insert a dummy/null value, and later fix it up\n * before the transaction commits.\n *\n * I.e. `INSERT author.favorite_book_id` as `NULL` and then later do an `UPDATE author\n * SET favorite_book_id = 1` after the book has been inserted/we have the id.\n */\nexport type InsertFixup = {\n entity: Entity;\n tableName: string;\n column: OpColumn;\n value: any;\n};\n\n/**\n * Builds AST-ish `Ops` for the inserts/updates/deletes in `todos`.\n *\n * This helps decouple the database-specific driver/library from the knowledge\n * of turning entities into table operations, i.e. so they can be unaware of\n * complexities like field -> column mapping, oplocks, and class table inheritance.\n *\n * We still assume Postgres b/c we assume all ids have been pre-assigned for INSERTs,\n * and don't do any topological sorting of cross-row FK dependencies.\n *\n * But this should let us experiment with knex vs. raw client/etc.\n */\nexport function generateOps(todos: Record<string, Todo>): Ops {\n const ops: Ops = { inserts: [], updates: [], deletes: [] };\n const fixups: InsertFixup[] = [];\n // Would be nice to conditionally sort\n const sorted = Object.values(todos).sort(\n (a, b) => (a.metadata.nonDeferredFkOrder ?? 0) - (b.metadata.nonDeferredFkOrder ?? 0),\n );\n for (const todo of sorted) {\n addInserts(ops, todo, fixups);\n addUpdates(ops, todo);\n addDeletes(ops, todo);\n }\n if (fixups.length > 0) translateFixupsIntoUpdates(ops, fixups);\n return ops;\n}\n\nfunction addInserts(ops: Ops, todo: Todo, fixups: InsertFixup[]): void {\n if (todo.inserts.length > 0) {\n // If we have subtypes, this todo.metadata will always be the base type\n const meta = todo.metadata;\n if (meta.subTypes.length > 0) {\n if (meta.inheritanceType === \"cti\") {\n // Insert into each of the CTI tables\n for (const [meta, group] of groupEntitiesByTable(todo.inserts)) {\n ops.inserts.push(newInsertOp(meta, group, fixups));\n }\n } else if (meta.inheritanceType === \"sti\") {\n ops.inserts.push(newStiInsertOp(meta, todo.inserts, fixups));\n } else {\n throw new Error(`Found ${meta.tableName} subTypes without a known inheritanceType ${meta.inheritanceType}`);\n }\n } else {\n ops.inserts.push(newInsertOp(meta, todo.inserts, fixups));\n }\n }\n}\n\nfunction newInsertOp(meta: EntityMetadata, entities: Entity[], fixups: InsertFixup[]): InsertOp {\n // Purposefully use `meta.fields` instead of `allFields` b/c each CTI table has its own `InsertOp`\n const columns = Object.values(meta.fields)\n .filter(hasSerde)\n .flatMap((f) => f.serde.columns);\n const columnValues = collectBindings(entities, meta.tableName, columns, fixups);\n return { tableName: meta.tableName, columns, columnValues };\n}\n\nfunction newStiInsertOp(root: EntityMetadata, entities: Entity[], fixups: InsertFixup[]): InsertOp {\n // Get the unique set of subtypes\n const subTypes = new Set<EntityMetadata>();\n for (const e of entities) subTypes.add(getMetadata(e));\n // All the root fields (including id)\n const fields: Field[] = Object.values(root.fields);\n // Then the subtype fields that haven't been seen yet (subtypes have the root fields + can share non-root fields)\n for (const st of subTypes) {\n for (const f of Object.values(st.fields)) {\n if (!fields.some((f2) => f2.fieldName === f.fieldName)) {\n fields.push(f);\n }\n }\n }\n const columns = fields.filter(hasSerde).flatMap((f) => f.serde.columns);\n // And then collect the same bindings across each STI\n const columnValues = collectBindings(entities, root.tableName, columns, fixups);\n return { tableName: root.tableName, columns, columnValues };\n}\n\nfunction addUpdates(ops: Ops, todo: Todo): void {\n if (todo.updates.length > 0) {\n const meta = todo.metadata;\n if (meta.subTypes.length > 0) {\n if (meta.inheritanceType === \"cti\") {\n for (const [meta, group] of groupEntitiesByTable(todo.updates)) {\n const op = newUpdateOp(meta, group);\n if (op) ops.updates.push(op);\n addLazyUpdates(ops, meta, group);\n }\n } else if (meta.inheritanceType === \"sti\") {\n const op = newUpdateOp(meta, todo.updates);\n if (op) ops.updates.push(op);\n addLazyUpdates(ops, meta, todo.updates);\n } else {\n throw new Error(`Found ${meta.tableName} subTypes without a known inheritanceType ${meta.inheritanceType}`);\n }\n } else {\n const op = newUpdateOp(meta, todo.updates);\n if (op) ops.updates.push(op);\n addLazyUpdates(ops, meta, todo.updates);\n }\n }\n}\n\n/**\n * Writes changed `lazy` columns via a targeted `UPDATE table SET lazy_col = ... WHERE id in (...)`.\n *\n * Lazy columns are excluded from the main batch UPDATE (which spans the batch's union of changed fields),\n * so that entities in the batch that never loaded a lazy column keep their existing db value instead of\n * being overwritten with null. Here we write each lazy column only for the entities that actually changed it.\n */\nfunction addLazyUpdates(ops: Ops, meta: EntityMetadata, entities: Entity[]): void {\n const idColumn = meta.fields[\"id\"].serde!.columns[0];\n for (const fieldName of meta.lazyFieldNames!) {\n const field = meta.fields[fieldName];\n if (!hasSerde(field)) continue;\n const changed = entities.filter((e) => fieldName in getInstanceData(e).changedData);\n if (changed.length === 0) continue;\n const columns: BindingColumn[] = [idColumn, ...field.serde.columns];\n const columnValues = collectBindings(changed, meta.tableName, columns, undefined);\n ops.updates.push({ tableName: meta.tableName, columns, columnValues, updatedAt: undefined });\n }\n}\n\nfunction newUpdateOp(meta: EntityMetadata, entities: Entity[]): UpdateOp | undefined {\n // We only include changed fields in our `UPDATE`--maybe we could change this\n // to always use the same fields, to take advantage of Prepared Statements.\n const changedFields = new Set<string>();\n for (const entity of entities) {\n for (const fieldName in getInstanceData(entity).changedData) changedFields.add(fieldName);\n }\n // Sometimes with derived fields, an instance will be marked as an update, but if the derived field hasn't\n // actually changed, it'll be a noop, so just short-circuit if it looks like that happened. Unless touched.\n if (changedFields.size === 0 && !entities.some((e) => getInstanceData(e).isTouched)) {\n return undefined;\n }\n\n // We may have loaded a1 and a2, and changed a1.firstName, and a2.lastName, but either one\n // might be missing the other's changed fields in it's lazy-initialized data field...\n // (Use `?` because subtypes won't have the updatedAt, and it will be handled by the base type\n // `newUpdateUp`--except STI where we're doing it all in one go, probably needs checked here.)\n const updatedAt = meta.timestampFields?.updatedAt;\n changedFields.add(\"id\");\n if (updatedAt) changedFields.add(updatedAt);\n // `lazy` columns are deliberately excluded from the batch UPDATE and written by `addLazyUpdates`; an\n // entity that never loaded a lazy column isn't in `row`, so forcing `getField` here would clobber it to null.\n const lazyFieldNames = meta.lazyFieldNames!;\n for (const entity of entities) {\n const { data } = getInstanceData(entity);\n for (const key of changedFields) {\n // Check isChangeableField because we might be updating the base `publishers` table\n // and `originalData` might have fields from a subclass `large_publishers` table.\n if (!(key in data) && isChangeableField(entity, key) && !lazyFieldNames.has(key)) {\n getField(entity, key);\n }\n }\n }\n\n const columns: Array<BindingColumn> = (\n meta.inheritanceType === \"sti\"\n ? // Hack this one handling of STI into here...\n getBaseSelfAndSubMetas(meta).flatMap((meta) =>\n meta.stiDiscriminatorField\n ? Object.values(meta.fields)\n : Object.values(meta.fields).filter((f) => f.fieldName !== \"id\"),\n )\n : Object.values(meta.fields)\n )\n .filter((f) => changedFields.has(f.fieldName))\n .filter((f) => !lazyFieldNames.has(f.fieldName))\n .filter(hasSerde)\n .flatMap((f) => f.serde.columns);\n\n // If we're using class table inheritance, base/child tables may not have any columns to update\n if (columns.length === 1) {\n return undefined;\n }\n\n // We already have the bumped updated_at column, but also include the original updated_at for the data CTE\n if (updatedAt) {\n const serde = meta.fields[updatedAt].serde as TimestampSerde<unknown>;\n columns.push({\n columnName: \"__original_updated_at\",\n dbType: \"timestamptz\",\n dbValue: (_, entity) => serde.dbValue(getInstanceData(entity).originalData),\n });\n }\n\n const columnValues = collectBindings(entities, meta.tableName, columns, []);\n const updatedAtColumn = updatedAt ? (meta.fields[updatedAt] as PrimitiveField).serde.columns[0] : undefined;\n return { tableName: meta.tableName, columns, updatedAt: updatedAtColumn?.columnName, columnValues };\n}\n\nfunction addDeletes(ops: Ops, todo: Todo): void {\n if (todo.deletes.length > 0) {\n const meta = todo.metadata;\n const ids = todo.deletes.map((e) => keyToNumber(meta, e.idTagged!).toString());\n if (meta.subTypes.length > 0) {\n getBaseSelfAndSubMetas(meta).forEach((meta) => {\n ops.deletes.push({ tableName: meta.tableName, ids });\n });\n } else {\n ops.deletes.push({ tableName: meta.tableName, ids });\n }\n }\n}\n\nfunction groupEntitiesByTable(entities: Entity[]): Array<[EntityMetadata, Entity[]]> {\n const entitiesByType: Map<EntityMetadata, Entity[]> = new Map();\n for (const e of entities) {\n for (const m of getBaseAndSelfMetas(getMetadata(e))) {\n let list = entitiesByType.get(m);\n if (!list) {\n list = [];\n entitiesByType.set(m, list);\n }\n list.push(e);\n }\n }\n return [...entitiesByType.entries()];\n}\n\ntype BindingColumn = OpColumn & Pick<FieldColumn, \"dbValue\">;\ntype EntityWithData = Entity & { __data: { data: Record<string, unknown> } };\n\n/**\n * Builds a *columnar* array of bindings for the given `entities` and `columns`.\n *\n * We use a columnar approach, instead of `rows[]`, to best match the unnest-based\n * column operations in our `batchInsert` / `batchUpdate` SQL statements.\n */\nfunction collectBindings(\n entities: Entity[],\n tableName: string,\n columns: BindingColumn[],\n fixups: InsertFixup[] | undefined,\n): any[][] {\n const entityCount = entities.length;\n const bindings: any[][] = new Array(columns.length);\n const entitiesWithData = entities as EntityWithData[];\n // Cache data separately; this benchmarks faster than `entities[i].__data.data` in the inner loop.\n const entityData = new Array(entityCount);\n for (let i = 0; i < entityCount; i++) entityData[i] = entitiesWithData[i].__data.data;\n for (let columnIndex = 0; columnIndex < columns.length; columnIndex++) {\n const column = columns[columnIndex];\n const columnValues: any[] = new Array(entityCount);\n for (let entityIndex = 0; entityIndex < entityCount; entityIndex++) {\n columnValues[entityIndex] =\n column.dbValue(entityData[entityIndex], entities[entityIndex], tableName, fixups) ?? null;\n }\n bindings[columnIndex] = columnValues;\n }\n return bindings;\n}\n/**\n * Given `fixups` that indicate where we inserted `NULL` into non-deferred FKs, create `UPDATE`s\n * that insert the value now that the FK check will succeed.\n */\nfunction translateFixupsIntoUpdates(ops: Ops, fixups: InsertFixup[]): void {\n // Create a single `UPDATE` for the N fixups we might have for each table/column combination\n groupBy(fixups, (f) => `${f.tableName}.${f.column.columnName}`).forEach((fixups) => {\n const { tableName, entity, column } = fixups[0];\n ops.updates.push({\n tableName,\n columns: [getMetadata(entity).fields[\"id\"].serde!.columns[0], column],\n columnValues: [\n // Make 1 column of ids, and 1 column of values\n fixups.map((fixup) => fixup.entity.id),\n fixups.map((fixup) => fixup.value),\n ],\n updatedAt: undefined,\n });\n });\n}\n"],"mappings":";;;;;;;;;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file":"EntityWriter.js","names":[],"sources":["../../src/drivers/EntityWriter.ts"],"sourcesContent":["import { getInstanceData } from \"../BaseEntity.ts\";\nimport { type Entity } from \"../Entity.ts\";\nimport {\n type EntityMetadata,\n type Field,\n type PrimitiveField,\n getBaseAndSelfMetas,\n getBaseSelfAndSubMetas,\n getMetadata,\n} from \"../EntityMetadata.ts\";\nimport { getField, isChangeableField } from \"../fields.ts\";\nimport { type FieldColumn, type TimestampSerde, hasSerde } from \"../fieldSerde.ts\";\nimport { keyToNumber } from \"../keys.ts\";\nimport { type Todo } from \"../Todo.ts\";\nimport { groupBy } from \"../utils.ts\";\n\n/** A simplified view of columns, with only the keys necessary to create SQL statements. */\nexport type OpColumn = { columnName: string; dbType: string; isNullableArray?: boolean };\nexport type InsertOp = { tableName: string; columns: OpColumn[]; columnValues: any[][] };\n/**\n * A logical `update` operation.\n *\n * If we're using op locks, `columns` will include both the new `updatedAt` value (as bumped\n * by the `EntityManager` on mutate), as well as an extra/last \"original updated at\" column\n * (with respective pre-update values in the `rows` data), for including in the conditional\n * update clause.\n */\nexport type UpdateOp = {\n tableName: string;\n columns: OpColumn[];\n columnValues: any[][];\n updatedAt: string | undefined;\n};\nexport type DeleteOp = { tableName: string; ids: any[] };\n\ntype Ops = { inserts: InsertOp[]; updates: UpdateOp[]; deletes: DeleteOp[] };\n\n/**\n * In schemas with entity FK cycles, we may insert a dummy/null value, and later fix it up\n * before the transaction commits.\n *\n * I.e. `INSERT author.favorite_book_id` as `NULL` and then later do an `UPDATE author\n * SET favorite_book_id = 1` after the book has been inserted/we have the id.\n */\nexport type InsertFixup = {\n entity: Entity;\n tableName: string;\n column: OpColumn;\n value: any;\n};\n\n/**\n * Builds AST-ish `Ops` for the inserts/updates/deletes in `todos`.\n *\n * This helps decouple the database-specific driver/library from the knowledge\n * of turning entities into table operations, i.e. so they can be unaware of\n * complexities like field -> column mapping, oplocks, and class table inheritance.\n *\n * We still assume Postgres b/c we assume all ids have been pre-assigned for INSERTs,\n * and don't do any topological sorting of cross-row FK dependencies.\n *\n * But this should let us experiment with knex vs. raw client/etc.\n */\nexport function generateOps(todos: Record<string, Todo>): Ops {\n const ops: Ops = { inserts: [], updates: [], deletes: [] };\n const fixups: InsertFixup[] = [];\n // Would be nice to conditionally sort\n const sorted = Object.values(todos).sort(\n (a, b) => (a.metadata.nonDeferredFkOrder ?? 0) - (b.metadata.nonDeferredFkOrder ?? 0),\n );\n for (const todo of sorted) {\n addInserts(ops, todo, fixups);\n addUpdates(ops, todo);\n addDeletes(ops, todo);\n }\n if (fixups.length > 0) translateFixupsIntoUpdates(ops, fixups);\n return ops;\n}\n\nfunction addInserts(ops: Ops, todo: Todo, fixups: InsertFixup[]): void {\n if (todo.inserts.length > 0) {\n // If we have subtypes, this todo.metadata will always be the base type\n const meta = todo.metadata;\n if (meta.subTypes.length > 0) {\n if (meta.inheritanceType === \"cti\") {\n // Insert into each of the CTI tables\n for (const [meta, group] of groupEntitiesByTable(todo.inserts)) {\n ops.inserts.push(newInsertOp(meta, group, fixups));\n }\n } else if (meta.inheritanceType === \"sti\") {\n // One INSERT per subtype, so each statement's column list spans exactly what that subtype can\n // set. A single statement across subtypes has to bind NULL for the other subtypes' columns,\n // which defeats their database defaults, and outright fails for notNull ones.\n for (const group of groupBy(todo.inserts, (e) => getMetadata(e)).values()) {\n ops.inserts.push(newStiInsertOp(meta, group, fixups));\n }\n } else {\n throw new Error(`Found ${meta.tableName} subTypes without a known inheritanceType ${meta.inheritanceType}`);\n }\n } else {\n ops.inserts.push(newInsertOp(meta, todo.inserts, fixups));\n }\n }\n}\n\nfunction newInsertOp(meta: EntityMetadata, entities: Entity[], fixups: InsertFixup[]): InsertOp {\n // Purposefully use `meta.fields` instead of `allFields` b/c each CTI table has its own `InsertOp`\n const columns = Object.values(meta.fields)\n .filter(hasSerde)\n .flatMap((f) => f.serde.columns);\n const columnValues = collectBindings(entities, meta.tableName, columns, fixups);\n return { tableName: meta.tableName, columns, columnValues };\n}\n\nfunction newStiInsertOp(root: EntityMetadata, entities: Entity[], fixups: InsertFixup[]): InsertOp {\n // `allFields` is the base's fields plus this subtype's own, i.e. everything this subtype can write.\n // Anything it can't write is left out of the statement entirely, so the database applies its default.\n const fields: Field[] = Object.values(getMetadata(entities[0]).allFields);\n const columns = fields.filter(hasSerde).flatMap((f) => f.serde.columns);\n const columnValues = collectBindings(entities, root.tableName, columns, fixups);\n return { tableName: root.tableName, columns, columnValues };\n}\n\nfunction addUpdates(ops: Ops, todo: Todo): void {\n if (todo.updates.length > 0) {\n const meta = todo.metadata;\n if (meta.subTypes.length > 0) {\n if (meta.inheritanceType === \"cti\") {\n for (const [meta, group] of groupEntitiesByTable(todo.updates)) {\n const op = newUpdateOp(meta, group);\n if (op) ops.updates.push(op);\n addLazyUpdates(ops, meta, group);\n }\n } else if (meta.inheritanceType === \"sti\") {\n const op = newUpdateOp(meta, todo.updates);\n if (op) ops.updates.push(op);\n addLazyUpdates(ops, meta, todo.updates);\n } else {\n throw new Error(`Found ${meta.tableName} subTypes without a known inheritanceType ${meta.inheritanceType}`);\n }\n } else {\n const op = newUpdateOp(meta, todo.updates);\n if (op) ops.updates.push(op);\n addLazyUpdates(ops, meta, todo.updates);\n }\n }\n}\n\n/**\n * Writes changed `lazy` columns via a targeted `UPDATE table SET lazy_col = ... WHERE id in (...)`.\n *\n * Lazy columns are excluded from the main batch UPDATE (which spans the batch's union of changed fields),\n * so that entities in the batch that never loaded a lazy column keep their existing db value instead of\n * being overwritten with null. Here we write each lazy column only for the entities that actually changed it.\n */\nfunction addLazyUpdates(ops: Ops, meta: EntityMetadata, entities: Entity[]): void {\n const idColumn = meta.fields[\"id\"].serde!.columns[0];\n for (const fieldName of meta.lazyFieldNames!) {\n const field = meta.fields[fieldName];\n if (!hasSerde(field)) continue;\n const changed = entities.filter((e) => fieldName in getInstanceData(e).changedData);\n if (changed.length === 0) continue;\n const columns: BindingColumn[] = [idColumn, ...field.serde.columns];\n const columnValues = collectBindings(changed, meta.tableName, columns, undefined);\n ops.updates.push({ tableName: meta.tableName, columns, columnValues, updatedAt: undefined });\n }\n}\n\nfunction newUpdateOp(meta: EntityMetadata, entities: Entity[]): UpdateOp | undefined {\n // We only include changed fields in our `UPDATE`--maybe we could change this\n // to always use the same fields, to take advantage of Prepared Statements.\n const changedFields = new Set<string>();\n for (const entity of entities) {\n for (const fieldName in getInstanceData(entity).changedData) changedFields.add(fieldName);\n }\n // Sometimes with derived fields, an instance will be marked as an update, but if the derived field hasn't\n // actually changed, it'll be a noop, so just short-circuit if it looks like that happened. Unless touched.\n if (changedFields.size === 0 && !entities.some((e) => getInstanceData(e).isTouched)) {\n return undefined;\n }\n\n // We may have loaded a1 and a2, and changed a1.firstName, and a2.lastName, but either one\n // might be missing the other's changed fields in it's lazy-initialized data field...\n // (Use `?` because subtypes won't have the updatedAt, and it will be handled by the base type\n // `newUpdateUp`--except STI where we're doing it all in one go, probably needs checked here.)\n const updatedAt = meta.timestampFields?.updatedAt;\n changedFields.add(\"id\");\n if (updatedAt) changedFields.add(updatedAt);\n // `lazy` columns are deliberately excluded from the batch UPDATE and written by `addLazyUpdates`; an\n // entity that never loaded a lazy column isn't in `row`, so forcing `getField` here would clobber it to null.\n const lazyFieldNames = meta.lazyFieldNames!;\n for (const entity of entities) {\n const { data } = getInstanceData(entity);\n for (const key of changedFields) {\n // Check isChangeableField because we might be updating the base `publishers` table\n // and `originalData` might have fields from a subclass `large_publishers` table.\n if (!(key in data) && isChangeableField(entity, key) && !lazyFieldNames.has(key)) {\n getField(entity, key);\n }\n }\n }\n\n const columns: Array<BindingColumn> = (\n meta.inheritanceType === \"sti\"\n ? // Hack this one handling of STI into here...\n getBaseSelfAndSubMetas(meta).flatMap((meta) =>\n meta.stiDiscriminatorField\n ? Object.values(meta.fields)\n : Object.values(meta.fields).filter((f) => f.fieldName !== \"id\"),\n )\n : Object.values(meta.fields)\n )\n .filter((f) => changedFields.has(f.fieldName))\n .filter((f) => !lazyFieldNames.has(f.fieldName))\n .filter(hasSerde)\n .flatMap((f) => f.serde.columns);\n\n // If we're using class table inheritance, base/child tables may not have any columns to update\n if (columns.length === 1) {\n return undefined;\n }\n\n // We already have the bumped updated_at column, but also include the original updated_at for the data CTE\n if (updatedAt) {\n const serde = meta.fields[updatedAt].serde as TimestampSerde<unknown>;\n columns.push({\n columnName: \"__original_updated_at\",\n dbType: \"timestamptz\",\n dbValue: (_, entity) => serde.dbValue(getInstanceData(entity).originalData),\n });\n }\n\n const columnValues = collectBindings(entities, meta.tableName, columns, []);\n const updatedAtColumn = updatedAt ? (meta.fields[updatedAt] as PrimitiveField).serde.columns[0] : undefined;\n return { tableName: meta.tableName, columns, updatedAt: updatedAtColumn?.columnName, columnValues };\n}\n\nfunction addDeletes(ops: Ops, todo: Todo): void {\n if (todo.deletes.length > 0) {\n const meta = todo.metadata;\n const ids = todo.deletes.map((e) => keyToNumber(meta, e.idTagged!).toString());\n if (meta.subTypes.length > 0) {\n getBaseSelfAndSubMetas(meta).forEach((meta) => {\n ops.deletes.push({ tableName: meta.tableName, ids });\n });\n } else {\n ops.deletes.push({ tableName: meta.tableName, ids });\n }\n }\n}\n\nfunction groupEntitiesByTable(entities: Entity[]): Array<[EntityMetadata, Entity[]]> {\n const entitiesByType: Map<EntityMetadata, Entity[]> = new Map();\n for (const e of entities) {\n for (const m of getBaseAndSelfMetas(getMetadata(e))) {\n let list = entitiesByType.get(m);\n if (!list) {\n list = [];\n entitiesByType.set(m, list);\n }\n list.push(e);\n }\n }\n return [...entitiesByType.entries()];\n}\n\ntype BindingColumn = OpColumn & Pick<FieldColumn, \"dbValue\">;\ntype EntityWithData = Entity & { __data: { data: Record<string, unknown> } };\n\n/**\n * Builds a *columnar* array of bindings for the given `entities` and `columns`.\n *\n * We use a columnar approach, instead of `rows[]`, to best match the unnest-based\n * column operations in our `batchInsert` / `batchUpdate` SQL statements.\n */\nfunction collectBindings(\n entities: Entity[],\n tableName: string,\n columns: BindingColumn[],\n fixups: InsertFixup[] | undefined,\n): any[][] {\n const entityCount = entities.length;\n const bindings: any[][] = new Array(columns.length);\n const entitiesWithData = entities as EntityWithData[];\n // Cache data separately; this benchmarks faster than `entities[i].__data.data` in the inner loop.\n const entityData = new Array(entityCount);\n for (let i = 0; i < entityCount; i++) entityData[i] = entitiesWithData[i].__data.data;\n for (let columnIndex = 0; columnIndex < columns.length; columnIndex++) {\n const column = columns[columnIndex];\n const columnValues: any[] = new Array(entityCount);\n for (let entityIndex = 0; entityIndex < entityCount; entityIndex++) {\n columnValues[entityIndex] =\n column.dbValue(entityData[entityIndex], entities[entityIndex], tableName, fixups) ?? null;\n }\n bindings[columnIndex] = columnValues;\n }\n return bindings;\n}\n/**\n * Given `fixups` that indicate where we inserted `NULL` into non-deferred FKs, create `UPDATE`s\n * that insert the value now that the FK check will succeed.\n */\nfunction translateFixupsIntoUpdates(ops: Ops, fixups: InsertFixup[]): void {\n // Create a single `UPDATE` for the N fixups we might have for each table/column combination\n groupBy(fixups, (f) => `${f.tableName}.${f.column.columnName}`).forEach((fixups) => {\n const { tableName, entity, column } = fixups[0];\n ops.updates.push({\n tableName,\n columns: [getMetadata(entity).fields[\"id\"].serde!.columns[0], column],\n columnValues: [\n // Make 1 column of ids, and 1 column of values\n fixups.map((fixup) => fixup.entity.id),\n fixups.map((fixup) => fixup.value),\n ],\n updatedAt: undefined,\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+DA,SAAgB,YAAY,OAAkC;CAC5D,MAAM,MAAW;EAAE,SAAS,CAAC;EAAG,SAAS,CAAC;EAAG,SAAS,CAAC;CAAE;CACzD,MAAM,SAAwB,CAAC;CAE/B,MAAM,SAAS,OAAO,OAAO,KAAK,CAAC,CAAC,MACjC,GAAG,OAAO,EAAE,SAAS,sBAAsB,MAAM,EAAE,SAAS,sBAAsB,EACrF;CACA,KAAK,MAAM,QAAQ,QAAQ;EACzB,WAAW,KAAK,MAAM,MAAM;EAC5B,WAAW,KAAK,IAAI;EACpB,WAAW,KAAK,IAAI;CACt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,cAAc,QAAQ,QAAQ,eAAe;EACrE,MAAM,SAAS,QAAQ;EACvB,MAAM,eAAsB,IAAI,MAAM,WAAW;EACjD,KAAK,IAAI,cAAc,GAAG,cAAc,aAAa,eACnD,aAAa,eACX,OAAO,QAAQ,WAAW,cAAc,SAAS,cAAc,WAAW,MAAM,KAAK;EAEzF,SAAS,eAAe;CAC1B;CACA,OAAO;AACT;;;;;AAKA,SAAS,2BAA2B,KAAU,QAA6B;CAEzE,QAAQ,SAAS,MAAM,GAAG,EAAE,UAAU,GAAG,EAAE,OAAO,YAAY,CAAC,CAAC,SAAS,WAAW;EAClF,MAAM,EAAE,WAAW,QAAQ,WAAW,OAAO;EAC7C,IAAI,QAAQ,KAAK;GACf;GACA,SAAS,CAAC,YAAY,MAAM,CAAC,CAAC,OAAO,KAAK,CAAC,MAAO,QAAQ,IAAI,MAAM;GACpE,cAAc,CAEZ,OAAO,KAAK,UAAU,MAAM,OAAO,EAAE,GACrC,OAAO,KAAK,UAAU,MAAM,KAAK,CACnC;GACA,WAAW,KAAA;EACb,CAAC;CACH,CAAC;AACH"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["getMetadata","getProperties","getBaseMeta","getField","AbstractRelationImpl","isLazyField","isProperty","isAsyncProperty","isReactiveGetter","isReactiveField","isAsyncReactiveField","FactoryInitialValue","ReactiveFieldImpl","AsyncReactiveFieldImpl","getInstanceData"],"sources":["../src/index.ts"],"sourcesContent":["import { getInstanceData } from \"./BaseEntity.ts\";\nimport { getDefaultDependencies } from \"./defaults.ts\";\nimport { buildWhereClause } from \"./drivers/buildUtils.ts\";\nimport { type Entity } from \"./Entity.ts\";\nimport { type EntityConstructor, type MaybeAbstractEntityConstructor } from \"./EntityManager.ts\";\nimport { type EntityMetadata, getBaseMeta, getMetadata } from \"./EntityMetadata.ts\";\nimport { getField, setField } from \"./fields.ts\";\nimport { getProperties } from \"./getProperties.ts\";\nimport { type New } from \"./loadHints.ts\";\nimport { isAllSqlPaths } from \"./loadLens.ts\";\nimport { FactoryInitialValue } from \"./newTestInstance.ts\";\nimport { partitionHint } from \"./preloading/partitionHint.ts\";\nimport { AbstractRelationImpl } from \"./relations/AbstractRelationImpl.ts\";\nimport { AsyncReactiveFieldImpl } from \"./relations/AsyncReactiveField.ts\";\nimport {\n isAsyncProperty,\n isAsyncReactiveField,\n isLazyField,\n isProperty,\n isReactiveField,\n isReactiveGetter,\n} from \"./relations/index.ts\";\nimport { ReactiveFieldImpl } from \"./relations/ReactiveField.ts\";\nimport { type OptsOf } from \"./typeMap.ts\";\nimport { fail } from \"./utils.ts\";\n\nexport const testing = { isAllSqlPaths, getDefaultDependencies, partitionHint };\nexport const internals = { buildWhereClause };\nexport { newPgConnectionConfig } from \"joist-utils\";\nexport { AliasAssigner } from \"./AliasAssigner.ts\";\nexport {\n type ConditionGroup,\n type DomainPredicate,\n type PredicateBrand,\n type SqlCondition,\n type SqlPredicate,\n} from \"./conditions.ts\";\n// Domain aliases belong to em.find; physical table expressions belong to em.query/em.execute.\nexport {\n alias,\n aliases,\n getAliasMetadata,\n getAliasMgmt,\n getMaybeCtiAlias,\n isAlias,\n newAliasProxy,\n type Alias,\n type AliasBrand,\n type AliasMgmt,\n type AliasColumn,\n type EntityAlias,\n type PolyAlias,\n type PrimitiveAlias,\n} from \"./Aliases.ts\";\nexport {\n table,\n tables,\n tableMgmt,\n getTableMetadata,\n getTableMgmt,\n isTable,\n newTableProxy,\n type Table,\n type TableFilter,\n type TableBrand,\n type TableFor,\n type TableMgmt,\n type ReferenceJoin,\n type PrimitiveColumn,\n type EntityColumn,\n type ReferenceColumn,\n type CollectionJoin,\n type PolyReference,\n} from \"./Tables.ts\";\nexport { BaseEntity, getInstanceData } from \"./BaseEntity.ts\";\nexport { ConditionBuilder } from \"./ConditionBuilder.ts\";\nexport { type Entity, type IdType, isEntity } from \"./Entity.ts\";\nexport type * from \"./EntityFields.ts\";\nexport * from \"./EntityFilter.ts\";\nexport * from \"./EntityGraphQLFilter.ts\";\nexport * from \"./EntityManager.ts\";\nexport * from \"./EntityMetadata.ts\";\nexport type {\n DeleteStatement,\n ExecuteResult,\n InsertStatement,\n InsertValues,\n MutationReturning,\n MutationStatement,\n UpdateStatement,\n UpdateValues,\n} from \"./execute.ts\";\nexport type { EnumMetadata } from \"./EnumMetadata.ts\";\n// `em.query`'s expression surface. Only the user-facing types are re-exported: the runtime half\n// (BaseExpr, asNode, deferredCondition, the FnExpr/TemplateExpr node classes) stays internal to\n// joist-core, so `toSql`/`decode`/`encode` never show up as something a user could call.\nexport { type Expr, type ExprBrand, exprBrand, type ExprLike, type InnerJoin, type LeftJoin } from \"./Expr.ts\";\nexport { skipCondition } from \"./skipCondition.ts\";\nexport type { EntityOrId, HintNode } from \"./HintTree.ts\";\nexport { InstanceData } from \"./InstanceData.ts\";\nexport { type JoinColumnValue, type JoinRow, JoinRowOperation, type ManyToManyLike } from \"./JoinRows.ts\";\nexport type * from \"./PendingChanges.ts\";\nexport { Plugin } from \"./PluginManager.ts\";\nexport * from \"./QueryParser.ts\";\nexport * from \"./QueryParser.collectionJoins.ts\";\nexport { visitConditions } from \"./QueryVisitor.ts\";\nexport * from \"./RowData.ts\";\nexport { type JoinRowTodo, Todo } from \"./Todo.ts\";\nexport * from \"./changes.ts\";\nexport { ConfigApi, type EntityHook, resetBootFlag } from \"./config.ts\";\nexport {\n configureMetadata,\n getConstructorFromTaggedId,\n getMetadataForTable,\n getMetadataForType,\n maybeGetConstructorFromReference,\n} from \"./configure.ts\";\nexport { driverApi } from \"./driverApi.ts\";\nexport * from \"./drivers/index.ts\";\nexport { getField, isChangeableField, isFieldSet, setField } from \"./fields.ts\";\nexport * from \"./getProperties.ts\";\nexport * from \"./json.ts\";\nexport * from \"./keys.ts\";\nexport { kq, kqDot, kqStar } from \"./keywords.ts\";\nexport {\n assertLoaded,\n type DeepNew,\n ensureLoaded,\n isLoaded,\n isNew,\n type Loadable,\n type Loaded,\n type LoadHint,\n type MarkLoaded,\n maybePopulateThen,\n type NestedLoadHint,\n type New,\n type RelationsIn,\n unsafeLoaded,\n} from \"./loadHints.ts\";\nexport * from \"./loadLens.ts\";\nexport { setFactoryWriter } from \"./logging/FactoryLogger.ts\";\nexport * from \"./logging/FieldLogger.ts\";\nexport { ReactionLogger, setReactionLogging } from \"./logging/ReactionLogger.ts\";\nexport { lazyField } from \"./newEntity.ts\";\nexport {\n defaultValue,\n factories,\n type FactoryEntityOpt,\n type FactoryOpts,\n getTestIndex,\n isFactoryCreation,\n maybeBranchValue,\n maybeNew,\n maybeNewPoly,\n newTestInstance,\n noValue,\n setFactoryLogging,\n testIndex,\n} from \"./newTestInstance.ts\";\nexport { deepNormalizeHint, normalizeHint } from \"./normalizeHints.ts\";\nexport { ImmutableEntitiesPlugin } from \"./plugins/ImmutableEntitiesPlugin.ts\";\nexport type { JoinResult, PreloadHydrator, PreloadPlugin } from \"./plugins/PreloadPlugin.ts\";\nexport { JsonAggregatePreloader } from \"./preloading/JsonAggregatePreloader.ts\";\n// `em.query`'s query surface; the parse pipeline (SubqueryHandle, parseUserQuery, Plan) stays internal\nexport {\n type CheckScope,\n type Clauses,\n type EntityQuery,\n type ExistsQuery,\n entityQueryBrand,\n type MaybeNull,\n type NameOf,\n type NotWidened,\n type OrderByDirection,\n type OrderByKeys,\n type Query,\n type QueryArg,\n type QueryCondition,\n type QueryJoin,\n type QueryJoins,\n type QueryOrderBy,\n type QueryRow,\n type QuerySelect,\n type QuerySource,\n type QueryValue,\n recursiveQuery,\n type RecursiveOptions,\n type ScalarQuery,\n type SetQuery,\n query,\n sql,\n type Subquery,\n type SubqueryBrand,\n subqueryBrand,\n type WithInput,\n type WithSource,\n} from \"./query.ts\";\nexport {\n convertToLoadHint,\n isTypeOrSubType,\n type Reactable,\n type Reacted,\n type ReactiveHint,\n type ReactiveTarget,\n reverseReactiveHint,\n} from \"./reactiveHints.ts\";\nexport * from \"./relations/index.ts\";\nexport {\n cannotBeChanged,\n cannotBeUpdated,\n type GenericError,\n maxValueRule,\n minValueRule,\n mustBeSubType,\n newRequiredLazyFieldRule,\n newRequiredRule,\n rangeValueRule,\n ValidationCode,\n type ValidationError,\n ValidationErrors,\n type ValidationRule,\n type ValidationRuleInternal,\n type ValidationRuleResult,\n} from \"./rules.ts\";\nexport { getRuntimeConfig, setRuntimeConfig, type RuntimeConfig } from \"./runtimeConfig.ts\";\nexport { nowUTC } from \"./nowUTC.ts\";\nexport * from \"./serde.ts\";\nexport * from \"./columns.ts\";\nexport * from \"./fieldSerde.ts\";\nexport * from \"./scopes.ts\";\nexport { maybeRequireTemporal, requireTemporal, Temporal } from \"./temporal.ts\";\nexport * from \"./temporalMappers.ts\";\nexport { isInTrustedContext, runInTrustedContext } from \"./trusted.ts\";\nexport type * from \"./typeMap.ts\";\nexport { buildUnnestCte, ensureRectangularArraySizes } from \"./unnest.ts\";\nexport { type DeepPartialOrNull, updatePartial, upsert } from \"./upsert.ts\";\nexport {\n abbreviation,\n asNew,\n assertNever,\n cleanSql,\n cleanStringValue,\n fail,\n failIfAnyRejected,\n indexBy,\n partition,\n zeroTo,\n} from \"./utils.ts\";\nexport { ensureWithLoaded, StubbedRelation, type WithLoaded, withLoaded } from \"./withLoaded.ts\";\n\n// https://spin.atomicobject.com/2018/01/15/typescript-flexible-nominal-typing/\ninterface Flavoring<FlavorT> {\n _type?: FlavorT;\n}\n\nexport type Flavor<T, FlavorT> = T & Flavoring<FlavorT>;\n\n/**\n * Sets each value in `values` on the current entity.\n *\n * The default behavior is that passing a value as either `null` or `undefined` will set\n * the field as `undefined`, i.e. automatic `null` to `undefined` conversion.\n *\n * However, if you pass `ignoreUndefined: true`, then any opt that is `undefined` will be treated\n * as \"do not set\", and `null` will still mean \"set to `undefined`\". This is useful for implementing\n * APIs were an input of `undefined` means \"do not set / noop\" and `null` means \"unset\".\n *\n * Note that constructors _always_ call this method, but if the call is coming from `em.hydrate`, we\n * use `values` being a primary key to short-circuit and let hydration callers assign the values\n * returned by the serde `fromRow` methods.\n */\nexport function setOpts<T extends Entity>(\n entity: T,\n values: Partial<OptsOf<T>> | undefined,\n opts?: { partial?: boolean; calledFromConstructor?: boolean },\n): void {\n const { calledFromConstructor = false, partial } = opts || {};\n // If `values` is undefined, we're being called by `createPartial` that will do its\n // own opt handling, but we still want the sync defaults applied after this opts handling.\n if (values !== undefined) {\n const meta = getMetadata(entity);\n for (const [key, _value] of Object.entries(values as {})) {\n setOpt(meta, entity, key, _value, partial, calledFromConstructor);\n }\n }\n}\n\n/**\n * Applies some standard behavior & protections to `entity[key] = value`. I.e.\n *\n * - We don't set over AsyncProperties/relations/etc., and instead call current.set(value)\n * - We catch missing/invalid field names\n * - We handle FactoryInitialValues\n */\nexport function setOpt<T extends Entity>(\n meta: EntityMetadata<T>,\n entity: T,\n key: string,\n _value: any,\n partial = false,\n calledFromConstructor = false,\n): void {\n const field = meta.allFields[key];\n if (!field) {\n // Allow setting non-field properties like fullName setters\n const prop = getProperties(meta)[key];\n if (!prop) {\n throw new Error(`Unknown field ${key}`);\n }\n }\n\n // If partial is set, we treat undefined as a noop\n if (partial && _value === undefined) return;\n // Ignore the STI discriminator, em.register will set this accordingly\n if (meta.inheritanceType === \"sti\" && getBaseMeta(meta).stiDiscriminatorField === key) return;\n\n // We let optional opts fields be `| null` for convenience, and convert to undefined.\n const value = _value === null ? undefined : _value;\n\n // Use `getField` to side-step `id` blowing up on new entities that are setting an\n // explicit id; otherwise use `entity[key]` to get back the relation.\n const current = key === \"id\" ? getField(entity, key) : (entity as any)[key];\n\n if (current instanceof AbstractRelationImpl) {\n if (calledFromConstructor) {\n current.setFromOpts(value);\n } else {\n current.set(value);\n }\n } else if (isLazyField(current)) {\n current.set(value);\n } else if (isProperty(current) || isAsyncProperty(current) || isReactiveGetter(current)) {\n throw new Error(`Invalid argument, cannot set over ${key} ${current.constructor.name}`);\n } else if (isReactiveField(current) || isAsyncReactiveField(current)) {\n if (value instanceof FactoryInitialValue) {\n if (current instanceof ReactiveFieldImpl) {\n current.setFactoryValue(value.value);\n } else if (current instanceof AsyncReactiveFieldImpl) {\n current.setFactoryValue(value.value);\n } else {\n throw new Error(`Unhandled case ${current.constructor.name}`);\n }\n } else {\n throw new Error(`Invalid argument, cannot set over ${key} ${current.constructor.name}`);\n }\n } else {\n // If setting an explicit id, go through setField, otherwise use\n // `entity[key]` to set the value directly to that we go through setters.\n if (key === \"id\" && entity.isNewEntity) {\n setField(entity, key, value);\n } else {\n (entity as any)[key] = value;\n }\n }\n}\n\nexport function ensureNotDeleted(entity: Entity, ignore?: \"pending\"): void {\n if (entity.isDeletedEntity && (ignore === undefined || getInstanceData(entity).isDeletedAndFlushed)) {\n fail(`${entity} is marked as deleted`);\n }\n}\n\n/** Adds `null` to every key in `T` to accept partial-update-style input. */\nexport type PartialOrNull<T> = {\n [P in keyof T]?: T[P] | null;\n};\n\nexport function getRequiredKeys<T extends Entity>(entity: T): string[];\nexport function getRequiredKeys<T extends Entity>(type: EntityConstructor<T>): string[];\nexport function getRequiredKeys<T extends Entity>(entityOrType: T | EntityConstructor<T>): string[] {\n return Object.values(getMetadata(entityOrType as any).fields)\n .filter((f) => f.required)\n .map((f) => f.fieldName);\n}\n\nexport function getRelations(entity: Entity): AbstractRelationImpl<any, any>[] {\n return Object.entries(getProperties(getMetadata(entity)))\n .filter(([, v]) => v instanceof AbstractRelationImpl)\n .map(([name]) => (entity as any)[name]);\n}\n\nexport function getRelationEntries(entity: Entity): [string, AbstractRelationImpl<any, any>][] {\n return Object.entries(getProperties(getMetadata(entity)))\n .filter(([, v]) => v instanceof AbstractRelationImpl)\n .map(([name]) => [name, (entity as any)[name]]);\n}\n\n/** Casts a \"maybe abstract\" cstr to a concrete cstr when the calling code knows it's safe. */\nexport function asConcreteCstr<T extends Entity>(cstr: MaybeAbstractEntityConstructor<T>): EntityConstructor<T> {\n return cstr as any;\n}\n\n/**\n * Thrown when `.id` is accessed on an entity that does not have an id yet.\n *\n * For Postgres, entities are actually allowed to have ids pre-INSERT, if you call\n * `em.assignNewIds()`. Other databases typically require INSERTs to trigger the auto\n * id assignment.\n */\nexport class NoIdError extends Error {}\n\n/** Throws a `NoIdError` for `entity`, i.e. because `id` was called before being saved. */\nexport function failNoIdYet(entity: string): never {\n throw new NoIdError(`${entity} has no id yet`);\n}\n\n/**\n * Add a static function since getters can't have type guards.\n *\n * See https://github.com/microsoft/TypeScript/issues/43368\n */\nexport function isNewEntity<T extends Entity>(entity: T): entity is New<T> {\n return entity.isNewEntity;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,UAAU;CAAE,eAAA,iBAAA;CAAe,wBAAA,iBAAA;CAAwB,eAAA,iCAAA;AAAc;AAC9E,MAAa,YAAY,EAAE,kBAAA,2BAAA,iBAAiB;;;;;;;;;;;;;;;AAqP5C,SAAgB,QACd,QACA,QACA,MACM;CACN,MAAM,EAAE,wBAAwB,OAAO,YAAY,QAAQ,CAAC;CAG5D,IAAI,WAAW,KAAA,GAAW;EACxB,MAAM,OAAOA,uBAAAA,YAAY,MAAM;EAC/B,KAAK,MAAM,CAAC,KAAK,WAAW,OAAO,QAAQ,MAAY,GACrD,OAAO,MAAM,QAAQ,KAAK,QAAQ,SAAS,qBAAqB;CAEpE;AACF;;;;;;;;AASA,SAAgB,OACd,MACA,QACA,KACA,QACA,UAAU,OACV,wBAAwB,OAClB;CAEN,IAAI,CADU,KAAK,UAAU,MAIvB;MAAA,CADSC,sBAAAA,cAAc,IAAI,CAAC,CAAC,MAE/B,MAAM,IAAI,MAAM,iBAAiB,KAAK;CAAA;CAK1C,IAAI,WAAW,WAAW,KAAA,GAAW;CAErC,IAAI,KAAK,oBAAoB,SAASC,uBAAAA,YAAY,IAAI,CAAC,CAAC,0BAA0B,KAAK;CAGvF,MAAM,QAAQ,WAAW,OAAO,KAAA,IAAY;CAI5C,MAAM,UAAU,QAAQ,OAAOC,eAAAA,SA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AcD,uBAAAA,YAAY,MAAM,CAAC,CAAC,CAAC,CACtD,QAAQ,GAAG,OAAO,aAAaI,uCAAAA,oBAAoB,CAAC,CACpD,KAAK,CAAC,UAAW,OAAe,KAAK;AAC1C;AAEA,SAAgB,mBAAmB,QAA4D;CAC7F,OAAO,OAAO,QAAQH,sBAAAA,cAAcD,uBAAAA,YAAY,MAAM,CAAC,CAAC,CAAC,CACtD,QAAQ,GAAG,OAAO,aAAaI,uCAAAA,oBAAoB,CAAC,CACpD,KAAK,CAAC,UAAU,CAAC,MAAO,OAAe,KAAK,CAAC;AAClD;;AAGA,SAAgB,eAAiC,MAA+D;CAC9G,OAAO;AACT;;;;;;;;AASA,IAAa,YAAb,cAA+B,MAAM,CAAC;;AAGtC,SAAgB,YAAY,QAAuB;CACjD,MAAM,IAAI,UAAU,GAAG,OAAO,eAAe;AAC/C;;;;;;AAOA,SAAgB,YAA8B,QAA6B;CACzE,OAAO,OAAO;AAChB"}
1
+ {"version":3,"file":"index.cjs","names":["getMetadata","getProperties","getBaseMeta","getField","AbstractRelationImpl","isLazyField","isProperty","isAsyncProperty","isReactiveGetter","isReactiveField","isAsyncReactiveField","FactoryInitialValue","ReactiveFieldImpl","AsyncReactiveFieldImpl","getInstanceData"],"sources":["../src/index.ts"],"sourcesContent":["import { getInstanceData } from \"./BaseEntity.ts\";\nimport { getDefaultDependencies } from \"./defaults.ts\";\nimport { buildWhereClause } from \"./drivers/buildUtils.ts\";\nimport { type Entity } from \"./Entity.ts\";\nimport { type EntityConstructor, type MaybeAbstractEntityConstructor } from \"./EntityManager.ts\";\nimport { type EntityMetadata, getBaseMeta, getMetadata } from \"./EntityMetadata.ts\";\nimport { getField, setField } from \"./fields.ts\";\nimport { getProperties } from \"./getProperties.ts\";\nimport { type New } from \"./loadHints.ts\";\nimport { isAllSqlPaths } from \"./loadLens.ts\";\nimport { FactoryInitialValue } from \"./newTestInstance.ts\";\nimport { partitionHint } from \"./preloading/partitionHint.ts\";\nimport { AbstractRelationImpl } from \"./relations/AbstractRelationImpl.ts\";\nimport { AsyncReactiveFieldImpl } from \"./relations/AsyncReactiveField.ts\";\nimport {\n isAsyncProperty,\n isAsyncReactiveField,\n isLazyField,\n isProperty,\n isReactiveField,\n isReactiveGetter,\n} from \"./relations/index.ts\";\nimport { ReactiveFieldImpl } from \"./relations/ReactiveField.ts\";\nimport { type OptsOf } from \"./typeMap.ts\";\nimport { fail } from \"./utils.ts\";\n\nexport const testing = { isAllSqlPaths, getDefaultDependencies, partitionHint };\nexport const internals = { buildWhereClause };\nexport { newPgConnectionConfig } from \"joist-utils\";\nexport { AliasAssigner } from \"./AliasAssigner.ts\";\nexport {\n type AndCondition,\n type ConditionGroup,\n type DomainPredicate,\n type OrCondition,\n type PredicateBrand,\n type SqlCondition,\n type SqlPredicate,\n} from \"./conditions.ts\";\n// Domain aliases belong to em.find; physical table expressions belong to em.query/em.execute.\nexport {\n alias,\n aliases,\n getAliasMetadata,\n getAliasMgmt,\n getMaybeCtiAlias,\n isAlias,\n newAliasProxy,\n type Alias,\n type AliasBrand,\n type AliasMgmt,\n type AliasColumn,\n type EntityAlias,\n type PolyAlias,\n type PrimitiveAlias,\n} from \"./Aliases.ts\";\nexport {\n table,\n tables,\n tableMgmt,\n getTableMetadata,\n getTableMgmt,\n isTable,\n newTableProxy,\n type Table,\n type TableFilter,\n type TableBrand,\n type TableFor,\n type TableMgmt,\n type ReferenceJoin,\n type PrimitiveColumn,\n type EntityColumn,\n type ReferenceColumn,\n type CollectionJoin,\n type PolyReference,\n} from \"./Tables.ts\";\nexport { BaseEntity, getInstanceData } from \"./BaseEntity.ts\";\nexport { ConditionBuilder } from \"./ConditionBuilder.ts\";\nexport { type Entity, type IdType, isEntity } from \"./Entity.ts\";\nexport type * from \"./EntityFields.ts\";\nexport * from \"./EntityFilter.ts\";\nexport * from \"./EntityGraphQLFilter.ts\";\nexport * from \"./EntityManager.ts\";\nexport * from \"./EntityMetadata.ts\";\nexport type {\n DeleteStatement,\n ExecuteResult,\n InsertStatement,\n InsertValues,\n MutationReturning,\n MutationStatement,\n UpdateStatement,\n UpdateValues,\n} from \"./execute.ts\";\nexport type { EnumMetadata } from \"./EnumMetadata.ts\";\n// `em.query`'s expression surface. Only the user-facing types are re-exported: the runtime half\n// (BaseExpr, asNode, deferredCondition, the FnExpr/TemplateExpr node classes) stays internal to\n// joist-core, so `toSql`/`decode`/`encode` never show up as something a user could call.\nexport { type Expr, type ExprBrand, exprBrand, type ExprLike, type InnerJoin, type LeftJoin } from \"./Expr.ts\";\nexport { skipCondition } from \"./skipCondition.ts\";\nexport type { EntityOrId, HintNode } from \"./HintTree.ts\";\nexport { InstanceData } from \"./InstanceData.ts\";\nexport { type JoinColumnValue, type JoinRow, JoinRowOperation, type ManyToManyLike } from \"./JoinRows.ts\";\nexport type * from \"./PendingChanges.ts\";\nexport { Plugin } from \"./PluginManager.ts\";\nexport * from \"./QueryParser.ts\";\nexport * from \"./QueryParser.collectionJoins.ts\";\nexport { visitConditions } from \"./QueryVisitor.ts\";\nexport * from \"./RowData.ts\";\nexport { type JoinRowTodo, Todo } from \"./Todo.ts\";\nexport * from \"./changes.ts\";\nexport { ConfigApi, type EntityHook, resetBootFlag } from \"./config.ts\";\nexport {\n configureMetadata,\n getConstructorFromTaggedId,\n getMetadataForTable,\n getMetadataForType,\n maybeGetConstructorFromReference,\n} from \"./configure.ts\";\nexport { driverApi } from \"./driverApi.ts\";\nexport * from \"./drivers/index.ts\";\nexport { getField, isChangeableField, isFieldSet, setField } from \"./fields.ts\";\nexport * from \"./getProperties.ts\";\nexport * from \"./json.ts\";\nexport * from \"./keys.ts\";\nexport { kq, kqDot, kqStar } from \"./keywords.ts\";\nexport {\n assertLoaded,\n type DeepNew,\n ensureLoaded,\n isLoaded,\n isNew,\n type Loadable,\n type Loaded,\n type LoadHint,\n type MarkLoaded,\n maybePopulateThen,\n type NestedLoadHint,\n type New,\n type RelationsIn,\n unsafeLoaded,\n} from \"./loadHints.ts\";\nexport * from \"./loadLens.ts\";\nexport { setFactoryWriter } from \"./logging/FactoryLogger.ts\";\nexport * from \"./logging/FieldLogger.ts\";\nexport { ReactionLogger, setReactionLogging } from \"./logging/ReactionLogger.ts\";\nexport { lazyField } from \"./newEntity.ts\";\nexport {\n defaultValue,\n factories,\n type FactoryEntityOpt,\n type FactoryOpts,\n getTestIndex,\n isFactoryCreation,\n maybeBranchValue,\n maybeNew,\n maybeNewPoly,\n newTestInstance,\n noValue,\n setFactoryLogging,\n testIndex,\n} from \"./newTestInstance.ts\";\nexport { deepNormalizeHint, normalizeHint } from \"./normalizeHints.ts\";\nexport { ImmutableEntitiesPlugin } from \"./plugins/ImmutableEntitiesPlugin.ts\";\nexport type { JoinResult, PreloadHydrator, PreloadPlugin } from \"./plugins/PreloadPlugin.ts\";\nexport { JsonAggregatePreloader } from \"./preloading/JsonAggregatePreloader.ts\";\n// `em.query`'s query surface; the parse pipeline (SubqueryHandle, parseUserQuery, Plan) stays internal\nexport {\n type CheckScope,\n type Clauses,\n type EntityQuery,\n type ExistsQuery,\n entityQueryBrand,\n type MaybeNull,\n type NameOf,\n type NotWidened,\n type OrderByDirection,\n type OrderByKeys,\n type Query,\n type QueryArg,\n type QueryCondition,\n type QueryJoin,\n type QueryJoins,\n type QueryOrderBy,\n type QueryRow,\n type QuerySelect,\n type QuerySource,\n type QueryValue,\n recursiveQuery,\n type RecursiveOptions,\n type ScalarQuery,\n type SetQuery,\n query,\n sql,\n type Subquery,\n type SubqueryBrand,\n subqueryBrand,\n type WithInput,\n type WithSource,\n} from \"./query.ts\";\nexport {\n convertToLoadHint,\n isTypeOrSubType,\n type Reactable,\n type Reacted,\n type ReactiveHint,\n type ReactiveTarget,\n reverseReactiveHint,\n} from \"./reactiveHints.ts\";\nexport * from \"./relations/index.ts\";\nexport {\n cannotBeChanged,\n cannotBeUpdated,\n type GenericError,\n maxValueRule,\n minValueRule,\n mustBeSubType,\n newRequiredLazyFieldRule,\n newRequiredRule,\n rangeValueRule,\n ValidationCode,\n type ValidationError,\n ValidationErrors,\n type ValidationRule,\n type ValidationRuleInternal,\n type ValidationRuleResult,\n} from \"./rules.ts\";\nexport { getRuntimeConfig, setRuntimeConfig, type RuntimeConfig } from \"./runtimeConfig.ts\";\nexport { nowUTC } from \"./nowUTC.ts\";\nexport * from \"./serde.ts\";\nexport * from \"./columns.ts\";\nexport * from \"./fieldSerde.ts\";\nexport * from \"./scopes.ts\";\nexport { maybeRequireTemporal, requireTemporal, Temporal } from \"./temporal.ts\";\nexport * from \"./temporalMappers.ts\";\nexport { isInTrustedContext, runInTrustedContext } from \"./trusted.ts\";\nexport type * from \"./typeMap.ts\";\nexport { buildUnnestCte, ensureRectangularArraySizes } from \"./unnest.ts\";\nexport { type DeepPartialOrNull, updatePartial, upsert } from \"./upsert.ts\";\nexport {\n abbreviation,\n asNew,\n assertNever,\n cleanSql,\n cleanStringValue,\n fail,\n failIfAnyRejected,\n indexBy,\n partition,\n zeroTo,\n} from \"./utils.ts\";\nexport { ensureWithLoaded, StubbedRelation, type WithLoaded, withLoaded } from \"./withLoaded.ts\";\n\n// https://spin.atomicobject.com/2018/01/15/typescript-flexible-nominal-typing/\ninterface Flavoring<FlavorT> {\n _type?: FlavorT;\n}\n\nexport type Flavor<T, FlavorT> = T & Flavoring<FlavorT>;\n\n/**\n * Sets each value in `values` on the current entity.\n *\n * The default behavior is that passing a value as either `null` or `undefined` will set\n * the field as `undefined`, i.e. automatic `null` to `undefined` conversion.\n *\n * However, if you pass `ignoreUndefined: true`, then any opt that is `undefined` will be treated\n * as \"do not set\", and `null` will still mean \"set to `undefined`\". This is useful for implementing\n * APIs were an input of `undefined` means \"do not set / noop\" and `null` means \"unset\".\n *\n * Note that constructors _always_ call this method, but if the call is coming from `em.hydrate`, we\n * use `values` being a primary key to short-circuit and let hydration callers assign the values\n * returned by the serde `fromRow` methods.\n */\nexport function setOpts<T extends Entity>(\n entity: T,\n values: Partial<OptsOf<T>> | undefined,\n opts?: { partial?: boolean; calledFromConstructor?: boolean },\n): void {\n const { calledFromConstructor = false, partial } = opts || {};\n // If `values` is undefined, we're being called by `createPartial` that will do its\n // own opt handling, but we still want the sync defaults applied after this opts handling.\n if (values !== undefined) {\n const meta = getMetadata(entity);\n for (const [key, _value] of Object.entries(values as {})) {\n setOpt(meta, entity, key, _value, partial, calledFromConstructor);\n }\n }\n}\n\n/**\n * Applies some standard behavior & protections to `entity[key] = value`. I.e.\n *\n * - We don't set over AsyncProperties/relations/etc., and instead call current.set(value)\n * - We catch missing/invalid field names\n * - We handle FactoryInitialValues\n */\nexport function setOpt<T extends Entity>(\n meta: EntityMetadata<T>,\n entity: T,\n key: string,\n _value: any,\n partial = false,\n calledFromConstructor = false,\n): void {\n const field = meta.allFields[key];\n if (!field) {\n // Allow setting non-field properties like fullName setters\n const prop = getProperties(meta)[key];\n if (!prop) {\n throw new Error(`Unknown field ${key}`);\n }\n }\n\n // If partial is set, we treat undefined as a noop\n if (partial && _value === undefined) return;\n // Ignore the STI discriminator, em.register will set this accordingly\n if (meta.inheritanceType === \"sti\" && getBaseMeta(meta).stiDiscriminatorField === key) return;\n\n // We let optional opts fields be `| null` for convenience, and convert to undefined.\n const value = _value === null ? undefined : _value;\n\n // Use `getField` to side-step `id` blowing up on new entities that are setting an\n // explicit id; otherwise use `entity[key]` to get back the relation.\n const current = key === \"id\" ? getField(entity, key) : (entity as any)[key];\n\n if (current instanceof AbstractRelationImpl) {\n if (calledFromConstructor) {\n current.setFromOpts(value);\n } else {\n current.set(value);\n }\n } else if (isLazyField(current)) {\n current.set(value);\n } else if (isProperty(current) || isAsyncProperty(current) || isReactiveGetter(current)) {\n throw new Error(`Invalid argument, cannot set over ${key} ${current.constructor.name}`);\n } else if (isReactiveField(current) || isAsyncReactiveField(current)) {\n if (value instanceof FactoryInitialValue) {\n if (current instanceof ReactiveFieldImpl) {\n current.setFactoryValue(value.value);\n } else if (current instanceof AsyncReactiveFieldImpl) {\n current.setFactoryValue(value.value);\n } else {\n throw new Error(`Unhandled case ${current.constructor.name}`);\n }\n } else {\n throw new Error(`Invalid argument, cannot set over ${key} ${current.constructor.name}`);\n }\n } else {\n // If setting an explicit id, go through setField, otherwise use\n // `entity[key]` to set the value directly to that we go through setters.\n if (key === \"id\" && entity.isNewEntity) {\n setField(entity, key, value);\n } else {\n (entity as any)[key] = value;\n }\n }\n}\n\nexport function ensureNotDeleted(entity: Entity, ignore?: \"pending\"): void {\n if (entity.isDeletedEntity && (ignore === undefined || getInstanceData(entity).isDeletedAndFlushed)) {\n fail(`${entity} is marked as deleted`);\n }\n}\n\n/** Adds `null` to every key in `T` to accept partial-update-style input. */\nexport type PartialOrNull<T> = {\n [P in keyof T]?: T[P] | null;\n};\n\nexport function getRequiredKeys<T extends Entity>(entity: T): string[];\nexport function getRequiredKeys<T extends Entity>(type: EntityConstructor<T>): string[];\nexport function getRequiredKeys<T extends Entity>(entityOrType: T | EntityConstructor<T>): string[] {\n return Object.values(getMetadata(entityOrType as any).fields)\n .filter((f) => f.required)\n .map((f) => f.fieldName);\n}\n\nexport function getRelations(entity: Entity): AbstractRelationImpl<any, any>[] {\n return Object.entries(getProperties(getMetadata(entity)))\n .filter(([, v]) => v instanceof AbstractRelationImpl)\n .map(([name]) => (entity as any)[name]);\n}\n\nexport function getRelationEntries(entity: Entity): [string, AbstractRelationImpl<any, any>][] {\n return Object.entries(getProperties(getMetadata(entity)))\n .filter(([, v]) => v instanceof AbstractRelationImpl)\n .map(([name]) => [name, (entity as any)[name]]);\n}\n\n/** Casts a \"maybe abstract\" cstr to a concrete cstr when the calling code knows it's safe. */\nexport function asConcreteCstr<T extends Entity>(cstr: MaybeAbstractEntityConstructor<T>): EntityConstructor<T> {\n return cstr as any;\n}\n\n/**\n * Thrown when `.id` is accessed on an entity that does not have an id yet.\n *\n * For Postgres, entities are actually allowed to have ids pre-INSERT, if you call\n * `em.assignNewIds()`. Other databases typically require INSERTs to trigger the auto\n * id assignment.\n */\nexport class NoIdError extends Error {}\n\n/** Throws a `NoIdError` for `entity`, i.e. because `id` was called before being saved. */\nexport function failNoIdYet(entity: string): never {\n throw new NoIdError(`${entity} has no id yet`);\n}\n\n/**\n * Add a static function since getters can't have type guards.\n *\n * See https://github.com/microsoft/TypeScript/issues/43368\n */\nexport function isNewEntity<T extends Entity>(entity: T): entity is New<T> {\n return entity.isNewEntity;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,UAAU;CAAE,eAAA,iBAAA;CAAe,wBAAA,iBAAA;CAAwB,eAAA,iCAAA;AAAc;AAC9E,MAAa,YAAY,EAAE,kBAAA,2BAAA,iBAAiB;;;;;;;;;;;;;;;AAuP5C,SAAgB,QACd,QACA,QACA,MACM;CACN,MAAM,EAAE,wBAAwB,OAAO,YAAY,QAAQ,CAAC;CAG5D,IAAI,WAAW,KAAA,GAAW;EACxB,MAAM,OAAOA,uBAAAA,YAAY,MAAM;EAC/B,KAAK,MAAM,CAAC,KAAK,WAAW,OAAO,QAAQ,MAAY,GACrD,OAAO,MAAM,QAAQ,KAAK,QAAQ,SAAS,qBAAqB;CAEpE;AACF;;;;;;;;AASA,SAAgB,OACd,MACA,QACA,KACA,QACA,UAAU,OACV,wBAAwB,OAClB;CAEN,IAAI,CADU,KAAK,UAAU,MAIvB;MAAA,CADSC,sBAAAA,cAAc,IAAI,CAAC,CAAC,MAE/B,MAAM,IAAI,MAAM,iBAAiB,KAAK;CAAA;CAK1C,IAAI,WAAW,WAAW,KAAA,GAAW;CAErC,IAAI,KAAK,oBAAoB,SAASC,uBAAAA,YAAY,IAAI,CAAC,CAAC,0BAA0B,KAAK;CAGvF,MAAM,QAAQ,WAAW,OAAO,KAAA,IAAY;CAI5C,MAAM,UAAU,QAAQ,OAAOC,eAAAA,SAAS,QAAQ,GAAG,IAAK,OAAe;CAEvE,IAAI,mBAAmBC,uCAAAA,sBAAsB;EAC3C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,uCAAAA,oBAAoB,CAAC,CACpD,KAAK,CAAC,UAAW,OAAe,KAAK;AAC1C;AAEA,SAAgB,mBAAmB,QAA4D;CAC7F,OAAO,OAAO,QAAQH,sBAAAA,cAAcD,uBAAAA,YAAY,MAAM,CAAC,CAAC,CAAC,CACtD,QAAQ,GAAG,OAAO,aAAaI,uCAAAA,oBAAoB,CAAC,CACpD,KAAK,CAAC,UAAU,CAAC,MAAO,OAAe,KAAK,CAAC;AAClD;;AAGA,SAAgB,eAAiC,MAA+D;CAC9G,OAAO;AACT;;;;;;;;AASA,IAAa,YAAb,cAA+B,MAAM,CAAC;;AAGtC,SAAgB,YAAY,QAAuB;CACjD,MAAM,IAAI,UAAU,GAAG,OAAO,eAAe;AAC/C;;;;;;AAOA,SAAgB,YAA8B,QAA6B;CACzE,OAAO,OAAO;AAChB"}
package/build/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { ConditionGroup, DomainPredicate, PredicateBrand, SqlCondition, SqlPredicate } from "./conditions.cjs";
1
+ import { AndCondition, ConditionGroup, DomainPredicate, OrCondition, PredicateBrand, SqlCondition, SqlPredicate } from "./conditions.cjs";
2
2
  import { Temporal, maybeRequireTemporal, requireTemporal } from "./temporal.cjs";
3
3
  import { BigIntSerde, CustomSerde, CustomSerdeAdapter, DateSerde, DecimalToNumberSerde, EnumArrayFieldSerde, EnumFieldSerde, JsonSerde, KeySerde, PlainDateSerde, PlainDateTimeSerde, PlainTimeSerde, PrimitiveSerde, ScalarCodec, SuperstructSerde, TimestampCodec, ZodSerde, ZonedDateTimeSerde } from "./serde.cjs";
4
4
  import { Column, ColumnDescriptors } from "./columns.cjs";
@@ -168,5 +168,5 @@ declare function failNoIdYet(entity: string): never;
168
168
  */
169
169
  declare function isNewEntity<T extends Entity>(entity: T): entity is New<T>;
170
170
  //#endregion
171
- export { type ActualFactoryOpts, type Alias, AliasAssigner, type AliasBrand, type AliasColumn, AliasFn, type AliasMgmt, type AsyncMethod, type AsyncProperty, AsyncPropertyImpl, BaseEntity, BigIntSerde, BooleanFilter, BooleanGraphQLFilter, Changes, type CheckScope, type Clauses, type Collection, type CollectionJoin, Column, ColumnCondition, ColumnDescriptors, type ColumnsOf, ConditionBuilder, type ConditionGroup, ConfigApi, CrossJoinTable, CustomCollection, CustomJsonKeyHint, CustomReference, CustomSerde, CustomSerdeAdapter, DateSerde, DecimalToNumberSerde, type DeepNew, type DeepPartialOrNull, DeleteOp, type DeleteStatement, type DomainPredicate, type Driver, type DriverQueryResult, type Entity, type EntityAlias, EntityChanges, type EntityColumn, EntityConstructor, type EntityField, type EntityFields, EntityFilter, EntityFilterObject, EntityGraphQLFilter, type EntityHook, EntityKeyJsonHint, EntityManager, EntityManagerHook, EntityManagerInternalApi, EntityManagerMode, EntityManagerOpts, EntityMetadata, type EntityOf, type EntityOrId, type EntityQuery, EnumArrayFieldSerde, type EnumCollection, EnumCollectionFieldStatus, EnumCollectionImpl, EnumField, EnumFieldSerde, type EnumMetadata, type ExecuteResult, ExistsCondition, type ExistsQuery, type Expr, type ExprBrand, type ExprLike, ExpressionCondition, ExpressionFilter, type FactoryEntityOpt, type FactoryExtrasOf, type FactoryOpts, Field, FieldColumn, FieldLogger, FieldLoggerWatch, FieldSerde, FieldStatus, type FieldsOf, FilterAndSettings, type FilterOf, FilterWithAlias, FindCountFilterOptions, FindFilter, FindFilterOptions, FindGqlFilterOptions, FindOperation, Flavor, FlushOptions, type GenericError, GraphQLFilterAndSettings, type GraphQLFilterOf, GraphQLFilterWithAlias, type HintNode, IdAssigner, IdOf, type IdType, ImmutableEntitiesPlugin, type InheritanceTypeOf, type InnerJoin, InsertFixup, InsertOp, type InsertStatement, type InsertValues, InstanceData, type JoinColumnValue, type JoinResult, type JoinRow, JoinRowOperation, type JoinRowTodo, JoinTable, JsonAggregatePreloader, JsonHint, JsonPayload, JsonSerde, Jsonable, JsonableValue, KeySerde, type LargeCollection, LargeOneToManyField, LateralJoinTable, type LazyField, LazyFieldImpl, type LeftJoin, Lens, type LoadHint, type Loadable, type Loaded, type LoadedCollection, type LoadedEnumCollection, type LoadedMethod, type LoadedProperty, type LoadedReadOnlyCollection, type LoadedReference, LoaderCache, ManyToManyCollection, ManyToManyEnumField, ManyToManyField, ManyToManyFieldStatus, ManyToManyLargeCollection, type ManyToManyLike, ManyToOneField, ManyToOneFieldStatus, type ManyToOneReference, ManyToOneReferenceImpl, type MarkLoaded, MaybeAbstractEntityConstructor, type MaybeNull, type MutationReturning, type MutationStatement, type NameOf, NestedJsonHint, type NestedLoadHint, type New, NoIdError, NotFoundError, type NotWidened, OneToManyCollection, OneToManyField, OneToManyFieldStatus, OneToManyLargeCollection, OneToOneField, type OneToOneReference, OneToOneReferenceImpl, OpColumn, Operator, type OptIdsOf, type OptsOf, OrderBy, type OrderByDirection, type OrderByKeys, type OrderOf, ParsedCteClause, ParsedEntityFilter, ParsedExpressionCondition, ParsedExpressionFilter, ParsedFindQuery, ParsedGroupBy, ParsedOrderBy, ParsedSelect, ParsedTable, ParsedValueFilter, PartialOrNull, type PendingChange, type PendingCreate, type PendingDelete, type PendingM2M, type PendingUpdate, PlainDateSerde, PlainDateTimeSerde, PlainTimeSerde, Plugin, PojoRowData, type PolyAlias, PolyComponent, type PolyReference, PolymorphicField, PolymorphicFieldComponent, PolymorphicKeySerde, type PolymorphicReference, PolymorphicReferenceImpl, type PredicateBrand, type PreloadHydrator, type PreloadPlugin, PrimaryKeyField, PrimaryTable, type PrimitiveAlias, type PrimitiveColumn, PrimitiveField, PrimitiveFieldStatus, PrimitiveSerde, type Property, PropertyImpl, type Query, type QueryArg, type QueryCondition, type QueryJoin, type QueryJoins, type QueryOrderBy, type QueryRow, type QuerySelect, type QuerySource, type QueryValue, RandomUuidAssigner, RawCondition, type Reactable, type Reacted, ReactionLogger, type ReactiveField, type ReactiveGetter, type ReactiveHint, type ReactiveManyToMany, ReactiveManyToManyImpl, type ReactiveManyToManyOtherSide, ReactiveManyToManyOtherSideImpl, type ReactiveReference, ReactiveReferenceImpl, type ReactiveTarget, type ReadOnlyCollection, ReadOnlyError, RecursiveCycleError, type RecursiveOptions, type Reference, type ReferenceColumn, type ReferenceJoin, type Relation, type RelationsIn, type RelationsOf, ResolvedScope, type RootTypeNameOf, RowData, type RuntimeConfig, ScalarCodec, type ScalarQuery, Scope, ScopeFilterFragment, ScopeFn, ScopeJoinFilter, ScopeQuery, SequenceIdAssigner, SerdeField, type SetQuery, type SettableFields, SimpleFieldSerde, type SqlCondition, type SqlPredicate, StubbedRelation, type Subquery, type SubqueryBrand, SubqueryRenderer, SuperstructSerde, type Table, type TableBrand, type TableFilter, type TableFor, type TableMgmt, TaggedId, Temporal, TestUuidAssigner, TimestampCodec, TimestampFields, TimestampSerde, ToJsonHint, Todo, TooManyError, type TypeMap, type TypeMapEntry, type TypeNameOf, UniqueFilter, UnknownProperty, UpdateOp, type UpdateStatement, type UpdateValues, ValidationCode, type ValidationError, ValidationErrors, type ValidationRule, type ValidationRuleInternal, type ValidationRuleResult, ValueFilter, ValueGraphQLFilter, type WithInput, type WithLoaded, type WithSource, WriteFn, ZodSerde, ZonedDateTimeSerde, abbreviation, addTablePerClassJoinsAndClassTag, alias, aliases, appendStack, asConcreteCstr, asNew, assertIdIsTagged, assertIdsAreTagged, assertLoaded, assertNever, buildCteSql, buildRawQuery, buildUnnestCte, buildValueCondition, buildWhereClause, cannotBeChanged, cannotBeUpdated, cleanSql, cleanStringValue, configureMetadata, convertToLoadHint, createRowFromEntityData, deTagId, deTagIds, deepNormalizeHint, defaultValue, driverAfterBegin, driverAfterCommit, driverApi, driverBeforeBegin, driverBeforeCommit, emptyRowData, ensureLoaded, ensureNotDeleted, ensureRectangularArraySizes, ensureTagged, ensureWithLoaded, entityQueryBrand, exprBrand, factories, fail, failIfAnyRejected, failNoIdYet, filterSoftDeletes, findFilterField, generateOps, getAliasMetadata, getAliasMgmt, getBaseAndSelfMetas, getBaseMeta, getBaseSelfAndSubMetas, getConstructorFromTaggedId, getDefaultEntityLimit, getEmInternalApi, getField, getInstanceData, getLazyFields, getLens, getLensPath, getMaybeCtiAlias, getMetadata, getMetadataForField, getMetadataForTable, getMetadataForType, getProperties, getRelationEntries, getRelations, getRequiredKeys, getRuntimeConfig, getSubMetas, getTableMetadata, getTableMgmt, getTables, getTestIndex, hasAsyncMethod, hasAsyncProperty, hasAsyncReactiveField, hasCustomCollection, hasCustomReference, hasEnumCollection, hasLargeMany, hasLargeManyToMany, hasLazyField, hasMany, hasManyDerived, hasManyThrough, hasManyToMany, hasOne, hasOneDerived, hasOnePolymorphic, hasOneThrough, hasOneToOne, hasProperty, hasReactiveField, hasReactiveGetter, hasReactiveManyToMany, hasReactiveManyToManyOtherSide, hasReactiveProperty, hasReactiveReference, hasRecursiveChildren, hasRecursiveM2m, hasRecursiveParents, hasSerde, indexBy, internals, isAlias, isAllSqlPaths, isAsyncProperty, isAsyncReactiveField, isChangeableField, isCollection, isCollectionField, isDefined, isEntity, isFactoryCreation, isFieldSet, isId, isInTrustedContext, isKey, isLazyField, isLensLoaded, isLensLoadedPath, isLoaded, isLoadedAsyncProperty, isLoadedCollection, isLoadedLazyField, isLoadedOneToOneReference, isLoadedProperty, isLoadedReadOnlyCollection, isLoadedReference, isManyToManyEnumField, isManyToManyField, isManyToOneField, isManyToOneReference, isNew, isNewEntity, isOneToManyField, isOneToOneField, isOneToOneReference, isPolymorphicField, isPolymorphicReference, isProperty, isReactiveField, isReactiveGetter, isReactiveManyToMany, isReactiveManyToManyOtherSide, isReactiveReference, isReadOnlyCollection, isReference, isReferenceField, isRelation, isScope, isScopeJoinFilter, isSelectAllFilter, isTable, isTaggedId, isTypeOrSubType, keyToNumber, keyToTaggedId, kq, kqDot, kqStar, lazyExcludedSelects, lazyField, lensPathToLoadHint, lensToLoadHint, lensToPath, loadLens, loadLensPath, makeLike, mapPathsToTarget, mapToDb, maxValueRule, maybeAddIdNotNulls, maybeAddNotSoftDeleted, maybeAddOrderBy, maybeBranchValue, maybeGetConstructorFromReference, maybeNew, maybeNewPoly, maybePopulateThen, maybeRequireTemporal, maybeResolveReferenceToId, mergeFindOptions, minValueRule, mustBeSubType, newAliasProxy, newChangesProxy, newPgConnectionConfig, newRequiredLazyFieldRule, newRequiredRule, newScopeFn, newTableProxy, newTestInstance, noValue, noopFieldLogger, normalizeHint, nowUTC, opToFn, operators, optimizeCollectionJoins, parseAlias, parseEntityFilter, parseFindQuery, parseValueFilter, partition, plainDateMapper, plainDateTimeMapper, plainTimeMapper, polymorphicField, query, rangeValueRule, recursiveQuery, requireTemporal, resetBootFlag, resetDefaultEntityLimit, resolveScope, reverseReactiveHint, runInTrustedContext, sameEntity, sameReference, setDefaultEntityLimit, setFactoryLogging, setFactoryWriter, setField, setLastNow, setOpt, setOpts, setReactionLogging, setRuntimeConfig, setTaggedIdDelimiter, skipCondition, sql, stiSubtypeFilter, subqueryBrand, table, tableMgmt, tables, tagFromId, tagId, tagIds, testIndex, testing, toIdOf, toJSON, toTaggedId, unsafeDeTagIds, unsafeLoaded, updatePartial, upsert, visitConditions, withLoaded, zeroTo, zonedDateTimeMapper };
171
+ export { type ActualFactoryOpts, type Alias, AliasAssigner, type AliasBrand, type AliasColumn, AliasFn, type AliasMgmt, type AndCondition, type AsyncMethod, type AsyncProperty, AsyncPropertyImpl, BaseEntity, BigIntSerde, BooleanFilter, BooleanGraphQLFilter, Changes, type CheckScope, type Clauses, type Collection, type CollectionJoin, Column, ColumnCondition, ColumnDescriptors, type ColumnsOf, ConditionBuilder, type ConditionGroup, ConfigApi, CrossJoinTable, CustomCollection, CustomJsonKeyHint, CustomReference, CustomSerde, CustomSerdeAdapter, DateSerde, DecimalToNumberSerde, type DeepNew, type DeepPartialOrNull, DeleteOp, type DeleteStatement, type DomainPredicate, type Driver, type DriverQueryResult, type Entity, type EntityAlias, EntityChanges, type EntityColumn, EntityConstructor, type EntityField, type EntityFields, EntityFilter, EntityFilterObject, EntityGraphQLFilter, type EntityHook, EntityKeyJsonHint, EntityManager, EntityManagerHook, EntityManagerInternalApi, EntityManagerMode, EntityManagerOpts, EntityMetadata, type EntityOf, type EntityOrId, type EntityQuery, EnumArrayFieldSerde, type EnumCollection, EnumCollectionFieldStatus, EnumCollectionImpl, EnumField, EnumFieldSerde, type EnumMetadata, type ExecuteResult, ExistsCondition, type ExistsQuery, type Expr, type ExprBrand, type ExprLike, ExpressionCondition, ExpressionFilter, type FactoryEntityOpt, type FactoryExtrasOf, type FactoryOpts, Field, FieldColumn, FieldLogger, FieldLoggerWatch, FieldSerde, FieldStatus, type FieldsOf, FilterAndSettings, type FilterOf, FilterWithAlias, FindCountFilterOptions, FindFilter, FindFilterOptions, FindGqlFilterOptions, FindOperation, Flavor, FlushOptions, type GenericError, GraphQLFilterAndSettings, type GraphQLFilterOf, GraphQLFilterWithAlias, type HintNode, IdAssigner, IdOf, type IdType, ImmutableEntitiesPlugin, type InheritanceTypeOf, type InnerJoin, InsertFixup, InsertOp, type InsertStatement, type InsertValues, InstanceData, type JoinColumnValue, type JoinResult, type JoinRow, JoinRowOperation, type JoinRowTodo, JoinTable, JsonAggregatePreloader, JsonHint, JsonPayload, JsonSerde, Jsonable, JsonableValue, KeySerde, type LargeCollection, LargeOneToManyField, LateralJoinTable, type LazyField, LazyFieldImpl, type LeftJoin, Lens, type LoadHint, type Loadable, type Loaded, type LoadedCollection, type LoadedEnumCollection, type LoadedMethod, type LoadedProperty, type LoadedReadOnlyCollection, type LoadedReference, LoaderCache, ManyToManyCollection, ManyToManyEnumField, ManyToManyField, ManyToManyFieldStatus, ManyToManyLargeCollection, type ManyToManyLike, ManyToOneField, ManyToOneFieldStatus, type ManyToOneReference, ManyToOneReferenceImpl, type MarkLoaded, MaybeAbstractEntityConstructor, type MaybeNull, type MutationReturning, type MutationStatement, type NameOf, NestedJsonHint, type NestedLoadHint, type New, NoIdError, NotFoundError, type NotWidened, OneToManyCollection, OneToManyField, OneToManyFieldStatus, OneToManyLargeCollection, OneToOneField, type OneToOneReference, OneToOneReferenceImpl, OpColumn, Operator, type OptIdsOf, type OptsOf, type OrCondition, OrderBy, type OrderByDirection, type OrderByKeys, type OrderOf, ParsedCteClause, ParsedEntityFilter, ParsedExpressionCondition, ParsedExpressionFilter, ParsedFindQuery, ParsedGroupBy, ParsedOrderBy, ParsedSelect, ParsedTable, ParsedValueFilter, PartialOrNull, type PendingChange, type PendingCreate, type PendingDelete, type PendingM2M, type PendingUpdate, PlainDateSerde, PlainDateTimeSerde, PlainTimeSerde, Plugin, PojoRowData, type PolyAlias, PolyComponent, type PolyReference, PolymorphicField, PolymorphicFieldComponent, PolymorphicKeySerde, type PolymorphicReference, PolymorphicReferenceImpl, type PredicateBrand, type PreloadHydrator, type PreloadPlugin, PrimaryKeyField, PrimaryTable, type PrimitiveAlias, type PrimitiveColumn, PrimitiveField, PrimitiveFieldStatus, PrimitiveSerde, type Property, PropertyImpl, type Query, type QueryArg, type QueryCondition, type QueryJoin, type QueryJoins, type QueryOrderBy, type QueryRow, type QuerySelect, type QuerySource, type QueryValue, RandomUuidAssigner, RawCondition, type Reactable, type Reacted, ReactionLogger, type ReactiveField, type ReactiveGetter, type ReactiveHint, type ReactiveManyToMany, ReactiveManyToManyImpl, type ReactiveManyToManyOtherSide, ReactiveManyToManyOtherSideImpl, type ReactiveReference, ReactiveReferenceImpl, type ReactiveTarget, type ReadOnlyCollection, ReadOnlyError, RecursiveCycleError, type RecursiveOptions, type Reference, type ReferenceColumn, type ReferenceJoin, type Relation, type RelationsIn, type RelationsOf, ResolvedScope, type RootTypeNameOf, RowData, type RuntimeConfig, ScalarCodec, type ScalarQuery, Scope, ScopeFilterFragment, ScopeFn, ScopeJoinFilter, ScopeQuery, SequenceIdAssigner, SerdeField, type SetQuery, type SettableFields, SimpleFieldSerde, type SqlCondition, type SqlPredicate, StubbedRelation, type Subquery, type SubqueryBrand, SubqueryRenderer, SuperstructSerde, type Table, type TableBrand, type TableFilter, type TableFor, type TableMgmt, TaggedId, Temporal, TestUuidAssigner, TimestampCodec, TimestampFields, TimestampSerde, ToJsonHint, Todo, TooManyError, type TypeMap, type TypeMapEntry, type TypeNameOf, UniqueFilter, UnknownProperty, UpdateOp, type UpdateStatement, type UpdateValues, ValidationCode, type ValidationError, ValidationErrors, type ValidationRule, type ValidationRuleInternal, type ValidationRuleResult, ValueFilter, ValueGraphQLFilter, type WithInput, type WithLoaded, type WithSource, WriteFn, ZodSerde, ZonedDateTimeSerde, abbreviation, addTablePerClassJoinsAndClassTag, alias, aliases, appendStack, asConcreteCstr, asNew, assertIdIsTagged, assertIdsAreTagged, assertLoaded, assertNever, buildCteSql, buildRawQuery, buildUnnestCte, buildValueCondition, buildWhereClause, cannotBeChanged, cannotBeUpdated, cleanSql, cleanStringValue, configureMetadata, convertToLoadHint, createRowFromEntityData, deTagId, deTagIds, deepNormalizeHint, defaultValue, driverAfterBegin, driverAfterCommit, driverApi, driverBeforeBegin, driverBeforeCommit, emptyRowData, ensureLoaded, ensureNotDeleted, ensureRectangularArraySizes, ensureTagged, ensureWithLoaded, entityQueryBrand, exprBrand, factories, fail, failIfAnyRejected, failNoIdYet, filterSoftDeletes, findFilterField, generateOps, getAliasMetadata, getAliasMgmt, getBaseAndSelfMetas, getBaseMeta, getBaseSelfAndSubMetas, getConstructorFromTaggedId, getDefaultEntityLimit, getEmInternalApi, getField, getInstanceData, getLazyFields, getLens, getLensPath, getMaybeCtiAlias, getMetadata, getMetadataForField, getMetadataForTable, getMetadataForType, getProperties, getRelationEntries, getRelations, getRequiredKeys, getRuntimeConfig, getSubMetas, getTableMetadata, getTableMgmt, getTables, getTestIndex, hasAsyncMethod, hasAsyncProperty, hasAsyncReactiveField, hasCustomCollection, hasCustomReference, hasEnumCollection, hasLargeMany, hasLargeManyToMany, hasLazyField, hasMany, hasManyDerived, hasManyThrough, hasManyToMany, hasOne, hasOneDerived, hasOnePolymorphic, hasOneThrough, hasOneToOne, hasProperty, hasReactiveField, hasReactiveGetter, hasReactiveManyToMany, hasReactiveManyToManyOtherSide, hasReactiveProperty, hasReactiveReference, hasRecursiveChildren, hasRecursiveM2m, hasRecursiveParents, hasSerde, indexBy, internals, isAlias, isAllSqlPaths, isAsyncProperty, isAsyncReactiveField, isChangeableField, isCollection, isCollectionField, isDefined, isEntity, isFactoryCreation, isFieldSet, isId, isInTrustedContext, isKey, isLazyField, isLensLoaded, isLensLoadedPath, isLoaded, isLoadedAsyncProperty, isLoadedCollection, isLoadedLazyField, isLoadedOneToOneReference, isLoadedProperty, isLoadedReadOnlyCollection, isLoadedReference, isManyToManyEnumField, isManyToManyField, isManyToOneField, isManyToOneReference, isNew, isNewEntity, isOneToManyField, isOneToOneField, isOneToOneReference, isPolymorphicField, isPolymorphicReference, isProperty, isReactiveField, isReactiveGetter, isReactiveManyToMany, isReactiveManyToManyOtherSide, isReactiveReference, isReadOnlyCollection, isReference, isReferenceField, isRelation, isScope, isScopeJoinFilter, isSelectAllFilter, isTable, isTaggedId, isTypeOrSubType, keyToNumber, keyToTaggedId, kq, kqDot, kqStar, lazyExcludedSelects, lazyField, lensPathToLoadHint, lensToLoadHint, lensToPath, loadLens, loadLensPath, makeLike, mapPathsToTarget, mapToDb, maxValueRule, maybeAddIdNotNulls, maybeAddNotSoftDeleted, maybeAddOrderBy, maybeBranchValue, maybeGetConstructorFromReference, maybeNew, maybeNewPoly, maybePopulateThen, maybeRequireTemporal, maybeResolveReferenceToId, mergeFindOptions, minValueRule, mustBeSubType, newAliasProxy, newChangesProxy, newPgConnectionConfig, newRequiredLazyFieldRule, newRequiredRule, newScopeFn, newTableProxy, newTestInstance, noValue, noopFieldLogger, normalizeHint, nowUTC, opToFn, operators, optimizeCollectionJoins, parseAlias, parseEntityFilter, parseFindQuery, parseValueFilter, partition, plainDateMapper, plainDateTimeMapper, plainTimeMapper, polymorphicField, query, rangeValueRule, recursiveQuery, requireTemporal, resetBootFlag, resetDefaultEntityLimit, resolveScope, reverseReactiveHint, runInTrustedContext, sameEntity, sameReference, setDefaultEntityLimit, setFactoryLogging, setFactoryWriter, setField, setLastNow, setOpt, setOpts, setReactionLogging, setRuntimeConfig, setTaggedIdDelimiter, skipCondition, sql, stiSubtypeFilter, subqueryBrand, table, tableMgmt, tables, tagFromId, tagId, tagIds, testIndex, testing, toIdOf, toJSON, toTaggedId, unsafeDeTagIds, unsafeLoaded, updatePartial, upsert, visitConditions, withLoaded, zeroTo, zonedDateTimeMapper };
172
172
  //# sourceMappingURL=index.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA0Ba;;;;;cACA;2BAAA;;UAiOH,UAAU;EAClB,QAAQ;;KAGE,OAAO,GAAG,WAAW,IAAI,UAAU;;;;;;;;;;;;;;;iBAgB/B,QAAQ,UAAU,QAChC,QAAQ,GACR,QAAQ,QAAQ,OAAO,iBACvB;EAAS;EAAmB;;;;;;;;;iBAoBd,OAAO,UAAU,QAC/B,MAAM,eAAe,IACrB,QAAQ,GACR,aACA,aACA,mBACA;iBAwDc,iBAAiB,QAAQ,QAAQ;;KAOrC,cAAc,QACvB,WAAW,KAAK,EAAE;iBAGL,gBAAgB,UAAU,QAAQ,QAAQ;iBAC1C,gBAAgB,UAAU,QAAQ,MAAM,kBAAkB;iBAO1D,aAAa,QAAQ,SAAS;iBAM9B,mBAAmB,QAAQ,kBAAkB;;iBAO7C,eAAe,UAAU,QAAQ,MAAM,+BAA+B,KAAK,kBAAkB;;;;;;;;cAWhG,kBAAkB;;iBAGf,YAAY;;;;;;iBASZ,YAAY,UAAU,QAAQ,QAAQ,IAAI,UAAU,IAAI"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA0Ba;;;;;cACA;2BAAA;;UAmOH,UAAU;EAClB,QAAQ;;KAGE,OAAO,GAAG,WAAW,IAAI,UAAU;;;;;;;;;;;;;;;iBAgB/B,QAAQ,UAAU,QAChC,QAAQ,GACR,QAAQ,QAAQ,OAAO,iBACvB;EAAS;EAAmB;;;;;;;;;iBAoBd,OAAO,UAAU,QAC/B,MAAM,eAAe,IACrB,QAAQ,GACR,aACA,aACA,mBACA;iBAwDc,iBAAiB,QAAQ,QAAQ;;KAOrC,cAAc,QACvB,WAAW,KAAK,EAAE;iBAGL,gBAAgB,UAAU,QAAQ,QAAQ;iBAC1C,gBAAgB,UAAU,QAAQ,MAAM,kBAAkB;iBAO1D,aAAa,QAAQ,SAAS;iBAM9B,mBAAmB,QAAQ,kBAAkB;;iBAO7C,eAAe,UAAU,QAAQ,MAAM,+BAA+B,KAAK,kBAAkB;;;;;;;;cAWhG,kBAAkB;;iBAGf,YAAY;;;;;;iBASZ,YAAY,UAAU,QAAQ,QAAQ,IAAI,UAAU,IAAI"}
package/build/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { ConditionGroup, DomainPredicate, PredicateBrand, SqlCondition, SqlPredicate } from "./conditions.mjs";
1
+ import { AndCondition, ConditionGroup, DomainPredicate, OrCondition, PredicateBrand, SqlCondition, SqlPredicate } from "./conditions.mjs";
2
2
  import { Temporal, maybeRequireTemporal, requireTemporal } from "./temporal.mjs";
3
3
  import { BigIntSerde, CustomSerde, CustomSerdeAdapter, DateSerde, DecimalToNumberSerde, EnumArrayFieldSerde, EnumFieldSerde, JsonSerde, KeySerde, PlainDateSerde, PlainDateTimeSerde, PlainTimeSerde, PrimitiveSerde, ScalarCodec, SuperstructSerde, TimestampCodec, ZodSerde, ZonedDateTimeSerde } from "./serde.mjs";
4
4
  import { Column, ColumnDescriptors } from "./columns.mjs";
@@ -168,5 +168,5 @@ declare function failNoIdYet(entity: string): never;
168
168
  */
169
169
  declare function isNewEntity<T extends Entity>(entity: T): entity is New<T>;
170
170
  //#endregion
171
- export { type ActualFactoryOpts, type Alias, AliasAssigner, type AliasBrand, type AliasColumn, AliasFn, type AliasMgmt, type AsyncMethod, type AsyncProperty, AsyncPropertyImpl, BaseEntity, BigIntSerde, BooleanFilter, BooleanGraphQLFilter, Changes, type CheckScope, type Clauses, type Collection, type CollectionJoin, Column, ColumnCondition, ColumnDescriptors, type ColumnsOf, ConditionBuilder, type ConditionGroup, ConfigApi, CrossJoinTable, CustomCollection, CustomJsonKeyHint, CustomReference, CustomSerde, CustomSerdeAdapter, DateSerde, DecimalToNumberSerde, type DeepNew, type DeepPartialOrNull, DeleteOp, type DeleteStatement, type DomainPredicate, type Driver, type DriverQueryResult, type Entity, type EntityAlias, EntityChanges, type EntityColumn, EntityConstructor, type EntityField, type EntityFields, EntityFilter, EntityFilterObject, EntityGraphQLFilter, type EntityHook, EntityKeyJsonHint, EntityManager, EntityManagerHook, EntityManagerInternalApi, EntityManagerMode, EntityManagerOpts, EntityMetadata, type EntityOf, type EntityOrId, type EntityQuery, EnumArrayFieldSerde, type EnumCollection, EnumCollectionFieldStatus, EnumCollectionImpl, EnumField, EnumFieldSerde, type EnumMetadata, type ExecuteResult, ExistsCondition, type ExistsQuery, type Expr, type ExprBrand, type ExprLike, ExpressionCondition, ExpressionFilter, type FactoryEntityOpt, type FactoryExtrasOf, type FactoryOpts, Field, FieldColumn, FieldLogger, FieldLoggerWatch, FieldSerde, FieldStatus, type FieldsOf, FilterAndSettings, type FilterOf, FilterWithAlias, FindCountFilterOptions, FindFilter, FindFilterOptions, FindGqlFilterOptions, FindOperation, Flavor, FlushOptions, type GenericError, GraphQLFilterAndSettings, type GraphQLFilterOf, GraphQLFilterWithAlias, type HintNode, IdAssigner, IdOf, type IdType, ImmutableEntitiesPlugin, type InheritanceTypeOf, type InnerJoin, InsertFixup, InsertOp, type InsertStatement, type InsertValues, InstanceData, type JoinColumnValue, type JoinResult, type JoinRow, JoinRowOperation, type JoinRowTodo, JoinTable, JsonAggregatePreloader, JsonHint, JsonPayload, JsonSerde, Jsonable, JsonableValue, KeySerde, type LargeCollection, LargeOneToManyField, LateralJoinTable, type LazyField, LazyFieldImpl, type LeftJoin, Lens, type LoadHint, type Loadable, type Loaded, type LoadedCollection, type LoadedEnumCollection, type LoadedMethod, type LoadedProperty, type LoadedReadOnlyCollection, type LoadedReference, LoaderCache, ManyToManyCollection, ManyToManyEnumField, ManyToManyField, ManyToManyFieldStatus, ManyToManyLargeCollection, type ManyToManyLike, ManyToOneField, ManyToOneFieldStatus, type ManyToOneReference, ManyToOneReferenceImpl, type MarkLoaded, MaybeAbstractEntityConstructor, type MaybeNull, type MutationReturning, type MutationStatement, type NameOf, NestedJsonHint, type NestedLoadHint, type New, NoIdError, NotFoundError, type NotWidened, OneToManyCollection, OneToManyField, OneToManyFieldStatus, OneToManyLargeCollection, OneToOneField, type OneToOneReference, OneToOneReferenceImpl, OpColumn, Operator, type OptIdsOf, type OptsOf, OrderBy, type OrderByDirection, type OrderByKeys, type OrderOf, ParsedCteClause, ParsedEntityFilter, ParsedExpressionCondition, ParsedExpressionFilter, ParsedFindQuery, ParsedGroupBy, ParsedOrderBy, ParsedSelect, ParsedTable, ParsedValueFilter, PartialOrNull, type PendingChange, type PendingCreate, type PendingDelete, type PendingM2M, type PendingUpdate, PlainDateSerde, PlainDateTimeSerde, PlainTimeSerde, Plugin, PojoRowData, type PolyAlias, PolyComponent, type PolyReference, PolymorphicField, PolymorphicFieldComponent, PolymorphicKeySerde, type PolymorphicReference, PolymorphicReferenceImpl, type PredicateBrand, type PreloadHydrator, type PreloadPlugin, PrimaryKeyField, PrimaryTable, type PrimitiveAlias, type PrimitiveColumn, PrimitiveField, PrimitiveFieldStatus, PrimitiveSerde, type Property, PropertyImpl, type Query, type QueryArg, type QueryCondition, type QueryJoin, type QueryJoins, type QueryOrderBy, type QueryRow, type QuerySelect, type QuerySource, type QueryValue, RandomUuidAssigner, RawCondition, type Reactable, type Reacted, ReactionLogger, type ReactiveField, type ReactiveGetter, type ReactiveHint, type ReactiveManyToMany, ReactiveManyToManyImpl, type ReactiveManyToManyOtherSide, ReactiveManyToManyOtherSideImpl, type ReactiveReference, ReactiveReferenceImpl, type ReactiveTarget, type ReadOnlyCollection, ReadOnlyError, RecursiveCycleError, type RecursiveOptions, type Reference, type ReferenceColumn, type ReferenceJoin, type Relation, type RelationsIn, type RelationsOf, ResolvedScope, type RootTypeNameOf, RowData, type RuntimeConfig, ScalarCodec, type ScalarQuery, Scope, ScopeFilterFragment, ScopeFn, ScopeJoinFilter, ScopeQuery, SequenceIdAssigner, SerdeField, type SetQuery, type SettableFields, SimpleFieldSerde, type SqlCondition, type SqlPredicate, StubbedRelation, type Subquery, type SubqueryBrand, SubqueryRenderer, SuperstructSerde, type Table, type TableBrand, type TableFilter, type TableFor, type TableMgmt, TaggedId, Temporal, TestUuidAssigner, TimestampCodec, TimestampFields, TimestampSerde, ToJsonHint, Todo, TooManyError, type TypeMap, type TypeMapEntry, type TypeNameOf, UniqueFilter, UnknownProperty, UpdateOp, type UpdateStatement, type UpdateValues, ValidationCode, type ValidationError, ValidationErrors, type ValidationRule, type ValidationRuleInternal, type ValidationRuleResult, ValueFilter, ValueGraphQLFilter, type WithInput, type WithLoaded, type WithSource, WriteFn, ZodSerde, ZonedDateTimeSerde, abbreviation, addTablePerClassJoinsAndClassTag, alias, aliases, appendStack, asConcreteCstr, asNew, assertIdIsTagged, assertIdsAreTagged, assertLoaded, assertNever, buildCteSql, buildRawQuery, buildUnnestCte, buildValueCondition, buildWhereClause, cannotBeChanged, cannotBeUpdated, cleanSql, cleanStringValue, configureMetadata, convertToLoadHint, createRowFromEntityData, deTagId, deTagIds, deepNormalizeHint, defaultValue, driverAfterBegin, driverAfterCommit, driverApi, driverBeforeBegin, driverBeforeCommit, emptyRowData, ensureLoaded, ensureNotDeleted, ensureRectangularArraySizes, ensureTagged, ensureWithLoaded, entityQueryBrand, exprBrand, factories, fail, failIfAnyRejected, failNoIdYet, filterSoftDeletes, findFilterField, generateOps, getAliasMetadata, getAliasMgmt, getBaseAndSelfMetas, getBaseMeta, getBaseSelfAndSubMetas, getConstructorFromTaggedId, getDefaultEntityLimit, getEmInternalApi, getField, getInstanceData, getLazyFields, getLens, getLensPath, getMaybeCtiAlias, getMetadata, getMetadataForField, getMetadataForTable, getMetadataForType, getProperties, getRelationEntries, getRelations, getRequiredKeys, getRuntimeConfig, getSubMetas, getTableMetadata, getTableMgmt, getTables, getTestIndex, hasAsyncMethod, hasAsyncProperty, hasAsyncReactiveField, hasCustomCollection, hasCustomReference, hasEnumCollection, hasLargeMany, hasLargeManyToMany, hasLazyField, hasMany, hasManyDerived, hasManyThrough, hasManyToMany, hasOne, hasOneDerived, hasOnePolymorphic, hasOneThrough, hasOneToOne, hasProperty, hasReactiveField, hasReactiveGetter, hasReactiveManyToMany, hasReactiveManyToManyOtherSide, hasReactiveProperty, hasReactiveReference, hasRecursiveChildren, hasRecursiveM2m, hasRecursiveParents, hasSerde, indexBy, internals, isAlias, isAllSqlPaths, isAsyncProperty, isAsyncReactiveField, isChangeableField, isCollection, isCollectionField, isDefined, isEntity, isFactoryCreation, isFieldSet, isId, isInTrustedContext, isKey, isLazyField, isLensLoaded, isLensLoadedPath, isLoaded, isLoadedAsyncProperty, isLoadedCollection, isLoadedLazyField, isLoadedOneToOneReference, isLoadedProperty, isLoadedReadOnlyCollection, isLoadedReference, isManyToManyEnumField, isManyToManyField, isManyToOneField, isManyToOneReference, isNew, isNewEntity, isOneToManyField, isOneToOneField, isOneToOneReference, isPolymorphicField, isPolymorphicReference, isProperty, isReactiveField, isReactiveGetter, isReactiveManyToMany, isReactiveManyToManyOtherSide, isReactiveReference, isReadOnlyCollection, isReference, isReferenceField, isRelation, isScope, isScopeJoinFilter, isSelectAllFilter, isTable, isTaggedId, isTypeOrSubType, keyToNumber, keyToTaggedId, kq, kqDot, kqStar, lazyExcludedSelects, lazyField, lensPathToLoadHint, lensToLoadHint, lensToPath, loadLens, loadLensPath, makeLike, mapPathsToTarget, mapToDb, maxValueRule, maybeAddIdNotNulls, maybeAddNotSoftDeleted, maybeAddOrderBy, maybeBranchValue, maybeGetConstructorFromReference, maybeNew, maybeNewPoly, maybePopulateThen, maybeRequireTemporal, maybeResolveReferenceToId, mergeFindOptions, minValueRule, mustBeSubType, newAliasProxy, newChangesProxy, newPgConnectionConfig, newRequiredLazyFieldRule, newRequiredRule, newScopeFn, newTableProxy, newTestInstance, noValue, noopFieldLogger, normalizeHint, nowUTC, opToFn, operators, optimizeCollectionJoins, parseAlias, parseEntityFilter, parseFindQuery, parseValueFilter, partition, plainDateMapper, plainDateTimeMapper, plainTimeMapper, polymorphicField, query, rangeValueRule, recursiveQuery, requireTemporal, resetBootFlag, resetDefaultEntityLimit, resolveScope, reverseReactiveHint, runInTrustedContext, sameEntity, sameReference, setDefaultEntityLimit, setFactoryLogging, setFactoryWriter, setField, setLastNow, setOpt, setOpts, setReactionLogging, setRuntimeConfig, setTaggedIdDelimiter, skipCondition, sql, stiSubtypeFilter, subqueryBrand, table, tableMgmt, tables, tagFromId, tagId, tagIds, testIndex, testing, toIdOf, toJSON, toTaggedId, unsafeDeTagIds, unsafeLoaded, updatePartial, upsert, visitConditions, withLoaded, zeroTo, zonedDateTimeMapper };
171
+ export { type ActualFactoryOpts, type Alias, AliasAssigner, type AliasBrand, type AliasColumn, AliasFn, type AliasMgmt, type AndCondition, type AsyncMethod, type AsyncProperty, AsyncPropertyImpl, BaseEntity, BigIntSerde, BooleanFilter, BooleanGraphQLFilter, Changes, type CheckScope, type Clauses, type Collection, type CollectionJoin, Column, ColumnCondition, ColumnDescriptors, type ColumnsOf, ConditionBuilder, type ConditionGroup, ConfigApi, CrossJoinTable, CustomCollection, CustomJsonKeyHint, CustomReference, CustomSerde, CustomSerdeAdapter, DateSerde, DecimalToNumberSerde, type DeepNew, type DeepPartialOrNull, DeleteOp, type DeleteStatement, type DomainPredicate, type Driver, type DriverQueryResult, type Entity, type EntityAlias, EntityChanges, type EntityColumn, EntityConstructor, type EntityField, type EntityFields, EntityFilter, EntityFilterObject, EntityGraphQLFilter, type EntityHook, EntityKeyJsonHint, EntityManager, EntityManagerHook, EntityManagerInternalApi, EntityManagerMode, EntityManagerOpts, EntityMetadata, type EntityOf, type EntityOrId, type EntityQuery, EnumArrayFieldSerde, type EnumCollection, EnumCollectionFieldStatus, EnumCollectionImpl, EnumField, EnumFieldSerde, type EnumMetadata, type ExecuteResult, ExistsCondition, type ExistsQuery, type Expr, type ExprBrand, type ExprLike, ExpressionCondition, ExpressionFilter, type FactoryEntityOpt, type FactoryExtrasOf, type FactoryOpts, Field, FieldColumn, FieldLogger, FieldLoggerWatch, FieldSerde, FieldStatus, type FieldsOf, FilterAndSettings, type FilterOf, FilterWithAlias, FindCountFilterOptions, FindFilter, FindFilterOptions, FindGqlFilterOptions, FindOperation, Flavor, FlushOptions, type GenericError, GraphQLFilterAndSettings, type GraphQLFilterOf, GraphQLFilterWithAlias, type HintNode, IdAssigner, IdOf, type IdType, ImmutableEntitiesPlugin, type InheritanceTypeOf, type InnerJoin, InsertFixup, InsertOp, type InsertStatement, type InsertValues, InstanceData, type JoinColumnValue, type JoinResult, type JoinRow, JoinRowOperation, type JoinRowTodo, JoinTable, JsonAggregatePreloader, JsonHint, JsonPayload, JsonSerde, Jsonable, JsonableValue, KeySerde, type LargeCollection, LargeOneToManyField, LateralJoinTable, type LazyField, LazyFieldImpl, type LeftJoin, Lens, type LoadHint, type Loadable, type Loaded, type LoadedCollection, type LoadedEnumCollection, type LoadedMethod, type LoadedProperty, type LoadedReadOnlyCollection, type LoadedReference, LoaderCache, ManyToManyCollection, ManyToManyEnumField, ManyToManyField, ManyToManyFieldStatus, ManyToManyLargeCollection, type ManyToManyLike, ManyToOneField, ManyToOneFieldStatus, type ManyToOneReference, ManyToOneReferenceImpl, type MarkLoaded, MaybeAbstractEntityConstructor, type MaybeNull, type MutationReturning, type MutationStatement, type NameOf, NestedJsonHint, type NestedLoadHint, type New, NoIdError, NotFoundError, type NotWidened, OneToManyCollection, OneToManyField, OneToManyFieldStatus, OneToManyLargeCollection, OneToOneField, type OneToOneReference, OneToOneReferenceImpl, OpColumn, Operator, type OptIdsOf, type OptsOf, type OrCondition, OrderBy, type OrderByDirection, type OrderByKeys, type OrderOf, ParsedCteClause, ParsedEntityFilter, ParsedExpressionCondition, ParsedExpressionFilter, ParsedFindQuery, ParsedGroupBy, ParsedOrderBy, ParsedSelect, ParsedTable, ParsedValueFilter, PartialOrNull, type PendingChange, type PendingCreate, type PendingDelete, type PendingM2M, type PendingUpdate, PlainDateSerde, PlainDateTimeSerde, PlainTimeSerde, Plugin, PojoRowData, type PolyAlias, PolyComponent, type PolyReference, PolymorphicField, PolymorphicFieldComponent, PolymorphicKeySerde, type PolymorphicReference, PolymorphicReferenceImpl, type PredicateBrand, type PreloadHydrator, type PreloadPlugin, PrimaryKeyField, PrimaryTable, type PrimitiveAlias, type PrimitiveColumn, PrimitiveField, PrimitiveFieldStatus, PrimitiveSerde, type Property, PropertyImpl, type Query, type QueryArg, type QueryCondition, type QueryJoin, type QueryJoins, type QueryOrderBy, type QueryRow, type QuerySelect, type QuerySource, type QueryValue, RandomUuidAssigner, RawCondition, type Reactable, type Reacted, ReactionLogger, type ReactiveField, type ReactiveGetter, type ReactiveHint, type ReactiveManyToMany, ReactiveManyToManyImpl, type ReactiveManyToManyOtherSide, ReactiveManyToManyOtherSideImpl, type ReactiveReference, ReactiveReferenceImpl, type ReactiveTarget, type ReadOnlyCollection, ReadOnlyError, RecursiveCycleError, type RecursiveOptions, type Reference, type ReferenceColumn, type ReferenceJoin, type Relation, type RelationsIn, type RelationsOf, ResolvedScope, type RootTypeNameOf, RowData, type RuntimeConfig, ScalarCodec, type ScalarQuery, Scope, ScopeFilterFragment, ScopeFn, ScopeJoinFilter, ScopeQuery, SequenceIdAssigner, SerdeField, type SetQuery, type SettableFields, SimpleFieldSerde, type SqlCondition, type SqlPredicate, StubbedRelation, type Subquery, type SubqueryBrand, SubqueryRenderer, SuperstructSerde, type Table, type TableBrand, type TableFilter, type TableFor, type TableMgmt, TaggedId, Temporal, TestUuidAssigner, TimestampCodec, TimestampFields, TimestampSerde, ToJsonHint, Todo, TooManyError, type TypeMap, type TypeMapEntry, type TypeNameOf, UniqueFilter, UnknownProperty, UpdateOp, type UpdateStatement, type UpdateValues, ValidationCode, type ValidationError, ValidationErrors, type ValidationRule, type ValidationRuleInternal, type ValidationRuleResult, ValueFilter, ValueGraphQLFilter, type WithInput, type WithLoaded, type WithSource, WriteFn, ZodSerde, ZonedDateTimeSerde, abbreviation, addTablePerClassJoinsAndClassTag, alias, aliases, appendStack, asConcreteCstr, asNew, assertIdIsTagged, assertIdsAreTagged, assertLoaded, assertNever, buildCteSql, buildRawQuery, buildUnnestCte, buildValueCondition, buildWhereClause, cannotBeChanged, cannotBeUpdated, cleanSql, cleanStringValue, configureMetadata, convertToLoadHint, createRowFromEntityData, deTagId, deTagIds, deepNormalizeHint, defaultValue, driverAfterBegin, driverAfterCommit, driverApi, driverBeforeBegin, driverBeforeCommit, emptyRowData, ensureLoaded, ensureNotDeleted, ensureRectangularArraySizes, ensureTagged, ensureWithLoaded, entityQueryBrand, exprBrand, factories, fail, failIfAnyRejected, failNoIdYet, filterSoftDeletes, findFilterField, generateOps, getAliasMetadata, getAliasMgmt, getBaseAndSelfMetas, getBaseMeta, getBaseSelfAndSubMetas, getConstructorFromTaggedId, getDefaultEntityLimit, getEmInternalApi, getField, getInstanceData, getLazyFields, getLens, getLensPath, getMaybeCtiAlias, getMetadata, getMetadataForField, getMetadataForTable, getMetadataForType, getProperties, getRelationEntries, getRelations, getRequiredKeys, getRuntimeConfig, getSubMetas, getTableMetadata, getTableMgmt, getTables, getTestIndex, hasAsyncMethod, hasAsyncProperty, hasAsyncReactiveField, hasCustomCollection, hasCustomReference, hasEnumCollection, hasLargeMany, hasLargeManyToMany, hasLazyField, hasMany, hasManyDerived, hasManyThrough, hasManyToMany, hasOne, hasOneDerived, hasOnePolymorphic, hasOneThrough, hasOneToOne, hasProperty, hasReactiveField, hasReactiveGetter, hasReactiveManyToMany, hasReactiveManyToManyOtherSide, hasReactiveProperty, hasReactiveReference, hasRecursiveChildren, hasRecursiveM2m, hasRecursiveParents, hasSerde, indexBy, internals, isAlias, isAllSqlPaths, isAsyncProperty, isAsyncReactiveField, isChangeableField, isCollection, isCollectionField, isDefined, isEntity, isFactoryCreation, isFieldSet, isId, isInTrustedContext, isKey, isLazyField, isLensLoaded, isLensLoadedPath, isLoaded, isLoadedAsyncProperty, isLoadedCollection, isLoadedLazyField, isLoadedOneToOneReference, isLoadedProperty, isLoadedReadOnlyCollection, isLoadedReference, isManyToManyEnumField, isManyToManyField, isManyToOneField, isManyToOneReference, isNew, isNewEntity, isOneToManyField, isOneToOneField, isOneToOneReference, isPolymorphicField, isPolymorphicReference, isProperty, isReactiveField, isReactiveGetter, isReactiveManyToMany, isReactiveManyToManyOtherSide, isReactiveReference, isReadOnlyCollection, isReference, isReferenceField, isRelation, isScope, isScopeJoinFilter, isSelectAllFilter, isTable, isTaggedId, isTypeOrSubType, keyToNumber, keyToTaggedId, kq, kqDot, kqStar, lazyExcludedSelects, lazyField, lensPathToLoadHint, lensToLoadHint, lensToPath, loadLens, loadLensPath, makeLike, mapPathsToTarget, mapToDb, maxValueRule, maybeAddIdNotNulls, maybeAddNotSoftDeleted, maybeAddOrderBy, maybeBranchValue, maybeGetConstructorFromReference, maybeNew, maybeNewPoly, maybePopulateThen, maybeRequireTemporal, maybeResolveReferenceToId, mergeFindOptions, minValueRule, mustBeSubType, newAliasProxy, newChangesProxy, newPgConnectionConfig, newRequiredLazyFieldRule, newRequiredRule, newScopeFn, newTableProxy, newTestInstance, noValue, noopFieldLogger, normalizeHint, nowUTC, opToFn, operators, optimizeCollectionJoins, parseAlias, parseEntityFilter, parseFindQuery, parseValueFilter, partition, plainDateMapper, plainDateTimeMapper, plainTimeMapper, polymorphicField, query, rangeValueRule, recursiveQuery, requireTemporal, resetBootFlag, resetDefaultEntityLimit, resolveScope, reverseReactiveHint, runInTrustedContext, sameEntity, sameReference, setDefaultEntityLimit, setFactoryLogging, setFactoryWriter, setField, setLastNow, setOpt, setOpts, setReactionLogging, setRuntimeConfig, setTaggedIdDelimiter, skipCondition, sql, stiSubtypeFilter, subqueryBrand, table, tableMgmt, tables, tagFromId, tagId, tagIds, testIndex, testing, toIdOf, toJSON, toTaggedId, unsafeDeTagIds, unsafeLoaded, updatePartial, upsert, visitConditions, withLoaded, zeroTo, zonedDateTimeMapper };
172
172
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA0Ba;;;;;cACA;2BAAA;;UAiOH,UAAU;EAClB,QAAQ;;KAGE,OAAO,GAAG,WAAW,IAAI,UAAU;;;;;;;;;;;;;;;iBAgB/B,QAAQ,UAAU,QAChC,QAAQ,GACR,QAAQ,QAAQ,OAAO,iBACvB;EAAS;EAAmB;;;;;;;;;iBAoBd,OAAO,UAAU,QAC/B,MAAM,eAAe,IACrB,QAAQ,GACR,aACA,aACA,mBACA;iBAwDc,iBAAiB,QAAQ,QAAQ;;KAOrC,cAAc,QACvB,WAAW,KAAK,EAAE;iBAGL,gBAAgB,UAAU,QAAQ,QAAQ;iBAC1C,gBAAgB,UAAU,QAAQ,MAAM,kBAAkB;iBAO1D,aAAa,QAAQ,SAAS;iBAM9B,mBAAmB,QAAQ,kBAAkB;;iBAO7C,eAAe,UAAU,QAAQ,MAAM,+BAA+B,KAAK,kBAAkB;;;;;;;;cAWhG,kBAAkB;;iBAGf,YAAY;;;;;;iBASZ,YAAY,UAAU,QAAQ,QAAQ,IAAI,UAAU,IAAI"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA0Ba;;;;;cACA;2BAAA;;UAmOH,UAAU;EAClB,QAAQ;;KAGE,OAAO,GAAG,WAAW,IAAI,UAAU;;;;;;;;;;;;;;;iBAgB/B,QAAQ,UAAU,QAChC,QAAQ,GACR,QAAQ,QAAQ,OAAO,iBACvB;EAAS;EAAmB;;;;;;;;;iBAoBd,OAAO,UAAU,QAC/B,MAAM,eAAe,IACrB,QAAQ,GACR,aACA,aACA,mBACA;iBAwDc,iBAAiB,QAAQ,QAAQ;;KAOrC,cAAc,QACvB,WAAW,KAAK,EAAE;iBAGL,gBAAgB,UAAU,QAAQ,QAAQ;iBAC1C,gBAAgB,UAAU,QAAQ,MAAM,kBAAkB;iBAO1D,aAAa,QAAQ,SAAS;iBAM9B,mBAAmB,QAAQ,kBAAkB;;iBAO7C,eAAe,UAAU,QAAQ,MAAM,+BAA+B,KAAK,kBAAkB;;;;;;;;cAWhG,kBAAkB;;iBAGf,YAAY;;;;;;iBASZ,YAAY,UAAU,QAAQ,QAAQ,IAAI,UAAU,IAAI"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { getInstanceData } from \"./BaseEntity.ts\";\nimport { getDefaultDependencies } from \"./defaults.ts\";\nimport { buildWhereClause } from \"./drivers/buildUtils.ts\";\nimport { type Entity } from \"./Entity.ts\";\nimport { type EntityConstructor, type MaybeAbstractEntityConstructor } from \"./EntityManager.ts\";\nimport { type EntityMetadata, getBaseMeta, getMetadata } from \"./EntityMetadata.ts\";\nimport { getField, setField } from \"./fields.ts\";\nimport { getProperties } from \"./getProperties.ts\";\nimport { type New } from \"./loadHints.ts\";\nimport { isAllSqlPaths } from \"./loadLens.ts\";\nimport { FactoryInitialValue } from \"./newTestInstance.ts\";\nimport { partitionHint } from \"./preloading/partitionHint.ts\";\nimport { AbstractRelationImpl } from \"./relations/AbstractRelationImpl.ts\";\nimport { AsyncReactiveFieldImpl } from \"./relations/AsyncReactiveField.ts\";\nimport {\n isAsyncProperty,\n isAsyncReactiveField,\n isLazyField,\n isProperty,\n isReactiveField,\n isReactiveGetter,\n} from \"./relations/index.ts\";\nimport { ReactiveFieldImpl } from \"./relations/ReactiveField.ts\";\nimport { type OptsOf } from \"./typeMap.ts\";\nimport { fail } from \"./utils.ts\";\n\nexport const testing = { isAllSqlPaths, getDefaultDependencies, partitionHint };\nexport const internals = { buildWhereClause };\nexport { newPgConnectionConfig } from \"joist-utils\";\nexport { AliasAssigner } from \"./AliasAssigner.ts\";\nexport {\n type ConditionGroup,\n type DomainPredicate,\n type PredicateBrand,\n type SqlCondition,\n type SqlPredicate,\n} from \"./conditions.ts\";\n// Domain aliases belong to em.find; physical table expressions belong to em.query/em.execute.\nexport {\n alias,\n aliases,\n getAliasMetadata,\n getAliasMgmt,\n getMaybeCtiAlias,\n isAlias,\n newAliasProxy,\n type Alias,\n type AliasBrand,\n type AliasMgmt,\n type AliasColumn,\n type EntityAlias,\n type PolyAlias,\n type PrimitiveAlias,\n} from \"./Aliases.ts\";\nexport {\n table,\n tables,\n tableMgmt,\n getTableMetadata,\n getTableMgmt,\n isTable,\n newTableProxy,\n type Table,\n type TableFilter,\n type TableBrand,\n type TableFor,\n type TableMgmt,\n type ReferenceJoin,\n type PrimitiveColumn,\n type EntityColumn,\n type ReferenceColumn,\n type CollectionJoin,\n type PolyReference,\n} from \"./Tables.ts\";\nexport { BaseEntity, getInstanceData } from \"./BaseEntity.ts\";\nexport { ConditionBuilder } from \"./ConditionBuilder.ts\";\nexport { type Entity, type IdType, isEntity } from \"./Entity.ts\";\nexport type * from \"./EntityFields.ts\";\nexport * from \"./EntityFilter.ts\";\nexport * from \"./EntityGraphQLFilter.ts\";\nexport * from \"./EntityManager.ts\";\nexport * from \"./EntityMetadata.ts\";\nexport type {\n DeleteStatement,\n ExecuteResult,\n InsertStatement,\n InsertValues,\n MutationReturning,\n MutationStatement,\n UpdateStatement,\n UpdateValues,\n} from \"./execute.ts\";\nexport type { EnumMetadata } from \"./EnumMetadata.ts\";\n// `em.query`'s expression surface. Only the user-facing types are re-exported: the runtime half\n// (BaseExpr, asNode, deferredCondition, the FnExpr/TemplateExpr node classes) stays internal to\n// joist-core, so `toSql`/`decode`/`encode` never show up as something a user could call.\nexport { type Expr, type ExprBrand, exprBrand, type ExprLike, type InnerJoin, type LeftJoin } from \"./Expr.ts\";\nexport { skipCondition } from \"./skipCondition.ts\";\nexport type { EntityOrId, HintNode } from \"./HintTree.ts\";\nexport { InstanceData } from \"./InstanceData.ts\";\nexport { type JoinColumnValue, type JoinRow, JoinRowOperation, type ManyToManyLike } from \"./JoinRows.ts\";\nexport type * from \"./PendingChanges.ts\";\nexport { Plugin } from \"./PluginManager.ts\";\nexport * from \"./QueryParser.ts\";\nexport * from \"./QueryParser.collectionJoins.ts\";\nexport { visitConditions } from \"./QueryVisitor.ts\";\nexport * from \"./RowData.ts\";\nexport { type JoinRowTodo, Todo } from \"./Todo.ts\";\nexport * from \"./changes.ts\";\nexport { ConfigApi, type EntityHook, resetBootFlag } from \"./config.ts\";\nexport {\n configureMetadata,\n getConstructorFromTaggedId,\n getMetadataForTable,\n getMetadataForType,\n maybeGetConstructorFromReference,\n} from \"./configure.ts\";\nexport { driverApi } from \"./driverApi.ts\";\nexport * from \"./drivers/index.ts\";\nexport { getField, isChangeableField, isFieldSet, setField } from \"./fields.ts\";\nexport * from \"./getProperties.ts\";\nexport * from \"./json.ts\";\nexport * from \"./keys.ts\";\nexport { kq, kqDot, kqStar } from \"./keywords.ts\";\nexport {\n assertLoaded,\n type DeepNew,\n ensureLoaded,\n isLoaded,\n isNew,\n type Loadable,\n type Loaded,\n type LoadHint,\n type MarkLoaded,\n maybePopulateThen,\n type NestedLoadHint,\n type New,\n type RelationsIn,\n unsafeLoaded,\n} from \"./loadHints.ts\";\nexport * from \"./loadLens.ts\";\nexport { setFactoryWriter } from \"./logging/FactoryLogger.ts\";\nexport * from \"./logging/FieldLogger.ts\";\nexport { ReactionLogger, setReactionLogging } from \"./logging/ReactionLogger.ts\";\nexport { lazyField } from \"./newEntity.ts\";\nexport {\n defaultValue,\n factories,\n type FactoryEntityOpt,\n type FactoryOpts,\n getTestIndex,\n isFactoryCreation,\n maybeBranchValue,\n maybeNew,\n maybeNewPoly,\n newTestInstance,\n noValue,\n setFactoryLogging,\n testIndex,\n} from \"./newTestInstance.ts\";\nexport { deepNormalizeHint, normalizeHint } from \"./normalizeHints.ts\";\nexport { ImmutableEntitiesPlugin } from \"./plugins/ImmutableEntitiesPlugin.ts\";\nexport type { JoinResult, PreloadHydrator, PreloadPlugin } from \"./plugins/PreloadPlugin.ts\";\nexport { JsonAggregatePreloader } from \"./preloading/JsonAggregatePreloader.ts\";\n// `em.query`'s query surface; the parse pipeline (SubqueryHandle, parseUserQuery, Plan) stays internal\nexport {\n type CheckScope,\n type Clauses,\n type EntityQuery,\n type ExistsQuery,\n entityQueryBrand,\n type MaybeNull,\n type NameOf,\n type NotWidened,\n type OrderByDirection,\n type OrderByKeys,\n type Query,\n type QueryArg,\n type QueryCondition,\n type QueryJoin,\n type QueryJoins,\n type QueryOrderBy,\n type QueryRow,\n type QuerySelect,\n type QuerySource,\n type QueryValue,\n recursiveQuery,\n type RecursiveOptions,\n type ScalarQuery,\n type SetQuery,\n query,\n sql,\n type Subquery,\n type SubqueryBrand,\n subqueryBrand,\n type WithInput,\n type WithSource,\n} from \"./query.ts\";\nexport {\n convertToLoadHint,\n isTypeOrSubType,\n type Reactable,\n type Reacted,\n type ReactiveHint,\n type ReactiveTarget,\n reverseReactiveHint,\n} from \"./reactiveHints.ts\";\nexport * from \"./relations/index.ts\";\nexport {\n cannotBeChanged,\n cannotBeUpdated,\n type GenericError,\n maxValueRule,\n minValueRule,\n mustBeSubType,\n newRequiredLazyFieldRule,\n newRequiredRule,\n rangeValueRule,\n ValidationCode,\n type ValidationError,\n ValidationErrors,\n type ValidationRule,\n type ValidationRuleInternal,\n type ValidationRuleResult,\n} from \"./rules.ts\";\nexport { getRuntimeConfig, setRuntimeConfig, type RuntimeConfig } from \"./runtimeConfig.ts\";\nexport { nowUTC } from \"./nowUTC.ts\";\nexport * from \"./serde.ts\";\nexport * from \"./columns.ts\";\nexport * from \"./fieldSerde.ts\";\nexport * from \"./scopes.ts\";\nexport { maybeRequireTemporal, requireTemporal, Temporal } from \"./temporal.ts\";\nexport * from \"./temporalMappers.ts\";\nexport { isInTrustedContext, runInTrustedContext } from \"./trusted.ts\";\nexport type * from \"./typeMap.ts\";\nexport { buildUnnestCte, ensureRectangularArraySizes } from \"./unnest.ts\";\nexport { type DeepPartialOrNull, updatePartial, upsert } from \"./upsert.ts\";\nexport {\n abbreviation,\n asNew,\n assertNever,\n cleanSql,\n cleanStringValue,\n fail,\n failIfAnyRejected,\n indexBy,\n partition,\n zeroTo,\n} from \"./utils.ts\";\nexport { ensureWithLoaded, StubbedRelation, type WithLoaded, withLoaded } from \"./withLoaded.ts\";\n\n// https://spin.atomicobject.com/2018/01/15/typescript-flexible-nominal-typing/\ninterface Flavoring<FlavorT> {\n _type?: FlavorT;\n}\n\nexport type Flavor<T, FlavorT> = T & Flavoring<FlavorT>;\n\n/**\n * Sets each value in `values` on the current entity.\n *\n * The default behavior is that passing a value as either `null` or `undefined` will set\n * the field as `undefined`, i.e. automatic `null` to `undefined` conversion.\n *\n * However, if you pass `ignoreUndefined: true`, then any opt that is `undefined` will be treated\n * as \"do not set\", and `null` will still mean \"set to `undefined`\". This is useful for implementing\n * APIs were an input of `undefined` means \"do not set / noop\" and `null` means \"unset\".\n *\n * Note that constructors _always_ call this method, but if the call is coming from `em.hydrate`, we\n * use `values` being a primary key to short-circuit and let hydration callers assign the values\n * returned by the serde `fromRow` methods.\n */\nexport function setOpts<T extends Entity>(\n entity: T,\n values: Partial<OptsOf<T>> | undefined,\n opts?: { partial?: boolean; calledFromConstructor?: boolean },\n): void {\n const { calledFromConstructor = false, partial } = opts || {};\n // If `values` is undefined, we're being called by `createPartial` that will do its\n // own opt handling, but we still want the sync defaults applied after this opts handling.\n if (values !== undefined) {\n const meta = getMetadata(entity);\n for (const [key, _value] of Object.entries(values as {})) {\n setOpt(meta, entity, key, _value, partial, calledFromConstructor);\n }\n }\n}\n\n/**\n * Applies some standard behavior & protections to `entity[key] = value`. I.e.\n *\n * - We don't set over AsyncProperties/relations/etc., and instead call current.set(value)\n * - We catch missing/invalid field names\n * - We handle FactoryInitialValues\n */\nexport function setOpt<T extends Entity>(\n meta: EntityMetadata<T>,\n entity: T,\n key: string,\n _value: any,\n partial = false,\n calledFromConstructor = false,\n): void {\n const field = meta.allFields[key];\n if (!field) {\n // Allow setting non-field properties like fullName setters\n const prop = getProperties(meta)[key];\n if (!prop) {\n throw new Error(`Unknown field ${key}`);\n }\n }\n\n // If partial is set, we treat undefined as a noop\n if (partial && _value === undefined) return;\n // Ignore the STI discriminator, em.register will set this accordingly\n if (meta.inheritanceType === \"sti\" && getBaseMeta(meta).stiDiscriminatorField === key) return;\n\n // We let optional opts fields be `| null` for convenience, and convert to undefined.\n const value = _value === null ? undefined : _value;\n\n // Use `getField` to side-step `id` blowing up on new entities that are setting an\n // explicit id; otherwise use `entity[key]` to get back the relation.\n const current = key === \"id\" ? getField(entity, key) : (entity as any)[key];\n\n if (current instanceof AbstractRelationImpl) {\n if (calledFromConstructor) {\n current.setFromOpts(value);\n } else {\n current.set(value);\n }\n } else if (isLazyField(current)) {\n current.set(value);\n } else if (isProperty(current) || isAsyncProperty(current) || isReactiveGetter(current)) {\n throw new Error(`Invalid argument, cannot set over ${key} ${current.constructor.name}`);\n } else if (isReactiveField(current) || isAsyncReactiveField(current)) {\n if (value instanceof FactoryInitialValue) {\n if (current instanceof ReactiveFieldImpl) {\n current.setFactoryValue(value.value);\n } else if (current instanceof AsyncReactiveFieldImpl) {\n current.setFactoryValue(value.value);\n } else {\n throw new Error(`Unhandled case ${current.constructor.name}`);\n }\n } else {\n throw new Error(`Invalid argument, cannot set over ${key} ${current.constructor.name}`);\n }\n } else {\n // If setting an explicit id, go through setField, otherwise use\n // `entity[key]` to set the value directly to that we go through setters.\n if (key === \"id\" && entity.isNewEntity) {\n setField(entity, key, value);\n } else {\n (entity as any)[key] = value;\n }\n }\n}\n\nexport function ensureNotDeleted(entity: Entity, ignore?: \"pending\"): void {\n if (entity.isDeletedEntity && (ignore === undefined || getInstanceData(entity).isDeletedAndFlushed)) {\n fail(`${entity} is marked as deleted`);\n }\n}\n\n/** Adds `null` to every key in `T` to accept partial-update-style input. */\nexport type PartialOrNull<T> = {\n [P in keyof T]?: T[P] | null;\n};\n\nexport function getRequiredKeys<T extends Entity>(entity: T): string[];\nexport function getRequiredKeys<T extends Entity>(type: EntityConstructor<T>): string[];\nexport function getRequiredKeys<T extends Entity>(entityOrType: T | EntityConstructor<T>): string[] {\n return Object.values(getMetadata(entityOrType as any).fields)\n .filter((f) => f.required)\n .map((f) => f.fieldName);\n}\n\nexport function getRelations(entity: Entity): AbstractRelationImpl<any, any>[] {\n return Object.entries(getProperties(getMetadata(entity)))\n .filter(([, v]) => v instanceof AbstractRelationImpl)\n .map(([name]) => (entity as any)[name]);\n}\n\nexport function getRelationEntries(entity: Entity): [string, AbstractRelationImpl<any, any>][] {\n return Object.entries(getProperties(getMetadata(entity)))\n .filter(([, v]) => v instanceof AbstractRelationImpl)\n .map(([name]) => [name, (entity as any)[name]]);\n}\n\n/** Casts a \"maybe abstract\" cstr to a concrete cstr when the calling code knows it's safe. */\nexport function asConcreteCstr<T extends Entity>(cstr: MaybeAbstractEntityConstructor<T>): EntityConstructor<T> {\n return cstr as any;\n}\n\n/**\n * Thrown when `.id` is accessed on an entity that does not have an id yet.\n *\n * For Postgres, entities are actually allowed to have ids pre-INSERT, if you call\n * `em.assignNewIds()`. Other databases typically require INSERTs to trigger the auto\n * id assignment.\n */\nexport class NoIdError extends Error {}\n\n/** Throws a `NoIdError` for `entity`, i.e. because `id` was called before being saved. */\nexport function failNoIdYet(entity: string): never {\n throw new NoIdError(`${entity} has no id yet`);\n}\n\n/**\n * Add a static function since getters can't have type guards.\n *\n * See https://github.com/microsoft/TypeScript/issues/43368\n */\nexport function isNewEntity<T extends Entity>(entity: T): entity is New<T> {\n return entity.isNewEntity;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,UAAU;CAAE;CAAe;CAAwB;AAAc;AAC9E,MAAa,YAAY,EAAE,iBAAiB;;;;;;;;;;;;;;;AAqP5C,SAAgB,QACd,QACA,QACA,MACM;CACN,MAAM,EAAE,wBAAwB,OAAO,YAAY,QAAQ,CAAC;CAG5D,IAAI,WAAW,KAAA,GAAW;EACxB,MAAM,OAAO,YAAY,MAAM;EAC/B,KAAK,MAAM,CAAC,KAAK,WAAW,OAAO,QAAQ,MAAY,GACrD,OAAO,MAAM,QAAQ,KAAK,QAAQ,SAAS,qBAAqB;CAEpE;AACF;;;;;;;;AASA,SAAgB,OACd,MACA,QACA,KACA,QACA,UAAU,OACV,wBAAwB,OAClB;CAEN,IAAI,CADU,KAAK,UAAU,MAIvB;MAAA,CADS,cAAc,IAAI,CAAC,CAAC,MAE/B,MAAM,IAAI,MAAM,iBAAiB,KAAK;CAAA;CAK1C,IAAI,WAAW,WAAW,KAAA,GAAW;CAErC,IAAI,KAAK,oBAAoB,SAAS,YAAY,IAAI,CAAC,CAAC,0BAA0B,KAAK;CAGvF,MAAM,QAAQ,WAAW,OAAO,KAAA,IAAY;CAI5C,MAAM,UAAU,QAAQ,OAAO,SAAS,QAAQ,GAAG,IAAK,OAAe;CAEvE,IAAI,mBAAmB,sBAAsB;EAC3C,IAAI,uBACF,QAAQ,YAAY,KAAK;OAEzB,QAAQ,IAAI,KAAK;CAErB,OAAO,IAAI,YAAY,OAAO,GAC5B,QAAQ,IA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,CAAC;AAClD;;AAGA,SAAgB,eAAiC,MAA+D;CAC9G,OAAO;AACT;;;;;;;;AASA,IAAa,YAAb,cAA+B,MAAM,CAAC;;AAGtC,SAAgB,YAAY,QAAuB;CACjD,MAAM,IAAI,UAAU,GAAG,OAAO,eAAe;AAC/C;;;;;;AAOA,SAAgB,YAA8B,QAA6B;CACzE,OAAO,OAAO;AAChB"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/index.ts"],"sourcesContent":["import { getInstanceData } from \"./BaseEntity.ts\";\nimport { getDefaultDependencies } from \"./defaults.ts\";\nimport { buildWhereClause } from \"./drivers/buildUtils.ts\";\nimport { type Entity } from \"./Entity.ts\";\nimport { type EntityConstructor, type MaybeAbstractEntityConstructor } from \"./EntityManager.ts\";\nimport { type EntityMetadata, getBaseMeta, getMetadata } from \"./EntityMetadata.ts\";\nimport { getField, setField } from \"./fields.ts\";\nimport { getProperties } from \"./getProperties.ts\";\nimport { type New } from \"./loadHints.ts\";\nimport { isAllSqlPaths } from \"./loadLens.ts\";\nimport { FactoryInitialValue } from \"./newTestInstance.ts\";\nimport { partitionHint } from \"./preloading/partitionHint.ts\";\nimport { AbstractRelationImpl } from \"./relations/AbstractRelationImpl.ts\";\nimport { AsyncReactiveFieldImpl } from \"./relations/AsyncReactiveField.ts\";\nimport {\n isAsyncProperty,\n isAsyncReactiveField,\n isLazyField,\n isProperty,\n isReactiveField,\n isReactiveGetter,\n} from \"./relations/index.ts\";\nimport { ReactiveFieldImpl } from \"./relations/ReactiveField.ts\";\nimport { type OptsOf } from \"./typeMap.ts\";\nimport { fail } from \"./utils.ts\";\n\nexport const testing = { isAllSqlPaths, getDefaultDependencies, partitionHint };\nexport const internals = { buildWhereClause };\nexport { newPgConnectionConfig } from \"joist-utils\";\nexport { AliasAssigner } from \"./AliasAssigner.ts\";\nexport {\n type AndCondition,\n type ConditionGroup,\n type DomainPredicate,\n type OrCondition,\n type PredicateBrand,\n type SqlCondition,\n type SqlPredicate,\n} from \"./conditions.ts\";\n// Domain aliases belong to em.find; physical table expressions belong to em.query/em.execute.\nexport {\n alias,\n aliases,\n getAliasMetadata,\n getAliasMgmt,\n getMaybeCtiAlias,\n isAlias,\n newAliasProxy,\n type Alias,\n type AliasBrand,\n type AliasMgmt,\n type AliasColumn,\n type EntityAlias,\n type PolyAlias,\n type PrimitiveAlias,\n} from \"./Aliases.ts\";\nexport {\n table,\n tables,\n tableMgmt,\n getTableMetadata,\n getTableMgmt,\n isTable,\n newTableProxy,\n type Table,\n type TableFilter,\n type TableBrand,\n type TableFor,\n type TableMgmt,\n type ReferenceJoin,\n type PrimitiveColumn,\n type EntityColumn,\n type ReferenceColumn,\n type CollectionJoin,\n type PolyReference,\n} from \"./Tables.ts\";\nexport { BaseEntity, getInstanceData } from \"./BaseEntity.ts\";\nexport { ConditionBuilder } from \"./ConditionBuilder.ts\";\nexport { type Entity, type IdType, isEntity } from \"./Entity.ts\";\nexport type * from \"./EntityFields.ts\";\nexport * from \"./EntityFilter.ts\";\nexport * from \"./EntityGraphQLFilter.ts\";\nexport * from \"./EntityManager.ts\";\nexport * from \"./EntityMetadata.ts\";\nexport type {\n DeleteStatement,\n ExecuteResult,\n InsertStatement,\n InsertValues,\n MutationReturning,\n MutationStatement,\n UpdateStatement,\n UpdateValues,\n} from \"./execute.ts\";\nexport type { EnumMetadata } from \"./EnumMetadata.ts\";\n// `em.query`'s expression surface. Only the user-facing types are re-exported: the runtime half\n// (BaseExpr, asNode, deferredCondition, the FnExpr/TemplateExpr node classes) stays internal to\n// joist-core, so `toSql`/`decode`/`encode` never show up as something a user could call.\nexport { type Expr, type ExprBrand, exprBrand, type ExprLike, type InnerJoin, type LeftJoin } from \"./Expr.ts\";\nexport { skipCondition } from \"./skipCondition.ts\";\nexport type { EntityOrId, HintNode } from \"./HintTree.ts\";\nexport { InstanceData } from \"./InstanceData.ts\";\nexport { type JoinColumnValue, type JoinRow, JoinRowOperation, type ManyToManyLike } from \"./JoinRows.ts\";\nexport type * from \"./PendingChanges.ts\";\nexport { Plugin } from \"./PluginManager.ts\";\nexport * from \"./QueryParser.ts\";\nexport * from \"./QueryParser.collectionJoins.ts\";\nexport { visitConditions } from \"./QueryVisitor.ts\";\nexport * from \"./RowData.ts\";\nexport { type JoinRowTodo, Todo } from \"./Todo.ts\";\nexport * from \"./changes.ts\";\nexport { ConfigApi, type EntityHook, resetBootFlag } from \"./config.ts\";\nexport {\n configureMetadata,\n getConstructorFromTaggedId,\n getMetadataForTable,\n getMetadataForType,\n maybeGetConstructorFromReference,\n} from \"./configure.ts\";\nexport { driverApi } from \"./driverApi.ts\";\nexport * from \"./drivers/index.ts\";\nexport { getField, isChangeableField, isFieldSet, setField } from \"./fields.ts\";\nexport * from \"./getProperties.ts\";\nexport * from \"./json.ts\";\nexport * from \"./keys.ts\";\nexport { kq, kqDot, kqStar } from \"./keywords.ts\";\nexport {\n assertLoaded,\n type DeepNew,\n ensureLoaded,\n isLoaded,\n isNew,\n type Loadable,\n type Loaded,\n type LoadHint,\n type MarkLoaded,\n maybePopulateThen,\n type NestedLoadHint,\n type New,\n type RelationsIn,\n unsafeLoaded,\n} from \"./loadHints.ts\";\nexport * from \"./loadLens.ts\";\nexport { setFactoryWriter } from \"./logging/FactoryLogger.ts\";\nexport * from \"./logging/FieldLogger.ts\";\nexport { ReactionLogger, setReactionLogging } from \"./logging/ReactionLogger.ts\";\nexport { lazyField } from \"./newEntity.ts\";\nexport {\n defaultValue,\n factories,\n type FactoryEntityOpt,\n type FactoryOpts,\n getTestIndex,\n isFactoryCreation,\n maybeBranchValue,\n maybeNew,\n maybeNewPoly,\n newTestInstance,\n noValue,\n setFactoryLogging,\n testIndex,\n} from \"./newTestInstance.ts\";\nexport { deepNormalizeHint, normalizeHint } from \"./normalizeHints.ts\";\nexport { ImmutableEntitiesPlugin } from \"./plugins/ImmutableEntitiesPlugin.ts\";\nexport type { JoinResult, PreloadHydrator, PreloadPlugin } from \"./plugins/PreloadPlugin.ts\";\nexport { JsonAggregatePreloader } from \"./preloading/JsonAggregatePreloader.ts\";\n// `em.query`'s query surface; the parse pipeline (SubqueryHandle, parseUserQuery, Plan) stays internal\nexport {\n type CheckScope,\n type Clauses,\n type EntityQuery,\n type ExistsQuery,\n entityQueryBrand,\n type MaybeNull,\n type NameOf,\n type NotWidened,\n type OrderByDirection,\n type OrderByKeys,\n type Query,\n type QueryArg,\n type QueryCondition,\n type QueryJoin,\n type QueryJoins,\n type QueryOrderBy,\n type QueryRow,\n type QuerySelect,\n type QuerySource,\n type QueryValue,\n recursiveQuery,\n type RecursiveOptions,\n type ScalarQuery,\n type SetQuery,\n query,\n sql,\n type Subquery,\n type SubqueryBrand,\n subqueryBrand,\n type WithInput,\n type WithSource,\n} from \"./query.ts\";\nexport {\n convertToLoadHint,\n isTypeOrSubType,\n type Reactable,\n type Reacted,\n type ReactiveHint,\n type ReactiveTarget,\n reverseReactiveHint,\n} from \"./reactiveHints.ts\";\nexport * from \"./relations/index.ts\";\nexport {\n cannotBeChanged,\n cannotBeUpdated,\n type GenericError,\n maxValueRule,\n minValueRule,\n mustBeSubType,\n newRequiredLazyFieldRule,\n newRequiredRule,\n rangeValueRule,\n ValidationCode,\n type ValidationError,\n ValidationErrors,\n type ValidationRule,\n type ValidationRuleInternal,\n type ValidationRuleResult,\n} from \"./rules.ts\";\nexport { getRuntimeConfig, setRuntimeConfig, type RuntimeConfig } from \"./runtimeConfig.ts\";\nexport { nowUTC } from \"./nowUTC.ts\";\nexport * from \"./serde.ts\";\nexport * from \"./columns.ts\";\nexport * from \"./fieldSerde.ts\";\nexport * from \"./scopes.ts\";\nexport { maybeRequireTemporal, requireTemporal, Temporal } from \"./temporal.ts\";\nexport * from \"./temporalMappers.ts\";\nexport { isInTrustedContext, runInTrustedContext } from \"./trusted.ts\";\nexport type * from \"./typeMap.ts\";\nexport { buildUnnestCte, ensureRectangularArraySizes } from \"./unnest.ts\";\nexport { type DeepPartialOrNull, updatePartial, upsert } from \"./upsert.ts\";\nexport {\n abbreviation,\n asNew,\n assertNever,\n cleanSql,\n cleanStringValue,\n fail,\n failIfAnyRejected,\n indexBy,\n partition,\n zeroTo,\n} from \"./utils.ts\";\nexport { ensureWithLoaded, StubbedRelation, type WithLoaded, withLoaded } from \"./withLoaded.ts\";\n\n// https://spin.atomicobject.com/2018/01/15/typescript-flexible-nominal-typing/\ninterface Flavoring<FlavorT> {\n _type?: FlavorT;\n}\n\nexport type Flavor<T, FlavorT> = T & Flavoring<FlavorT>;\n\n/**\n * Sets each value in `values` on the current entity.\n *\n * The default behavior is that passing a value as either `null` or `undefined` will set\n * the field as `undefined`, i.e. automatic `null` to `undefined` conversion.\n *\n * However, if you pass `ignoreUndefined: true`, then any opt that is `undefined` will be treated\n * as \"do not set\", and `null` will still mean \"set to `undefined`\". This is useful for implementing\n * APIs were an input of `undefined` means \"do not set / noop\" and `null` means \"unset\".\n *\n * Note that constructors _always_ call this method, but if the call is coming from `em.hydrate`, we\n * use `values` being a primary key to short-circuit and let hydration callers assign the values\n * returned by the serde `fromRow` methods.\n */\nexport function setOpts<T extends Entity>(\n entity: T,\n values: Partial<OptsOf<T>> | undefined,\n opts?: { partial?: boolean; calledFromConstructor?: boolean },\n): void {\n const { calledFromConstructor = false, partial } = opts || {};\n // If `values` is undefined, we're being called by `createPartial` that will do its\n // own opt handling, but we still want the sync defaults applied after this opts handling.\n if (values !== undefined) {\n const meta = getMetadata(entity);\n for (const [key, _value] of Object.entries(values as {})) {\n setOpt(meta, entity, key, _value, partial, calledFromConstructor);\n }\n }\n}\n\n/**\n * Applies some standard behavior & protections to `entity[key] = value`. I.e.\n *\n * - We don't set over AsyncProperties/relations/etc., and instead call current.set(value)\n * - We catch missing/invalid field names\n * - We handle FactoryInitialValues\n */\nexport function setOpt<T extends Entity>(\n meta: EntityMetadata<T>,\n entity: T,\n key: string,\n _value: any,\n partial = false,\n calledFromConstructor = false,\n): void {\n const field = meta.allFields[key];\n if (!field) {\n // Allow setting non-field properties like fullName setters\n const prop = getProperties(meta)[key];\n if (!prop) {\n throw new Error(`Unknown field ${key}`);\n }\n }\n\n // If partial is set, we treat undefined as a noop\n if (partial && _value === undefined) return;\n // Ignore the STI discriminator, em.register will set this accordingly\n if (meta.inheritanceType === \"sti\" && getBaseMeta(meta).stiDiscriminatorField === key) return;\n\n // We let optional opts fields be `| null` for convenience, and convert to undefined.\n const value = _value === null ? undefined : _value;\n\n // Use `getField` to side-step `id` blowing up on new entities that are setting an\n // explicit id; otherwise use `entity[key]` to get back the relation.\n const current = key === \"id\" ? getField(entity, key) : (entity as any)[key];\n\n if (current instanceof AbstractRelationImpl) {\n if (calledFromConstructor) {\n current.setFromOpts(value);\n } else {\n current.set(value);\n }\n } else if (isLazyField(current)) {\n current.set(value);\n } else if (isProperty(current) || isAsyncProperty(current) || isReactiveGetter(current)) {\n throw new Error(`Invalid argument, cannot set over ${key} ${current.constructor.name}`);\n } else if (isReactiveField(current) || isAsyncReactiveField(current)) {\n if (value instanceof FactoryInitialValue) {\n if (current instanceof ReactiveFieldImpl) {\n current.setFactoryValue(value.value);\n } else if (current instanceof AsyncReactiveFieldImpl) {\n current.setFactoryValue(value.value);\n } else {\n throw new Error(`Unhandled case ${current.constructor.name}`);\n }\n } else {\n throw new Error(`Invalid argument, cannot set over ${key} ${current.constructor.name}`);\n }\n } else {\n // If setting an explicit id, go through setField, otherwise use\n // `entity[key]` to set the value directly to that we go through setters.\n if (key === \"id\" && entity.isNewEntity) {\n setField(entity, key, value);\n } else {\n (entity as any)[key] = value;\n }\n }\n}\n\nexport function ensureNotDeleted(entity: Entity, ignore?: \"pending\"): void {\n if (entity.isDeletedEntity && (ignore === undefined || getInstanceData(entity).isDeletedAndFlushed)) {\n fail(`${entity} is marked as deleted`);\n }\n}\n\n/** Adds `null` to every key in `T` to accept partial-update-style input. */\nexport type PartialOrNull<T> = {\n [P in keyof T]?: T[P] | null;\n};\n\nexport function getRequiredKeys<T extends Entity>(entity: T): string[];\nexport function getRequiredKeys<T extends Entity>(type: EntityConstructor<T>): string[];\nexport function getRequiredKeys<T extends Entity>(entityOrType: T | EntityConstructor<T>): string[] {\n return Object.values(getMetadata(entityOrType as any).fields)\n .filter((f) => f.required)\n .map((f) => f.fieldName);\n}\n\nexport function getRelations(entity: Entity): AbstractRelationImpl<any, any>[] {\n return Object.entries(getProperties(getMetadata(entity)))\n .filter(([, v]) => v instanceof AbstractRelationImpl)\n .map(([name]) => (entity as any)[name]);\n}\n\nexport function getRelationEntries(entity: Entity): [string, AbstractRelationImpl<any, any>][] {\n return Object.entries(getProperties(getMetadata(entity)))\n .filter(([, v]) => v instanceof AbstractRelationImpl)\n .map(([name]) => [name, (entity as any)[name]]);\n}\n\n/** Casts a \"maybe abstract\" cstr to a concrete cstr when the calling code knows it's safe. */\nexport function asConcreteCstr<T extends Entity>(cstr: MaybeAbstractEntityConstructor<T>): EntityConstructor<T> {\n return cstr as any;\n}\n\n/**\n * Thrown when `.id` is accessed on an entity that does not have an id yet.\n *\n * For Postgres, entities are actually allowed to have ids pre-INSERT, if you call\n * `em.assignNewIds()`. Other databases typically require INSERTs to trigger the auto\n * id assignment.\n */\nexport class NoIdError extends Error {}\n\n/** Throws a `NoIdError` for `entity`, i.e. because `id` was called before being saved. */\nexport function failNoIdYet(entity: string): never {\n throw new NoIdError(`${entity} has no id yet`);\n}\n\n/**\n * Add a static function since getters can't have type guards.\n *\n * See https://github.com/microsoft/TypeScript/issues/43368\n */\nexport function isNewEntity<T extends Entity>(entity: T): entity is New<T> {\n return entity.isNewEntity;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,UAAU;CAAE;CAAe;CAAwB;AAAc;AAC9E,MAAa,YAAY,EAAE,iBAAiB;;;;;;;;;;;;;;;AAuP5C,SAAgB,QACd,QACA,QACA,MACM;CACN,MAAM,EAAE,wBAAwB,OAAO,YAAY,QAAQ,CAA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SAAS,QAAQ,KAAK,KAAK;MAE3B,OAAgB,OAAO;AAG7B;AAEA,SAAgB,iBAAiB,QAAgB,QAA0B;CACzE,IAAI,OAAO,oBAAoB,WAAW,KAAA,KAAa,gBAAgB,MAAM,CAAC,CAAC,sBAC7E,KAAK,GAAG,OAAO,sBAAsB;AAEzC;AASA,SAAgB,gBAAkC,cAAkD;CAClG,OAAO,OAAO,OAAO,YAAY,YAAmB,CAAC,CAAC,MAAM,CAAC,CAC1D,QAAQ,MAAM,EAAE,QAAQ,CAAC,CACzB,KAAK,MAAM,EAAE,SAAS;AAC3B;AAEA,SAAgB,aAAa,QAAkD;CAC7E,OAAO,OAAO,QAAQ,cAAc,YAAY,MAAM,CAAC,CAAC,CAAC,CACtD,QAAQ,GAAG,OAAO,aAAa,oBAAoB,CAAC,CACpD,KAAK,CAAC,UAAW,OAAe,KAAK;AAC1C;AAEA,SAAgB,mBAAmB,QAA4D;CAC7F,OAAO,OAAO,QAAQ,cAAc,YAAY,MAAM,CAAC,CAAC,CAAC,CACtD,QAAQ,GAAG,OAAO,aAAa,oBAAoB,CAAC,CACpD,KAAK,CAAC,UAAU,CAAC,MAAO,OAAe,KAAK,CAAC;AAClD;;AAGA,SAAgB,eAAiC,MAA+D;CAC9G,OAAO;AACT;;;;;;;;AASA,IAAa,YAAb,cAA+B,MAAM,CAAC;;AAGtC,SAAgB,YAAY,QAAuB;CACjD,MAAM,IAAI,UAAU,GAAG,OAAO,eAAe;AAC/C;;;;;;AAOA,SAAgB,YAA8B,QAA6B;CACzE,OAAO,OAAO;AAChB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "joist-core",
3
- "version": "2.3.0-next.81",
3
+ "version": "2.3.0-next.83",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "repository": {
@@ -42,7 +42,7 @@
42
42
  "build"
43
43
  ],
44
44
  "peerDependencies": {
45
- "joist-utils": "2.3.0-next.81"
45
+ "joist-utils": "2.3.0-next.83"
46
46
  },
47
47
  "dependencies": {
48
48
  "ansis": "^4.3.1",