joist-core 2.5.0-next.12 → 2.5.0-next.13

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.
@@ -139,7 +139,7 @@ var JoinRows = class {
139
139
  const others = this.index.getOthers(columnName, entity);
140
140
  if (others.length === 0) return [];
141
141
  const [c1, c2] = Object.keys(others[0].columns);
142
- const c = others[0].columns[c1] === entity ? c2 : c1;
142
+ const c = c1 === columnName ? c2 : c1;
143
143
  return others.filter((o) => !o.deleted).map((row) => row.columns[c]);
144
144
  }
145
145
  /** Drops all in-memory rows where `entity` is on `columnName`, e.g. when it is being deleted. */
@@ -1 +1 @@
1
- {"version":3,"file":"JoinRows.cjs","names":["keyToTaggedId","keyToNumber","getEmInternalApi","getBaseAndSelfMetas"],"sources":["../../src/flush/JoinRows.ts"],"sourcesContent":["import type { Entity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type EntityMetadata, getBaseAndSelfMetas } from \"src/EntityMetadata.ts\";\nimport type { EnumMetadata } from \"src/EnumMetadata.ts\";\nimport type { JoinRowTodo } from \"src/flush/Todo.ts\";\nimport { keyToNumber, keyToTaggedId } from \"src/keys.ts\";\nimport type { ReactionsManager } from \"src/reactivity/ReactionsManager.ts\";\nimport { remove } from \"src/utils.ts\";\n\n/**\n * A simplified interface for ManyToManyCollection-like relations.\n *\n * Specifically lets ReactiveManyToMany & ReactiveManyToManyOtherSide use JoinRows\n * as if they were full-fledged m2m relations.\n *\n * The \"other\" side of the join table is usually a second entity, but for `EnumCollection`s\n * (i.e. `Publisher.logoColors`) it is an enum table; in that case `otherEnum` is set and the\n * other column's value is the enum's numeric id rather than an `Entity` (there is also no\n * `otherMeta`/`otherFieldName`, since enums have no reverse collection to keep in sync).\n */\nexport type ManyToManyLike = {\n entity: Entity;\n joinTableName: string;\n columnName: string;\n otherColumnName: string;\n fieldName: string;\n meta: EntityMetadata;\n /** Undefined when the other side is an enum. */\n otherFieldName?: string;\n /** Undefined when the other side is an enum. */\n otherMeta?: EntityMetadata;\n /** Set when the other side is an enum table, for mapping enum codes <-> their numeric ids. */\n otherEnum?: EnumMetadata<any, any, number>;\n /** Whether the join table has a surrogate `id` PK; if false the FK pair is the composite PK. */\n hasJoinTableId: boolean;\n};\n\n/** The value of a join row's column: an `Entity`, or an enum's numeric id for `EnumCollection`s. */\nexport type JoinColumnValue = Entity | number;\n\n/** Whether a join column points at a not-yet-inserted entity (enum ids are never \"new\"). */\nfunction isNewColumn(value: JoinColumnValue): boolean {\n return typeof value !== \"number\" && value.isNewEntity;\n}\n\n/** A small holder around m2m join rows, which we treat as psuedo-entities. */\nexport class JoinRows {\n // The in-memory rows for our m2m table.\n private readonly rows: JoinRow[] = [];\n private readonly index: ManyToManyIndex;\n\n constructor(\n // This could be either side of the m2m relation, depending on which is accessed first.\n // Regardless of which m2m side, we still have a single `JoinRows` instance in memory per m2m table.\n readonly m2m: ManyToManyLike,\n private rm: ReactionsManager,\n ) {\n this.index = new ManyToManyIndex(m2m);\n }\n\n /** Adds a new join row to this table. */\n addNew(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n if (!e1) throw new Error(`Cannot add a m2m row with an entity that is ${e1}`);\n if (!e2) throw new Error(`Cannot add a m2m row with an entity that is ${e2}`);\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n existing.deleted = false;\n existing.op = JoinRowOperation.Pending;\n } else {\n const row = {\n op: JoinRowOperation.Pending,\n id: undefined,\n persisted: false,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n this.#reactToChange(m2m, e1, e2);\n }\n\n /** Adds a new remove to this table. */\n addRemove(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n if (!existing.persisted) {\n // It was only added in-memory and never persisted, so just drop it\n remove(this.rows, existing);\n this.index.remove(existing);\n } else {\n existing.deleted = true;\n }\n existing.op = JoinRowOperation.Pending;\n } else {\n // We're removing against an unloaded collection, so assume the row exists in the database\n // (persisted: true) and queue a delete; the delete keys off the (col1, col2) composite.\n const row = {\n op: JoinRowOperation.Pending,\n id: undefined,\n persisted: true,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n deleted: true,\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n this.#reactToChange(m2m, e1, e2);\n }\n\n /** Return any \"old values\" for a m2m collection that might need reactivity checks. */\n removedFor(m2m: ManyToManyLike, e1: Entity): JoinColumnValue[] {\n const { otherColumnName } = m2m;\n // I.e. if we did `t1.books.remove(b1)` find all join rows that have\n // `tag_id=t1`, are marked for deletion, and then `.map` them to the removed book.\n const removedRows = this.index.getOthers(m2m.columnName, e1).filter((r) => r.deleted);\n return removedRows.map((r) => r.columns[otherColumnName]);\n }\n\n addedFor(m2m: ManyToManyLike, e1: Entity): JoinColumnValue[] {\n const { otherColumnName } = m2m;\n const addedRows = this.index\n .getOthers(m2m.columnName, e1)\n .filter(\n (r) =>\n ((!r.persisted && r.op === JoinRowOperation.Pending) || r.op === JoinRowOperation.Flushed) &&\n r.deleted !== true,\n );\n return addedRows.map((r) => r.columns[otherColumnName]);\n }\n\n /** Adds an existing join row to this table. */\n addPreloadedRow(m2m: ManyToManyLike, id: number | undefined, e1: Entity, e2: JoinColumnValue): void {\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n // Treat any existing WIP change as source-of-truth, so leave it alone\n } else {\n const row = {\n op: JoinRowOperation.Pending,\n id,\n persisted: true,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n }\n\n /** Look up/create our internal JoinRow psuedo-entities for the db rows. */\n async loadRows(tuples: [string, string][], dbRows: any[]): Promise<void> {\n const { em } = this.m2m.entity;\n const { columnName: column1, otherColumnName: column2, meta: meta1, otherMeta: meta2, otherEnum } = this.m2m;\n\n const oneIds: string[] = [];\n // Tagged ids for an entity other-side, or raw enum ids for an enum other-side.\n const twoVals: JoinColumnValue[] = [];\n for (const dbRow of dbRows) {\n oneIds.push(keyToTaggedId(meta1, dbRow[column1])!);\n twoVals.push(\n otherEnum ? (dbRow[column2] as number) : (em.getEntity(keyToTaggedId(meta2!, dbRow[column2])!) as any),\n );\n }\n\n // Make sure we have entities in memory for all the joined-to tables. The enum side has no\n // entities to load; the entity sides do (and `twoVals` is re-resolved to entities below).\n await Promise.all([\n em.loadAll(meta1.cstr, oneIds),\n otherEnum\n ? Promise.resolve([])\n : em.loadAll(\n meta2!.cstr,\n dbRows.map((dbRow) => keyToTaggedId(meta2!, dbRow[column2])!),\n ),\n ]);\n\n // If we're doing a em.refresh/reload, we need to watch for rows that are no longer here. For an\n // enum other-side, only persisted rows are delete-candidates (pending in-memory adds are kept,\n // since `EnumCollection` relies on `JoinRows` to hold them rather than re-asserting on load).\n const existingRows = new Set<JoinRow>();\n for (const [columnName, id] of tuples) {\n const others = this.index.getOthers(columnName, em.getEntity(id)!);\n for (const row of others) if (!otherEnum || row.persisted) existingRows.add(row);\n }\n\n let i = 0;\n for (const dbRow of dbRows) {\n const e1 = em.getEntity(oneIds[i])!;\n const e2 = otherEnum ? (dbRow[column2] as number) : em.getEntity(keyToTaggedId(meta2!, dbRow[column2])!)!;\n i++;\n let row = this.index.get(this.m2m, e1, e2);\n if (!row) {\n row = {\n op: JoinRowOperation.Completed,\n id: dbRow.id,\n persisted: true,\n columns: { [column1]: e1, [column2]: e2 },\n created_at: dbRow.created_at,\n };\n this.rows.push(row);\n this.index.add(this.m2m, e1, e2, row);\n } else {\n // If a placeholder row was created while a ManyToManyCollection was unloaded, and we find it during\n // a subsequent load/query, update its id to be what is in the database and mark it persisted.\n row.id = dbRow.id;\n row.persisted = true;\n // Mark this row as still valid\n existingRows.delete(row);\n }\n }\n\n // Mark all no-longer-there rows as deleted\n for (const row of existingRows) row.deleted = true;\n }\n\n getOthers(columnName: string, entity: Entity): JoinColumnValue[] {\n const others = this.index.getOthers(columnName, entity);\n if (others.length === 0) return [];\n const [c1, c2] = Object.keys(others[0].columns);\n const c = others[0].columns[c1] === entity ? c2 : c1;\n return others.filter((o) => !o.deleted).map((row) => row.columns[c]);\n }\n\n /** Drops all in-memory rows where `entity` is on `columnName`, e.g. when it is being deleted. */\n removeAllFor(columnName: string, entity: Entity): void {\n for (const row of this.index.getOthers(columnName, entity)) {\n remove(this.rows, row);\n this.index.remove(row);\n }\n }\n\n /** Drops a single `(e1, e2)` row without queuing a flush, e.g. when mirroring another em's removal. */\n removePreloadedRow(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const row = this.index.get(m2m, e1, e2);\n if (row) {\n remove(this.rows, row);\n this.index.remove(row);\n }\n }\n\n /** Scans our `rows` for newly-added/newly-deleted rows that need `INSERT`s/`UPDATE`s. */\n toTodo(): JoinRowTodo | undefined {\n const newRows = this.rows.filter((r) => !r.persisted && r.deleted !== true && r.op === \"pending\");\n const deletedRows = this.rows.filter((r) => r.persisted && r.deleted === true && r.op === \"pending\");\n if (newRows.length === 0 && deletedRows.length === 0) {\n return undefined;\n }\n return {\n m2m: this.m2m,\n newRows,\n deletedRows,\n resetAfterFlushed: () => {\n for (const row of this.rows) {\n if (row.op === JoinRowOperation.Pending || row.op === JoinRowOperation.Flushed)\n row.op = JoinRowOperation.Completed;\n }\n },\n // The driver flushes pure (int, int) FK pairs; resolve them here so it never has to know\n // whether a column points at an entity (use its id) or an enum (its value is already the id).\n dbValue: (row, columnName) => this.#dbValue(row, columnName),\n isNew: (row, columnName) => isNewColumn(row.columns[columnName]),\n };\n }\n\n get hasChanges() {\n return this.rows.some(({ op }) => op === JoinRowOperation.Pending || op === JoinRowOperation.Flushed);\n }\n\n /** The db int value for `row`'s `columnName`: an entity's id, or (for enums) the enum's id itself. */\n #dbValue(row: JoinRow, columnName: string): number {\n const value = row.columns[columnName];\n if (typeof value === \"number\") return value;\n const meta = columnName === this.m2m.columnName ? this.m2m.meta : this.m2m.otherMeta!;\n return keyToNumber(meta, value.idTagged)!;\n }\n\n /**\n * Invalidates caches & queues reactivity for a join-row change.\n *\n * The owning entity (`e1`) always reacts; the \"other\" side only reacts when it is an entity,\n * since enum other-sides have no `em`/reverse-field to keep in sync.\n */\n #reactToChange(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const { em } = this.m2m.entity;\n const api = getEmInternalApi(e1.em);\n api.isLoadedCache.resetIsLoaded(e1, m2m.fieldName);\n this.rm.queueDownstreamReactables(e1, m2m.fieldName);\n if (getBaseAndSelfMetas(e1).some((meta) => meta.config.__data.touchOnChange.has(m2m.fieldName))) {\n em.touch(e1);\n }\n if (!m2m.otherEnum) {\n const other = e2 as Entity;\n const otherFieldName = m2m.otherFieldName!;\n api.isLoadedCache.resetIsLoaded(other, otherFieldName);\n this.rm.queueDownstreamReactables(other, otherFieldName);\n if (getBaseAndSelfMetas(other).some((meta) => meta.config.__data.touchOnChange.has(otherFieldName))) {\n em.touch(other);\n }\n }\n }\n}\n\n/**\n * A \"psuedo-entity\" for a join row.\n *\n * We treat this as a special entity, i.e. it has two \"relations\" to each entity for the current\n * row, an optional surrogate `id` primary key, and an optional `created_at` column.\n *\n * These rows are immutable, i.e. once created we don't change either FK, and instead make\n * collection changes only by inserting new rows and deleting old rows.\n *\n * This makes the column1+column2 combination a composite key. For id-less join tables, that\n * composite is the actual primary key and `id` is always undefined.\n */\nexport interface JoinRow {\n /**\n * Whether our relation has been processed or not.\n *\n * - `pending` means we've not flushed it to the Database\n * - `flushed` means we've flushed but `em.flush` hasn't fully completed yet, likely due to AsyncReactiveField calcs\n * - `completed` means we've been flushed and `em.flush` has completed\n */\n op: JoinRowOperation;\n /** The surrogate key for id-ful join tables; always undefined for id-less tables. */\n id: number | undefined;\n /**\n * Whether this row exists (or is assumed to exist) in the database.\n *\n * This is orthogonal to `op` (the flush lifecycle) and is what distinguishes a pending insert\n * from a pending delete: a `pending` row that is `!persisted` is a pending INSERT (added in\n * memory, not yet in the db), while a `pending` row that is `persisted` is a pending DELETE\n * (in the db, marked `deleted`). `op` alone cannot tell these apart, because both inserts and\n * deletes walk the same `pending -> flushed -> completed` progression.\n *\n * We track this as its own flag rather than inferring it from `id` being set/unset, because\n * id-less join tables (whose PK is just the composite of the two FKs) never have an `id` — so\n * `id === undefined` would be ambiguous. `persisted` is the id-agnostic generalization of the\n * `id`-is-set check that id-ful tables historically relied on.\n *\n * It must survive add/remove/re-add sequences: e.g. loading a row (persisted), removing it\n * (pending delete), then re-adding it (`deleted` flipped back to false, `op` back to `pending`)\n * leaves a `pending && !deleted` row that looks identical to a fresh insert — but it is still in\n * the db, so a subsequent remove must issue a DELETE, which only `persisted` can tell us.\n */\n persisted: boolean;\n /** Maps each FK column to its value: an `Entity`, or (for `EnumCollection`s) an enum's numeric id. */\n columns: Record<string, JoinColumnValue>;\n created_at?: Date;\n deleted?: boolean;\n}\n\n/** An enum to track our insert/delete state progression. */\nexport enum JoinRowOperation {\n Pending = \"pending\",\n Flushed = \"flushed\",\n Completed = \"completed\",\n}\n\n/** Keep an in-memory index to avoid sequentially scanning `rows`. */\nclass ManyToManyIndex {\n private indexes: Record<string, Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>> = {};\n\n constructor(private readonly m2m: ManyToManyLike) {\n this.indexes[m2m.columnName] = new Map();\n this.indexes[m2m.otherColumnName] = new Map();\n }\n\n add(m2m: ManyToManyLike, e1: JoinColumnValue, e2: JoinColumnValue, value: JoinRow): void {\n // Store both e1+e2 => value and e2+e1 => value so we can do lookups from either side\n this.#doAdd(this.indexes[m2m.columnName], e1, e2, value);\n this.#doAdd(this.indexes[m2m.otherColumnName], e2, e1, value);\n }\n\n remove(value: JoinRow): void {\n const [[column1, e1], [column2, e2]] = Object.entries(value.columns);\n this.#doRemove(this.indexes[column1], e1, e2);\n this.#doRemove(this.indexes[column2], e2, e1);\n }\n\n get(m2m: ManyToManyLike, e1: JoinColumnValue, e2: JoinColumnValue): JoinRow | undefined {\n return this.indexes[m2m.columnName].get(e1)?.get(e2);\n }\n\n /** Cheat and use the index to return \"the other entities\" for `entity`. */\n getOthers(columnName: string, entity: JoinColumnValue): JoinRow[] {\n // It's empty m2m collection won't have any other entities, and so no index entries\n const map = this.indexes[columnName].get(entity);\n if (!map) return [];\n // Sort for a stable order regardless of how many batches contributed rows — the underlying\n // Map preserves insertion order, which depends on DataLoader timing and is non-deterministic\n // across processes. New rows (no key yet) sort last.\n const rows = Array.from(map.values());\n if (this.m2m.hasJoinTableId) {\n // Sort by join-row id.\n return rows.sort((a, b) => (a.id ?? Infinity) - (b.id ?? Infinity));\n }\n // Id-less tables have no surrogate id, so sort by the other side's id.\n const otherColumn = columnName === this.m2m.columnName ? this.m2m.otherColumnName : this.m2m.columnName;\n if (this.m2m.otherEnum && otherColumn === this.m2m.otherColumnName) {\n // The other side is an enum, so its column value is already its numeric id.\n return rows.sort((a, b) => (a.columns[otherColumn] as number) - (b.columns[otherColumn] as number));\n }\n const otherMeta = columnName === this.m2m.columnName ? this.m2m.otherMeta! : this.m2m.meta;\n const key = (r: JoinRow) => {\n const other = r.columns[otherColumn] as Entity;\n return other.isNewEntity ? Infinity : keyToNumber(otherMeta, other.id)!;\n };\n return rows.sort((a, b) => key(a) - key(b));\n }\n\n #doAdd(\n index: Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>,\n e1: JoinColumnValue,\n e2: JoinColumnValue,\n value: JoinRow,\n ): void {\n const map = index.get(e1) ?? new Map();\n if (map.size === 0) index.set(e1, map);\n map.set(e2, value);\n }\n\n #doRemove(\n index: Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>,\n e1: JoinColumnValue,\n e2: JoinColumnValue,\n ): void {\n index.get(e1)?.delete(e2);\n }\n}\n"],"mappings":";;;;;;;AAyCA,SAAS,YAAY,OAAiC;CACpD,OAAO,OAAO,UAAU,YAAY,MAAM;A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Rows.cjs","names":["keyToTaggedId","keyToNumber","getEmInternalApi","getBaseAndSelfMetas"],"sources":["../../src/flush/JoinRows.ts"],"sourcesContent":["import type { Entity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type EntityMetadata, getBaseAndSelfMetas } from \"src/EntityMetadata.ts\";\nimport type { EnumMetadata } from \"src/EnumMetadata.ts\";\nimport type { JoinRowTodo } from \"src/flush/Todo.ts\";\nimport { keyToNumber, keyToTaggedId } from \"src/keys.ts\";\nimport type { ReactionsManager } from \"src/reactivity/ReactionsManager.ts\";\nimport { remove } from \"src/utils.ts\";\n\n/**\n * A simplified interface for ManyToManyCollection-like relations.\n *\n * Specifically lets ReactiveManyToMany & ReactiveManyToManyOtherSide use JoinRows\n * as if they were full-fledged m2m relations.\n *\n * The \"other\" side of the join table is usually a second entity, but for `EnumCollection`s\n * (i.e. `Publisher.logoColors`) it is an enum table; in that case `otherEnum` is set and the\n * other column's value is the enum's numeric id rather than an `Entity` (there is also no\n * `otherMeta`/`otherFieldName`, since enums have no reverse collection to keep in sync).\n */\nexport type ManyToManyLike = {\n entity: Entity;\n joinTableName: string;\n columnName: string;\n otherColumnName: string;\n fieldName: string;\n meta: EntityMetadata;\n /** Undefined when the other side is an enum. */\n otherFieldName?: string;\n /** Undefined when the other side is an enum. */\n otherMeta?: EntityMetadata;\n /** Set when the other side is an enum table, for mapping enum codes <-> their numeric ids. */\n otherEnum?: EnumMetadata<any, any, number>;\n /** Whether the join table has a surrogate `id` PK; if false the FK pair is the composite PK. */\n hasJoinTableId: boolean;\n};\n\n/** The value of a join row's column: an `Entity`, or an enum's numeric id for `EnumCollection`s. */\nexport type JoinColumnValue = Entity | number;\n\n/** Whether a join column points at a not-yet-inserted entity (enum ids are never \"new\"). */\nfunction isNewColumn(value: JoinColumnValue): boolean {\n return typeof value !== \"number\" && value.isNewEntity;\n}\n\n/** A small holder around m2m join rows, which we treat as psuedo-entities. */\nexport class JoinRows {\n // The in-memory rows for our m2m table.\n private readonly rows: JoinRow[] = [];\n private readonly index: ManyToManyIndex;\n\n constructor(\n // This could be either side of the m2m relation, depending on which is accessed first.\n // Regardless of which m2m side, we still have a single `JoinRows` instance in memory per m2m table.\n readonly m2m: ManyToManyLike,\n private rm: ReactionsManager,\n ) {\n this.index = new ManyToManyIndex(m2m);\n }\n\n /** Adds a new join row to this table. */\n addNew(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n if (!e1) throw new Error(`Cannot add a m2m row with an entity that is ${e1}`);\n if (!e2) throw new Error(`Cannot add a m2m row with an entity that is ${e2}`);\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n existing.deleted = false;\n existing.op = JoinRowOperation.Pending;\n } else {\n const row = {\n op: JoinRowOperation.Pending,\n id: undefined,\n persisted: false,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n this.#reactToChange(m2m, e1, e2);\n }\n\n /** Adds a new remove to this table. */\n addRemove(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n if (!existing.persisted) {\n // It was only added in-memory and never persisted, so just drop it\n remove(this.rows, existing);\n this.index.remove(existing);\n } else {\n existing.deleted = true;\n }\n existing.op = JoinRowOperation.Pending;\n } else {\n // We're removing against an unloaded collection, so assume the row exists in the database\n // (persisted: true) and queue a delete; the delete keys off the (col1, col2) composite.\n const row = {\n op: JoinRowOperation.Pending,\n id: undefined,\n persisted: true,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n deleted: true,\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n this.#reactToChange(m2m, e1, e2);\n }\n\n /** Return any \"old values\" for a m2m collection that might need reactivity checks. */\n removedFor(m2m: ManyToManyLike, e1: Entity): JoinColumnValue[] {\n const { otherColumnName } = m2m;\n // I.e. if we did `t1.books.remove(b1)` find all join rows that have\n // `tag_id=t1`, are marked for deletion, and then `.map` them to the removed book.\n const removedRows = this.index.getOthers(m2m.columnName, e1).filter((r) => r.deleted);\n return removedRows.map((r) => r.columns[otherColumnName]);\n }\n\n addedFor(m2m: ManyToManyLike, e1: Entity): JoinColumnValue[] {\n const { otherColumnName } = m2m;\n const addedRows = this.index\n .getOthers(m2m.columnName, e1)\n .filter(\n (r) =>\n ((!r.persisted && r.op === JoinRowOperation.Pending) || r.op === JoinRowOperation.Flushed) &&\n r.deleted !== true,\n );\n return addedRows.map((r) => r.columns[otherColumnName]);\n }\n\n /** Adds an existing join row to this table. */\n addPreloadedRow(m2m: ManyToManyLike, id: number | undefined, e1: Entity, e2: JoinColumnValue): void {\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n // Treat any existing WIP change as source-of-truth, so leave it alone\n } else {\n const row = {\n op: JoinRowOperation.Pending,\n id,\n persisted: true,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n }\n\n /** Look up/create our internal JoinRow psuedo-entities for the db rows. */\n async loadRows(tuples: [string, string][], dbRows: any[]): Promise<void> {\n const { em } = this.m2m.entity;\n const { columnName: column1, otherColumnName: column2, meta: meta1, otherMeta: meta2, otherEnum } = this.m2m;\n\n const oneIds: string[] = [];\n // Tagged ids for an entity other-side, or raw enum ids for an enum other-side.\n const twoVals: JoinColumnValue[] = [];\n for (const dbRow of dbRows) {\n oneIds.push(keyToTaggedId(meta1, dbRow[column1])!);\n twoVals.push(\n otherEnum ? (dbRow[column2] as number) : (em.getEntity(keyToTaggedId(meta2!, dbRow[column2])!) as any),\n );\n }\n\n // Make sure we have entities in memory for all the joined-to tables. The enum side has no\n // entities to load; the entity sides do (and `twoVals` is re-resolved to entities below).\n await Promise.all([\n em.loadAll(meta1.cstr, oneIds),\n otherEnum\n ? Promise.resolve([])\n : em.loadAll(\n meta2!.cstr,\n dbRows.map((dbRow) => keyToTaggedId(meta2!, dbRow[column2])!),\n ),\n ]);\n\n // If we're doing a em.refresh/reload, we need to watch for rows that are no longer here. For an\n // enum other-side, only persisted rows are delete-candidates (pending in-memory adds are kept,\n // since `EnumCollection` relies on `JoinRows` to hold them rather than re-asserting on load).\n const existingRows = new Set<JoinRow>();\n for (const [columnName, id] of tuples) {\n const others = this.index.getOthers(columnName, em.getEntity(id)!);\n for (const row of others) if (!otherEnum || row.persisted) existingRows.add(row);\n }\n\n let i = 0;\n for (const dbRow of dbRows) {\n const e1 = em.getEntity(oneIds[i])!;\n const e2 = otherEnum ? (dbRow[column2] as number) : em.getEntity(keyToTaggedId(meta2!, dbRow[column2])!)!;\n i++;\n let row = this.index.get(this.m2m, e1, e2);\n if (!row) {\n row = {\n op: JoinRowOperation.Completed,\n id: dbRow.id,\n persisted: true,\n columns: { [column1]: e1, [column2]: e2 },\n created_at: dbRow.created_at,\n };\n this.rows.push(row);\n this.index.add(this.m2m, e1, e2, row);\n } else {\n // If a placeholder row was created while a ManyToManyCollection was unloaded, and we find it during\n // a subsequent load/query, update its id to be what is in the database and mark it persisted.\n row.id = dbRow.id;\n row.persisted = true;\n // Mark this row as still valid\n existingRows.delete(row);\n }\n }\n\n // Mark all no-longer-there rows as deleted\n for (const row of existingRows) row.deleted = true;\n }\n\n getOthers(columnName: string, entity: Entity): JoinColumnValue[] {\n const others = this.index.getOthers(columnName, entity);\n if (others.length === 0) return [];\n const [c1, c2] = Object.keys(others[0].columns);\n // Self-referencing rows can contain the same entity in both columns, so identity cannot tell the sides apart.\n const c = c1 === columnName ? c2 : c1;\n return others.filter((o) => !o.deleted).map((row) => row.columns[c]);\n }\n\n /** Drops all in-memory rows where `entity` is on `columnName`, e.g. when it is being deleted. */\n removeAllFor(columnName: string, entity: Entity): void {\n for (const row of this.index.getOthers(columnName, entity)) {\n remove(this.rows, row);\n this.index.remove(row);\n }\n }\n\n /** Drops a single `(e1, e2)` row without queuing a flush, e.g. when mirroring another em's removal. */\n removePreloadedRow(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const row = this.index.get(m2m, e1, e2);\n if (row) {\n remove(this.rows, row);\n this.index.remove(row);\n }\n }\n\n /** Scans our `rows` for newly-added/newly-deleted rows that need `INSERT`s/`UPDATE`s. */\n toTodo(): JoinRowTodo | undefined {\n const newRows = this.rows.filter((r) => !r.persisted && r.deleted !== true && r.op === \"pending\");\n const deletedRows = this.rows.filter((r) => r.persisted && r.deleted === true && r.op === \"pending\");\n if (newRows.length === 0 && deletedRows.length === 0) {\n return undefined;\n }\n return {\n m2m: this.m2m,\n newRows,\n deletedRows,\n resetAfterFlushed: () => {\n for (const row of this.rows) {\n if (row.op === JoinRowOperation.Pending || row.op === JoinRowOperation.Flushed)\n row.op = JoinRowOperation.Completed;\n }\n },\n // The driver flushes pure (int, int) FK pairs; resolve them here so it never has to know\n // whether a column points at an entity (use its id) or an enum (its value is already the id).\n dbValue: (row, columnName) => this.#dbValue(row, columnName),\n isNew: (row, columnName) => isNewColumn(row.columns[columnName]),\n };\n }\n\n get hasChanges() {\n return this.rows.some(({ op }) => op === JoinRowOperation.Pending || op === JoinRowOperation.Flushed);\n }\n\n /** The db int value for `row`'s `columnName`: an entity's id, or (for enums) the enum's id itself. */\n #dbValue(row: JoinRow, columnName: string): number {\n const value = row.columns[columnName];\n if (typeof value === \"number\") return value;\n const meta = columnName === this.m2m.columnName ? this.m2m.meta : this.m2m.otherMeta!;\n return keyToNumber(meta, value.idTagged)!;\n }\n\n /**\n * Invalidates caches & queues reactivity for a join-row change.\n *\n * The owning entity (`e1`) always reacts; the \"other\" side only reacts when it is an entity,\n * since enum other-sides have no `em`/reverse-field to keep in sync.\n */\n #reactToChange(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const { em } = this.m2m.entity;\n const api = getEmInternalApi(e1.em);\n api.isLoadedCache.resetIsLoaded(e1, m2m.fieldName);\n this.rm.queueDownstreamReactables(e1, m2m.fieldName);\n if (getBaseAndSelfMetas(e1).some((meta) => meta.config.__data.touchOnChange.has(m2m.fieldName))) {\n em.touch(e1);\n }\n if (!m2m.otherEnum) {\n const other = e2 as Entity;\n const otherFieldName = m2m.otherFieldName!;\n api.isLoadedCache.resetIsLoaded(other, otherFieldName);\n this.rm.queueDownstreamReactables(other, otherFieldName);\n if (getBaseAndSelfMetas(other).some((meta) => meta.config.__data.touchOnChange.has(otherFieldName))) {\n em.touch(other);\n }\n }\n }\n}\n\n/**\n * A \"psuedo-entity\" for a join row.\n *\n * We treat this as a special entity, i.e. it has two \"relations\" to each entity for the current\n * row, an optional surrogate `id` primary key, and an optional `created_at` column.\n *\n * These rows are immutable, i.e. once created we don't change either FK, and instead make\n * collection changes only by inserting new rows and deleting old rows.\n *\n * This makes the column1+column2 combination a composite key. For id-less join tables, that\n * composite is the actual primary key and `id` is always undefined.\n */\nexport interface JoinRow {\n /**\n * Whether our relation has been processed or not.\n *\n * - `pending` means we've not flushed it to the Database\n * - `flushed` means we've flushed but `em.flush` hasn't fully completed yet, likely due to AsyncReactiveField calcs\n * - `completed` means we've been flushed and `em.flush` has completed\n */\n op: JoinRowOperation;\n /** The surrogate key for id-ful join tables; always undefined for id-less tables. */\n id: number | undefined;\n /**\n * Whether this row exists (or is assumed to exist) in the database.\n *\n * This is orthogonal to `op` (the flush lifecycle) and is what distinguishes a pending insert\n * from a pending delete: a `pending` row that is `!persisted` is a pending INSERT (added in\n * memory, not yet in the db), while a `pending` row that is `persisted` is a pending DELETE\n * (in the db, marked `deleted`). `op` alone cannot tell these apart, because both inserts and\n * deletes walk the same `pending -> flushed -> completed` progression.\n *\n * We track this as its own flag rather than inferring it from `id` being set/unset, because\n * id-less join tables (whose PK is just the composite of the two FKs) never have an `id` — so\n * `id === undefined` would be ambiguous. `persisted` is the id-agnostic generalization of the\n * `id`-is-set check that id-ful tables historically relied on.\n *\n * It must survive add/remove/re-add sequences: e.g. loading a row (persisted), removing it\n * (pending delete), then re-adding it (`deleted` flipped back to false, `op` back to `pending`)\n * leaves a `pending && !deleted` row that looks identical to a fresh insert — but it is still in\n * the db, so a subsequent remove must issue a DELETE, which only `persisted` can tell us.\n */\n persisted: boolean;\n /** Maps each FK column to its value: an `Entity`, or (for `EnumCollection`s) an enum's numeric id. */\n columns: Record<string, JoinColumnValue>;\n created_at?: Date;\n deleted?: boolean;\n}\n\n/** An enum to track our insert/delete state progression. */\nexport enum JoinRowOperation {\n Pending = \"pending\",\n Flushed = \"flushed\",\n Completed = \"completed\",\n}\n\n/** Keep an in-memory index to avoid sequentially scanning `rows`. */\nclass ManyToManyIndex {\n private indexes: Record<string, Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>> = {};\n\n constructor(private readonly m2m: ManyToManyLike) {\n this.indexes[m2m.columnName] = new Map();\n this.indexes[m2m.otherColumnName] = new Map();\n }\n\n add(m2m: ManyToManyLike, e1: JoinColumnValue, e2: JoinColumnValue, value: JoinRow): void {\n // Store both e1+e2 => value and e2+e1 => value so we can do lookups from either side\n this.#doAdd(this.indexes[m2m.columnName], e1, e2, value);\n this.#doAdd(this.indexes[m2m.otherColumnName], e2, e1, value);\n }\n\n remove(value: JoinRow): void {\n const [[column1, e1], [column2, e2]] = Object.entries(value.columns);\n this.#doRemove(this.indexes[column1], e1, e2);\n this.#doRemove(this.indexes[column2], e2, e1);\n }\n\n get(m2m: ManyToManyLike, e1: JoinColumnValue, e2: JoinColumnValue): JoinRow | undefined {\n return this.indexes[m2m.columnName].get(e1)?.get(e2);\n }\n\n /** Cheat and use the index to return \"the other entities\" for `entity`. */\n getOthers(columnName: string, entity: JoinColumnValue): JoinRow[] {\n // It's empty m2m collection won't have any other entities, and so no index entries\n const map = this.indexes[columnName].get(entity);\n if (!map) return [];\n // Sort for a stable order regardless of how many batches contributed rows — the underlying\n // Map preserves insertion order, which depends on DataLoader timing and is non-deterministic\n // across processes. New rows (no key yet) sort last.\n const rows = Array.from(map.values());\n if (this.m2m.hasJoinTableId) {\n // Sort by join-row id.\n return rows.sort((a, b) => (a.id ?? Infinity) - (b.id ?? Infinity));\n }\n // Id-less tables have no surrogate id, so sort by the other side's id.\n const otherColumn = columnName === this.m2m.columnName ? this.m2m.otherColumnName : this.m2m.columnName;\n if (this.m2m.otherEnum && otherColumn === this.m2m.otherColumnName) {\n // The other side is an enum, so its column value is already its numeric id.\n return rows.sort((a, b) => (a.columns[otherColumn] as number) - (b.columns[otherColumn] as number));\n }\n const otherMeta = columnName === this.m2m.columnName ? this.m2m.otherMeta! : this.m2m.meta;\n const key = (r: JoinRow) => {\n const other = r.columns[otherColumn] as Entity;\n return other.isNewEntity ? Infinity : keyToNumber(otherMeta, other.id)!;\n };\n return rows.sort((a, b) => key(a) - key(b));\n }\n\n #doAdd(\n index: Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>,\n e1: JoinColumnValue,\n e2: JoinColumnValue,\n value: JoinRow,\n ): void {\n const map = index.get(e1) ?? new Map();\n if (map.size === 0) index.set(e1, map);\n map.set(e2, value);\n }\n\n #doRemove(\n index: Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>,\n e1: JoinColumnValue,\n e2: JoinColumnValue,\n ): void {\n index.get(e1)?.delete(e2);\n }\n}\n"],"mappings":";;;;;;;AAyCA,SAAS,YAAY,OAAiC;CACpD,OAAO,OAAO,UAAU,YAAY,MAAM;AAC5C;;AAGA,IAAa,WAAb,MAAsB;CAQT;CACD;CAPV,OAAmC,CAAC;CACpC;CAEA,YAGE,KACA,IACA;EAFS,KAAA,MAAA;EACD,KAAA,KAAA;EAER,KAAK,QAAQ,IAAI,gBAAgB,GAAG;CACtC;;CAGA,OAAO,KAAqB,IAAY,IAA2B;EACjE,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C,IAAI;EAC5E,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C,IAAI;EAC5E,MAAM,WAAW,KAAK,MAAM,IAAI,KAAK,IAAI,EAAE;EAC3C,IAAI,UAAU;GACZ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{"version":3,"file":"JoinRows.d.mts","names":[],"sources":["../../src/flush/JoinRows.ts"],"mappings":";;;;;;;;;;;;;;;;YAoBY;EACV,QAAQ;EACR;EACA;EACA;EACA;EACA,MAAM;;EAEN;;EAEA,YAAY;;EAEZ,YAAY;;EAEZ;;;YAIU,kBAAkB;;qBAQjB;;WAQA,KAAK;UACN;mBAPO;mBACA;EAEjB,YAGW,KAAK,gBACN,IAAI;;EAMd,OAAO,KAAK,gBAAgB,IAAI,QAAQ,IAAI;;EAqB5C,UAAU,KAAK,gBAAgB,IAAI,QAAQ,IAAI;;EA4B/C,WAAW,KAAK,gBAAgB,IAAI,SAAS;EAQ7C,SAAS,KAAK,gBAAgB,IAAI,SAAS;;EAa3C,gBAAgB,KAAK,gBAAgB,wBAAwB,IAAI,QAAQ,IAAI;;EAiBvE,SAAS,4BAA4B,gBAAgB;EAiE3D,UAAU,oBAAoB,QAAQ,SAAS;;EAS/C,aAAa,oBAAoB,QAAQ;;EAQzC,mBAAmB,KAAK,gBAAgB,IAAI,QAAQ,IAAI;;EASxD,UAAU;MAuBN;;;;;;;;;;;;;;iBAkDW;;;;;;;;EAQf,IAAI;;EAEJ;;;;;;;;;;;;;;;;;;;;EAoBA;;EAEA,SAAS,eAAe;EACxB,aAAa;EACb;;;oBAIU;EACV;EACA;EACA"}
1
+ {"version":3,"file":"JoinRows.d.mts","names":[],"sources":["../../src/flush/JoinRows.ts"],"mappings":";;;;;;;;;;;;;;;;YAoBY;EACV,QAAQ;EACR;EACA;EACA;EACA;EACA,MAAM;;EAEN;;EAEA,YAAY;;EAEZ,YAAY;;EAEZ;;;YAIU,kBAAkB;;qBAQjB;;WAQA,KAAK;UACN;mBAPO;mBACA;EAEjB,YAGW,KAAK,gBACN,IAAI;;EAMd,OAAO,KAAK,gBAAgB,IAAI,QAAQ,IAAI;;EAqB5C,UAAU,KAAK,gBAAgB,IAAI,QAAQ,IAAI;;EA4B/C,WAAW,KAAK,gBAAgB,IAAI,SAAS;EAQ7C,SAAS,KAAK,gBAAgB,IAAI,SAAS;;EAa3C,gBAAgB,KAAK,gBAAgB,wBAAwB,IAAI,QAAQ,IAAI;;EAiBvE,SAAS,4BAA4B,gBAAgB;EAiE3D,UAAU,oBAAoB,QAAQ,SAAS;;EAU/C,aAAa,oBAAoB,QAAQ;;EAQzC,mBAAmB,KAAK,gBAAgB,IAAI,QAAQ,IAAI;;EASxD,UAAU;MAuBN;;;;;;;;;;;;;;iBAkDW;;;;;;;;EAQf,IAAI;;EAEJ;;;;;;;;;;;;;;;;;;;;EAoBA;;EAEA,SAAS,eAAe;EACxB,aAAa;EACb;;;oBAIU;EACV;EACA;EACA"}
@@ -138,7 +138,7 @@ var JoinRows = class {
138
138
  const others = this.index.getOthers(columnName, entity);
139
139
  if (others.length === 0) return [];
140
140
  const [c1, c2] = Object.keys(others[0].columns);
141
- const c = others[0].columns[c1] === entity ? c2 : c1;
141
+ const c = c1 === columnName ? c2 : c1;
142
142
  return others.filter((o) => !o.deleted).map((row) => row.columns[c]);
143
143
  }
144
144
  /** Drops all in-memory rows where `entity` is on `columnName`, e.g. when it is being deleted. */
@@ -1 +1 @@
1
- {"version":3,"file":"JoinRows.js","names":[],"sources":["../../src/flush/JoinRows.ts"],"sourcesContent":["import type { Entity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type EntityMetadata, getBaseAndSelfMetas } from \"src/EntityMetadata.ts\";\nimport type { EnumMetadata } from \"src/EnumMetadata.ts\";\nimport type { JoinRowTodo } from \"src/flush/Todo.ts\";\nimport { keyToNumber, keyToTaggedId } from \"src/keys.ts\";\nimport type { ReactionsManager } from \"src/reactivity/ReactionsManager.ts\";\nimport { remove } from \"src/utils.ts\";\n\n/**\n * A simplified interface for ManyToManyCollection-like relations.\n *\n * Specifically lets ReactiveManyToMany & ReactiveManyToManyOtherSide use JoinRows\n * as if they were full-fledged m2m relations.\n *\n * The \"other\" side of the join table is usually a second entity, but for `EnumCollection`s\n * (i.e. `Publisher.logoColors`) it is an enum table; in that case `otherEnum` is set and the\n * other column's value is the enum's numeric id rather than an `Entity` (there is also no\n * `otherMeta`/`otherFieldName`, since enums have no reverse collection to keep in sync).\n */\nexport type ManyToManyLike = {\n entity: Entity;\n joinTableName: string;\n columnName: string;\n otherColumnName: string;\n fieldName: string;\n meta: EntityMetadata;\n /** Undefined when the other side is an enum. */\n otherFieldName?: string;\n /** Undefined when the other side is an enum. */\n otherMeta?: EntityMetadata;\n /** Set when the other side is an enum table, for mapping enum codes <-> their numeric ids. */\n otherEnum?: EnumMetadata<any, any, number>;\n /** Whether the join table has a surrogate `id` PK; if false the FK pair is the composite PK. */\n hasJoinTableId: boolean;\n};\n\n/** The value of a join row's column: an `Entity`, or an enum's numeric id for `EnumCollection`s. */\nexport type JoinColumnValue = Entity | number;\n\n/** Whether a join column points at a not-yet-inserted entity (enum ids are never \"new\"). */\nfunction isNewColumn(value: JoinColumnValue): boolean {\n return typeof value !== \"number\" && value.isNewEntity;\n}\n\n/** A small holder around m2m join rows, which we treat as psuedo-entities. */\nexport class JoinRows {\n // The in-memory rows for our m2m table.\n private readonly rows: JoinRow[] = [];\n private readonly index: ManyToManyIndex;\n\n constructor(\n // This could be either side of the m2m relation, depending on which is accessed first.\n // Regardless of which m2m side, we still have a single `JoinRows` instance in memory per m2m table.\n readonly m2m: ManyToManyLike,\n private rm: ReactionsManager,\n ) {\n this.index = new ManyToManyIndex(m2m);\n }\n\n /** Adds a new join row to this table. */\n addNew(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n if (!e1) throw new Error(`Cannot add a m2m row with an entity that is ${e1}`);\n if (!e2) throw new Error(`Cannot add a m2m row with an entity that is ${e2}`);\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n existing.deleted = false;\n existing.op = JoinRowOperation.Pending;\n } else {\n const row = {\n op: JoinRowOperation.Pending,\n id: undefined,\n persisted: false,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n this.#reactToChange(m2m, e1, e2);\n }\n\n /** Adds a new remove to this table. */\n addRemove(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n if (!existing.persisted) {\n // It was only added in-memory and never persisted, so just drop it\n remove(this.rows, existing);\n this.index.remove(existing);\n } else {\n existing.deleted = true;\n }\n existing.op = JoinRowOperation.Pending;\n } else {\n // We're removing against an unloaded collection, so assume the row exists in the database\n // (persisted: true) and queue a delete; the delete keys off the (col1, col2) composite.\n const row = {\n op: JoinRowOperation.Pending,\n id: undefined,\n persisted: true,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n deleted: true,\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n this.#reactToChange(m2m, e1, e2);\n }\n\n /** Return any \"old values\" for a m2m collection that might need reactivity checks. */\n removedFor(m2m: ManyToManyLike, e1: Entity): JoinColumnValue[] {\n const { otherColumnName } = m2m;\n // I.e. if we did `t1.books.remove(b1)` find all join rows that have\n // `tag_id=t1`, are marked for deletion, and then `.map` them to the removed book.\n const removedRows = this.index.getOthers(m2m.columnName, e1).filter((r) => r.deleted);\n return removedRows.map((r) => r.columns[otherColumnName]);\n }\n\n addedFor(m2m: ManyToManyLike, e1: Entity): JoinColumnValue[] {\n const { otherColumnName } = m2m;\n const addedRows = this.index\n .getOthers(m2m.columnName, e1)\n .filter(\n (r) =>\n ((!r.persisted && r.op === JoinRowOperation.Pending) || r.op === JoinRowOperation.Flushed) &&\n r.deleted !== true,\n );\n return addedRows.map((r) => r.columns[otherColumnName]);\n }\n\n /** Adds an existing join row to this table. */\n addPreloadedRow(m2m: ManyToManyLike, id: number | undefined, e1: Entity, e2: JoinColumnValue): void {\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n // Treat any existing WIP change as source-of-truth, so leave it alone\n } else {\n const row = {\n op: JoinRowOperation.Pending,\n id,\n persisted: true,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n }\n\n /** Look up/create our internal JoinRow psuedo-entities for the db rows. */\n async loadRows(tuples: [string, string][], dbRows: any[]): Promise<void> {\n const { em } = this.m2m.entity;\n const { columnName: column1, otherColumnName: column2, meta: meta1, otherMeta: meta2, otherEnum } = this.m2m;\n\n const oneIds: string[] = [];\n // Tagged ids for an entity other-side, or raw enum ids for an enum other-side.\n const twoVals: JoinColumnValue[] = [];\n for (const dbRow of dbRows) {\n oneIds.push(keyToTaggedId(meta1, dbRow[column1])!);\n twoVals.push(\n otherEnum ? (dbRow[column2] as number) : (em.getEntity(keyToTaggedId(meta2!, dbRow[column2])!) as any),\n );\n }\n\n // Make sure we have entities in memory for all the joined-to tables. The enum side has no\n // entities to load; the entity sides do (and `twoVals` is re-resolved to entities below).\n await Promise.all([\n em.loadAll(meta1.cstr, oneIds),\n otherEnum\n ? Promise.resolve([])\n : em.loadAll(\n meta2!.cstr,\n dbRows.map((dbRow) => keyToTaggedId(meta2!, dbRow[column2])!),\n ),\n ]);\n\n // If we're doing a em.refresh/reload, we need to watch for rows that are no longer here. For an\n // enum other-side, only persisted rows are delete-candidates (pending in-memory adds are kept,\n // since `EnumCollection` relies on `JoinRows` to hold them rather than re-asserting on load).\n const existingRows = new Set<JoinRow>();\n for (const [columnName, id] of tuples) {\n const others = this.index.getOthers(columnName, em.getEntity(id)!);\n for (const row of others) if (!otherEnum || row.persisted) existingRows.add(row);\n }\n\n let i = 0;\n for (const dbRow of dbRows) {\n const e1 = em.getEntity(oneIds[i])!;\n const e2 = otherEnum ? (dbRow[column2] as number) : em.getEntity(keyToTaggedId(meta2!, dbRow[column2])!)!;\n i++;\n let row = this.index.get(this.m2m, e1, e2);\n if (!row) {\n row = {\n op: JoinRowOperation.Completed,\n id: dbRow.id,\n persisted: true,\n columns: { [column1]: e1, [column2]: e2 },\n created_at: dbRow.created_at,\n };\n this.rows.push(row);\n this.index.add(this.m2m, e1, e2, row);\n } else {\n // If a placeholder row was created while a ManyToManyCollection was unloaded, and we find it during\n // a subsequent load/query, update its id to be what is in the database and mark it persisted.\n row.id = dbRow.id;\n row.persisted = true;\n // Mark this row as still valid\n existingRows.delete(row);\n }\n }\n\n // Mark all no-longer-there rows as deleted\n for (const row of existingRows) row.deleted = true;\n }\n\n getOthers(columnName: string, entity: Entity): JoinColumnValue[] {\n const others = this.index.getOthers(columnName, entity);\n if (others.length === 0) return [];\n const [c1, c2] = Object.keys(others[0].columns);\n const c = others[0].columns[c1] === entity ? c2 : c1;\n return others.filter((o) => !o.deleted).map((row) => row.columns[c]);\n }\n\n /** Drops all in-memory rows where `entity` is on `columnName`, e.g. when it is being deleted. */\n removeAllFor(columnName: string, entity: Entity): void {\n for (const row of this.index.getOthers(columnName, entity)) {\n remove(this.rows, row);\n this.index.remove(row);\n }\n }\n\n /** Drops a single `(e1, e2)` row without queuing a flush, e.g. when mirroring another em's removal. */\n removePreloadedRow(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const row = this.index.get(m2m, e1, e2);\n if (row) {\n remove(this.rows, row);\n this.index.remove(row);\n }\n }\n\n /** Scans our `rows` for newly-added/newly-deleted rows that need `INSERT`s/`UPDATE`s. */\n toTodo(): JoinRowTodo | undefined {\n const newRows = this.rows.filter((r) => !r.persisted && r.deleted !== true && r.op === \"pending\");\n const deletedRows = this.rows.filter((r) => r.persisted && r.deleted === true && r.op === \"pending\");\n if (newRows.length === 0 && deletedRows.length === 0) {\n return undefined;\n }\n return {\n m2m: this.m2m,\n newRows,\n deletedRows,\n resetAfterFlushed: () => {\n for (const row of this.rows) {\n if (row.op === JoinRowOperation.Pending || row.op === JoinRowOperation.Flushed)\n row.op = JoinRowOperation.Completed;\n }\n },\n // The driver flushes pure (int, int) FK pairs; resolve them here so it never has to know\n // whether a column points at an entity (use its id) or an enum (its value is already the id).\n dbValue: (row, columnName) => this.#dbValue(row, columnName),\n isNew: (row, columnName) => isNewColumn(row.columns[columnName]),\n };\n }\n\n get hasChanges() {\n return this.rows.some(({ op }) => op === JoinRowOperation.Pending || op === JoinRowOperation.Flushed);\n }\n\n /** The db int value for `row`'s `columnName`: an entity's id, or (for enums) the enum's id itself. */\n #dbValue(row: JoinRow, columnName: string): number {\n const value = row.columns[columnName];\n if (typeof value === \"number\") return value;\n const meta = columnName === this.m2m.columnName ? this.m2m.meta : this.m2m.otherMeta!;\n return keyToNumber(meta, value.idTagged)!;\n }\n\n /**\n * Invalidates caches & queues reactivity for a join-row change.\n *\n * The owning entity (`e1`) always reacts; the \"other\" side only reacts when it is an entity,\n * since enum other-sides have no `em`/reverse-field to keep in sync.\n */\n #reactToChange(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const { em } = this.m2m.entity;\n const api = getEmInternalApi(e1.em);\n api.isLoadedCache.resetIsLoaded(e1, m2m.fieldName);\n this.rm.queueDownstreamReactables(e1, m2m.fieldName);\n if (getBaseAndSelfMetas(e1).some((meta) => meta.config.__data.touchOnChange.has(m2m.fieldName))) {\n em.touch(e1);\n }\n if (!m2m.otherEnum) {\n const other = e2 as Entity;\n const otherFieldName = m2m.otherFieldName!;\n api.isLoadedCache.resetIsLoaded(other, otherFieldName);\n this.rm.queueDownstreamReactables(other, otherFieldName);\n if (getBaseAndSelfMetas(other).some((meta) => meta.config.__data.touchOnChange.has(otherFieldName))) {\n em.touch(other);\n }\n }\n }\n}\n\n/**\n * A \"psuedo-entity\" for a join row.\n *\n * We treat this as a special entity, i.e. it has two \"relations\" to each entity for the current\n * row, an optional surrogate `id` primary key, and an optional `created_at` column.\n *\n * These rows are immutable, i.e. once created we don't change either FK, and instead make\n * collection changes only by inserting new rows and deleting old rows.\n *\n * This makes the column1+column2 combination a composite key. For id-less join tables, that\n * composite is the actual primary key and `id` is always undefined.\n */\nexport interface JoinRow {\n /**\n * Whether our relation has been processed or not.\n *\n * - `pending` means we've not flushed it to the Database\n * - `flushed` means we've flushed but `em.flush` hasn't fully completed yet, likely due to AsyncReactiveField calcs\n * - `completed` means we've been flushed and `em.flush` has completed\n */\n op: JoinRowOperation;\n /** The surrogate key for id-ful join tables; always undefined for id-less tables. */\n id: number | undefined;\n /**\n * Whether this row exists (or is assumed to exist) in the database.\n *\n * This is orthogonal to `op` (the flush lifecycle) and is what distinguishes a pending insert\n * from a pending delete: a `pending` row that is `!persisted` is a pending INSERT (added in\n * memory, not yet in the db), while a `pending` row that is `persisted` is a pending DELETE\n * (in the db, marked `deleted`). `op` alone cannot tell these apart, because both inserts and\n * deletes walk the same `pending -> flushed -> completed` progression.\n *\n * We track this as its own flag rather than inferring it from `id` being set/unset, because\n * id-less join tables (whose PK is just the composite of the two FKs) never have an `id` — so\n * `id === undefined` would be ambiguous. `persisted` is the id-agnostic generalization of the\n * `id`-is-set check that id-ful tables historically relied on.\n *\n * It must survive add/remove/re-add sequences: e.g. loading a row (persisted), removing it\n * (pending delete), then re-adding it (`deleted` flipped back to false, `op` back to `pending`)\n * leaves a `pending && !deleted` row that looks identical to a fresh insert — but it is still in\n * the db, so a subsequent remove must issue a DELETE, which only `persisted` can tell us.\n */\n persisted: boolean;\n /** Maps each FK column to its value: an `Entity`, or (for `EnumCollection`s) an enum's numeric id. */\n columns: Record<string, JoinColumnValue>;\n created_at?: Date;\n deleted?: boolean;\n}\n\n/** An enum to track our insert/delete state progression. */\nexport enum JoinRowOperation {\n Pending = \"pending\",\n Flushed = \"flushed\",\n Completed = \"completed\",\n}\n\n/** Keep an in-memory index to avoid sequentially scanning `rows`. */\nclass ManyToManyIndex {\n private indexes: Record<string, Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>> = {};\n\n constructor(private readonly m2m: ManyToManyLike) {\n this.indexes[m2m.columnName] = new Map();\n this.indexes[m2m.otherColumnName] = new Map();\n }\n\n add(m2m: ManyToManyLike, e1: JoinColumnValue, e2: JoinColumnValue, value: JoinRow): void {\n // Store both e1+e2 => value and e2+e1 => value so we can do lookups from either side\n this.#doAdd(this.indexes[m2m.columnName], e1, e2, value);\n this.#doAdd(this.indexes[m2m.otherColumnName], e2, e1, value);\n }\n\n remove(value: JoinRow): void {\n const [[column1, e1], [column2, e2]] = Object.entries(value.columns);\n this.#doRemove(this.indexes[column1], e1, e2);\n this.#doRemove(this.indexes[column2], e2, e1);\n }\n\n get(m2m: ManyToManyLike, e1: JoinColumnValue, e2: JoinColumnValue): JoinRow | undefined {\n return this.indexes[m2m.columnName].get(e1)?.get(e2);\n }\n\n /** Cheat and use the index to return \"the other entities\" for `entity`. */\n getOthers(columnName: string, entity: JoinColumnValue): JoinRow[] {\n // It's empty m2m collection won't have any other entities, and so no index entries\n const map = this.indexes[columnName].get(entity);\n if (!map) return [];\n // Sort for a stable order regardless of how many batches contributed rows — the underlying\n // Map preserves insertion order, which depends on DataLoader timing and is non-deterministic\n // across processes. New rows (no key yet) sort last.\n const rows = Array.from(map.values());\n if (this.m2m.hasJoinTableId) {\n // Sort by join-row id.\n return rows.sort((a, b) => (a.id ?? Infinity) - (b.id ?? Infinity));\n }\n // Id-less tables have no surrogate id, so sort by the other side's id.\n const otherColumn = columnName === this.m2m.columnName ? this.m2m.otherColumnName : this.m2m.columnName;\n if (this.m2m.otherEnum && otherColumn === this.m2m.otherColumnName) {\n // The other side is an enum, so its column value is already its numeric id.\n return rows.sort((a, b) => (a.columns[otherColumn] as number) - (b.columns[otherColumn] as number));\n }\n const otherMeta = columnName === this.m2m.columnName ? this.m2m.otherMeta! : this.m2m.meta;\n const key = (r: JoinRow) => {\n const other = r.columns[otherColumn] as Entity;\n return other.isNewEntity ? Infinity : keyToNumber(otherMeta, other.id)!;\n };\n return rows.sort((a, b) => key(a) - key(b));\n }\n\n #doAdd(\n index: Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>,\n e1: JoinColumnValue,\n e2: JoinColumnValue,\n value: JoinRow,\n ): void {\n const map = index.get(e1) ?? new Map();\n if (map.size === 0) index.set(e1, map);\n map.set(e2, value);\n }\n\n #doRemove(\n index: Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>,\n e1: JoinColumnValue,\n e2: JoinColumnValue,\n ): void {\n index.get(e1)?.delete(e2);\n }\n}\n"],"mappings":";;;;;;AAyCA,SAAS,YAAY,OAAiC;CACpD,OAAO,OAAO,UAAU,YAAY,MAAM;AAC5C;;AAGA,IAAa,WAAb,MAAsB;CAQT;CACD;CAPV,OAAmC,CAAC;CACpC;CAEA,YAGE,KACA,IACA;EAFS,KAAA,MAAA;EACD,KAAA,KAAA;EAER,KAAK,QAAQ,IAAI,gBAAgB,GAAG;CACtC;;CAGA,OAAO,KAAqB,IAAY,IAA2B;EACjE,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C,IAAI;EAC5E,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C,IAAI;EAC5E,MAAM,WAAW,KAAK,MAAM,IAAI,KAAK,IAAI,EAAE;EAC3C,IAAI,UAAU;GACZ,SAAS,UAAU;GACnB,SAAS,KAAA;EACX,OAAO;GACL,MAAM,MAAM;IACV,IAAA;IACA,IAAI,KAAA;IACJ,WAAW;IACX,SAAS;MAAG,IAAI,aAAa;MAAK,IAAI,kBAAkB;IAAG;GAC7D;GACA,KAAK,KAAK,KAAK,GAAG;GAClB,KAAK,MAAM,IAAI,KAAK,IAAI,IAAI,GAAG;EACjC;EACA,KAAK,eAAe,KAAK,IAAI,EAAE;CACjC;;CAGA,UAAU,KAAqB,IAAY,IAA2B;EACpE,MAAM,WAAW,KAAK,MAAM,IAAI,KAAK,IAAI,EAAE;EAC3C,IAAI,UAAU;GACZ,IAAI,CAAC,SAAS,WAAW;IAEvB,OAAO,KAAK,MAAM,QAAQ;IAC1B,KAAK,MAAM,OAAO,QAAQ;GAC5B,OACE,SAAS,UAAU;GAErB,SAAS,KAAA;EACX,OAAO;GAGL,MAAM,MAAM;IACV,IAAA;IACA,IAAI,KAAA;IACJ,W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;EACrC,IAAI,IAAI,IAAI,KAAK;CACnB;CAEA,UACE,OACA,IACA,IACM;EACN,MAAM,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE;CAC1B;AACF"}
1
+ {"version":3,"file":"JoinRows.js","names":[],"sources":["../../src/flush/JoinRows.ts"],"sourcesContent":["import type { Entity } from \"src/Entity.ts\";\nimport { getEmInternalApi } from \"src/EntityManager.ts\";\nimport { type EntityMetadata, getBaseAndSelfMetas } from \"src/EntityMetadata.ts\";\nimport type { EnumMetadata } from \"src/EnumMetadata.ts\";\nimport type { JoinRowTodo } from \"src/flush/Todo.ts\";\nimport { keyToNumber, keyToTaggedId } from \"src/keys.ts\";\nimport type { ReactionsManager } from \"src/reactivity/ReactionsManager.ts\";\nimport { remove } from \"src/utils.ts\";\n\n/**\n * A simplified interface for ManyToManyCollection-like relations.\n *\n * Specifically lets ReactiveManyToMany & ReactiveManyToManyOtherSide use JoinRows\n * as if they were full-fledged m2m relations.\n *\n * The \"other\" side of the join table is usually a second entity, but for `EnumCollection`s\n * (i.e. `Publisher.logoColors`) it is an enum table; in that case `otherEnum` is set and the\n * other column's value is the enum's numeric id rather than an `Entity` (there is also no\n * `otherMeta`/`otherFieldName`, since enums have no reverse collection to keep in sync).\n */\nexport type ManyToManyLike = {\n entity: Entity;\n joinTableName: string;\n columnName: string;\n otherColumnName: string;\n fieldName: string;\n meta: EntityMetadata;\n /** Undefined when the other side is an enum. */\n otherFieldName?: string;\n /** Undefined when the other side is an enum. */\n otherMeta?: EntityMetadata;\n /** Set when the other side is an enum table, for mapping enum codes <-> their numeric ids. */\n otherEnum?: EnumMetadata<any, any, number>;\n /** Whether the join table has a surrogate `id` PK; if false the FK pair is the composite PK. */\n hasJoinTableId: boolean;\n};\n\n/** The value of a join row's column: an `Entity`, or an enum's numeric id for `EnumCollection`s. */\nexport type JoinColumnValue = Entity | number;\n\n/** Whether a join column points at a not-yet-inserted entity (enum ids are never \"new\"). */\nfunction isNewColumn(value: JoinColumnValue): boolean {\n return typeof value !== \"number\" && value.isNewEntity;\n}\n\n/** A small holder around m2m join rows, which we treat as psuedo-entities. */\nexport class JoinRows {\n // The in-memory rows for our m2m table.\n private readonly rows: JoinRow[] = [];\n private readonly index: ManyToManyIndex;\n\n constructor(\n // This could be either side of the m2m relation, depending on which is accessed first.\n // Regardless of which m2m side, we still have a single `JoinRows` instance in memory per m2m table.\n readonly m2m: ManyToManyLike,\n private rm: ReactionsManager,\n ) {\n this.index = new ManyToManyIndex(m2m);\n }\n\n /** Adds a new join row to this table. */\n addNew(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n if (!e1) throw new Error(`Cannot add a m2m row with an entity that is ${e1}`);\n if (!e2) throw new Error(`Cannot add a m2m row with an entity that is ${e2}`);\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n existing.deleted = false;\n existing.op = JoinRowOperation.Pending;\n } else {\n const row = {\n op: JoinRowOperation.Pending,\n id: undefined,\n persisted: false,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n this.#reactToChange(m2m, e1, e2);\n }\n\n /** Adds a new remove to this table. */\n addRemove(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n if (!existing.persisted) {\n // It was only added in-memory and never persisted, so just drop it\n remove(this.rows, existing);\n this.index.remove(existing);\n } else {\n existing.deleted = true;\n }\n existing.op = JoinRowOperation.Pending;\n } else {\n // We're removing against an unloaded collection, so assume the row exists in the database\n // (persisted: true) and queue a delete; the delete keys off the (col1, col2) composite.\n const row = {\n op: JoinRowOperation.Pending,\n id: undefined,\n persisted: true,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n deleted: true,\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n this.#reactToChange(m2m, e1, e2);\n }\n\n /** Return any \"old values\" for a m2m collection that might need reactivity checks. */\n removedFor(m2m: ManyToManyLike, e1: Entity): JoinColumnValue[] {\n const { otherColumnName } = m2m;\n // I.e. if we did `t1.books.remove(b1)` find all join rows that have\n // `tag_id=t1`, are marked for deletion, and then `.map` them to the removed book.\n const removedRows = this.index.getOthers(m2m.columnName, e1).filter((r) => r.deleted);\n return removedRows.map((r) => r.columns[otherColumnName]);\n }\n\n addedFor(m2m: ManyToManyLike, e1: Entity): JoinColumnValue[] {\n const { otherColumnName } = m2m;\n const addedRows = this.index\n .getOthers(m2m.columnName, e1)\n .filter(\n (r) =>\n ((!r.persisted && r.op === JoinRowOperation.Pending) || r.op === JoinRowOperation.Flushed) &&\n r.deleted !== true,\n );\n return addedRows.map((r) => r.columns[otherColumnName]);\n }\n\n /** Adds an existing join row to this table. */\n addPreloadedRow(m2m: ManyToManyLike, id: number | undefined, e1: Entity, e2: JoinColumnValue): void {\n const existing = this.index.get(m2m, e1, e2);\n if (existing) {\n // Treat any existing WIP change as source-of-truth, so leave it alone\n } else {\n const row = {\n op: JoinRowOperation.Pending,\n id,\n persisted: true,\n columns: { [m2m.columnName]: e1, [m2m.otherColumnName]: e2 },\n } satisfies JoinRow;\n this.rows.push(row);\n this.index.add(m2m, e1, e2, row);\n }\n }\n\n /** Look up/create our internal JoinRow psuedo-entities for the db rows. */\n async loadRows(tuples: [string, string][], dbRows: any[]): Promise<void> {\n const { em } = this.m2m.entity;\n const { columnName: column1, otherColumnName: column2, meta: meta1, otherMeta: meta2, otherEnum } = this.m2m;\n\n const oneIds: string[] = [];\n // Tagged ids for an entity other-side, or raw enum ids for an enum other-side.\n const twoVals: JoinColumnValue[] = [];\n for (const dbRow of dbRows) {\n oneIds.push(keyToTaggedId(meta1, dbRow[column1])!);\n twoVals.push(\n otherEnum ? (dbRow[column2] as number) : (em.getEntity(keyToTaggedId(meta2!, dbRow[column2])!) as any),\n );\n }\n\n // Make sure we have entities in memory for all the joined-to tables. The enum side has no\n // entities to load; the entity sides do (and `twoVals` is re-resolved to entities below).\n await Promise.all([\n em.loadAll(meta1.cstr, oneIds),\n otherEnum\n ? Promise.resolve([])\n : em.loadAll(\n meta2!.cstr,\n dbRows.map((dbRow) => keyToTaggedId(meta2!, dbRow[column2])!),\n ),\n ]);\n\n // If we're doing a em.refresh/reload, we need to watch for rows that are no longer here. For an\n // enum other-side, only persisted rows are delete-candidates (pending in-memory adds are kept,\n // since `EnumCollection` relies on `JoinRows` to hold them rather than re-asserting on load).\n const existingRows = new Set<JoinRow>();\n for (const [columnName, id] of tuples) {\n const others = this.index.getOthers(columnName, em.getEntity(id)!);\n for (const row of others) if (!otherEnum || row.persisted) existingRows.add(row);\n }\n\n let i = 0;\n for (const dbRow of dbRows) {\n const e1 = em.getEntity(oneIds[i])!;\n const e2 = otherEnum ? (dbRow[column2] as number) : em.getEntity(keyToTaggedId(meta2!, dbRow[column2])!)!;\n i++;\n let row = this.index.get(this.m2m, e1, e2);\n if (!row) {\n row = {\n op: JoinRowOperation.Completed,\n id: dbRow.id,\n persisted: true,\n columns: { [column1]: e1, [column2]: e2 },\n created_at: dbRow.created_at,\n };\n this.rows.push(row);\n this.index.add(this.m2m, e1, e2, row);\n } else {\n // If a placeholder row was created while a ManyToManyCollection was unloaded, and we find it during\n // a subsequent load/query, update its id to be what is in the database and mark it persisted.\n row.id = dbRow.id;\n row.persisted = true;\n // Mark this row as still valid\n existingRows.delete(row);\n }\n }\n\n // Mark all no-longer-there rows as deleted\n for (const row of existingRows) row.deleted = true;\n }\n\n getOthers(columnName: string, entity: Entity): JoinColumnValue[] {\n const others = this.index.getOthers(columnName, entity);\n if (others.length === 0) return [];\n const [c1, c2] = Object.keys(others[0].columns);\n // Self-referencing rows can contain the same entity in both columns, so identity cannot tell the sides apart.\n const c = c1 === columnName ? c2 : c1;\n return others.filter((o) => !o.deleted).map((row) => row.columns[c]);\n }\n\n /** Drops all in-memory rows where `entity` is on `columnName`, e.g. when it is being deleted. */\n removeAllFor(columnName: string, entity: Entity): void {\n for (const row of this.index.getOthers(columnName, entity)) {\n remove(this.rows, row);\n this.index.remove(row);\n }\n }\n\n /** Drops a single `(e1, e2)` row without queuing a flush, e.g. when mirroring another em's removal. */\n removePreloadedRow(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const row = this.index.get(m2m, e1, e2);\n if (row) {\n remove(this.rows, row);\n this.index.remove(row);\n }\n }\n\n /** Scans our `rows` for newly-added/newly-deleted rows that need `INSERT`s/`UPDATE`s. */\n toTodo(): JoinRowTodo | undefined {\n const newRows = this.rows.filter((r) => !r.persisted && r.deleted !== true && r.op === \"pending\");\n const deletedRows = this.rows.filter((r) => r.persisted && r.deleted === true && r.op === \"pending\");\n if (newRows.length === 0 && deletedRows.length === 0) {\n return undefined;\n }\n return {\n m2m: this.m2m,\n newRows,\n deletedRows,\n resetAfterFlushed: () => {\n for (const row of this.rows) {\n if (row.op === JoinRowOperation.Pending || row.op === JoinRowOperation.Flushed)\n row.op = JoinRowOperation.Completed;\n }\n },\n // The driver flushes pure (int, int) FK pairs; resolve them here so it never has to know\n // whether a column points at an entity (use its id) or an enum (its value is already the id).\n dbValue: (row, columnName) => this.#dbValue(row, columnName),\n isNew: (row, columnName) => isNewColumn(row.columns[columnName]),\n };\n }\n\n get hasChanges() {\n return this.rows.some(({ op }) => op === JoinRowOperation.Pending || op === JoinRowOperation.Flushed);\n }\n\n /** The db int value for `row`'s `columnName`: an entity's id, or (for enums) the enum's id itself. */\n #dbValue(row: JoinRow, columnName: string): number {\n const value = row.columns[columnName];\n if (typeof value === \"number\") return value;\n const meta = columnName === this.m2m.columnName ? this.m2m.meta : this.m2m.otherMeta!;\n return keyToNumber(meta, value.idTagged)!;\n }\n\n /**\n * Invalidates caches & queues reactivity for a join-row change.\n *\n * The owning entity (`e1`) always reacts; the \"other\" side only reacts when it is an entity,\n * since enum other-sides have no `em`/reverse-field to keep in sync.\n */\n #reactToChange(m2m: ManyToManyLike, e1: Entity, e2: JoinColumnValue): void {\n const { em } = this.m2m.entity;\n const api = getEmInternalApi(e1.em);\n api.isLoadedCache.resetIsLoaded(e1, m2m.fieldName);\n this.rm.queueDownstreamReactables(e1, m2m.fieldName);\n if (getBaseAndSelfMetas(e1).some((meta) => meta.config.__data.touchOnChange.has(m2m.fieldName))) {\n em.touch(e1);\n }\n if (!m2m.otherEnum) {\n const other = e2 as Entity;\n const otherFieldName = m2m.otherFieldName!;\n api.isLoadedCache.resetIsLoaded(other, otherFieldName);\n this.rm.queueDownstreamReactables(other, otherFieldName);\n if (getBaseAndSelfMetas(other).some((meta) => meta.config.__data.touchOnChange.has(otherFieldName))) {\n em.touch(other);\n }\n }\n }\n}\n\n/**\n * A \"psuedo-entity\" for a join row.\n *\n * We treat this as a special entity, i.e. it has two \"relations\" to each entity for the current\n * row, an optional surrogate `id` primary key, and an optional `created_at` column.\n *\n * These rows are immutable, i.e. once created we don't change either FK, and instead make\n * collection changes only by inserting new rows and deleting old rows.\n *\n * This makes the column1+column2 combination a composite key. For id-less join tables, that\n * composite is the actual primary key and `id` is always undefined.\n */\nexport interface JoinRow {\n /**\n * Whether our relation has been processed or not.\n *\n * - `pending` means we've not flushed it to the Database\n * - `flushed` means we've flushed but `em.flush` hasn't fully completed yet, likely due to AsyncReactiveField calcs\n * - `completed` means we've been flushed and `em.flush` has completed\n */\n op: JoinRowOperation;\n /** The surrogate key for id-ful join tables; always undefined for id-less tables. */\n id: number | undefined;\n /**\n * Whether this row exists (or is assumed to exist) in the database.\n *\n * This is orthogonal to `op` (the flush lifecycle) and is what distinguishes a pending insert\n * from a pending delete: a `pending` row that is `!persisted` is a pending INSERT (added in\n * memory, not yet in the db), while a `pending` row that is `persisted` is a pending DELETE\n * (in the db, marked `deleted`). `op` alone cannot tell these apart, because both inserts and\n * deletes walk the same `pending -> flushed -> completed` progression.\n *\n * We track this as its own flag rather than inferring it from `id` being set/unset, because\n * id-less join tables (whose PK is just the composite of the two FKs) never have an `id` — so\n * `id === undefined` would be ambiguous. `persisted` is the id-agnostic generalization of the\n * `id`-is-set check that id-ful tables historically relied on.\n *\n * It must survive add/remove/re-add sequences: e.g. loading a row (persisted), removing it\n * (pending delete), then re-adding it (`deleted` flipped back to false, `op` back to `pending`)\n * leaves a `pending && !deleted` row that looks identical to a fresh insert — but it is still in\n * the db, so a subsequent remove must issue a DELETE, which only `persisted` can tell us.\n */\n persisted: boolean;\n /** Maps each FK column to its value: an `Entity`, or (for `EnumCollection`s) an enum's numeric id. */\n columns: Record<string, JoinColumnValue>;\n created_at?: Date;\n deleted?: boolean;\n}\n\n/** An enum to track our insert/delete state progression. */\nexport enum JoinRowOperation {\n Pending = \"pending\",\n Flushed = \"flushed\",\n Completed = \"completed\",\n}\n\n/** Keep an in-memory index to avoid sequentially scanning `rows`. */\nclass ManyToManyIndex {\n private indexes: Record<string, Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>> = {};\n\n constructor(private readonly m2m: ManyToManyLike) {\n this.indexes[m2m.columnName] = new Map();\n this.indexes[m2m.otherColumnName] = new Map();\n }\n\n add(m2m: ManyToManyLike, e1: JoinColumnValue, e2: JoinColumnValue, value: JoinRow): void {\n // Store both e1+e2 => value and e2+e1 => value so we can do lookups from either side\n this.#doAdd(this.indexes[m2m.columnName], e1, e2, value);\n this.#doAdd(this.indexes[m2m.otherColumnName], e2, e1, value);\n }\n\n remove(value: JoinRow): void {\n const [[column1, e1], [column2, e2]] = Object.entries(value.columns);\n this.#doRemove(this.indexes[column1], e1, e2);\n this.#doRemove(this.indexes[column2], e2, e1);\n }\n\n get(m2m: ManyToManyLike, e1: JoinColumnValue, e2: JoinColumnValue): JoinRow | undefined {\n return this.indexes[m2m.columnName].get(e1)?.get(e2);\n }\n\n /** Cheat and use the index to return \"the other entities\" for `entity`. */\n getOthers(columnName: string, entity: JoinColumnValue): JoinRow[] {\n // It's empty m2m collection won't have any other entities, and so no index entries\n const map = this.indexes[columnName].get(entity);\n if (!map) return [];\n // Sort for a stable order regardless of how many batches contributed rows — the underlying\n // Map preserves insertion order, which depends on DataLoader timing and is non-deterministic\n // across processes. New rows (no key yet) sort last.\n const rows = Array.from(map.values());\n if (this.m2m.hasJoinTableId) {\n // Sort by join-row id.\n return rows.sort((a, b) => (a.id ?? Infinity) - (b.id ?? Infinity));\n }\n // Id-less tables have no surrogate id, so sort by the other side's id.\n const otherColumn = columnName === this.m2m.columnName ? this.m2m.otherColumnName : this.m2m.columnName;\n if (this.m2m.otherEnum && otherColumn === this.m2m.otherColumnName) {\n // The other side is an enum, so its column value is already its numeric id.\n return rows.sort((a, b) => (a.columns[otherColumn] as number) - (b.columns[otherColumn] as number));\n }\n const otherMeta = columnName === this.m2m.columnName ? this.m2m.otherMeta! : this.m2m.meta;\n const key = (r: JoinRow) => {\n const other = r.columns[otherColumn] as Entity;\n return other.isNewEntity ? Infinity : keyToNumber(otherMeta, other.id)!;\n };\n return rows.sort((a, b) => key(a) - key(b));\n }\n\n #doAdd(\n index: Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>,\n e1: JoinColumnValue,\n e2: JoinColumnValue,\n value: JoinRow,\n ): void {\n const map = index.get(e1) ?? new Map();\n if (map.size === 0) index.set(e1, map);\n map.set(e2, value);\n }\n\n #doRemove(\n index: Map<JoinColumnValue, Map<JoinColumnValue, JoinRow>>,\n e1: JoinColumnValue,\n e2: JoinColumnValue,\n ): void {\n index.get(e1)?.delete(e2);\n }\n}\n"],"mappings":";;;;;;AAyCA,SAAS,YAAY,OAAiC;CACpD,OAAO,OAAO,UAAU,YAAY,MAAM;AAC5C;;AAGA,IAAa,WAAb,MAAsB;CAQT;CACD;CAPV,OAAmC,CAAC;CACpC;CAEA,YAGE,KACA,IACA;EAFS,KAAA,MAAA;EACD,KAAA,KAAA;EAER,KAAK,QAAQ,IAAI,gBAAgB,GAAG;CACtC;;CAGA,OAAO,KAAqB,IAAY,IAA2B;EACjE,IAAI,CAAC,IAAI,MAAM,IAAI,MAAM,+CAA+C,IAAI;EAC5E,IAAI,CAAC,IAAI,MAAM,IAAI,MAA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,GAAG,OAAO,EAAE,MAAM,aAAa,EAAE,MAAM,SAAS;EAGpE,MAAM,cAAc,eAAe,KAAK,IAAI,aAAa,KAAK,IAAI,kBAAkB,KAAK,IAAI;EAC7F,IAAI,KAAK,IAAI,aAAa,gBAAgB,KAAK,IAAI,iBAEjD,OAAO,KAAK,MAAM,GAAG,MAAO,EAAE,QAAQ,eAA2B,EAAE,QAAQ,YAAuB;EAEpG,MAAM,YAAY,eAAe,KAAK,IAAI,aAAa,KAAK,IAAI,YAAa,KAAK,IAAI;EACtF,MAAM,OAAO,MAAe;GAC1B,MAAM,QAAQ,EAAE,QAAQ;GACxB,OAAO,MAAM,cAAc,WAAW,YAAY,WAAW,MAAM,EAAE;EACvE;EACA,OAAO,KAAK,MAAM,GAAG,MAAM,IAAI,CAAC,IAAI,IAAI,CAAC,CAAC;CAC5C;CAEA,OACE,OACA,IACA,IACA,OACM;EACN,MAAM,MAAM,MAAM,IAAI,EAAE,qBAAK,IAAI,IAAI;EACrC,IAAI,IAAI,SAAS,GAAG,MAAM,IAAI,IAAI,GAAG;EACrC,IAAI,IAAI,IAAI,KAAK;CACnB;CAEA,UACE,OACA,IACA,IACM;EACN,MAAM,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE;CAC1B;AACF"}
@@ -107,6 +107,10 @@ var ReactiveManyToManyImpl = class extends require_relations_AbstractRelationImp
107
107
  get get() {
108
108
  return this.#doGet({ withDeleted: false });
109
109
  }
110
+ /** Returns the stored membership without deriving or queuing join-row changes. */
111
+ current() {
112
+ return this.#loaded ?? require_EntityManager.getEmInternalApi(this.entity.em).joinRows(this).getOthers(this.columnName, this.entity);
113
+ }
110
114
  set() {
111
115
  require_utils.fail(`Cannot set ${this.entity}.${this.fieldName} ReactiveManyToMany directly.`);
112
116
  }
@@ -158,7 +162,20 @@ var ReactiveManyToManyImpl = class extends require_relations_AbstractRelationImp
158
162
  get isPreloaded() {
159
163
  return false;
160
164
  }
161
- preload() {}
165
+ /** Installs materialized membership without deriving, e.g. when RunPlugin mirrors a flush. */
166
+ preload() {
167
+ if (this.entity.isNewEntity) return;
168
+ const api = require_EntityManager.getEmInternalApi(this.entity.em);
169
+ const preloaded = api.getPreloadedRelation(this.entity.idTagged, this.fieldName);
170
+ if (preloaded) {
171
+ this.#loaded = preloaded;
172
+ this.#loadedMode = "ref";
173
+ this.#isJoinTableLoaded = true;
174
+ this.#isLoaded = true;
175
+ this.#isCached = false;
176
+ api.isLoadedCache.add(this);
177
+ }
178
+ }
162
179
  import(other, _, mapEntities) {
163
180
  this.#loaded = mapEntities(other.#loaded);
164
181
  this.#isJoinTableLoaded = this.entity.isNewEntity;
@@ -1 +1 @@
1
- {"version":3,"file":"ReactiveManyToMany.cjs","names":["lazyField","getMetadata","AbstractRelationImpl","getInstanceData","getEmInternalApi","isLoaded","convertToLoadHint","getMetadataForField","isCascadeDelete","manyToManyBatchLoader","RelationT","RelationU"],"sources":["../../src/relations/ReactiveManyToMany.ts"],"sourcesContent":["import { manyToManyBatchLoader } from \"src/batchloaders/manyToManyBatchLoader.ts\";\nimport {\n type Entity,\n type EntityMetadata,\n type ManyToManyField,\n type ReadOnlyCollection,\n ensureNotDeleted,\n fail,\n getEmInternalApi,\n getInstanceData,\n getMetadata,\n getMetadataForField,\n isLoaded,\n} from \"src/index.ts\";\nimport type { IsLoadedCachable } from \"src/loading/IsLoadedCache.ts\";\nimport { lazyField } from \"src/newEntity.ts\";\nimport {\n type MaybeReactedEntity,\n type Reacted,\n type ReactiveHint,\n convertToLoadHint,\n} from \"src/reactivity/reactiveHints.ts\";\nimport { AbstractRelationImpl } from \"src/relations/AbstractRelationImpl.ts\";\nimport { isCascadeDelete } from \"src/relations/isCascadeDelete.ts\";\nimport { RelationT, RelationU } from \"src/relations/RelationSymbols.ts\";\n\n/**\n * A reactive, derived many-to-many collection.\n *\n * Similar to `ReactiveReference` but for collections--membership is calculated from a reactive\n * function and persisted to the underlying join table.\n */\nexport interface ReactiveManyToMany<T extends Entity, U extends Entity> extends ReadOnlyCollection<T, U> {\n load(opts?: { withDeleted?: boolean; forceReload?: boolean }): Promise<readonly U[]>;\n}\n\n/** Creates a `ReactiveManyToMany`. */\nexport function hasReactiveManyToMany<T extends Entity, U extends Entity, const H extends ReactiveHint<T>>(\n hint: H,\n fn: (entity: Reacted<T, H>) => readonly MaybeReactedEntity<U>[],\n): ReactiveManyToMany<T, U> {\n return lazyField((entity: T, fieldName) => {\n const m2m = getMetadata(entity).allFields[fieldName] as ManyToManyField;\n return new ReactiveManyToManyImpl<T, U, H>(entity, m2m, hint, fn);\n });\n}\n\n/** Implements ReactiveManyToMany, initially a copy/paste of ReactiveReference but for m2m. */\nexport class ReactiveManyToManyImpl<T extends Entity, U extends Entity, H extends ReactiveHint<T>>\n extends AbstractRelationImpl<T, U[]>\n implements ReactiveManyToMany<T, U>, IsLoadedCachable\n{\n readonly #field: ManyToManyField;\n\n // Could be either the ref-loaded stored array, or full-loaded calculated array\n #loaded: U[] | undefined;\n // Recalculation needs the old membership even when the derivation hint is already loaded.\n #isJoinTableLoaded: boolean;\n // In ref-mode, we use our materialized FK value (which might be undefined)\n // If full-mode, we calculate the FK value from the subgraph\n #loadedMode: \"ref\" | \"full\" | undefined = undefined;\n // #isLoaded doesn't necessary care if we're ref-mode or full-mode, it's just\n // whether a caller can call `.get` and not have it blow up.\n #isLoaded: boolean | undefined = undefined;\n #isCached: boolean = false;\n #loadPromise: Promise<ReadonlyArray<U>> | undefined;\n\n constructor(\n entity: T,\n field: ManyToManyField,\n public reactiveHint: H,\n private fn: (entity: Reacted<T, H>) => readonly MaybeReactedEntity<U>[],\n ) {\n super(entity);\n this.#field = field;\n this.#isJoinTableLoaded = getInstanceData(entity).isOrWasNew;\n (getInstanceData(entity).relations ??= {})[this.fieldName] = this;\n }\n\n async load(opts?: { withDeleted?: boolean; forceReload?: boolean }): Promise<ReadonlyArray<U>> {\n ensureNotDeleted(this.entity, \"pending\");\n const { loadHint } = this;\n\n if (!this.isLoaded || opts?.forceReload) {\n const { em } = this.entity;\n const maybeDirty = opts?.forceReload || getEmInternalApi(em).rm.isMaybePendingRecalc(this.entity, this.fieldName);\n\n if (maybeDirty) {\n this.#isCached = false;\n return (this.#loadPromise ??= Promise.all([\n em.populate(this.entity, { hint: loadHint, ...opts }),\n !this.#isJoinTableLoaded || opts?.forceReload ? this.#loadFromJoinTable() : undefined,\n ]).then(() => {\n this.#loadPromise = undefined;\n this.#loadedMode = \"full\";\n this.#isLoaded = true;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n return this.#doGet(opts);\n }));\n } else {\n // Load from join table (existing materialized state)\n return (this.#loadPromise ??= this.#loadFromJoinTable().then((loaded) => {\n this.#loadPromise = undefined;\n this.#loadedMode = \"ref\";\n this.#isLoaded = true;\n this.#loaded = loaded;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n return this.#filterDeleted(loaded, opts);\n }));\n }\n }\n return this.#doGet(opts);\n }\n\n get isLoaded(): boolean {\n if (this.#isLoaded !== undefined) return this.#isLoaded;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n // If a WIP mutation has marked our field as potentially dirty, we need to be \"full\" loaded\n const maybeDirty = getEmInternalApi(this.entity.em).rm.isMaybePendingRecalc(this.entity, this.fieldName);\n if (maybeDirty) {\n // ReactiveReferences can mark themselves isLoaded when merely their\n // loadHint is loaded, but for ReactiveManyToMany we need to also have\n // our old join rows loaded, to tell who needs to be removed\n this.#loadedMode = \"full\";\n this.#isLoaded = this.#isJoinTableLoaded && isLoaded(this.entity, this.loadHint);\n this.#isCached = false;\n } else {\n // If we've had `.load` called before, assume we're still loaded\n this.#isLoaded = !!this.#loadedMode;\n }\n return this.#isLoaded;\n }\n\n resetIsLoaded(): void {\n this.#isLoaded = undefined;\n this.#isCached = false;\n }\n\n #doGet(opts?: { withDeleted?: boolean }): U[] {\n const { fn } = this;\n ensureNotDeleted(this.entity, \"pending\");\n // Fast pass if we've already calculated this (cache invalidation will happen on\n // any mutation via #resetIsLoaded)..\n if (this.#isCached) {\n return this.#filterDeleted(this.#loaded ?? [], opts) as U[];\n }\n // Call isLoaded to probe the load hint, and get `#isLoaded` set, but still have\n // our `if` check the raw `#isLoaded` to know if we should eval-latest or return `loaded`.\n if (this.isLoaded && this.#loadedMode === \"full\") {\n const newValue = fn(this.entity as any) as unknown as U[];\n // Preserve deleted entities that were in the previous loaded value\n const previousDeleted = (this.#loaded ?? []).filter((e) => e.isDeletedEntity);\n for (const entity of previousDeleted) {\n if (!newValue.includes(entity)) newValue.push(entity);\n }\n if (!getEmInternalApi(this.entity.em).isValidating) {\n this.#syncJoinTableRows(newValue);\n }\n this.#loaded = newValue;\n this.#isCached = true;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n } else if (!!this.#loadedMode) {\n // We're either loadedMode=ref, or loadedMode=full (but not actually fully loaded),\n // but in theory loadedMode only gets set in `.load()`, so we should have #loaded\n // set to some value, even if it's not fully up-to-date.\n this.#isCached = true;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n } else {\n const noun = this.entity.isNewEntity ? \"derived\" : \"loaded\";\n throw new Error(`${this.entity}.${this.fieldName} has not been ${noun} yet`);\n }\n return this.#filterDeleted(this.#loaded ?? [], opts) as U[];\n }\n\n get getWithDeleted(): U[] {\n return this.#doGet({ withDeleted: true });\n }\n\n get get(): U[] {\n return this.#doGet({ withDeleted: false });\n }\n\n set(): void {\n fail(`Cannot set ${this.entity}.${this.fieldName} ReactiveManyToMany directly.`);\n }\n\n get loadHint(): any {\n const meta = getMetadata(this.entity);\n return (meta.config.__data.cachedReactiveLoadHints[this.fieldName] ??= convertToLoadHint(meta, this.reactiveHint));\n }\n\n setFromOpts(_others: U[]): void {\n throw new Error(`ReactiveManyToMany ${this.entity}.${this.fieldName} cannot be set via opts`);\n }\n\n maybeCascadeDelete(): void {\n if (this.#isCascadeDelete) {\n const jr = getEmInternalApi(this.entity.em).joinRows(this);\n (jr.getOthers(this.columnName, this.entity) as U[]).forEach((e) => this.entity.em.delete(e));\n }\n }\n\n async cleanupOnEntityDeleted(): Promise<void> {\n // Required relations may already be detached, so remove stored/pending rows without deriving.\n if (!this.#isJoinTableLoaded) await this.#loadFromJoinTable();\n const jr = getEmInternalApi(this.entity.em).joinRows(this);\n const existing = jr.getOthers(this.columnName, this.entity) as U[];\n for (const entity of existing) jr.addRemove(this, this.entity, entity);\n this.#loaded = [];\n this.#isLoaded = false;\n }\n\n // Properties needed for JoinRows/ManyToManyCollection compatibility\n get meta(): EntityMetadata {\n return getMetadataForField(getMetadata(this.entity), this.fieldName);\n }\n\n get fieldName(): string {\n return this.#field.fieldName;\n }\n\n get otherMeta(): EntityMetadata {\n return this.#field.otherMetadata();\n }\n\n get joinTableName(): string {\n return this.#field.joinTableName;\n }\n\n get columnName(): string {\n return this.#field.columnNames[0];\n }\n\n get otherColumnName(): string {\n return this.#field.columnNames[1];\n }\n\n get hasJoinTableId(): boolean {\n return this.#field.hasJoinTableId;\n }\n\n get otherFieldName(): string {\n return this.#field.otherFieldName;\n }\n\n get hasBeenSet(): boolean {\n return true;\n }\n\n get isPreloaded(): boolean {\n return false;\n }\n\n preload(): void {\n // No-op for now - could implement if needed\n }\n\n import(\n other: ReactiveManyToManyImpl<T, U, H>,\n _: unknown,\n mapEntities: (e: U[] | undefined) => U[] | undefined,\n ): void {\n this.#loaded = mapEntities(other.#loaded);\n // A fork copies members, not JoinRows; treat the snapshot as ref-mode until its own rows are loaded.\n this.#isJoinTableLoaded = this.entity.isNewEntity;\n this.#loadedMode = other.#loadedMode ? \"ref\" : undefined;\n this.#isLoaded = undefined;\n // Don't set `#isCached b/c we're not registering ourselves with `isLoadedCache` yet; let\n // the first caller to `#doGet` do that if needed.\n }\n\n public toString(): string {\n return `ReactiveManyToMany(entity: ${this.entity}, fieldName: ${this.fieldName}, otherMeta: ${this.otherMeta.type})`;\n }\n\n get #isCascadeDelete(): boolean {\n return isCascadeDelete(this, this.#field.fieldName);\n }\n\n /** Loads the previous membership so recalculation and deletion can remove its join rows. */\n async #loadFromJoinTable(): Promise<U[]> {\n const { em } = this.entity;\n if (!this.entity.isNewEntity) {\n const key = `${this.columnName}=${this.entity.id}`;\n // Use the existing m2m loader by creating a compatible collection-like object\n await manyToManyBatchLoader(em, this).load(key);\n }\n this.#isJoinTableLoaded = true;\n return getEmInternalApi(em).joinRows(this).getOthers(this.columnName, this.entity) as U[];\n }\n\n // This is like calling `setField` but for a m2m relation...\n #syncJoinTableRows(newValue: U[]): void {\n const jr = getEmInternalApi(this.entity.em).joinRows(this);\n const newSet = new Set(newValue);\n const oldSet = new Set(jr.getOthers(this.columnName, this.entity) as U[]);\n // Find entities to add (in new but not in old)\n for (const entity of newValue) {\n if (!oldSet.has(entity)) {\n jr.addNew(this, this.entity, entity);\n }\n }\n // Find entities to remove (in old but not in new)\n for (const entity of oldSet) {\n if (!newSet.has(entity)) {\n jr.addRemove(this, this.entity, entity);\n }\n }\n }\n\n #filterDeleted(entities: U[], opts?: { withDeleted?: boolean }): U[] {\n return opts?.withDeleted === true\n ? [...entities]\n : entities.filter((e) => !e.isDeletedEntity && !(e as any).isSoftDeletedEntity);\n }\n\n [RelationT]: T = null!;\n [RelationU]: U = null!;\n}\n\n/** Type guard utility for determining if an entity field is a ReactiveManyToMany. */\nexport function isReactiveManyToMany(\n maybeReactiveManyToMany: any,\n): maybeReactiveManyToMany is ReactiveManyToMany<any, any> {\n return maybeReactiveManyToMany instanceof ReactiveManyToManyImpl;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAqCA,SAAgB,sBACd,MACA,IAC0B;CAC1B,OAAOA,kBAAAA,WAAW,QAAW,cAAc;EACzC,MAAM,MAAMC,uBAAAA,YAAY,MAAM,CAAC,CAAC,UAAU;EAC1C,OAAO,IAAI,uBAAgC,QAAQ,KAAK,MAAM,EAAE;CAClE,CAAC;AACH;;AAGA,IAAa,yBAAb,cACUC,uCAAAA,qBAEV;CAmBW;CACC;CAnBV;CAGA;CAEA;CAGA,cAA0C,KAAA;CAG1C,YAAiC,KAAA;CAC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A,mBAAmB,UAAqB;EACtC,MAAM,KAAKA,sBAAAA,iBAAiB,KAAK,OAAO,EAAE,CAAC,CAAC,SAAS,IAAI;EACzD,MAAM,SAAS,IAAI,IAAI,QAAQ;EAC/B,MAAM,SAAS,IAAI,IAAI,GAAG,UAAU,KAAK,YAAY,KAAK,MAAM,CAAQ;EAExE,KAAK,MAAM,UAAU,UACnB,IAAI,CAAC,OAAO,IAAI,MAAM,GACpB,GAAG,OAAO,MAAM,KAAK,QAAQ,MAAM;EAIvC,KAAK,MAAM,UAAU,QACnB,IAAI,CAAC,OAAO,IAAI,MAAM,GACpB,GAAG,UAAU,MAAM,KAAK,QAAQ,MAAM;CAG5C;CAEA,eAAe,UAAe,MAAuC;EACnE,OAAO,MAAM,gBAAgB,OACzB,CAAC,GAAG,QAAQ,IACZ,SAAS,QAAQ,MAAM,CAAC,EAAE,mBAAmB,CAAE,EAAU,mBAAmB;CAClF;CAEA,CAACM,kCAAAA,aAAgB;CACjB,CAACC,kCAAAA,aAAgB;AACnB;;AAGA,SAAgB,qBACd,yBACyD;CACzD,OAAO,mCAAmC;AAC5C"}
1
+ {"version":3,"file":"ReactiveManyToMany.cjs","names":["lazyField","getMetadata","AbstractRelationImpl","getInstanceData","getEmInternalApi","isLoaded","convertToLoadHint","getMetadataForField","isCascadeDelete","manyToManyBatchLoader","RelationT","RelationU"],"sources":["../../src/relations/ReactiveManyToMany.ts"],"sourcesContent":["import { manyToManyBatchLoader } from \"src/batchloaders/manyToManyBatchLoader.ts\";\nimport {\n type Entity,\n type EntityMetadata,\n type ManyToManyField,\n type ReadOnlyCollection,\n ensureNotDeleted,\n fail,\n getEmInternalApi,\n getInstanceData,\n getMetadata,\n getMetadataForField,\n isLoaded,\n} from \"src/index.ts\";\nimport type { IsLoadedCachable } from \"src/loading/IsLoadedCache.ts\";\nimport { lazyField } from \"src/newEntity.ts\";\nimport {\n type MaybeReactedEntity,\n type Reacted,\n type ReactiveHint,\n convertToLoadHint,\n} from \"src/reactivity/reactiveHints.ts\";\nimport { AbstractRelationImpl } from \"src/relations/AbstractRelationImpl.ts\";\nimport { isCascadeDelete } from \"src/relations/isCascadeDelete.ts\";\nimport { RelationT, RelationU } from \"src/relations/RelationSymbols.ts\";\n\n/**\n * A reactive, derived many-to-many collection.\n *\n * Similar to `ReactiveReference` but for collections--membership is calculated from a reactive\n * function and persisted to the underlying join table.\n */\nexport interface ReactiveManyToMany<T extends Entity, U extends Entity> extends ReadOnlyCollection<T, U> {\n load(opts?: { withDeleted?: boolean; forceReload?: boolean }): Promise<readonly U[]>;\n}\n\n/** Creates a `ReactiveManyToMany`. */\nexport function hasReactiveManyToMany<T extends Entity, U extends Entity, const H extends ReactiveHint<T>>(\n hint: H,\n fn: (entity: Reacted<T, H>) => readonly MaybeReactedEntity<U>[],\n): ReactiveManyToMany<T, U> {\n return lazyField((entity: T, fieldName) => {\n const m2m = getMetadata(entity).allFields[fieldName] as ManyToManyField;\n return new ReactiveManyToManyImpl<T, U, H>(entity, m2m, hint, fn);\n });\n}\n\n/** Implements ReactiveManyToMany, initially a copy/paste of ReactiveReference but for m2m. */\nexport class ReactiveManyToManyImpl<T extends Entity, U extends Entity, H extends ReactiveHint<T>>\n extends AbstractRelationImpl<T, U[]>\n implements ReactiveManyToMany<T, U>, IsLoadedCachable\n{\n readonly #field: ManyToManyField;\n\n // Could be either the ref-loaded stored array, or full-loaded calculated array\n #loaded: U[] | undefined;\n // Recalculation needs the old membership even when the derivation hint is already loaded.\n #isJoinTableLoaded: boolean;\n // In ref-mode, we use our materialized FK value (which might be undefined)\n // If full-mode, we calculate the FK value from the subgraph\n #loadedMode: \"ref\" | \"full\" | undefined = undefined;\n // #isLoaded doesn't necessary care if we're ref-mode or full-mode, it's just\n // whether a caller can call `.get` and not have it blow up.\n #isLoaded: boolean | undefined = undefined;\n #isCached: boolean = false;\n #loadPromise: Promise<ReadonlyArray<U>> | undefined;\n\n constructor(\n entity: T,\n field: ManyToManyField,\n public reactiveHint: H,\n private fn: (entity: Reacted<T, H>) => readonly MaybeReactedEntity<U>[],\n ) {\n super(entity);\n this.#field = field;\n this.#isJoinTableLoaded = getInstanceData(entity).isOrWasNew;\n (getInstanceData(entity).relations ??= {})[this.fieldName] = this;\n }\n\n async load(opts?: { withDeleted?: boolean; forceReload?: boolean }): Promise<ReadonlyArray<U>> {\n ensureNotDeleted(this.entity, \"pending\");\n const { loadHint } = this;\n\n if (!this.isLoaded || opts?.forceReload) {\n const { em } = this.entity;\n const maybeDirty = opts?.forceReload || getEmInternalApi(em).rm.isMaybePendingRecalc(this.entity, this.fieldName);\n\n if (maybeDirty) {\n this.#isCached = false;\n return (this.#loadPromise ??= Promise.all([\n em.populate(this.entity, { hint: loadHint, ...opts }),\n !this.#isJoinTableLoaded || opts?.forceReload ? this.#loadFromJoinTable() : undefined,\n ]).then(() => {\n this.#loadPromise = undefined;\n this.#loadedMode = \"full\";\n this.#isLoaded = true;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n return this.#doGet(opts);\n }));\n } else {\n // Load from join table (existing materialized state)\n return (this.#loadPromise ??= this.#loadFromJoinTable().then((loaded) => {\n this.#loadPromise = undefined;\n this.#loadedMode = \"ref\";\n this.#isLoaded = true;\n this.#loaded = loaded;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n return this.#filterDeleted(loaded, opts);\n }));\n }\n }\n return this.#doGet(opts);\n }\n\n get isLoaded(): boolean {\n if (this.#isLoaded !== undefined) return this.#isLoaded;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n // If a WIP mutation has marked our field as potentially dirty, we need to be \"full\" loaded\n const maybeDirty = getEmInternalApi(this.entity.em).rm.isMaybePendingRecalc(this.entity, this.fieldName);\n if (maybeDirty) {\n // ReactiveReferences can mark themselves isLoaded when merely their\n // loadHint is loaded, but for ReactiveManyToMany we need to also have\n // our old join rows loaded, to tell who needs to be removed\n this.#loadedMode = \"full\";\n this.#isLoaded = this.#isJoinTableLoaded && isLoaded(this.entity, this.loadHint);\n this.#isCached = false;\n } else {\n // If we've had `.load` called before, assume we're still loaded\n this.#isLoaded = !!this.#loadedMode;\n }\n return this.#isLoaded;\n }\n\n resetIsLoaded(): void {\n this.#isLoaded = undefined;\n this.#isCached = false;\n }\n\n #doGet(opts?: { withDeleted?: boolean }): U[] {\n const { fn } = this;\n ensureNotDeleted(this.entity, \"pending\");\n // Fast pass if we've already calculated this (cache invalidation will happen on\n // any mutation via #resetIsLoaded)..\n if (this.#isCached) {\n return this.#filterDeleted(this.#loaded ?? [], opts) as U[];\n }\n // Call isLoaded to probe the load hint, and get `#isLoaded` set, but still have\n // our `if` check the raw `#isLoaded` to know if we should eval-latest or return `loaded`.\n if (this.isLoaded && this.#loadedMode === \"full\") {\n const newValue = fn(this.entity as any) as unknown as U[];\n // Preserve deleted entities that were in the previous loaded value\n const previousDeleted = (this.#loaded ?? []).filter((e) => e.isDeletedEntity);\n for (const entity of previousDeleted) {\n if (!newValue.includes(entity)) newValue.push(entity);\n }\n if (!getEmInternalApi(this.entity.em).isValidating) {\n this.#syncJoinTableRows(newValue);\n }\n this.#loaded = newValue;\n this.#isCached = true;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n } else if (!!this.#loadedMode) {\n // We're either loadedMode=ref, or loadedMode=full (but not actually fully loaded),\n // but in theory loadedMode only gets set in `.load()`, so we should have #loaded\n // set to some value, even if it's not fully up-to-date.\n this.#isCached = true;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n } else {\n const noun = this.entity.isNewEntity ? \"derived\" : \"loaded\";\n throw new Error(`${this.entity}.${this.fieldName} has not been ${noun} yet`);\n }\n return this.#filterDeleted(this.#loaded ?? [], opts) as U[];\n }\n\n get getWithDeleted(): U[] {\n return this.#doGet({ withDeleted: true });\n }\n\n get get(): U[] {\n return this.#doGet({ withDeleted: false });\n }\n\n /** Returns the stored membership without deriving or queuing join-row changes. */\n current(): readonly U[] {\n return (\n this.#loaded ?? (getEmInternalApi(this.entity.em).joinRows(this).getOthers(this.columnName, this.entity) as U[])\n );\n }\n\n set(): void {\n fail(`Cannot set ${this.entity}.${this.fieldName} ReactiveManyToMany directly.`);\n }\n\n get loadHint(): any {\n const meta = getMetadata(this.entity);\n return (meta.config.__data.cachedReactiveLoadHints[this.fieldName] ??= convertToLoadHint(meta, this.reactiveHint));\n }\n\n setFromOpts(_others: U[]): void {\n throw new Error(`ReactiveManyToMany ${this.entity}.${this.fieldName} cannot be set via opts`);\n }\n\n maybeCascadeDelete(): void {\n if (this.#isCascadeDelete) {\n const jr = getEmInternalApi(this.entity.em).joinRows(this);\n (jr.getOthers(this.columnName, this.entity) as U[]).forEach((e) => this.entity.em.delete(e));\n }\n }\n\n async cleanupOnEntityDeleted(): Promise<void> {\n // Required relations may already be detached, so remove stored/pending rows without deriving.\n if (!this.#isJoinTableLoaded) await this.#loadFromJoinTable();\n const jr = getEmInternalApi(this.entity.em).joinRows(this);\n const existing = jr.getOthers(this.columnName, this.entity) as U[];\n for (const entity of existing) jr.addRemove(this, this.entity, entity);\n this.#loaded = [];\n this.#isLoaded = false;\n }\n\n // Properties needed for JoinRows/ManyToManyCollection compatibility\n get meta(): EntityMetadata {\n return getMetadataForField(getMetadata(this.entity), this.fieldName);\n }\n\n get fieldName(): string {\n return this.#field.fieldName;\n }\n\n get otherMeta(): EntityMetadata {\n return this.#field.otherMetadata();\n }\n\n get joinTableName(): string {\n return this.#field.joinTableName;\n }\n\n get columnName(): string {\n return this.#field.columnNames[0];\n }\n\n get otherColumnName(): string {\n return this.#field.columnNames[1];\n }\n\n get hasJoinTableId(): boolean {\n return this.#field.hasJoinTableId;\n }\n\n get otherFieldName(): string {\n return this.#field.otherFieldName;\n }\n\n get hasBeenSet(): boolean {\n return true;\n }\n\n get isPreloaded(): boolean {\n // isPreloaded lets populate skip load(), but stored rows alone cannot satisfy a pending derivation.\n // Keep that shortcut disabled. RunPlugin calls preload() explicitly with already-derived membership.\n return false;\n }\n\n /** Installs materialized membership without deriving, e.g. when RunPlugin mirrors a flush. */\n preload(): void {\n if (this.entity.isNewEntity) return;\n const api = getEmInternalApi(this.entity.em);\n const preloaded = api.getPreloadedRelation<U>(this.entity.idTagged, this.fieldName);\n if (preloaded) {\n this.#loaded = preloaded;\n this.#loadedMode = \"ref\";\n this.#isJoinTableLoaded = true;\n this.#isLoaded = true;\n this.#isCached = false;\n api.isLoadedCache.add(this);\n }\n }\n\n import(\n other: ReactiveManyToManyImpl<T, U, H>,\n _: unknown,\n mapEntities: (e: U[] | undefined) => U[] | undefined,\n ): void {\n this.#loaded = mapEntities(other.#loaded);\n // A fork copies members, not JoinRows; treat the snapshot as ref-mode until its own rows are loaded.\n this.#isJoinTableLoaded = this.entity.isNewEntity;\n this.#loadedMode = other.#loadedMode ? \"ref\" : undefined;\n this.#isLoaded = undefined;\n // Don't set `#isCached b/c we're not registering ourselves with `isLoadedCache` yet; let\n // the first caller to `#doGet` do that if needed.\n }\n\n public toString(): string {\n return `ReactiveManyToMany(entity: ${this.entity}, fieldName: ${this.fieldName}, otherMeta: ${this.otherMeta.type})`;\n }\n\n get #isCascadeDelete(): boolean {\n return isCascadeDelete(this, this.#field.fieldName);\n }\n\n /** Loads the previous membership so recalculation and deletion can remove its join rows. */\n async #loadFromJoinTable(): Promise<U[]> {\n const { em } = this.entity;\n if (!this.entity.isNewEntity) {\n const key = `${this.columnName}=${this.entity.id}`;\n // Use the existing m2m loader by creating a compatible collection-like object\n await manyToManyBatchLoader(em, this).load(key);\n }\n this.#isJoinTableLoaded = true;\n return getEmInternalApi(em).joinRows(this).getOthers(this.columnName, this.entity) as U[];\n }\n\n // This is like calling `setField` but for a m2m relation...\n #syncJoinTableRows(newValue: U[]): void {\n const jr = getEmInternalApi(this.entity.em).joinRows(this);\n const newSet = new Set(newValue);\n const oldSet = new Set(jr.getOthers(this.columnName, this.entity) as U[]);\n // Find entities to add (in new but not in old)\n for (const entity of newValue) {\n if (!oldSet.has(entity)) {\n jr.addNew(this, this.entity, entity);\n }\n }\n // Find entities to remove (in old but not in new)\n for (const entity of oldSet) {\n if (!newSet.has(entity)) {\n jr.addRemove(this, this.entity, entity);\n }\n }\n }\n\n #filterDeleted(entities: U[], opts?: { withDeleted?: boolean }): U[] {\n return opts?.withDeleted === true\n ? [...entities]\n : entities.filter((e) => !e.isDeletedEntity && !(e as any).isSoftDeletedEntity);\n }\n\n [RelationT]: T = null!;\n [RelationU]: U = null!;\n}\n\n/** Type guard utility for determining if an entity field is a ReactiveManyToMany. */\nexport function isReactiveManyToMany(\n maybeReactiveManyToMany: any,\n): maybeReactiveManyToMany is ReactiveManyToMany<any, any> {\n return maybeReactiveManyToMany instanceof ReactiveManyToManyImpl;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAqCA,SAAgB,sBACd,MACA,IAC0B;CAC1B,OAAOA,kBAAAA,WAAW,QAAW,cAAc;EACzC,MAAM,MAAMC,uBAAAA,YAAY,MAAM,CAAC,CAAC,UAAU;EAC1C,OAAO,IAAI,uBAAgC,QAAQ,KAAK,MAAM,EAAE;CAClE,CAAC;AACH;;AAGA,IAAa,yBAAb,cACUC,uCAAAA,qBAEV;CAmBW;CACC;CAnBV;CAGA;CAEA;CAGA,cAA0C,KAAA;CAG1C,YAAiC,KAAA;CACjC,YAAqB;CACrB;CAEA,YACE,QACA,OACA,cACA,IACA;EACA,MAAM,MAAM;EAHL,KAAA,eAAA;EACC,KAAA,KAAA;EAGR,KAAK,SAAS;EACd,KAAK,qBAAqBC,mBAAAA,gBAAgB,MAAM,CAAC,CAAC;EAClD,CAAC,mBAAA,gBAAgB,MAAM,CAAC,CAAC,cAAc,CAAC,EAAA,CAAG,KAAK,aAAa;CAC/D;CAEA,MAAM,KAAK,MAAoF;EAC7F,cAAA,iBAAiB,KAAK,QAAQ,SAAS;EACvC,MAAM,EAAE,aAAa;EAErB,IAAI,CAAC,KAAK,YAAY,MAAM,aAAa;GACvC,MAAM,EAAE,OAAO,KAAK;GAGpB,IAFmB,MAAM,eAAeC,sBAAAA,iBAAiB,EAAE,CAAC,CAAC,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,iBAAiB,KAAK,OAAO,EAAE,CAAC,CAAC,SAAS,IAAI;EACzD,MAAM,SAAS,IAAI,IAAI,QAAQ;EAC/B,MAAM,SAAS,IAAI,IAAI,GAAG,UAAU,KAAK,YAAY,KAAK,MAAM,CAAQ;EAExE,KAAK,MAAM,UAAU,UACnB,IAAI,CAAC,OAAO,IAAI,MAAM,GACpB,GAAG,OAAO,MAAM,KAAK,QAAQ,MAAM;EAIvC,KAAK,MAAM,UAAU,QACnB,IAAI,CAAC,OAAO,IAAI,MAAM,GACpB,GAAG,UAAU,MAAM,KAAK,QAAQ,MAAM;CAG5C;CAEA,eAAe,UAAe,MAAuC;EACnE,OAAO,MAAM,gBAAgB,OACzB,CAAC,GAAG,QAAQ,IACZ,SAAS,QAAQ,MAAM,CAAC,EAAE,mBAAmB,CAAE,EAAU,mBAAmB;CAClF;CAEA,CAACM,kCAAAA,aAAgB;CACjB,CAACC,kCAAAA,aAAgB;AACnB;;AAGA,SAAgB,qBACd,yBACyD;CACzD,OAAO,mCAAmC;AAC5C"}
@@ -34,6 +34,8 @@ export declare class ReactiveManyToManyImpl<T extends Entity, U extends Entity,
34
34
  resetIsLoaded(): void;
35
35
  get getWithDeleted(): U[];
36
36
  get get(): U[];
37
+ /** Returns the stored membership without deriving or queuing join-row changes. */
38
+ current(): readonly U[];
37
39
  set(): void;
38
40
  get loadHint(): any;
39
41
  setFromOpts(_others: U[]): void;
@@ -49,6 +51,7 @@ export declare class ReactiveManyToManyImpl<T extends Entity, U extends Entity,
49
51
  get otherFieldName(): string;
50
52
  get hasBeenSet(): boolean;
51
53
  get isPreloaded(): boolean;
54
+ /** Installs materialized membership without deriving, e.g. when RunPlugin mirrors a flush. */
52
55
  preload(): void;
53
56
  import(other: ReactiveManyToManyImpl<T, U, H>, _: unknown, mapEntities: (e: U[] | undefined) => U[] | undefined): void;
54
57
  toString(): string;
@@ -1 +1 @@
1
- {"version":3,"file":"ReactiveManyToMany.d.cts","names":[],"sources":["../../src/relations/Reacti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AAU,aAAa,YACrF,qBAAqB,GAAG,gBACrB,mBAAmB,GAAG,IAAI;;EAoB5B,cAAc;UACb;EAJV,YACE,QAAQ,GACR,OAAO,iBACA,cAAc,GACb,KAAK,QAAQ,QAAQ,GAAG,gBAAgB,mBAAmB;EAQ/D,KAAK;IAAS;IAAuB;MAA0B,QAAQ,cAAc;MAmCvF;EAmBJ;MAyCI,kBAAkB;MAIlB,OAAO;;EAKX,oBAAoB;EAMpB;MAII;EAKJ,YAAY,SAAS;EAIrB;EAOM,0BAA0B;MAW5B,QAAQ;MAIR;MAIA,aAAa;MAIb;MAIA;MAIA;MAIA;MAIA;MAIA;MAIA;;EAOJ;EAcA,OACE,OAAO,uBAAuB,GAAG,GAAG,IACpC,YACA,cAAc,GAAG,oBAAoB;EAWhC;GA6CN,YAAY;GACZ,YAAY;;;wBAIC,qBACd,+BACC,2BAA2B"}
@@ -34,6 +34,8 @@ export declare class ReactiveManyToManyImpl<T extends Entity, U extends Entity,
34
34
  resetIsLoaded(): void;
35
35
  get getWithDeleted(): U[];
36
36
  get get(): U[];
37
+ /** Returns the stored membership without deriving or queuing join-row changes. */
38
+ current(): readonly U[];
37
39
  set(): void;
38
40
  get loadHint(): any;
39
41
  setFromOpts(_others: U[]): void;
@@ -49,6 +51,7 @@ export declare class ReactiveManyToManyImpl<T extends Entity, U extends Entity,
49
51
  get otherFieldName(): string;
50
52
  get hasBeenSet(): boolean;
51
53
  get isPreloaded(): boolean;
54
+ /** Installs materialized membership without deriving, e.g. when RunPlugin mirrors a flush. */
52
55
  preload(): void;
53
56
  import(other: ReactiveManyToManyImpl<T, U, H>, _: unknown, mapEntities: (e: U[] | undefined) => U[] | undefined): void;
54
57
  toString(): string;
@@ -1 +1 @@
1
- {"version":3,"file":"ReactiveManyToMany.d.mts","names":[],"sources":["../../src/relations/ReactiveManyToMany.ts"],"mappings":";;;;;;;;;;;;;;iBAgCiB,mBAAmB,UAAU,QAAQ,UAAU,gBAAgB,mBAAmB,GAAG;EACp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R,OAAO,iBACA,cAAc,GACb,KAAK,QAAQ,QAAQ,GAAG,gBAAgB,mBAAmB;EAQ/D,KAAK;IAAS;IAAuB;MAA0B,QAAQ,cAAc;MAmCvF;EAmBJ;MAyCI,kBAAkB;MAIlB,OAAO;;EAKX,oBAAoB;EAMpB;MAII;EAKJ,YAAY,SAAS;EAIrB;EAOM,0BAA0B;MAW5B,QAAQ;MAIR;MAIA,aAAa;MAIb;MAIA;MAIA;MAIA;MAIA;MAIA;MAIA;;EAOJ;EAcA,OACE,OAAO,uBAAuB,GAAG,GAAG,IACpC,YACA,cAAc,GAAG,oBAAoB;EAWhC;GA6CN,YAAY;GACZ,YAAY;;;wBAIC,qBACd,+BACC,2BAA2B"}
@@ -106,6 +106,10 @@ var ReactiveManyToManyImpl = class extends AbstractRelationImpl {
106
106
  get get() {
107
107
  return this.#doGet({ withDeleted: false });
108
108
  }
109
+ /** Returns the stored membership without deriving or queuing join-row changes. */
110
+ current() {
111
+ return this.#loaded ?? getEmInternalApi(this.entity.em).joinRows(this).getOthers(this.columnName, this.entity);
112
+ }
109
113
  set() {
110
114
  fail(`Cannot set ${this.entity}.${this.fieldName} ReactiveManyToMany directly.`);
111
115
  }
@@ -157,7 +161,20 @@ var ReactiveManyToManyImpl = class extends AbstractRelationImpl {
157
161
  get isPreloaded() {
158
162
  return false;
159
163
  }
160
- preload() {}
164
+ /** Installs materialized membership without deriving, e.g. when RunPlugin mirrors a flush. */
165
+ preload() {
166
+ if (this.entity.isNewEntity) return;
167
+ const api = getEmInternalApi(this.entity.em);
168
+ const preloaded = api.getPreloadedRelation(this.entity.idTagged, this.fieldName);
169
+ if (preloaded) {
170
+ this.#loaded = preloaded;
171
+ this.#loadedMode = "ref";
172
+ this.#isJoinTableLoaded = true;
173
+ this.#isLoaded = true;
174
+ this.#isCached = false;
175
+ api.isLoadedCache.add(this);
176
+ }
177
+ }
161
178
  import(other, _, mapEntities) {
162
179
  this.#loaded = mapEntities(other.#loaded);
163
180
  this.#isJoinTableLoaded = this.entity.isNewEntity;
@@ -1 +1 @@
1
- {"version":3,"file":"ReactiveManyToMany.js","names":[],"sources":["../../src/relations/ReactiveManyToMany.ts"],"sourcesContent":["import { manyToManyBatchLoader } from \"src/batchloaders/manyToManyBatchLoader.ts\";\nimport {\n type Entity,\n type EntityMetadata,\n type ManyToManyField,\n type ReadOnlyCollection,\n ensureNotDeleted,\n fail,\n getEmInternalApi,\n getInstanceData,\n getMetadata,\n getMetadataForField,\n isLoaded,\n} from \"src/index.ts\";\nimport type { IsLoadedCachable } from \"src/loading/IsLoadedCache.ts\";\nimport { lazyField } from \"src/newEntity.ts\";\nimport {\n type MaybeReactedEntity,\n type Reacted,\n type ReactiveHint,\n convertToLoadHint,\n} from \"src/reactivity/reactiveHints.ts\";\nimport { AbstractRelationImpl } from \"src/relations/AbstractRelationImpl.ts\";\nimport { isCascadeDelete } from \"src/relations/isCascadeDelete.ts\";\nimport { RelationT, RelationU } from \"src/relations/RelationSymbols.ts\";\n\n/**\n * A reactive, derived many-to-many collection.\n *\n * Similar to `ReactiveReference` but for collections--membership is calculated from a reactive\n * function and persisted to the underlying join table.\n */\nexport interface ReactiveManyToMany<T extends Entity, U extends Entity> extends ReadOnlyCollection<T, U> {\n load(opts?: { withDeleted?: boolean; forceReload?: boolean }): Promise<readonly U[]>;\n}\n\n/** Creates a `ReactiveManyToMany`. */\nexport function hasReactiveManyToMany<T extends Entity, U extends Entity, const H extends ReactiveHint<T>>(\n hint: H,\n fn: (entity: Reacted<T, H>) => readonly MaybeReactedEntity<U>[],\n): ReactiveManyToMany<T, U> {\n return lazyField((entity: T, fieldName) => {\n const m2m = getMetadata(entity).allFields[fieldName] as ManyToManyField;\n return new ReactiveManyToManyImpl<T, U, H>(entity, m2m, hint, fn);\n });\n}\n\n/** Implements ReactiveManyToMany, initially a copy/paste of ReactiveReference but for m2m. */\nexport class ReactiveManyToManyImpl<T extends Entity, U extends Entity, H extends ReactiveHint<T>>\n extends AbstractRelationImpl<T, U[]>\n implements ReactiveManyToMany<T, U>, IsLoadedCachable\n{\n readonly #field: ManyToManyField;\n\n // Could be either the ref-loaded stored array, or full-loaded calculated array\n #loaded: U[] | undefined;\n // Recalculation needs the old membership even when the derivation hint is already loaded.\n #isJoinTableLoaded: boolean;\n // In ref-mode, we use our materialized FK value (which might be undefined)\n // If full-mode, we calculate the FK value from the subgraph\n #loadedMode: \"ref\" | \"full\" | undefined = undefined;\n // #isLoaded doesn't necessary care if we're ref-mode or full-mode, it's just\n // whether a caller can call `.get` and not have it blow up.\n #isLoaded: boolean | undefined = undefined;\n #isCached: boolean = false;\n #loadPromise: Promise<ReadonlyArray<U>> | undefined;\n\n constructor(\n entity: T,\n field: ManyToManyField,\n public reactiveHint: H,\n private fn: (entity: Reacted<T, H>) => readonly MaybeReactedEntity<U>[],\n ) {\n super(entity);\n this.#field = field;\n this.#isJoinTableLoaded = getInstanceData(entity).isOrWasNew;\n (getInstanceData(entity).relations ??= {})[this.fieldName] = this;\n }\n\n async load(opts?: { withDeleted?: boolean; forceReload?: boolean }): Promise<ReadonlyArray<U>> {\n ensureNotDeleted(this.entity, \"pending\");\n const { loadHint } = this;\n\n if (!this.isLoaded || opts?.forceReload) {\n const { em } = this.entity;\n const maybeDirty = opts?.forceReload || getEmInternalApi(em).rm.isMaybePendingRecalc(this.entity, this.fieldName);\n\n if (maybeDirty) {\n this.#isCached = false;\n return (this.#loadPromise ??= Promise.all([\n em.populate(this.entity, { hint: loadHint, ...opts }),\n !this.#isJoinTableLoaded || opts?.forceReload ? this.#loadFromJoinTable() : undefined,\n ]).then(() => {\n this.#loadPromise = undefined;\n this.#loadedMode = \"full\";\n this.#isLoaded = true;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n return this.#doGet(opts);\n }));\n } else {\n // Load from join table (existing materialized state)\n return (this.#loadPromise ??= this.#loadFromJoinTable().then((loaded) => {\n this.#loadPromise = undefined;\n this.#loadedMode = \"ref\";\n this.#isLoaded = true;\n this.#loaded = loaded;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n return this.#filterDeleted(loaded, opts);\n }));\n }\n }\n return this.#doGet(opts);\n }\n\n get isLoaded(): boolean {\n if (this.#isLoaded !== undefined) return this.#isLoaded;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n // If a WIP mutation has marked our field as potentially dirty, we need to be \"full\" loaded\n const maybeDirty = getEmInternalApi(this.entity.em).rm.isMaybePendingRecalc(this.entity, this.fieldName);\n if (maybeDirty) {\n // ReactiveReferences can mark themselves isLoaded when merely their\n // loadHint is loaded, but for ReactiveManyToMany we need to also have\n // our old join rows loaded, to tell who needs to be removed\n this.#loadedMode = \"full\";\n this.#isLoaded = this.#isJoinTableLoaded && isLoaded(this.entity, this.loadHint);\n this.#isCached = false;\n } else {\n // If we've had `.load` called before, assume we're still loaded\n this.#isLoaded = !!this.#loadedMode;\n }\n return this.#isLoaded;\n }\n\n resetIsLoaded(): void {\n this.#isLoaded = undefined;\n this.#isCached = false;\n }\n\n #doGet(opts?: { withDeleted?: boolean }): U[] {\n const { fn } = this;\n ensureNotDeleted(this.entity, \"pending\");\n // Fast pass if we've already calculated this (cache invalidation will happen on\n // any mutation via #resetIsLoaded)..\n if (this.#isCached) {\n return this.#filterDeleted(this.#loaded ?? [], opts) as U[];\n }\n // Call isLoaded to probe the load hint, and get `#isLoaded` set, but still have\n // our `if` check the raw `#isLoaded` to know if we should eval-latest or return `loaded`.\n if (this.isLoaded && this.#loadedMode === \"full\") {\n const newValue = fn(this.entity as any) as unknown as U[];\n // Preserve deleted entities that were in the previous loaded value\n const previousDeleted = (this.#loaded ?? []).filter((e) => e.isDeletedEntity);\n for (const entity of previousDeleted) {\n if (!newValue.includes(entity)) newValue.push(entity);\n }\n if (!getEmInternalApi(this.entity.em).isValidating) {\n this.#syncJoinTableRows(newValue);\n }\n this.#loaded = newValue;\n this.#isCached = true;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n } else if (!!this.#loadedMode) {\n // We're either loadedMode=ref, or loadedMode=full (but not actually fully loaded),\n // but in theory loadedMode only gets set in `.load()`, so we should have #loaded\n // set to some value, even if it's not fully up-to-date.\n this.#isCached = true;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n } else {\n const noun = this.entity.isNewEntity ? \"derived\" : \"loaded\";\n throw new Error(`${this.entity}.${this.fieldName} has not been ${noun} yet`);\n }\n return this.#filterDeleted(this.#loaded ?? [], opts) as U[];\n }\n\n get getWithDeleted(): U[] {\n return this.#doGet({ withDeleted: true });\n }\n\n get get(): U[] {\n return this.#doGet({ withDeleted: false });\n }\n\n set(): void {\n fail(`Cannot set ${this.entity}.${this.fieldName} ReactiveManyToMany directly.`);\n }\n\n get loadHint(): any {\n const meta = getMetadata(this.entity);\n return (meta.config.__data.cachedReactiveLoadHints[this.fieldName] ??= convertToLoadHint(meta, this.reactiveHint));\n }\n\n setFromOpts(_others: U[]): void {\n throw new Error(`ReactiveManyToMany ${this.entity}.${this.fieldName} cannot be set via opts`);\n }\n\n maybeCascadeDelete(): void {\n if (this.#isCascadeDelete) {\n const jr = getEmInternalApi(this.entity.em).joinRows(this);\n (jr.getOthers(this.columnName, this.entity) as U[]).forEach((e) => this.entity.em.delete(e));\n }\n }\n\n async cleanupOnEntityDeleted(): Promise<void> {\n // Required relations may already be detached, so remove stored/pending rows without deriving.\n if (!this.#isJoinTableLoaded) await this.#loadFromJoinTable();\n const jr = getEmInternalApi(this.entity.em).joinRows(this);\n const existing = jr.getOthers(this.columnName, this.entity) as U[];\n for (const entity of existing) jr.addRemove(this, this.entity, entity);\n this.#loaded = [];\n this.#isLoaded = false;\n }\n\n // Properties needed for JoinRows/ManyToManyCollection compatibility\n get meta(): EntityMetadata {\n return getMetadataForField(getMetadata(this.entity), this.fieldName);\n }\n\n get fieldName(): string {\n return this.#field.fieldName;\n }\n\n get otherMeta(): EntityMetadata {\n return this.#field.otherMetadata();\n }\n\n get joinTableName(): string {\n return this.#field.joinTableName;\n }\n\n get columnName(): string {\n return this.#field.columnNames[0];\n }\n\n get otherColumnName(): string {\n return this.#field.columnNames[1];\n }\n\n get hasJoinTableId(): boolean {\n return this.#field.hasJoinTableId;\n }\n\n get otherFieldName(): string {\n return this.#field.otherFieldName;\n }\n\n get hasBeenSet(): boolean {\n return true;\n }\n\n get isPreloaded(): boolean {\n return false;\n }\n\n preload(): void {\n // No-op for now - could implement if needed\n }\n\n import(\n other: ReactiveManyToManyImpl<T, U, H>,\n _: unknown,\n mapEntities: (e: U[] | undefined) => U[] | undefined,\n ): void {\n this.#loaded = mapEntities(other.#loaded);\n // A fork copies members, not JoinRows; treat the snapshot as ref-mode until its own rows are loaded.\n this.#isJoinTableLoaded = this.entity.isNewEntity;\n this.#loadedMode = other.#loadedMode ? \"ref\" : undefined;\n this.#isLoaded = undefined;\n // Don't set `#isCached b/c we're not registering ourselves with `isLoadedCache` yet; let\n // the first caller to `#doGet` do that if needed.\n }\n\n public toString(): string {\n return `ReactiveManyToMany(entity: ${this.entity}, fieldName: ${this.fieldName}, otherMeta: ${this.otherMeta.type})`;\n }\n\n get #isCascadeDelete(): boolean {\n return isCascadeDelete(this, this.#field.fieldName);\n }\n\n /** Loads the previous membership so recalculation and deletion can remove its join rows. */\n async #loadFromJoinTable(): Promise<U[]> {\n const { em } = this.entity;\n if (!this.entity.isNewEntity) {\n const key = `${this.columnName}=${this.entity.id}`;\n // Use the existing m2m loader by creating a compatible collection-like object\n await manyToManyBatchLoader(em, this).load(key);\n }\n this.#isJoinTableLoaded = true;\n return getEmInternalApi(em).joinRows(this).getOthers(this.columnName, this.entity) as U[];\n }\n\n // This is like calling `setField` but for a m2m relation...\n #syncJoinTableRows(newValue: U[]): void {\n const jr = getEmInternalApi(this.entity.em).joinRows(this);\n const newSet = new Set(newValue);\n const oldSet = new Set(jr.getOthers(this.columnName, this.entity) as U[]);\n // Find entities to add (in new but not in old)\n for (const entity of newValue) {\n if (!oldSet.has(entity)) {\n jr.addNew(this, this.entity, entity);\n }\n }\n // Find entities to remove (in old but not in new)\n for (const entity of oldSet) {\n if (!newSet.has(entity)) {\n jr.addRemove(this, this.entity, entity);\n }\n }\n }\n\n #filterDeleted(entities: U[], opts?: { withDeleted?: boolean }): U[] {\n return opts?.withDeleted === true\n ? [...entities]\n : entities.filter((e) => !e.isDeletedEntity && !(e as any).isSoftDeletedEntity);\n }\n\n [RelationT]: T = null!;\n [RelationU]: U = null!;\n}\n\n/** Type guard utility for determining if an entity field is a ReactiveManyToMany. */\nexport function isReactiveManyToMany(\n maybeReactiveManyToMany: any,\n): maybeReactiveManyToMany is ReactiveManyToMany<any, any> {\n return maybeReactiveManyToMany instanceof ReactiveManyToManyImpl;\n}\n"],"mappings":";;;;;;;;;;;;;;AAqCA,SAAgB,sBACd,MACA,IAC0B;CAC1B,OAAO,WAAW,QAAW,cAAc;EACzC,MAAM,MAAM,YAAY,MAAM,CAAC,CAAC,UAAU;EAC1C,OAAO,IAAI,uBAAgC,QAAQ,KAAK,MAAM,EAAE;CAClE,CAAC;AACH;;AAGA,IAAa,yBAAb,cACU,qBAEV;CAmBW;CACC;CAnBV;CAGA;CAEA;CAGA,cAA0C,KAAA;CAG1C,YAAiC,KAAA;CACjC,YAAqB;CACrB;CAEA,YACE,QACA,OACA,cACA,IACA;EACA,MAAM,MAAM;EAHL,KAAA,eAAA;EACC,KAAA,KAAA;EAGR,KAAK,SAAS;EACd,KAAK,qBAAqB,gBAAgB,MAAM,CAAC,CAAC;EAClD,CAAC,gBAAgB,MAAM,CAAC,CAAC,cAAc,CAAC,EAAA,CAAG,KAAK,aAAa;CAC/D;CAEA,MAAM,KAAK,MAAoF;EAC7F,iBAAiB,KAAK,QAAQ,SAAS;EACvC,MAAM,EAAE,aAAa;EAErB,IAAI,CAAC,KAAK,YAAY,MAAM,aAAa;GACvC,MAAM,EAAE,OAAO,KAAK;GAGpB,IAFmB,MAAM,eAAe,iBAAiB,EAAE,CAAC,CAAC,GAAG,qBAAqB,KAAK,QAAQ,KAAK,SAAS,GAEhG;IACd,KAAK,YAA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["../../src/relations/ReactiveManyToMany.ts"],"sourcesContent":["import { manyToManyBatchLoader } from \"src/batchloaders/manyToManyBatchLoader.ts\";\nimport {\n type Entity,\n type EntityMetadata,\n type ManyToManyField,\n type ReadOnlyCollection,\n ensureNotDeleted,\n fail,\n getEmInternalApi,\n getInstanceData,\n getMetadata,\n getMetadataForField,\n isLoaded,\n} from \"src/index.ts\";\nimport type { IsLoadedCachable } from \"src/loading/IsLoadedCache.ts\";\nimport { lazyField } from \"src/newEntity.ts\";\nimport {\n type MaybeReactedEntity,\n type Reacted,\n type ReactiveHint,\n convertToLoadHint,\n} from \"src/reactivity/reactiveHints.ts\";\nimport { AbstractRelationImpl } from \"src/relations/AbstractRelationImpl.ts\";\nimport { isCascadeDelete } from \"src/relations/isCascadeDelete.ts\";\nimport { RelationT, RelationU } from \"src/relations/RelationSymbols.ts\";\n\n/**\n * A reactive, derived many-to-many collection.\n *\n * Similar to `ReactiveReference` but for collections--membership is calculated from a reactive\n * function and persisted to the underlying join table.\n */\nexport interface ReactiveManyToMany<T extends Entity, U extends Entity> extends ReadOnlyCollection<T, U> {\n load(opts?: { withDeleted?: boolean; forceReload?: boolean }): Promise<readonly U[]>;\n}\n\n/** Creates a `ReactiveManyToMany`. */\nexport function hasReactiveManyToMany<T extends Entity, U extends Entity, const H extends ReactiveHint<T>>(\n hint: H,\n fn: (entity: Reacted<T, H>) => readonly MaybeReactedEntity<U>[],\n): ReactiveManyToMany<T, U> {\n return lazyField((entity: T, fieldName) => {\n const m2m = getMetadata(entity).allFields[fieldName] as ManyToManyField;\n return new ReactiveManyToManyImpl<T, U, H>(entity, m2m, hint, fn);\n });\n}\n\n/** Implements ReactiveManyToMany, initially a copy/paste of ReactiveReference but for m2m. */\nexport class ReactiveManyToManyImpl<T extends Entity, U extends Entity, H extends ReactiveHint<T>>\n extends AbstractRelationImpl<T, U[]>\n implements ReactiveManyToMany<T, U>, IsLoadedCachable\n{\n readonly #field: ManyToManyField;\n\n // Could be either the ref-loaded stored array, or full-loaded calculated array\n #loaded: U[] | undefined;\n // Recalculation needs the old membership even when the derivation hint is already loaded.\n #isJoinTableLoaded: boolean;\n // In ref-mode, we use our materialized FK value (which might be undefined)\n // If full-mode, we calculate the FK value from the subgraph\n #loadedMode: \"ref\" | \"full\" | undefined = undefined;\n // #isLoaded doesn't necessary care if we're ref-mode or full-mode, it's just\n // whether a caller can call `.get` and not have it blow up.\n #isLoaded: boolean | undefined = undefined;\n #isCached: boolean = false;\n #loadPromise: Promise<ReadonlyArray<U>> | undefined;\n\n constructor(\n entity: T,\n field: ManyToManyField,\n public reactiveHint: H,\n private fn: (entity: Reacted<T, H>) => readonly MaybeReactedEntity<U>[],\n ) {\n super(entity);\n this.#field = field;\n this.#isJoinTableLoaded = getInstanceData(entity).isOrWasNew;\n (getInstanceData(entity).relations ??= {})[this.fieldName] = this;\n }\n\n async load(opts?: { withDeleted?: boolean; forceReload?: boolean }): Promise<ReadonlyArray<U>> {\n ensureNotDeleted(this.entity, \"pending\");\n const { loadHint } = this;\n\n if (!this.isLoaded || opts?.forceReload) {\n const { em } = this.entity;\n const maybeDirty = opts?.forceReload || getEmInternalApi(em).rm.isMaybePendingRecalc(this.entity, this.fieldName);\n\n if (maybeDirty) {\n this.#isCached = false;\n return (this.#loadPromise ??= Promise.all([\n em.populate(this.entity, { hint: loadHint, ...opts }),\n !this.#isJoinTableLoaded || opts?.forceReload ? this.#loadFromJoinTable() : undefined,\n ]).then(() => {\n this.#loadPromise = undefined;\n this.#loadedMode = \"full\";\n this.#isLoaded = true;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n return this.#doGet(opts);\n }));\n } else {\n // Load from join table (existing materialized state)\n return (this.#loadPromise ??= this.#loadFromJoinTable().then((loaded) => {\n this.#loadPromise = undefined;\n this.#loadedMode = \"ref\";\n this.#isLoaded = true;\n this.#loaded = loaded;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n return this.#filterDeleted(loaded, opts);\n }));\n }\n }\n return this.#doGet(opts);\n }\n\n get isLoaded(): boolean {\n if (this.#isLoaded !== undefined) return this.#isLoaded;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n // If a WIP mutation has marked our field as potentially dirty, we need to be \"full\" loaded\n const maybeDirty = getEmInternalApi(this.entity.em).rm.isMaybePendingRecalc(this.entity, this.fieldName);\n if (maybeDirty) {\n // ReactiveReferences can mark themselves isLoaded when merely their\n // loadHint is loaded, but for ReactiveManyToMany we need to also have\n // our old join rows loaded, to tell who needs to be removed\n this.#loadedMode = \"full\";\n this.#isLoaded = this.#isJoinTableLoaded && isLoaded(this.entity, this.loadHint);\n this.#isCached = false;\n } else {\n // If we've had `.load` called before, assume we're still loaded\n this.#isLoaded = !!this.#loadedMode;\n }\n return this.#isLoaded;\n }\n\n resetIsLoaded(): void {\n this.#isLoaded = undefined;\n this.#isCached = false;\n }\n\n #doGet(opts?: { withDeleted?: boolean }): U[] {\n const { fn } = this;\n ensureNotDeleted(this.entity, \"pending\");\n // Fast pass if we've already calculated this (cache invalidation will happen on\n // any mutation via #resetIsLoaded)..\n if (this.#isCached) {\n return this.#filterDeleted(this.#loaded ?? [], opts) as U[];\n }\n // Call isLoaded to probe the load hint, and get `#isLoaded` set, but still have\n // our `if` check the raw `#isLoaded` to know if we should eval-latest or return `loaded`.\n if (this.isLoaded && this.#loadedMode === \"full\") {\n const newValue = fn(this.entity as any) as unknown as U[];\n // Preserve deleted entities that were in the previous loaded value\n const previousDeleted = (this.#loaded ?? []).filter((e) => e.isDeletedEntity);\n for (const entity of previousDeleted) {\n if (!newValue.includes(entity)) newValue.push(entity);\n }\n if (!getEmInternalApi(this.entity.em).isValidating) {\n this.#syncJoinTableRows(newValue);\n }\n this.#loaded = newValue;\n this.#isCached = true;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n } else if (!!this.#loadedMode) {\n // We're either loadedMode=ref, or loadedMode=full (but not actually fully loaded),\n // but in theory loadedMode only gets set in `.load()`, so we should have #loaded\n // set to some value, even if it's not fully up-to-date.\n this.#isCached = true;\n getEmInternalApi(this.entity.em).isLoadedCache.add(this);\n } else {\n const noun = this.entity.isNewEntity ? \"derived\" : \"loaded\";\n throw new Error(`${this.entity}.${this.fieldName} has not been ${noun} yet`);\n }\n return this.#filterDeleted(this.#loaded ?? [], opts) as U[];\n }\n\n get getWithDeleted(): U[] {\n return this.#doGet({ withDeleted: true });\n }\n\n get get(): U[] {\n return this.#doGet({ withDeleted: false });\n }\n\n /** Returns the stored membership without deriving or queuing join-row changes. */\n current(): readonly U[] {\n return (\n this.#loaded ?? (getEmInternalApi(this.entity.em).joinRows(this).getOthers(this.columnName, this.entity) as U[])\n );\n }\n\n set(): void {\n fail(`Cannot set ${this.entity}.${this.fieldName} ReactiveManyToMany directly.`);\n }\n\n get loadHint(): any {\n const meta = getMetadata(this.entity);\n return (meta.config.__data.cachedReactiveLoadHints[this.fieldName] ??= convertToLoadHint(meta, this.reactiveHint));\n }\n\n setFromOpts(_others: U[]): void {\n throw new Error(`ReactiveManyToMany ${this.entity}.${this.fieldName} cannot be set via opts`);\n }\n\n maybeCascadeDelete(): void {\n if (this.#isCascadeDelete) {\n const jr = getEmInternalApi(this.entity.em).joinRows(this);\n (jr.getOthers(this.columnName, this.entity) as U[]).forEach((e) => this.entity.em.delete(e));\n }\n }\n\n async cleanupOnEntityDeleted(): Promise<void> {\n // Required relations may already be detached, so remove stored/pending rows without deriving.\n if (!this.#isJoinTableLoaded) await this.#loadFromJoinTable();\n const jr = getEmInternalApi(this.entity.em).joinRows(this);\n const existing = jr.getOthers(this.columnName, this.entity) as U[];\n for (const entity of existing) jr.addRemove(this, this.entity, entity);\n this.#loaded = [];\n this.#isLoaded = false;\n }\n\n // Properties needed for JoinRows/ManyToManyCollection compatibility\n get meta(): EntityMetadata {\n return getMetadataForField(getMetadata(this.entity), this.fieldName);\n }\n\n get fieldName(): string {\n return this.#field.fieldName;\n }\n\n get otherMeta(): EntityMetadata {\n return this.#field.otherMetadata();\n }\n\n get joinTableName(): string {\n return this.#field.joinTableName;\n }\n\n get columnName(): string {\n return this.#field.columnNames[0];\n }\n\n get otherColumnName(): string {\n return this.#field.columnNames[1];\n }\n\n get hasJoinTableId(): boolean {\n return this.#field.hasJoinTableId;\n }\n\n get otherFieldName(): string {\n return this.#field.otherFieldName;\n }\n\n get hasBeenSet(): boolean {\n return true;\n }\n\n get isPreloaded(): boolean {\n // isPreloaded lets populate skip load(), but stored rows alone cannot satisfy a pending derivation.\n // Keep that shortcut disabled. RunPlugin calls preload() explicitly with already-derived membership.\n return false;\n }\n\n /** Installs materialized membership without deriving, e.g. when RunPlugin mirrors a flush. */\n preload(): void {\n if (this.entity.isNewEntity) return;\n const api = getEmInternalApi(this.entity.em);\n const preloaded = api.getPreloadedRelation<U>(this.entity.idTagged, this.fieldName);\n if (preloaded) {\n this.#loaded = preloaded;\n this.#loadedMode = \"ref\";\n this.#isJoinTableLoaded = true;\n this.#isLoaded = true;\n this.#isCached = false;\n api.isLoadedCache.add(this);\n }\n }\n\n import(\n other: ReactiveManyToManyImpl<T, U, H>,\n _: unknown,\n mapEntities: (e: U[] | undefined) => U[] | undefined,\n ): void {\n this.#loaded = mapEntities(other.#loaded);\n // A fork copies members, not JoinRows; treat the snapshot as ref-mode until its own rows are loaded.\n this.#isJoinTableLoaded = this.entity.isNewEntity;\n this.#loadedMode = other.#loadedMode ? \"ref\" : undefined;\n this.#isLoaded = undefined;\n // Don't set `#isCached b/c we're not registering ourselves with `isLoadedCache` yet; let\n // the first caller to `#doGet` do that if needed.\n }\n\n public toString(): string {\n return `ReactiveManyToMany(entity: ${this.entity}, fieldName: ${this.fieldName}, otherMeta: ${this.otherMeta.type})`;\n }\n\n get #isCascadeDelete(): boolean {\n return isCascadeDelete(this, this.#field.fieldName);\n }\n\n /** Loads the previous membership so recalculation and deletion can remove its join rows. */\n async #loadFromJoinTable(): Promise<U[]> {\n const { em } = this.entity;\n if (!this.entity.isNewEntity) {\n const key = `${this.columnName}=${this.entity.id}`;\n // Use the existing m2m loader by creating a compatible collection-like object\n await manyToManyBatchLoader(em, this).load(key);\n }\n this.#isJoinTableLoaded = true;\n return getEmInternalApi(em).joinRows(this).getOthers(this.columnName, this.entity) as U[];\n }\n\n // This is like calling `setField` but for a m2m relation...\n #syncJoinTableRows(newValue: U[]): void {\n const jr = getEmInternalApi(this.entity.em).joinRows(this);\n const newSet = new Set(newValue);\n const oldSet = new Set(jr.getOthers(this.columnName, this.entity) as U[]);\n // Find entities to add (in new but not in old)\n for (const entity of newValue) {\n if (!oldSet.has(entity)) {\n jr.addNew(this, this.entity, entity);\n }\n }\n // Find entities to remove (in old but not in new)\n for (const entity of oldSet) {\n if (!newSet.has(entity)) {\n jr.addRemove(this, this.entity, entity);\n }\n }\n }\n\n #filterDeleted(entities: U[], opts?: { withDeleted?: boolean }): U[] {\n return opts?.withDeleted === true\n ? [...entities]\n : entities.filter((e) => !e.isDeletedEntity && !(e as any).isSoftDeletedEntity);\n }\n\n [RelationT]: T = null!;\n [RelationU]: U = null!;\n}\n\n/** Type guard utility for determining if an entity field is a ReactiveManyToMany. */\nexport function isReactiveManyToMany(\n maybeReactiveManyToMany: any,\n): maybeReactiveManyToMany is ReactiveManyToMany<any, any> {\n return maybeReactiveManyToMany instanceof ReactiveManyToManyImpl;\n}\n"],"mappings":";;;;;;;;;;;;;;AAqCA,SAAgB,sBACd,MACA,IAC0B;CAC1B,OAAO,WAAW,QAAW,cAAc;EACzC,MAAM,MAAM,YAAY,MAAM,CAAC,CAAC,UAAU;EAC1C,OAAO,IAAI,uBAAgC,QAAQ,KAAK,MAAM,EAAE;CAClE,CAAC;AACH;;AAGA,IAAa,yBAAb,cACU,qBAEV;CAmBW;CACC;CAnBV;CAGA;CAEA;CAGA,cAA0C,KAAA;CAG1C,YAAiC,KAAA;CACjC,YAAqB;CACrB;CAEA,YACE,QACA,OACA,cACA,IACA;EACA,MAAM,MAAM;EAHL,KAAA,eAAA;EACC,KAAA,KAAA;EAGR,KAAK,SAAS;EACd,KAAK,qBA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B,OAAO,iBAAiB,EAAE,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,UAAU,KAAK,YAAY,KAAK,MAAM;CACnF;CAGA,mBAAmB,UAAqB;EACtC,MAAM,KAAK,iBAAiB,KAAK,OAAO,EAAE,CAAC,CAAC,SAAS,IAAI;EACzD,MAAM,SAAS,IAAI,IAAI,QAAQ;EAC/B,MAAM,SAAS,IAAI,IAAI,GAAG,UAAU,KAAK,YAAY,KAAK,MAAM,CAAQ;EAExE,KAAK,MAAM,UAAU,UACnB,IAAI,CAAC,OAAO,IAAI,MAAM,GACpB,GAAG,OAAO,MAAM,KAAK,QAAQ,MAAM;EAIvC,KAAK,MAAM,UAAU,QACnB,IAAI,CAAC,OAAO,IAAI,MAAM,GACpB,GAAG,UAAU,MAAM,KAAK,QAAQ,MAAM;CAG5C;CAEA,eAAe,UAAe,MAAuC;EACnE,OAAO,MAAM,gBAAgB,OACzB,CAAC,GAAG,QAAQ,IACZ,SAAS,QAAQ,MAAM,CAAC,EAAE,mBAAmB,CAAE,EAAU,mBAAmB;CAClF;CAEA,CAAC,aAAgB;CACjB,CAAC,aAAgB;AACnB;;AAGA,SAAgB,qBACd,yBACyD;CACzD,OAAO,mCAAmC;AAC5C"}
@@ -94,9 +94,18 @@ var ReactiveManyToManyOtherSideImpl = class extends require_relations_AbstractRe
94
94
  return false;
95
95
  }
96
96
  get isPreloaded() {
97
- return false;
97
+ return !!this.#getPreloaded();
98
+ }
99
+ preload() {
100
+ const preloaded = this.#getPreloaded();
101
+ if (preloaded) {
102
+ this.#loaded = preloaded;
103
+ this.#isLoaded = true;
104
+ this.#cached = void 0;
105
+ this.#isCached = false;
106
+ require_EntityManager.getEmInternalApi(this.entity.em).isLoadedCache.addNaive(this);
107
+ }
98
108
  }
99
- preload() {}
100
109
  import(other, _, mapEntities) {
101
110
  this.#loaded = mapEntities(other.#loaded);
102
111
  this.#isLoaded = other.#isLoaded;
@@ -134,6 +143,11 @@ var ReactiveManyToManyOtherSideImpl = class extends require_relations_AbstractRe
134
143
  if (opts?.withDeleted === true) return entities;
135
144
  return entities.filter((e) => !e.isDeletedEntity && !e.isSoftDeletedEntity);
136
145
  }
146
+ /** Finds stored membership published by a preloader or RunPlugin. */
147
+ #getPreloaded() {
148
+ if (this.entity.isNewEntity) return void 0;
149
+ return require_EntityManager.getEmInternalApi(this.entity.em).getPreloadedRelation(this.entity.idTagged, this.fieldName);
150
+ }
137
151
  [require_relations_RelationSymbols.RelationT] = null;
138
152
  [require_relations_RelationSymbols.RelationU] = null;
139
153
  };
@@ -1 +1 @@
1
- {"version":3,"file":"ReactiveManyToManyOtherSide.cjs","names":["lazyField","getMetadata","AbstractRelationImpl","getMetadataForField","manyToManyBatchLoader","getEmInternalApi","RelationT","RelationU"],"sources":["../../src/relations/ReactiveManyToManyOtherSide.ts"],"sourcesContent":["import { manyToManyBatchLoader } from \"src/batchloaders/manyToManyBatchLoader.ts\";\nimport type { ManyToManyLike } from \"src/flush/JoinRows.ts\";\nimport {\n type Entity,\n type EntityMetadata,\n type ManyToManyField,\n type ReadOnlyCollection,\n ensureNotDeleted,\n getEmInternalApi,\n getInstanceData,\n getMetadata,\n getMetadataForField,\n} from \"src/index.ts\";\nimport type { IsLoadedCachable } from \"src/loading/IsLoadedCache.ts\";\nimport { lazyField } from \"src/newEntity.ts\";\nimport { AbstractRelationImpl } from \"src/relations/AbstractRelationImpl.ts\";\nimport { RelationT, RelationU } from \"src/relations/RelationSymbols.ts\";\n\n/**\n * A read-only collection representing the \"other side\" of a ReactiveManyToMany.\n *\n * I.e. when `Author.bestReviews` is a `ReactiveManyToMany` (controlling side), `BookReview.bestReviewAuthors`\n * the `ReactiveManyToManyOtherSide` (read-only view).\n */\nexport interface ReactiveManyToManyOtherSide<T extends Entity, U extends Entity> extends ReadOnlyCollection<T, U> {}\n\n/** Creates a ReactiveManyToManyOtherSide, the read-only other side of a ReactiveManyToMany. */\nexport function hasReactiveManyToManyOtherSide<T extends Entity, U extends Entity>(): ReactiveManyToManyOtherSide<\n T,\n U\n> {\n return lazyField((entity: T, fieldName) => {\n const m2m = getMetadata(entity).allFields[fieldName] as ManyToManyField;\n return new ReactiveManyToManyOtherSideImpl<T, U>(entity, m2m);\n });\n}\n\nexport class ReactiveManyToManyOtherSideImpl<T extends Entity, U extends Entity>\n extends AbstractRelationImpl<T, U[]>\n implements ReactiveManyToManyOtherSide<T, U>, ManyToManyLike, IsLoadedCachable\n{\n #field: ManyToManyField;\n // Loading state\n #loaded: U[] | undefined;\n #isLoaded: boolean = false;\n #loadPromise: Promise<readonly U[]> | undefined;\n // Cached result of applyPendingChanges (without deleted filtering)\n #cached: U[] | undefined;\n #isCached: boolean = false;\n\n constructor(entity: T, field: ManyToManyField) {\n super(entity);\n this.#field = field;\n (getInstanceData(entity).relations ??= {})[field.fieldName] = this;\n }\n\n async load(opts?: { withDeleted?: boolean; forceReload?: boolean }): Promise<readonly U[]> {\n ensureNotDeleted(this.entity, \"pending\");\n if (!this.#isLoaded || opts?.forceReload) {\n this.#isCached = false;\n return (this.#loadPromise ??= this.#loadFromJoinTable().then((loaded) => {\n this.#loadPromise = undefined;\n this.#loaded = loaded;\n this.#isLoaded = true;\n getEmInternalApi(this.entity.em).isLoadedCache.addNaive(this);\n return this.#doGet(opts);\n }));\n }\n return this.#doGet(opts);\n }\n\n get isLoaded(): boolean {\n return this.#isLoaded;\n }\n\n resetIsLoaded(): void {\n this.#isCached = false;\n }\n\n get get(): U[] {\n return this.#doGet({ withDeleted: false });\n }\n\n get getWithDeleted(): U[] {\n return this.#doGet({ withDeleted: true });\n }\n\n set(): void {\n throw new Error(`ReactiveManyToManyOtherSide ${this.entity}.${this.fieldName} cannot be set`);\n }\n\n setFromOpts(_others: U[]): void {\n throw new Error(`ReactiveManyToManyOtherSide ${this.entity}.${this.fieldName} cannot be set via opts`);\n }\n\n maybeCascadeDelete(): void {\n // Don't cascade - the controlling side handles this\n }\n\n async cleanupOnEntityDeleted(): Promise<void> {\n this.#loaded = [];\n this.#cached = undefined;\n this.#isCached = false;\n this.#isLoaded = false;\n }\n\n get fieldName(): string {\n return this.#field.fieldName;\n }\n\n // Properties for JoinRows/ManyToManyCollection compatibility\n get meta(): EntityMetadata {\n return getMetadataForField(getMetadata(this.entity), this.fieldName);\n }\n\n get otherMeta(): EntityMetadata {\n return this.#field.otherMetadata();\n }\n\n get joinTableName(): string {\n return this.#field.joinTableName;\n }\n\n get columnName(): string {\n return this.#field.columnNames[0];\n }\n\n get otherColumnName(): string {\n return this.#field.columnNames[1];\n }\n\n get hasJoinTableId(): boolean {\n return this.#field.hasJoinTableId;\n }\n\n get otherFieldName(): string {\n return this.#field.otherFieldName;\n }\n\n get hasBeenSet(): boolean {\n return false;\n }\n\n get isPreloaded(): boolean {\n return false;\n }\n\n preload(): void {\n // No-op for reactive m2m other side\n }\n\n import(\n other: ReactiveManyToManyOtherSideImpl<T, U>,\n _: unknown,\n mapEntities: (e: U[] | undefined) => U[] | undefined,\n ): void {\n this.#loaded = mapEntities(other.#loaded);\n this.#isLoaded = other.#isLoaded;\n // Don't copy #cached/#isCached since it assumes we're registered in `isLoaded`, let #doGet do that\n }\n\n public toString(): string {\n return `ReactiveManyToManyOtherSide(entity: ${this.entity}, fieldName: ${this.fieldName}, otherMeta: ${this.otherMeta.type})`;\n }\n\n #doGet(opts?: { withDeleted?: boolean }): U[] {\n ensureNotDeleted(this.entity, \"pending\");\n if (!this.#isLoaded) {\n throw new Error(`${this.entity}.${this.fieldName} has not been loaded yet`);\n }\n if (!this.#isCached) {\n this.#cached = this.#applyPendingChanges(this.#loaded ?? []);\n this.#isCached = true;\n getEmInternalApi(this.entity.em).isLoadedCache.addNaive(this);\n }\n return this.#filterDeleted(this.#cached!, opts);\n }\n\n async #loadFromJoinTable(): Promise<U[]> {\n const { em } = this.entity;\n const key = `${this.columnName}=${this.entity.id}`;\n await manyToManyBatchLoader(em, this).load(key);\n return getEmInternalApi(em).joinRows(this).getOthers(this.columnName, this.entity) as U[];\n }\n\n /** Apply pending changes from the controlling side. */\n #applyPendingChanges(baseEntities: U[]): U[] {\n const result = new Set(baseEntities);\n const jr = getEmInternalApi(this.entity.em).joinRows(this);\n const added = jr.addedFor(this, this.entity);\n for (const other of added) result.add(other as U);\n const removed = jr.removedFor(this, this.entity);\n for (const other of removed) result.delete(other as U);\n return [...result];\n }\n\n #filterDeleted(entities: U[], opts?: { withDeleted?: boolean }): U[] {\n if (opts?.withDeleted === true) {\n return entities;\n }\n return entities.filter((e) => !e.isDeletedEntity && !(e as any).isSoftDeletedEntity);\n }\n\n [RelationT]: T = null!;\n [RelationU]: U = null!;\n}\n\nexport function isReactiveManyToManyOtherSide(\n maybeCollection: any,\n): maybeCollection is ReactiveManyToManyOtherSide<any, any> {\n return maybeCollection instanceof ReactiveManyToManyOtherSideImpl;\n}\n"],"mappings":";;;;;;;;;;;AA2BA,SAAgB,iCAGd;CACA,OAAOA,kBAAAA,WAAW,QAAW,cAAc;EACzC,MAAM,MAAMC,uBAAAA,YAAY,MAAM,CAAC,CAAC,UAAU;EAC1C,OAAO,IAAI,gCAAsC,QAAQ,GAAG;CAC9D,CAAC;AACH;AAEA,IAAa,kCAAb,cACUC,uCAAAA,qBAEV;CACE;CAEA;CACA,YAAqB;CACrB;CAEA;CACA,YAAqB;CAErB,YAAY,QAAW,OAAwB;EAC7C,MAAM,MAAM;EACZ,KAAK,SAAS;EACd,CAAC,mBAAA,gBAAgB,MAAM,CAAC,CAAC,cAAc,CAAC,EAAA,CAAG,MAAM,aAAa;CAChE;CAEA,MAAM,KAAK,MAAgF;EACzF,cAAA,iBAAiB,KAAK,QAAQ,SAAS;EACvC,IAAI,CAAC,KAAK,aAAa,MAAM,aAAa;GACxC,KAAK,YAAY;GACjB,OAAQ,KAAK,iBAAiB,KAAK,mBAAmB,CAAC,CAAC,MAAM,WAAW;IACvE,KAAK,eAAe,KAAA;IACpB,KAAK,UAAU;IACf,KAAK,YAAY;IACjB,sBAAA,iBAAiB,KAAK,OAAO,EAAE,CAAC,CAAC,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E,IAAI,MAAM,gBAAgB,MACxB,OAAO;EAET,OAAO,SAAS,QAAQ,MAAM,CAAC,EAAE,mBAAmB,CAAE,EAAU,mBAAmB;CACrF;CAEA,CAACC,kCAAAA,aAAgB;CACjB,CAACC,kCAAAA,aAAgB;AACnB;AAEA,SAAgB,8BACd,iBAC0D;CAC1D,OAAO,2BAA2B;AACpC"}
1
+ {"version":3,"file":"ReactiveManyToManyOtherSide.cjs","names":["lazyField","getMetadata","AbstractRelationImpl","getMetadataForField","manyToManyBatchLoader","getEmInternalApi","RelationT","RelationU"],"sources":["../../src/relations/ReactiveManyToManyOtherSide.ts"],"sourcesContent":["import { manyToManyBatchLoader } from \"src/batchloaders/manyToManyBatchLoader.ts\";\nimport type { ManyToManyLike } from \"src/flush/JoinRows.ts\";\nimport {\n type Entity,\n type EntityMetadata,\n type ManyToManyField,\n type ReadOnlyCollection,\n ensureNotDeleted,\n getEmInternalApi,\n getInstanceData,\n getMetadata,\n getMetadataForField,\n} from \"src/index.ts\";\nimport type { IsLoadedCachable } from \"src/loading/IsLoadedCache.ts\";\nimport { lazyField } from \"src/newEntity.ts\";\nimport { AbstractRelationImpl } from \"src/relations/AbstractRelationImpl.ts\";\nimport { RelationT, RelationU } from \"src/relations/RelationSymbols.ts\";\n\n/**\n * A read-only collection representing the \"other side\" of a ReactiveManyToMany.\n *\n * I.e. when `Author.bestReviews` is a `ReactiveManyToMany` (controlling side), `BookReview.bestReviewAuthors`\n * the `ReactiveManyToManyOtherSide` (read-only view).\n */\nexport interface ReactiveManyToManyOtherSide<T extends Entity, U extends Entity> extends ReadOnlyCollection<T, U> {}\n\n/** Creates a ReactiveManyToManyOtherSide, the read-only other side of a ReactiveManyToMany. */\nexport function hasReactiveManyToManyOtherSide<T extends Entity, U extends Entity>(): ReactiveManyToManyOtherSide<\n T,\n U\n> {\n return lazyField((entity: T, fieldName) => {\n const m2m = getMetadata(entity).allFields[fieldName] as ManyToManyField;\n return new ReactiveManyToManyOtherSideImpl<T, U>(entity, m2m);\n });\n}\n\nexport class ReactiveManyToManyOtherSideImpl<T extends Entity, U extends Entity>\n extends AbstractRelationImpl<T, U[]>\n implements ReactiveManyToManyOtherSide<T, U>, ManyToManyLike, IsLoadedCachable\n{\n #field: ManyToManyField;\n // Loading state\n #loaded: U[] | undefined;\n #isLoaded: boolean = false;\n #loadPromise: Promise<readonly U[]> | undefined;\n // Cached result of applyPendingChanges (without deleted filtering)\n #cached: U[] | undefined;\n #isCached: boolean = false;\n\n constructor(entity: T, field: ManyToManyField) {\n super(entity);\n this.#field = field;\n (getInstanceData(entity).relations ??= {})[field.fieldName] = this;\n }\n\n async load(opts?: { withDeleted?: boolean; forceReload?: boolean }): Promise<readonly U[]> {\n ensureNotDeleted(this.entity, \"pending\");\n if (!this.#isLoaded || opts?.forceReload) {\n this.#isCached = false;\n return (this.#loadPromise ??= this.#loadFromJoinTable().then((loaded) => {\n this.#loadPromise = undefined;\n this.#loaded = loaded;\n this.#isLoaded = true;\n getEmInternalApi(this.entity.em).isLoadedCache.addNaive(this);\n return this.#doGet(opts);\n }));\n }\n return this.#doGet(opts);\n }\n\n get isLoaded(): boolean {\n return this.#isLoaded;\n }\n\n resetIsLoaded(): void {\n this.#isCached = false;\n }\n\n get get(): U[] {\n return this.#doGet({ withDeleted: false });\n }\n\n get getWithDeleted(): U[] {\n return this.#doGet({ withDeleted: true });\n }\n\n set(): void {\n throw new Error(`ReactiveManyToManyOtherSide ${this.entity}.${this.fieldName} cannot be set`);\n }\n\n setFromOpts(_others: U[]): void {\n throw new Error(`ReactiveManyToManyOtherSide ${this.entity}.${this.fieldName} cannot be set via opts`);\n }\n\n maybeCascadeDelete(): void {\n // Don't cascade - the controlling side handles this\n }\n\n async cleanupOnEntityDeleted(): Promise<void> {\n this.#loaded = [];\n this.#cached = undefined;\n this.#isCached = false;\n this.#isLoaded = false;\n }\n\n get fieldName(): string {\n return this.#field.fieldName;\n }\n\n // Properties for JoinRows/ManyToManyCollection compatibility\n get meta(): EntityMetadata {\n return getMetadataForField(getMetadata(this.entity), this.fieldName);\n }\n\n get otherMeta(): EntityMetadata {\n return this.#field.otherMetadata();\n }\n\n get joinTableName(): string {\n return this.#field.joinTableName;\n }\n\n get columnName(): string {\n return this.#field.columnNames[0];\n }\n\n get otherColumnName(): string {\n return this.#field.columnNames[1];\n }\n\n get hasJoinTableId(): boolean {\n return this.#field.hasJoinTableId;\n }\n\n get otherFieldName(): string {\n return this.#field.otherFieldName;\n }\n\n get hasBeenSet(): boolean {\n return false;\n }\n\n get isPreloaded(): boolean {\n // Only the controlling side derives membership; this inverse just reads its materialized rows.\n // Unlike ReactiveManyToMany, there is no derivation for populate's preload shortcut to skip.\n return !!this.#getPreloaded();\n }\n\n preload(): void {\n const preloaded = this.#getPreloaded();\n if (preloaded) {\n this.#loaded = preloaded;\n this.#isLoaded = true;\n this.#cached = undefined;\n this.#isCached = false;\n getEmInternalApi(this.entity.em).isLoadedCache.addNaive(this);\n }\n }\n\n import(\n other: ReactiveManyToManyOtherSideImpl<T, U>,\n _: unknown,\n mapEntities: (e: U[] | undefined) => U[] | undefined,\n ): void {\n this.#loaded = mapEntities(other.#loaded);\n this.#isLoaded = other.#isLoaded;\n // Don't copy #cached/#isCached since it assumes we're registered in `isLoaded`, let #doGet do that\n }\n\n public toString(): string {\n return `ReactiveManyToManyOtherSide(entity: ${this.entity}, fieldName: ${this.fieldName}, otherMeta: ${this.otherMeta.type})`;\n }\n\n #doGet(opts?: { withDeleted?: boolean }): U[] {\n ensureNotDeleted(this.entity, \"pending\");\n if (!this.#isLoaded) {\n throw new Error(`${this.entity}.${this.fieldName} has not been loaded yet`);\n }\n if (!this.#isCached) {\n this.#cached = this.#applyPendingChanges(this.#loaded ?? []);\n this.#isCached = true;\n getEmInternalApi(this.entity.em).isLoadedCache.addNaive(this);\n }\n return this.#filterDeleted(this.#cached!, opts);\n }\n\n async #loadFromJoinTable(): Promise<U[]> {\n const { em } = this.entity;\n const key = `${this.columnName}=${this.entity.id}`;\n await manyToManyBatchLoader(em, this).load(key);\n return getEmInternalApi(em).joinRows(this).getOthers(this.columnName, this.entity) as U[];\n }\n\n /** Apply pending changes from the controlling side. */\n #applyPendingChanges(baseEntities: U[]): U[] {\n const result = new Set(baseEntities);\n const jr = getEmInternalApi(this.entity.em).joinRows(this);\n const added = jr.addedFor(this, this.entity);\n for (const other of added) result.add(other as U);\n const removed = jr.removedFor(this, this.entity);\n for (const other of removed) result.delete(other as U);\n return [...result];\n }\n\n #filterDeleted(entities: U[], opts?: { withDeleted?: boolean }): U[] {\n if (opts?.withDeleted === true) {\n return entities;\n }\n return entities.filter((e) => !e.isDeletedEntity && !(e as any).isSoftDeletedEntity);\n }\n\n /** Finds stored membership published by a preloader or RunPlugin. */\n #getPreloaded(): U[] | undefined {\n if (this.entity.isNewEntity) return undefined;\n return getEmInternalApi(this.entity.em).getPreloadedRelation<U>(this.entity.idTagged, this.fieldName);\n }\n\n [RelationT]: T = null!;\n [RelationU]: U = null!;\n}\n\nexport function isReactiveManyToManyOtherSide(\n maybeCollection: any,\n): maybeCollection is ReactiveManyToManyOtherSide<any, any> {\n return maybeCollection instanceof ReactiveManyToManyOtherSideImpl;\n}\n"],"mappings":";;;;;;;;;;;AA2BA,SAAgB,iCAGd;CACA,OAAOA,kBAAAA,WAAW,QAAW,cAAc;EACzC,MAAM,MAAMC,uBAAAA,YAAY,MAAM,CAAC,CAAC,UAAU;EAC1C,OAAO,IAAI,gCAAsC,QAAQ,GAAG;CAC9D,CAAC;AACH;AAEA,IAAa,kCAAb,cACUC,uCAAAA,qBAEV;CACE;CAEA;CACA,YAAqB;CACrB;CAEA;CACA,YAAqB;CAErB,YAAY,QAAW,OAAwB;EAC7C,MAAM,MAAM;EACZ,KAAK,SAAS;EACd,CAAC,mBAAA,gBAAgB,MAAM,CAAC,CAAC,cAAc,CAAC,EAAA,CAAG,MAAM,aAAa;CAChE;CAEA,MAAM,KAAK,MAAgF;EACzF,cAAA,iBAAiB,KAAK,QAAQ,SAAS;EAC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AAS;IAAuB;MAA0B,iBAAiB;MAelF;EAIJ;MAII,OAAO;MAIP,kBAAkB;EAItB;EAIA,YAAY,SAAS;EAIrB;EAIM,0BAA0B;MAO5B;MAKA,QAAQ;MAIR,aAAa;MAIb;MAIA;MAIA;MAIA;MAIA;MAIA;MAIA;EAIJ;EAIA,OACE,OAAO,gCAAgC,GAAG,IAC1C,YACA,cAAc,GAAG,oBAAoB;EAOhC;GA0CN,YAAY;GACZ,YAAY;;wBAGC,8BACd,uBACC,mBAAmB"}
1
+ {"version":3,"file":"ReactiveManyToManyOtherSide.d.cts","names":[],"sources":["../../src/relations/ReactiveManyToManyOtherSide.ts"],"mappings":";;;;;;;;;;;;;;iBAwBiB,4BAA4B,UAAU,QAAQ,UAAU,gBAAgB,mBAAmB,GAAG;;wBAG/F,+BAA+B,UAAU,QAAQ,UAAU,WAAW,4BACpF,GACA;qBAQW,gCAAgC,UAAU,QAAQ,UAAU,gBAC/D,qBAAqB,GAAG,gBACrB,4BAA4B,GAAG,IAAI,gBAAgB;;EAW9D,YAAY,QAAQ,GAAG,OAAO;EAMxB,KAAK;IAAS;IAAuB;MAA0B,iBAAiB;MAelF;EAIJ;MAII,OAAO;MAIP,kBAAkB;EAItB;EAIA,YAAY,SAAS;EAIrB;EAIM,0BAA0B;MAO5B;MAKA,QAAQ;MAIR,aAAa;MAIb;MAIA;MAIA;MAIA;MAIA;MAIA;MAIA;EAMJ;EAWA,OACE,OAAO,gCAAgC,GAAG,IAC1C,YACA,cAAc,GAAG,oBAAoB;EAOhC;GAgDN,YAAY;GACZ,YAAY;;wBAGC,8BACd,uBACC,mBAAmB"}
@@ -1 +1 @@
1
- {"version":3,"file":"ReactiveManyToManyOtherSide.d.mts","names":[],"sources":["../../src/relations/ReactiveManyToManyOtherSide.ts"],"mappings":";;;;;;;;;;;;;;iBAwBiB,4BAA4B,UAAU,QAAQ,UAAU,gBAAgB,mBAAmB,GAAG;;wBAG/F,+BAA+B,UAAU,QAAQ,UAAU,WAAW,4BACpF,GACA;qBAQW,gCAAgC,UAAU,QAAQ,UAAU,gBAC/D,qBAAqB,GAAG,gBACrB,4BAA4B,GAAG,IAAI,gBAAgB;;EAW9D,YAAY,QAAQ,GAAG,OAAO;EAMxB,KAAK;IAAS;IAAuB;MAA0B,iBAAiB;MAelF;EAIJ;MAII,OAAO;MAIP,kBAAkB;EAItB;EAIA,YAAY,SAAS;EAIrB;EAIM,0BAA0B;MAO5B;MAKA,QAAQ;MAIR,aAAa;MAIb;MAIA;MAIA;MAIA;MAIA;MAIA;MAIA;EAIJ;EAIA,OACE,OAAO,gCAAgC,GAAG,IAC1C,YACA,cAAc,GAAG,oBAAoB;EAOhC;GA0CN,YAAY;GACZ,YAAY;;wBAGC,8BACd,uBACC,mBAAmB"}
1
+ {"version":3,"file":"ReactiveManyToManyOtherSide.d.mts","names":[],"sources":["../../src/relations/ReactiveManyToManyOtherSide.ts"],"mappings":";;;;;;;;;;;;;;iBAwBiB,4BAA4B,UAAU,QAAQ,UAAU,gBAAgB,mBAAmB,GAAG;;wBAG/F,+BAA+B,UAAU,QAAQ,UAAU,WAAW,4BACpF,GACA;qBAQW,gCAAgC,UAAU,QAAQ,UAAU,gBAC/D,qBAAqB,GAAG,gBACrB,4BAA4B,GAAG,IAAI,gBAAgB;;EAW9D,YAAY,QAAQ,GAAG,OAAO;EAMxB,KAAK;IAAS;IAAuB;MAA0B,iBAAiB;MAelF;EAIJ;MAII,OAAO;MAIP,kBAAkB;EAItB;EAIA,YAAY,SAAS;EAIrB;EAIM,0BAA0B;MAO5B;MAKA,QAAQ;MAIR,aAAa;MAIb;MAIA;MAIA;MAIA;MAIA;MAIA;MAIA;EAMJ;EAWA,OACE,OAAO,gCAAgC,GAAG,IAC1C,YACA,cAAc,GAAG,oBAAoB;EAOhC;GAgDN,YAAY;GACZ,YAAY;;wBAGC,8BACd,uBACC,mBAAmB"}
@@ -93,9 +93,18 @@ var ReactiveManyToManyOtherSideImpl = class extends AbstractRelationImpl {
93
93
  return false;
94
94
  }
95
95
  get isPreloaded() {
96
- return false;
96
+ return !!this.#getPreloaded();
97
+ }
98
+ preload() {
99
+ const preloaded = this.#getPreloaded();
100
+ if (preloaded) {
101
+ this.#loaded = preloaded;
102
+ this.#isLoaded = true;
103
+ this.#cached = void 0;
104
+ this.#isCached = false;
105
+ getEmInternalApi(this.entity.em).isLoadedCache.addNaive(this);
106
+ }
97
107
  }
98
- preload() {}
99
108
  import(other, _, mapEntities) {
100
109
  this.#loaded = mapEntities(other.#loaded);
101
110
  this.#isLoaded = other.#isLoaded;
@@ -133,6 +142,11 @@ var ReactiveManyToManyOtherSideImpl = class extends AbstractRelationImpl {
133
142
  if (opts?.withDeleted === true) return entities;
134
143
  return entities.filter((e) => !e.isDeletedEntity && !e.isSoftDeletedEntity);
135
144
  }
145
+ /** Finds stored membership published by a preloader or RunPlugin. */
146
+ #getPreloaded() {
147
+ if (this.entity.isNewEntity) return void 0;
148
+ return getEmInternalApi(this.entity.em).getPreloadedRelation(this.entity.idTagged, this.fieldName);
149
+ }
136
150
  [RelationT] = null;
137
151
  [RelationU] = null;
138
152
  };
@@ -1 +1 @@
1
- {"version":3,"file":"ReactiveManyToManyOtherSide.js","names":[],"sources":["../../src/relations/ReactiveManyToManyOtherSide.ts"],"sourcesContent":["import { manyToManyBatchLoader } from \"src/batchloaders/manyToManyBatchLoader.ts\";\nimport type { ManyToManyLike } from \"src/flush/JoinRows.ts\";\nimport {\n type Entity,\n type EntityMetadata,\n type ManyToManyField,\n type ReadOnlyCollection,\n ensureNotDeleted,\n getEmInternalApi,\n getInstanceData,\n getMetadata,\n getMetadataForField,\n} from \"src/index.ts\";\nimport type { IsLoadedCachable } from \"src/loading/IsLoadedCache.ts\";\nimport { lazyField } from \"src/newEntity.ts\";\nimport { AbstractRelationImpl } from \"src/relations/AbstractRelationImpl.ts\";\nimport { RelationT, RelationU } from \"src/relations/RelationSymbols.ts\";\n\n/**\n * A read-only collection representing the \"other side\" of a ReactiveManyToMany.\n *\n * I.e. when `Author.bestReviews` is a `ReactiveManyToMany` (controlling side), `BookReview.bestReviewAuthors`\n * the `ReactiveManyToManyOtherSide` (read-only view).\n */\nexport interface ReactiveManyToManyOtherSide<T extends Entity, U extends Entity> extends ReadOnlyCollection<T, U> {}\n\n/** Creates a ReactiveManyToManyOtherSide, the read-only other side of a ReactiveManyToMany. */\nexport function hasReactiveManyToManyOtherSide<T extends Entity, U extends Entity>(): ReactiveManyToManyOtherSide<\n T,\n U\n> {\n return lazyField((entity: T, fieldName) => {\n const m2m = getMetadata(entity).allFields[fieldName] as ManyToManyField;\n return new ReactiveManyToManyOtherSideImpl<T, U>(entity, m2m);\n });\n}\n\nexport class ReactiveManyToManyOtherSideImpl<T extends Entity, U extends Entity>\n extends AbstractRelationImpl<T, U[]>\n implements ReactiveManyToManyOtherSide<T, U>, ManyToManyLike, IsLoadedCachable\n{\n #field: ManyToManyField;\n // Loading state\n #loaded: U[] | undefined;\n #isLoaded: boolean = false;\n #loadPromise: Promise<readonly U[]> | undefined;\n // Cached result of applyPendingChanges (without deleted filtering)\n #cached: U[] | undefined;\n #isCached: boolean = false;\n\n constructor(entity: T, field: ManyToManyField) {\n super(entity);\n this.#field = field;\n (getInstanceData(entity).relations ??= {})[field.fieldName] = this;\n }\n\n async load(opts?: { withDeleted?: boolean; forceReload?: boolean }): Promise<readonly U[]> {\n ensureNotDeleted(this.entity, \"pending\");\n if (!this.#isLoaded || opts?.forceReload) {\n this.#isCached = false;\n return (this.#loadPromise ??= this.#loadFromJoinTable().then((loaded) => {\n this.#loadPromise = undefined;\n this.#loaded = loaded;\n this.#isLoaded = true;\n getEmInternalApi(this.entity.em).isLoadedCache.addNaive(this);\n return this.#doGet(opts);\n }));\n }\n return this.#doGet(opts);\n }\n\n get isLoaded(): boolean {\n return this.#isLoaded;\n }\n\n resetIsLoaded(): void {\n this.#isCached = false;\n }\n\n get get(): U[] {\n return this.#doGet({ withDeleted: false });\n }\n\n get getWithDeleted(): U[] {\n return this.#doGet({ withDeleted: true });\n }\n\n set(): void {\n throw new Error(`ReactiveManyToManyOtherSide ${this.entity}.${this.fieldName} cannot be set`);\n }\n\n setFromOpts(_others: U[]): void {\n throw new Error(`ReactiveManyToManyOtherSide ${this.entity}.${this.fieldName} cannot be set via opts`);\n }\n\n maybeCascadeDelete(): void {\n // Don't cascade - the controlling side handles this\n }\n\n async cleanupOnEntityDeleted(): Promise<void> {\n this.#loaded = [];\n this.#cached = undefined;\n this.#isCached = false;\n this.#isLoaded = false;\n }\n\n get fieldName(): string {\n return this.#field.fieldName;\n }\n\n // Properties for JoinRows/ManyToManyCollection compatibility\n get meta(): EntityMetadata {\n return getMetadataForField(getMetadata(this.entity), this.fieldName);\n }\n\n get otherMeta(): EntityMetadata {\n return this.#field.otherMetadata();\n }\n\n get joinTableName(): string {\n return this.#field.joinTableName;\n }\n\n get columnName(): string {\n return this.#field.columnNames[0];\n }\n\n get otherColumnName(): string {\n return this.#field.columnNames[1];\n }\n\n get hasJoinTableId(): boolean {\n return this.#field.hasJoinTableId;\n }\n\n get otherFieldName(): string {\n return this.#field.otherFieldName;\n }\n\n get hasBeenSet(): boolean {\n return false;\n }\n\n get isPreloaded(): boolean {\n return false;\n }\n\n preload(): void {\n // No-op for reactive m2m other side\n }\n\n import(\n other: ReactiveManyToManyOtherSideImpl<T, U>,\n _: unknown,\n mapEntities: (e: U[] | undefined) => U[] | undefined,\n ): void {\n this.#loaded = mapEntities(other.#loaded);\n this.#isLoaded = other.#isLoaded;\n // Don't copy #cached/#isCached since it assumes we're registered in `isLoaded`, let #doGet do that\n }\n\n public toString(): string {\n return `ReactiveManyToManyOtherSide(entity: ${this.entity}, fieldName: ${this.fieldName}, otherMeta: ${this.otherMeta.type})`;\n }\n\n #doGet(opts?: { withDeleted?: boolean }): U[] {\n ensureNotDeleted(this.entity, \"pending\");\n if (!this.#isLoaded) {\n throw new Error(`${this.entity}.${this.fieldName} has not been loaded yet`);\n }\n if (!this.#isCached) {\n this.#cached = this.#applyPendingChanges(this.#loaded ?? []);\n this.#isCached = true;\n getEmInternalApi(this.entity.em).isLoadedCache.addNaive(this);\n }\n return this.#filterDeleted(this.#cached!, opts);\n }\n\n async #loadFromJoinTable(): Promise<U[]> {\n const { em } = this.entity;\n const key = `${this.columnName}=${this.entity.id}`;\n await manyToManyBatchLoader(em, this).load(key);\n return getEmInternalApi(em).joinRows(this).getOthers(this.columnName, this.entity) as U[];\n }\n\n /** Apply pending changes from the controlling side. */\n #applyPendingChanges(baseEntities: U[]): U[] {\n const result = new Set(baseEntities);\n const jr = getEmInternalApi(this.entity.em).joinRows(this);\n const added = jr.addedFor(this, this.entity);\n for (const other of added) result.add(other as U);\n const removed = jr.removedFor(this, this.entity);\n for (const other of removed) result.delete(other as U);\n return [...result];\n }\n\n #filterDeleted(entities: U[], opts?: { withDeleted?: boolean }): U[] {\n if (opts?.withDeleted === true) {\n return entities;\n }\n return entities.filter((e) => !e.isDeletedEntity && !(e as any).isSoftDeletedEntity);\n }\n\n [RelationT]: T = null!;\n [RelationU]: U = null!;\n}\n\nexport function isReactiveManyToManyOtherSide(\n maybeCollection: any,\n): maybeCollection is ReactiveManyToManyOtherSide<any, any> {\n return maybeCollection instanceof ReactiveManyToManyOtherSideImpl;\n}\n"],"mappings":";;;;;;;;;;AA2BA,SAAgB,iCAGd;CACA,OAAO,WAAW,QAAW,cAAc;EACzC,MAAM,MAAM,YAAY,MAAM,CAAC,CAAC,UAAU;EAC1C,OAAO,IAAI,gCAAsC,QAAQ,GAAG;CAC9D,CAAC;AACH;AAEA,IAAa,kCAAb,cACU,qBAEV;CACE;CAEA;CACA,YAAqB;CACrB;CAEA;CACA,YAAqB;CAErB,YAAY,QAAW,OAAwB;EAC7C,MAAM,MAAM;EACZ,KAAK,SAAS;EACd,CAAC,gBAAgB,MAAM,CAAC,CAAC,cAAc,CAAC,EAAA,CAAG,MAAM,aAAa;CAChE;CAEA,MAAM,KAAK,MAAgF;EACzF,iBAAiB,KAAK,QAAQ,SAAS;EACvC,I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AChD,MAAM,UAAU,GAAG,WAAW,MAAM,KAAK,MAAM;EAC/C,KAAK,MAAM,SAAS,SAAS,OAAO,OAAO,KAAU;EACrD,OAAO,CAAC,GAAG,MAAM;CACnB;CAEA,eAAe,UAAe,MAAuC;EACnE,IAAI,MAAM,gBAAgB,MACxB,OAAO;EAET,OAAO,SAAS,QAAQ,MAAM,CAAC,EAAE,mBAAmB,CAAE,EAAU,mBAAmB;CACrF;CAEA,CAAC,aAAgB;CACjB,CAAC,aAAgB;AACnB;AAEA,SAAgB,8BACd,iBAC0D;CAC1D,OAAO,2BAA2B;AACpC"}
1
+ {"version":3,"file":"ReactiveManyToManyOtherSide.js","names":[],"sources":["../../src/relations/ReactiveManyToManyOtherSide.ts"],"sourcesContent":["import { manyToManyBatchLoader } from \"src/batchloaders/manyToManyBatchLoader.ts\";\nimport type { ManyToManyLike } from \"src/flush/JoinRows.ts\";\nimport {\n type Entity,\n type EntityMetadata,\n type ManyToManyField,\n type ReadOnlyCollection,\n ensureNotDeleted,\n getEmInternalApi,\n getInstanceData,\n getMetadata,\n getMetadataForField,\n} from \"src/index.ts\";\nimport type { IsLoadedCachable } from \"src/loading/IsLoadedCache.ts\";\nimport { lazyField } from \"src/newEntity.ts\";\nimport { AbstractRelationImpl } from \"src/relations/AbstractRelationImpl.ts\";\nimport { RelationT, RelationU } from \"src/relations/RelationSymbols.ts\";\n\n/**\n * A read-only collection representing the \"other side\" of a ReactiveManyToMany.\n *\n * I.e. when `Author.bestReviews` is a `ReactiveManyToMany` (controlling side), `BookReview.bestReviewAuthors`\n * the `ReactiveManyToManyOtherSide` (read-only view).\n */\nexport interface ReactiveManyToManyOtherSide<T extends Entity, U extends Entity> extends ReadOnlyCollection<T, U> {}\n\n/** Creates a ReactiveManyToManyOtherSide, the read-only other side of a ReactiveManyToMany. */\nexport function hasReactiveManyToManyOtherSide<T extends Entity, U extends Entity>(): ReactiveManyToManyOtherSide<\n T,\n U\n> {\n return lazyField((entity: T, fieldName) => {\n const m2m = getMetadata(entity).allFields[fieldName] as ManyToManyField;\n return new ReactiveManyToManyOtherSideImpl<T, U>(entity, m2m);\n });\n}\n\nexport class ReactiveManyToManyOtherSideImpl<T extends Entity, U extends Entity>\n extends AbstractRelationImpl<T, U[]>\n implements ReactiveManyToManyOtherSide<T, U>, ManyToManyLike, IsLoadedCachable\n{\n #field: ManyToManyField;\n // Loading state\n #loaded: U[] | undefined;\n #isLoaded: boolean = false;\n #loadPromise: Promise<readonly U[]> | undefined;\n // Cached result of applyPendingChanges (without deleted filtering)\n #cached: U[] | undefined;\n #isCached: boolean = false;\n\n constructor(entity: T, field: ManyToManyField) {\n super(entity);\n this.#field = field;\n (getInstanceData(entity).relations ??= {})[field.fieldName] = this;\n }\n\n async load(opts?: { withDeleted?: boolean; forceReload?: boolean }): Promise<readonly U[]> {\n ensureNotDeleted(this.entity, \"pending\");\n if (!this.#isLoaded || opts?.forceReload) {\n this.#isCached = false;\n return (this.#loadPromise ??= this.#loadFromJoinTable().then((loaded) => {\n this.#loadPromise = undefined;\n this.#loaded = loaded;\n this.#isLoaded = true;\n getEmInternalApi(this.entity.em).isLoadedCache.addNaive(this);\n return this.#doGet(opts);\n }));\n }\n return this.#doGet(opts);\n }\n\n get isLoaded(): boolean {\n return this.#isLoaded;\n }\n\n resetIsLoaded(): void {\n this.#isCached = false;\n }\n\n get get(): U[] {\n return this.#doGet({ withDeleted: false });\n }\n\n get getWithDeleted(): U[] {\n return this.#doGet({ withDeleted: true });\n }\n\n set(): void {\n throw new Error(`ReactiveManyToManyOtherSide ${this.entity}.${this.fieldName} cannot be set`);\n }\n\n setFromOpts(_others: U[]): void {\n throw new Error(`ReactiveManyToManyOtherSide ${this.entity}.${this.fieldName} cannot be set via opts`);\n }\n\n maybeCascadeDelete(): void {\n // Don't cascade - the controlling side handles this\n }\n\n async cleanupOnEntityDeleted(): Promise<void> {\n this.#loaded = [];\n this.#cached = undefined;\n this.#isCached = false;\n this.#isLoaded = false;\n }\n\n get fieldName(): string {\n return this.#field.fieldName;\n }\n\n // Properties for JoinRows/ManyToManyCollection compatibility\n get meta(): EntityMetadata {\n return getMetadataForField(getMetadata(this.entity), this.fieldName);\n }\n\n get otherMeta(): EntityMetadata {\n return this.#field.otherMetadata();\n }\n\n get joinTableName(): string {\n return this.#field.joinTableName;\n }\n\n get columnName(): string {\n return this.#field.columnNames[0];\n }\n\n get otherColumnName(): string {\n return this.#field.columnNames[1];\n }\n\n get hasJoinTableId(): boolean {\n return this.#field.hasJoinTableId;\n }\n\n get otherFieldName(): string {\n return this.#field.otherFieldName;\n }\n\n get hasBeenSet(): boolean {\n return false;\n }\n\n get isPreloaded(): boolean {\n // Only the controlling side derives membership; this inverse just reads its materialized rows.\n // Unlike ReactiveManyToMany, there is no derivation for populate's preload shortcut to skip.\n return !!this.#getPreloaded();\n }\n\n preload(): void {\n const preloaded = this.#getPreloaded();\n if (preloaded) {\n this.#loaded = preloaded;\n this.#isLoaded = true;\n this.#cached = undefined;\n this.#isCached = false;\n getEmInternalApi(this.entity.em).isLoadedCache.addNaive(this);\n }\n }\n\n import(\n other: ReactiveManyToManyOtherSideImpl<T, U>,\n _: unknown,\n mapEntities: (e: U[] | undefined) => U[] | undefined,\n ): void {\n this.#loaded = mapEntities(other.#loaded);\n this.#isLoaded = other.#isLoaded;\n // Don't copy #cached/#isCached since it assumes we're registered in `isLoaded`, let #doGet do that\n }\n\n public toString(): string {\n return `ReactiveManyToManyOtherSide(entity: ${this.entity}, fieldName: ${this.fieldName}, otherMeta: ${this.otherMeta.type})`;\n }\n\n #doGet(opts?: { withDeleted?: boolean }): U[] {\n ensureNotDeleted(this.entity, \"pending\");\n if (!this.#isLoaded) {\n throw new Error(`${this.entity}.${this.fieldName} has not been loaded yet`);\n }\n if (!this.#isCached) {\n this.#cached = this.#applyPendingChanges(this.#loaded ?? []);\n this.#isCached = true;\n getEmInternalApi(this.entity.em).isLoadedCache.addNaive(this);\n }\n return this.#filterDeleted(this.#cached!, opts);\n }\n\n async #loadFromJoinTable(): Promise<U[]> {\n const { em } = this.entity;\n const key = `${this.columnName}=${this.entity.id}`;\n await manyToManyBatchLoader(em, this).load(key);\n return getEmInternalApi(em).joinRows(this).getOthers(this.columnName, this.entity) as U[];\n }\n\n /** Apply pending changes from the controlling side. */\n #applyPendingChanges(baseEntities: U[]): U[] {\n const result = new Set(baseEntities);\n const jr = getEmInternalApi(this.entity.em).joinRows(this);\n const added = jr.addedFor(this, this.entity);\n for (const other of added) result.add(other as U);\n const removed = jr.removedFor(this, this.entity);\n for (const other of removed) result.delete(other as U);\n return [...result];\n }\n\n #filterDeleted(entities: U[], opts?: { withDeleted?: boolean }): U[] {\n if (opts?.withDeleted === true) {\n return entities;\n }\n return entities.filter((e) => !e.isDeletedEntity && !(e as any).isSoftDeletedEntity);\n }\n\n /** Finds stored membership published by a preloader or RunPlugin. */\n #getPreloaded(): U[] | undefined {\n if (this.entity.isNewEntity) return undefined;\n return getEmInternalApi(this.entity.em).getPreloadedRelation<U>(this.entity.idTagged, this.fieldName);\n }\n\n [RelationT]: T = null!;\n [RelationU]: U = null!;\n}\n\nexport function isReactiveManyToManyOtherSide(\n maybeCollection: any,\n): maybeCollection is ReactiveManyToManyOtherSide<any, any> {\n return maybeCollection instanceof ReactiveManyToManyOtherSideImpl;\n}\n"],"mappings":";;;;;;;;;;AA2BA,SAAgB,iCAGd;CACA,OAAO,WAAW,QAAW,cAAc;EACzC,MAAM,MAAM,YAAY,MAAM,CAAC,CAAC,UAAU;EAC1C,OAAO,IAAI,gCAAsC,QAAQ,GAAG;CAC9D,CAAC;AACH;AAEA,IAAa,kCAAb,cACU,qBAEV;CACE;CAEA;CACA,YAAqB;CACrB;CAEA;CACA,YAAqB;CAErB,YAAY,QAAW,OAAwB;EAC7C,MAAM,MAAM;EACZ,KAAK,SAAS;EACd,CAAC,gBAAgB,MAAM,CAAC,CAAC,cAAc,CAAC,EAAA,CAAG,MAAM,aAAa;CAChE;CAEA,MAAM,KAAK,MAAgF;EACzF,iBAA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KAAK,MAAM;CACnF;;CAGA,qBAAqB,cAAwB;EAC3C,MAAM,SAAS,IAAI,IAAI,YAAY;EACnC,MAAM,KAAK,iBAAiB,KAAK,OAAO,EAAE,CAAC,CAAC,SAAS,IAAI;EACzD,MAAM,QAAQ,GAAG,SAAS,MAAM,KAAK,MAAM;EAC3C,KAAK,MAAM,SAAS,OAAO,OAAO,IAAI,KAAU;EAChD,MAAM,UAAU,GAAG,WAAW,MAAM,KAAK,MAAM;EAC/C,KAAK,MAAM,SAAS,SAAS,OAAO,OAAO,KAAU;EACrD,OAAO,CAAC,GAAG,MAAM;CACnB;CAEA,eAAe,UAAe,MAAuC;EACnE,IAAI,MAAM,gBAAgB,MACxB,OAAO;EAET,OAAO,SAAS,QAAQ,MAAM,CAAC,EAAE,mBAAmB,CAAE,EAAU,mBAAmB;CACrF;;CAGA,gBAAiC;EAC/B,IAAI,KAAK,OAAO,aAAa,OAAO,KAAA;EACpC,OAAO,iBAAiB,KAAK,OAAO,EAAE,CAAC,CAAC,qBAAwB,KAAK,OAAO,UAAU,KAAK,SAAS;CACtG;CAEA,CAAC,aAAgB;CACjB,CAAC,aAAgB;AACnB;AAEA,SAAgB,8BACd,iBAC0D;CAC1D,OAAO,2BAA2B;AACpC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "joist-core",
3
- "version": "2.5.0-next.12",
3
+ "version": "2.5.0-next.13",
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.5.0-next.12"
45
+ "joist-utils": "2.5.0-next.13"
46
46
  },
47
47
  "dependencies": {
48
48
  "ansis": "^4.4.0",