joist-core 2.4.0-next.2 → 2.4.0-next.21

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.
Files changed (153) hide show
  1. package/build/EntityManager.cjs +25 -11
  2. package/build/EntityManager.cjs.map +1 -1
  3. package/build/EntityManager.d.cts +11 -4
  4. package/build/EntityManager.d.cts.map +1 -1
  5. package/build/EntityManager.d.mts +11 -4
  6. package/build/EntityManager.d.mts.map +1 -1
  7. package/build/EntityManager.js +25 -13
  8. package/build/EntityManager.js.map +1 -1
  9. package/build/EntityMetadata.cjs +0 -1
  10. package/build/EntityMetadata.cjs.map +1 -1
  11. package/build/EntityMetadata.d.cts +8 -4
  12. package/build/EntityMetadata.d.cts.map +1 -1
  13. package/build/EntityMetadata.d.mts +8 -4
  14. package/build/EntityMetadata.d.mts.map +1 -1
  15. package/build/EntityMetadata.js +0 -1
  16. package/build/EntityMetadata.js.map +1 -1
  17. package/build/IndexManager.cjs +23 -5
  18. package/build/IndexManager.cjs.map +1 -1
  19. package/build/IndexManager.d.cts.map +1 -1
  20. package/build/IndexManager.d.mts.map +1 -1
  21. package/build/IndexManager.js +23 -5
  22. package/build/IndexManager.js.map +1 -1
  23. package/build/batchloaders/populateBatchLoader.cjs +2 -2
  24. package/build/batchloaders/populateBatchLoader.js +2 -2
  25. package/build/batchloaders/recursiveChildrenBatchLoader.cjs +1 -1
  26. package/build/batchloaders/recursiveChildrenBatchLoader.js +1 -1
  27. package/build/batchloaders/recursiveM2mBatchLoader.cjs +1 -1
  28. package/build/batchloaders/recursiveM2mBatchLoader.js +1 -1
  29. package/build/batchloaders/recursiveParentsBatchLoader.cjs +1 -1
  30. package/build/batchloaders/recursiveParentsBatchLoader.js +1 -1
  31. package/build/config.cjs +74 -1
  32. package/build/config.cjs.map +1 -1
  33. package/build/config.d.cts +83 -2
  34. package/build/config.d.cts.map +1 -1
  35. package/build/config.d.mts +83 -2
  36. package/build/config.d.mts.map +1 -1
  37. package/build/config.js +74 -1
  38. package/build/config.js.map +1 -1
  39. package/build/configure.cjs +6 -2
  40. package/build/configure.cjs.map +1 -1
  41. package/build/configure.d.cts.map +1 -1
  42. package/build/configure.d.mts.map +1 -1
  43. package/build/configure.js +6 -2
  44. package/build/configure.js.map +1 -1
  45. package/build/dataloaders/findDataLoader.cjs +1 -1
  46. package/build/dataloaders/findDataLoader.js +1 -1
  47. package/build/dataloaders/findOrCreateDataLoader.cjs +6 -2
  48. package/build/dataloaders/findOrCreateDataLoader.cjs.map +1 -1
  49. package/build/dataloaders/findOrCreateDataLoader.d.cts.map +1 -1
  50. package/build/dataloaders/findOrCreateDataLoader.d.mts.map +1 -1
  51. package/build/dataloaders/findOrCreateDataLoader.js +7 -3
  52. package/build/dataloaders/findOrCreateDataLoader.js.map +1 -1
  53. package/build/dataloaders/findPaginatedDataLoader.cjs +1 -1
  54. package/build/dataloaders/findPaginatedDataLoader.js +1 -1
  55. package/build/defaults.cjs +2 -2
  56. package/build/defaults.js +2 -2
  57. package/build/fields.cjs +1 -0
  58. package/build/fields.cjs.map +1 -1
  59. package/build/fields.d.cts.map +1 -1
  60. package/build/fields.d.mts.map +1 -1
  61. package/build/fields.js +1 -0
  62. package/build/fields.js.map +1 -1
  63. package/build/index.cjs +13 -8
  64. package/build/index.cjs.map +1 -1
  65. package/build/index.d.cts +4 -3
  66. package/build/index.d.cts.map +1 -1
  67. package/build/index.d.mts +4 -3
  68. package/build/index.d.mts.map +1 -1
  69. package/build/index.js +13 -10
  70. package/build/index.js.map +1 -1
  71. package/build/json.cjs +3 -3
  72. package/build/json.js +3 -3
  73. package/build/loading/loadHints.cjs +1 -1
  74. package/build/loading/loadHints.js +1 -1
  75. package/build/loading/withLoaded.cjs +2 -2
  76. package/build/loading/withLoaded.js +2 -2
  77. package/build/newTestInstance.cjs +1 -0
  78. package/build/newTestInstance.cjs.map +1 -1
  79. package/build/newTestInstance.d.cts.map +1 -1
  80. package/build/newTestInstance.d.mts.map +1 -1
  81. package/build/newTestInstance.js +1 -0
  82. package/build/newTestInstance.js.map +1 -1
  83. package/build/preloading/partitionHint.cjs +1 -1
  84. package/build/preloading/partitionHint.js +1 -1
  85. package/build/queries/sql/execute.cjs +68 -89
  86. package/build/queries/sql/execute.cjs.map +1 -1
  87. package/build/queries/sql/execute.d.cts +35 -18
  88. package/build/queries/sql/execute.d.cts.map +1 -1
  89. package/build/queries/sql/execute.d.mts +35 -18
  90. package/build/queries/sql/execute.d.mts.map +1 -1
  91. package/build/queries/sql/execute.js +70 -91
  92. package/build/queries/sql/execute.js.map +1 -1
  93. package/build/queries/sql/query.cjs +77 -30
  94. package/build/queries/sql/query.cjs.map +1 -1
  95. package/build/queries/sql/query.d.cts +64 -21
  96. package/build/queries/sql/query.d.cts.map +1 -1
  97. package/build/queries/sql/query.d.mts +64 -21
  98. package/build/queries/sql/query.d.mts.map +1 -1
  99. package/build/queries/sql/query.js +75 -30
  100. package/build/queries/sql/query.js.map +1 -1
  101. package/build/reactivity/ReactionsManager.cjs +168 -2
  102. package/build/reactivity/ReactionsManager.cjs.map +1 -1
  103. package/build/reactivity/ReactionsManager.d.cts +54 -1
  104. package/build/reactivity/ReactionsManager.d.cts.map +1 -1
  105. package/build/reactivity/ReactionsManager.d.mts +54 -1
  106. package/build/reactivity/ReactionsManager.d.mts.map +1 -1
  107. package/build/reactivity/ReactionsManager.js +169 -3
  108. package/build/reactivity/ReactionsManager.js.map +1 -1
  109. package/build/reactivity/reactiveHints.cjs +3 -3
  110. package/build/reactivity/reactiveHints.cjs.map +1 -1
  111. package/build/reactivity/reactiveHints.d.cts.map +1 -1
  112. package/build/reactivity/reactiveHints.d.mts.map +1 -1
  113. package/build/reactivity/reactiveHints.js +3 -3
  114. package/build/reactivity/reactiveHints.js.map +1 -1
  115. package/build/relations/AsyncReactiveField.cjs +3 -3
  116. package/build/relations/AsyncReactiveField.js +3 -3
  117. package/build/relations/LazyField.cjs +14 -0
  118. package/build/relations/LazyField.cjs.map +1 -1
  119. package/build/relations/LazyField.d.cts +6 -0
  120. package/build/relations/LazyField.d.cts.map +1 -1
  121. package/build/relations/LazyField.d.mts +6 -0
  122. package/build/relations/LazyField.d.mts.map +1 -1
  123. package/build/relations/LazyField.js +14 -0
  124. package/build/relations/LazyField.js.map +1 -1
  125. package/build/relations/ReactiveField.cjs +2 -2
  126. package/build/relations/ReactiveField.js +2 -2
  127. package/build/relations/ReactiveManyToMany.cjs +1 -1
  128. package/build/relations/ReactiveManyToMany.js +1 -1
  129. package/build/relations/ReactiveReference.cjs +1 -1
  130. package/build/relations/ReactiveReference.js +1 -1
  131. package/build/relations/RecursiveCollection.cjs +3 -3
  132. package/build/relations/RecursiveCollection.js +3 -3
  133. package/build/relations/hasProperty.cjs +2 -2
  134. package/build/relations/hasProperty.js +2 -2
  135. package/build/relations/index.cjs +5 -5
  136. package/build/relations/index.js +5 -5
  137. package/build/resurrection.cjs +11 -1
  138. package/build/resurrection.cjs.map +1 -1
  139. package/build/resurrection.d.cts +4 -1
  140. package/build/resurrection.d.cts.map +1 -1
  141. package/build/resurrection.d.mts +4 -1
  142. package/build/resurrection.d.mts.map +1 -1
  143. package/build/resurrection.js +11 -2
  144. package/build/resurrection.js.map +1 -1
  145. package/build/transitions.cjs +89 -0
  146. package/build/transitions.cjs.map +1 -0
  147. package/build/transitions.d.cts +110 -0
  148. package/build/transitions.d.cts.map +1 -0
  149. package/build/transitions.d.mts +110 -0
  150. package/build/transitions.d.mts.map +1 -0
  151. package/build/transitions.js +84 -0
  152. package/build/transitions.js.map +1 -0
  153. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"newTestInstance.js","names":[],"sources":["../src/newTestInstance.ts"],"sourcesContent":["import { isPlainObject } from \"joist-utils\";\nimport { getInstanceData } from \"src/BaseEntity.ts\";\nimport { hasDefaultValue, setAsyncDefaultsSynchronously } from \"src/defaults.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport {\n type EntityConstructor,\n type EntityManager,\n type IdOf,\n type MaybeAbstractEntityConstructor,\n isId,\n} from \"src/EntityManager.ts\";\nimport {\n type EntityMetadata,\n type ManyToManyField,\n type ManyToOneField,\n type OneToManyField,\n type OneToOneField,\n type PolymorphicField,\n type PrimitiveField,\n getBaseAndSelfMetas,\n getBaseSelfAndSubMetas,\n getMetadata,\n isManyToOneField,\n isOneToOneField,\n} from \"src/EntityMetadata.ts\";\nimport { type DeepNew, type FactoryExtrasOf, type New } from \"src/index.ts\";\nimport { FactoryLogger } from \"src/logging/FactoryLogger.ts\";\nimport { maybeRequireTemporal } from \"src/serde/temporal.ts\";\nimport { type ActualFactoryOpts, type OptsOf } from \"src/typeMap.ts\";\nimport { assertNever } from \"src/utils.ts\";\n\nlet logger: FactoryLogger | undefined = undefined;\n\n// Maybe we should scope this per-em, but assuming tests are single-threaded for now\nlet factoryCreated = new WeakSet();\n\n// The last EntityManager used in a factory call, for the `factories` proxy to resolve entities\nlet lastFactoryEm: EntityManager | undefined;\n\nconst factoryKeyRegex = /^([a-zA-Z]+)(\\d+)$/;\n\n/**\n * A proxy that allows accessing factory-created entities by their factory id.\n *\n * For example, after creating entities with `as` keys:\n *\n * ```ts\n * newAuthor(em, { books: [{ is: \"b#1\" }, { is: \"b#2\", prequel: \"b#1\" }] });\n * const { b1, b2 } = factories;\n * ```\n *\n * The proxy parses property names like `b1` into `b#1` and looks up the entity\n * in the most recently used EntityManager.\n */\nexport const factories: Record<string, any> = new Proxy(Object.create(null), {\n get(_target, prop) {\n if (typeof prop !== \"string\") return undefined;\n const match = prop.match(factoryKeyRegex);\n if (!match) throw new Error(`Invalid id '${prop}', expected 'b1' or 'a2'`);\n const [, tag, id] = match;\n if (!lastFactoryEm) throw new Error(\"No EntityManager available; call a factory like newAuthor(em) first\");\n const testId = `${tag}#${id}`;\n const entity = lastFactoryEm.entities.find((e) => getTestId(lastFactoryEm!, e) === testId);\n if (!entity) throw new Error(`No factory entity found for '${testId}'`);\n return entity;\n },\n});\n\n/**\n * DeepPartial-esque type specific to our `newTestInstance` factory.\n *\n * Specifically (vs using DeepPartial directly) this:\n *\n * 1. Adds a `use` tag of `Entity | Entity[]` that will be checked for existing\n * entities before creating new ones (i.e. \"if `newTestInstance` needs a `Book`,\n * use the one in `use` instead of making a new one).\n *\n * 2. Works specifically against the constructor/entity opts fields.\n */\nexport type FactoryOpts<T extends Entity> = DeepPartialOpts<T> & {\n is?: string;\n use?: Entity | Entity[];\n useFactoryDefaults?: boolean | \"none\";\n useExistingCheck?: boolean;\n useLogging?: boolean;\n} & {\n // We use a mapped type here with an explicit `?`, instead of just `FactoryExtrasOf<T>`,\n // so that tsc knows that `{}` is a valid default opts value.\n [K in keyof FactoryExtrasOf<T>]?: FactoryExtrasOf<T>[K];\n};\n\n// Chosen b/c it's a monday https://www.timeanddate.com/calendar/monthly.html?year=2018&month=1&country=1\nconst jan1 = new Date(2018, 0, 1);\nexport const testDate = jan1;\nconst Temporal = maybeRequireTemporal()?.Temporal;\nexport const testPlainDate = Temporal?.PlainDate.from(\"2018-01-01\");\nexport const testPlainDateTime = testPlainDate?.toPlainDateTime(\"00:00:00\");\nexport const testZonedDateTime = testPlainDate?.toZonedDateTime(\"UTC\");\n\nconst knownUseKeys = [\"is\", \"use\", \"useLogging\", \"useExistingCheck\", \"useFactoryDefaults\"];\n\n/**\n * Creates a test instance of `T`.\n *\n * If the factory code passes factoryOpts.useExisting, they can \"intercept\" the `em.create`\n * to try and resolve \"already created\" / singleton instances. The `useExisting` callback is\n * useful b/c the `opts` will be the \"resolved-to-entity\" opts, and not the raw \"maybe object\n * literal, maybe object instance\" opts that tests pass into the factory.\n */\nexport function newTestInstance<T extends Entity>(\n em: EntityManager,\n cstr: EntityConstructor<T>,\n /** The test's test-specific override opts. */\n testOpts: FactoryOpts<T> = {},\n /** The factory file's default opts. */\n factoryOpts: FactoryOpts<T> & {\n useExisting?: (opts: OptsOf<T>, existing: DeepNew<T>) => boolean;\n } = {},\n): DeepNew<T> {\n // Remember the em so the `factories` proxy can look up entities\n lastFactoryEm = em;\n\n // The first factory that is asked to debug, without one in place, will create+unset the logger.\n let ownsTheLogger = !logger && testOpts.useLogging;\n if (ownsTheLogger) logger = new FactoryLogger();\n\n logger?.logCreating(cstr);\n logger?.indent();\n\n const meta = getMetadata(cstr);\n const opts = mergeOpts(meta, testOpts, factoryOpts);\n const use = getOrCreateUseMap(opts);\n\n const selfFields: string[] = [];\n\n // Create just the primitive and m2o fields 1st, so we can create a minimal/valid\n // instance of the entity. We'll do the o2m/other fields as a second pass.\n const initialOpts = Object.values(meta.allFields)\n .map((field) => {\n const { fieldName } = field;\n\n // Don't fill in required fields if told not to\n const ignoreAllDefaults = \"useFactoryDefaults\" in opts && opts.useFactoryDefaults === \"none\";\n // If the field has a default value, don't force fill it, even if passed `author: undefined`\n const required = field.required && !ignoreAllDefaults && !hasDefaultValue(meta, fieldName);\n\n // Use the opts value if they passed one in\n if (fieldName in opts && (opts as any)[fieldName] !== defaultValueMarker) {\n const optValue = (opts as any)[fieldName];\n // We don't explicitly support null (callers should pass undefined), but we accept it\n // because the factory might have done `const { author, ... } = opts` and is accidentally\n // passing an `author: undefined` without meaning too.\n const shouldRespectUndefined = !required;\n if (optValue === null || (optValue === undefined && shouldRespectUndefined)) {\n return [];\n }\n switch (field.kind) {\n case \"m2o\":\n case \"poly\":\n return [fieldName, resolveFactoryOpt(em, opts, field, optValue, undefined, undefined)];\n case \"o2o\":\n case \"o2m\":\n case \"m2m\":\n // We do these in the 2nd pass after `entity` exists (see additionalOpts)\n return [];\n case \"m2mEnum\":\n // Enum codes have no entity identity, so pass them straight through.\n return [fieldName, optValue];\n case \"lo2m\":\n // If a child is passing themselves into a parent that is a large collection, just ignore it\n return [];\n case \"primitive\":\n case \"enum\":\n case \"primaryKey\":\n // Look for strings that want to use the test index\n if (typeof optValue === \"string\" && optValue.includes(testIndexString)) {\n const actualIndex = getTestIndex(em, meta.cstr);\n const value = optValue.replace(testIndexString, String(actualIndex));\n return [fieldName, value];\n } else if (typeof optValue === \"number\" && optValue === testIndex) {\n const actualIndex = getTestIndex(em, meta.cstr);\n return [fieldName, actualIndex];\n }\n // Otherwise just use the user's opt value as-is\n return [fieldName, optValue];\n default:\n return assertNever(field);\n }\n }\n\n if (\n field.kind === \"primitive\" &&\n (required || (opts as any)[fieldName] === defaultValueMarker) &&\n !field.derived &&\n !field.protected\n ) {\n return [fieldName, defaultValueForField(em, cstr, field)];\n } else if (field.kind === \"m2o\" && !field.derived) {\n // If neither the user nor the factory (i.e. for an explicit \"fan out\" case) set this field,\n // then look in `use` and for an \"obvious\" there-is-only-one default (even for optional fields)\n const [existing, loggerKey] = getObviousDefault(em, field.otherMetadata(), use);\n // If this is a m2o pointing to an o2o, i.e. that as a unique constraint, make sure the\n // existing entity we found isn't already claimed\n const isUniqueAndAlreadyUsed =\n existing &&\n isOneToOneField(field.otherMetadata().allFields[field.otherFieldName]) &&\n (existing as any)[field.otherFieldName].isLoaded &&\n (existing as any)[field.otherFieldName].isSet;\n if (existing && !isUniqueAndAlreadyUsed && !ignoreAllDefaults) {\n logger?.[loggerKey](fieldName, existing);\n return [fieldName, existing];\n }\n // Otherwise, only make a new entity only if the field is required\n if (required) {\n // ...unless this is a self-referential key, in which case avoid infinite looping.\n if (field.otherMetadata() === meta) {\n selfFields.push(fieldName);\n return [];\n } else {\n return [fieldName, resolveFactoryOpt(em, opts, field, undefined, undefined, undefined)];\n }\n }\n } else if (field.kind === \"enum\" && required && !field.derived) {\n return [fieldName, field.enumDetailType.getValues()[0]];\n } else if (field.kind === \"poly\" && required) {\n return [fieldName, resolveFactoryOpt(em, opts, field, undefined, undefined, undefined)];\n }\n\n return [];\n })\n .filter((t) => t.length > 0);\n\n const createOpts = Object.fromEntries(initialOpts);\n\n if (factoryOpts.useExisting && testOpts.useExistingCheck !== false) {\n const existing = em.entities\n .filter((e) => e instanceof meta.cstr)\n .find((e) => factoryOpts.useExisting!(createOpts as OptsOf<T>, e as DeepNew<T>));\n if (existing) {\n logger?.logFoundExisting(existing);\n logger?.dedent();\n if (ownsTheLogger) logger = undefined;\n return existing as DeepNew<T>;\n }\n }\n\n const entity = em.create(cstr, createOpts) as New<T>;\n\n // Verify the `as` assertion if provided\n if ((opts as any).is) {\n const expected = (opts as any).is;\n const actual = getTestId(em, entity);\n if (actual !== expected) {\n throw new Error(`Test used 'is: ${expected}' but the entity is actually ${actual}`);\n }\n }\n\n // Report this as factory-created until the next em.flush\n factoryCreated.add(entity);\n\n // If the type we just made doesn't exist in `use` yet, remember it. This works better than\n // looking at the values in `fullOpts`, because instead of waiting until the end of the\n // `build fullOpts` loop, we're also invoking `newTestInstance` as we go through the loop itself,\n // creating each test instance within nested/recursive `newTestInstance` calls.\n if (!use.has(entity.constructor) || use.get(entity.constructor)![1] === \"diffBranch\") {\n addToUseMap(use, entity, \"sameBranch\");\n } else {\n // The `addToUseMap` does its own 'created & added to scope'\n logger?.logCreated(entity);\n }\n\n // Now that we've got the entity, do a 2nd pass for o2m/m2m where we pass\n // `{ parent: entity }` down to children (i.e. to replace our original\n // null marker approach).\n const additionalOpts = Object.entries(opts).map(([fieldName, optValue]) => {\n const field = meta.allFields[fieldName];\n // Look for `use` / etc\n if (knownUseKeys.includes(fieldName)) return [];\n if (!field) {\n // Look for extra/derived fields\n if (fieldName.startsWith(\"with\")) {\n const realName = fieldName[4].toLowerCase() + fieldName.substring(5);\n const realField = meta.allFields[realName];\n if (realField && \"derived\" in realField && realField.derived === \"async\") {\n return [realName, new FactoryInitialValue(optValue)];\n }\n }\n throw new Error(`Unknown field ${fieldName}`);\n }\n if (optValue === null || optValue === undefined) return [];\n if (field.kind === \"o2m\") {\n // If this is a list of children, i.e. book.authors, handle partials to newTestInstance'd\n return [\n fieldName,\n (optValue as Array<any>).map((opt, i) => {\n // console.log(`${field.fieldName}`, i);\n return resolveFactoryOpt(em, withBranchMap(opts), field, opt, entity, i);\n }),\n ];\n } else if (field.kind == \"m2m\") {\n return [\n fieldName,\n (optValue as Array<any>).map((opt, i) =>\n resolveFactoryOpt(em, withBranchMap(opts), field, opt, [entity] as any, i),\n ),\n ];\n } else if (field.kind === \"o2o\") {\n const otherField = field.otherMetadata().allFields[field.otherFieldName];\n const isReactiveReference = \"derived\" in otherField && otherField.derived === \"async\";\n if (isReactiveReference) return [];\n // If this is an o2o, i.e. author.image, just pass the optValue (i.e. it won't be a list)\n return [fieldName, resolveFactoryOpt(em, opts, field, optValue as any, entity, undefined)];\n } else {\n return []; // Assume createOpts handled this\n }\n });\n\n for (const fieldName of selfFields) {\n additionalOpts.push([fieldName, entity]);\n }\n\n entity.set(Object.fromEntries(additionalOpts.filter((t) => t.length > 0)));\n\n // em.create applied synchronous defaults automatically; since we're a factory with likely\n // deeply-loaded instances, go ahead and synchronously invoke the async defaults, at least\n // the ones that just use load hints + a synchronous lambda.\n // (...would be nice to log these in the setFactoryLogging output)\n setAsyncDefaultsSynchronously(em.ctx, entity);\n\n // Set it back to undefined\n logger?.dedent();\n if (ownsTheLogger) logger = undefined;\n\n return entity as DeepNew<T>;\n}\n\n/**\n * Resolves a `FactoryEntityOpt` (i.e. maybe an existing entity, maybe an id, maybe a hash of opts) to an entity.\n *\n * If `opt` is `undefined`, then the usual factory semantics of \"check use\", \"look for only one instance\" are\n * checked before finally creating a brand new entity.\n *\n * We also accept an optional `otherFieldName` so that, if we do create a new entity, we pass along the null\n * marker for them to know not to create their own version of us.\n *\n * (This was originally intended to be a public API, but the use case ended up being handled\n * by the more-ergonomic `maybeNew` feature; we could explore making this public if another\n * similar use case comes up in the future.)\n */\nfunction resolveFactoryOpt<T extends Entity>(\n em: EntityManager,\n opts: FactoryOpts<any>,\n field: OneToManyField | ManyToOneField | OneToOneField | ManyToManyField | PolymorphicField,\n opt: FactoryEntityOpt<any> | undefined,\n maybeEntity: T | undefined,\n fieldIndex: number | undefined,\n): T | IdOf<T> {\n const use = getOrCreateUseMap(opts);\n const { meta, otherFieldName } = metaFromFieldAndOpt(field, opt);\n // const meta = field.kind === \"poly\" ? field.components[0].otherMetadata() : field.otherMetadata();\n // const otherFieldName = field.kind === \"poly\" ? field.components[0].otherFieldName : field.otherFieldName;\n const fieldWithIndex = `${field.fieldName}${fieldIndex !== undefined ? `[${fieldIndex}]` : \"\"}`;\n if (isEntity(opt)) {\n logger?.logFoundOpt(fieldWithIndex, opt);\n return opt as T;\n } else if (isId(opt)) {\n // Try finding the entity in the UoW, otherwise fallback on just setting it as the id (which we support that now)\n const found = (em.entities.find((e) => e.idTaggedMaybe === opt || getTestId(em, e) === opt) as T) || opt;\n logger?.logFoundOpt(fieldWithIndex, found);\n return found;\n } else if (opt && !isPlainObject(opt) && !(opt instanceof MaybeNew)) {\n // If opt isn't a POJO, assume this is a completely-custom factory\n logger?.logNotFoundAndCreating(fieldWithIndex, meta);\n return meta.factory(em, opt);\n } else {\n // Look for an obvious default\n if (opt === undefined || opt instanceof MaybeNew) {\n if (\n field.kind === \"poly\" ||\n (field.otherMetadata().subTypes.length > 0 && opt instanceof MaybeNew && opt.polyRefPreferredOrder.length > 0)\n ) {\n // We have a polymorphic maybeNew to sort through\n const [existing, loggerKey] = (opt instanceof MaybeNew\n ? opt.polyRefPreferredOrder.map((cstr) => getMetadata(cstr))\n : field.kind === \"poly\"\n ? field.components.map((c) => c.otherMetadata())\n : [meta]\n )\n .map((meta) => getObviousDefault(em, meta, use))\n .find((existing) => !!existing[0]) || [undefined, undefined];\n if (existing) {\n logger?.[loggerKey](fieldWithIndex, existing);\n return existing as T;\n }\n } else {\n // Otherwise fall though to making a new entity via the factory\n const [existing, loggerKey] = getObviousDefault(em, meta, use);\n if (existing) {\n logger?.[loggerKey](fieldWithIndex, existing);\n return existing as T;\n }\n }\n }\n // If this is image.author (m2o) but the other-side is an o2o, pass null instead of []\n maybeEntity ??= (meta.allFields[otherFieldName].kind === \"o2o\" ? null : []) as any;\n logger?.logNotFoundAndCreating(fieldWithIndex, meta);\n return meta.factory(em, {\n // Because of the `!isPlainObject` above, opt will either be undefined or an object here\n ...applyUse((opt as any) || {}, use, meta),\n ...(opt instanceof MaybeNew && opt.opts),\n [otherFieldName]: maybeEntity,\n });\n }\n}\n\n/** Determines the metadata and otherFieldName to use in resolveFactoryOpt to account for polymorphic fields */\nfunction metaFromFieldAndOpt<T extends Entity>(\n field: OneToManyField | ManyToOneField | OneToOneField | ManyToManyField | PolymorphicField,\n opt: FactoryEntityOpt<T> | undefined,\n): { meta: EntityMetadata; otherFieldName: string } {\n if (field.kind === \"poly\") {\n let componentToUse =\n // Otherwise, we check if the `opt` specifies a particular component to use, and if not fall back to the first one\n field.components.find(\n (component) =>\n opt instanceof MaybeNew &&\n getBaseSelfAndSubMetas(component.otherMetadata())\n .map((m) => m.cstr)\n .includes(opt.polyRefPreferredOrder[0]),\n ) ?? field.components[0];\n return { meta: componentToUse.otherMetadata(), otherFieldName: componentToUse.otherFieldName };\n } else if (\n field.otherMetadata().subTypes.length > 0 &&\n opt instanceof MaybeNew &&\n opt.polyRefPreferredOrder.length > 0\n ) {\n const otherMeta = field.otherMetadata();\n const types = getBaseSelfAndSubMetas(otherMeta);\n const typeToUse = types.find((subType) => subType.cstr === opt.polyRefPreferredOrder[0]) ?? otherMeta;\n return { meta: typeToUse, otherFieldName: field.otherFieldName };\n } else {\n // If it isn't a poly field, then the field itself can tell us everything we need to know\n return { meta: field.otherMetadata(), otherFieldName: field.otherFieldName };\n }\n}\n\n/** We look for `use`-cached entities, which are either those we created, or had \"if-only-one\" defaults. */\nfunction getObviousDefault<T extends Entity>(\n em: EntityManager,\n metadata: EntityMetadata,\n use: UseMap,\n): [T, \"logFoundInUseMap\" | \"logFoundSingleEntity\"] | [undefined, undefined] {\n if (use.has(metadata.cstr)) {\n return [use.get(metadata.cstr)![0] as T, \"logFoundInUseMap\"];\n }\n // If there is a single existing instance of this type, assume the caller is fine with that.\n // ...in theory seeding our `use` map with the only-one entities was supposed to prevent the\n // need for doing this (the entities would already be in the use map that we just checked),\n // but that approach doesn't catch created-as-side-effect entities.\n const existing = em.getEntities(metadata.cstr);\n if (existing.length === 1) {\n return [existing[0] as T, \"logFoundSingleEntity\"];\n }\n return [undefined, undefined];\n}\n\n// When a factory is called, i.e. `newAuthor`, opts will:\n//\n// - Have values explicitly passed by the user/other factories\n// - Have values from the user's explicit `use` parameter\n// - NOT have guessed (i.e. \"only existing entity\") or an implicitly-created `use` parameter\n//\n// This allows the factory to \"fan out\" by default, i.e. newInternalUser creating its own User\n// and Market creating its own ProductAttribute, which originally we couldn't do when\n// guessed/implicit opts were passed directly to `newAuthor`.\n//\n// Now, if the `newAuthor` factory doesn't explicitly \"fan out\" (by passing `user: {}` to\n// `newTestInstance`), we still \"fan in\" by having `newTestInstance` sneak in the guessed/implicit\n// opts of only-one-existing or factory-created instances.\n\n/** Given we're going to call a factory, make sure any `use`s are put into `opts`. */\nfunction applyUse(optsMaybeNew: object, use: UseMap, metadata: EntityMetadata): object {\n const opts = optsMaybeNew instanceof MaybeNew ? optsMaybeNew.opts : optsMaybeNew;\n // Find any unset fields\n Object.values(metadata.fields)\n .filter((f) => !(f.fieldName in opts))\n .forEach((f) => {\n // And set them to the current `use` entity for their type, if it exists\n if (((isManyToOneField(f) && !f.derived) || isOneToOneField(f)) && use.has(f.otherMetadata().cstr)) {\n const def = use.get(f.otherMetadata().cstr)!;\n // Only pass explicit/user-defined `use` entities, so that factories can \"fan out\" if they want,\n // and not see other factory-created entities look like user-specific values.\n if (def[1] === \"useOpt\") {\n (opts as any)[f.fieldName] = def[0];\n }\n }\n });\n // Make a copy so that we don't leak `use` onto opts that tests might later use in assertions.\n return { ...opts, use };\n}\n\n/**\n * A marker value for later replacement with the test instance's \"unique-ish\" index.\n *\n * This is meant to just be a helpful identifier in fields like entity names/descriptions for\n * debugging purposes.\n */\nexport const testIndex: number = -1_111_111_222;\n\nconst testIndexString = String(testIndex);\n\nconst defaultValueMarker: any = {};\nconst branchValueSym = Symbol(\"branchValue\");\n\n/**\n * A marker value for the default `newTestInstance` behavior.\n *\n * Useful for passing arguments to `newTestInstance` where you sometimes want to\n * provide a specific value, and other times ask for the \"pick a default\" behavior\n * (i.e. you don't want to pass `undefined` b/c that means explicitly \"leave this\n * key unset\").\n *\n * Note that this is a function so that we can infer the return type as basically\n * `any` without really using `any` (which would disable type-checking in the rest\n * of the expression).\n */\nexport function defaultValue<T>(): T {\n return defaultValueMarker;\n}\n\n/**\n * A marker value to never set a field, even if it's required.\n *\n * The factories treat `{ author: undefined }` as \"still set the author\", because of how easy\n * it is for destructuring/restructuring opts to implicitly set `undefined` values.\n *\n * If you want to force a field to not be set, you can use `{ author: noValue() }`.\n */\nexport function noValue<T>(): T {\n return null as T;\n}\n\n/**\n * A marker value to accept values only if explicitly created-or-passed within the current,\n * unique \"branch\" of a factory call.\n *\n * This is useful for \"diamond-shape\" entity models like:\n *\n * ```\n * ParentGroup <-- ParentItem\n * | |\n * ChildGroup <-- ChildItem\n * ```\n *\n * Where it's important that the `ChildItem -> ParentItem -> ParentGroup` path matches\n * the `ChildItem -> ChildGroup -> ParentGroup` path.\n *\n * This can be hard to achieve in normal factory behavior, i.e. for a call like:\n *\n * ```ts\n * const c = newChild(em, {\n * groups: [\n * { childItems: [{}, {}] },\n * { childItems: [{}, {}] },\n * ],\n * });\n * ```\n *\n * The first `ChildGroup` will create a new `ParentGroup` that is used by everything, which\n * is not our intent, as both `ChildGroup`s, and all four `ParentItem`s, will live in a single\n * `ParentGroup`.\n *\n * An initial idea is to pass `parentGroup: {}` in the factories, because that turns off \"reusing\n * existing instances\", but for this problem the `{}` approach is \"too good\" at creating new\n * instances, b/c the above diamond pattern will be disconnected.\n *\n * So `branchValue` provides a middle ground, where _usually_ it will be a new entity, unless\n * it was explicitly created within the same \"branch\" of a factory call.\n */\nexport function maybeBranchValue<T>(opts?: ActualFactoryOpts<T>): T {\n // opts get mutated, so we have to return a new value\n return { [branchValueSym]: true, ...(opts ? opts : undefined) } as any;\n}\n\n/**\n * Allows a factory to declare that an optional relation should be filled in with an\n * \"obvious default\", or a new entity if one doesn't exist.\n *\n * This \"obvious default or new entity\" is what Joist already does for _required_ relations,\n * and so `maybeNew` lets the factory tell Joist to apply the same behavior to an optional\n * field.\n *\n * I.e.:\n *\n * ```typescript\n * export function newAuthor(em: Entity, opts: FactoryOpts<Author>) {\n * return newTestInstance(em, Author, {\n * // this always make a new publisher, unless explicitly overridden by the test,\n * // i.e. when each author really needs \"their own\" publisher.\n * publisher: {},\n * // this will make a new publisher but first looks for \"good defaults\" in the\n * // test, i.e. an already-created publisher. This is the default behavior of\n * // required fields (\"look for a good default\"), and `maybeNew` lets you tell\n * // Joist to invoke that same \"maybe new\" behavior for an optional field.\n * publisher: maybeNew<Publisher>({}),\n * ...opts,\n * });\n * }\n * ```\n */\nexport function maybeNew<T extends Entity>(opts?: ActualFactoryOpts<T>): FactoryEntityOpt<T> {\n // Return a marker that resolveFactoryOpt will look for\n return new MaybeNew<T>((opts || {}) as any) as any;\n}\n\n/**\n * Similar to `maybeNew` in behaviour/use but with enhancements to support polymorphic fields:\n * 1) Allows you to specify which entity type to create, if it is found a new one is needed\n * 2) Allows you to prioritize which existing entities to select\n *\n * For example below, we are specifying that an Author should be created if needed (and optionally it's default opts\n * in the `ifNewOpts` field), and also that the priority order for choosing existing entities is Author, Book, and then Publisher.\n * Note since BookReview is excluded from `existingSearchOrder`, an existing BookReview will never be chosen.\n *\n * ```typescript\n * export function newComment(em: EntityManager, opts: FactoryOpts<Comment> = {}): New<Comment> {\n * return newTestInstance(em, Comment, {\n * parent: maybeNewPoly<CommentParent, Author>(\n * Author, {\n * ifNewOpts: { firstName: \"optional\"},\n * existingSearchOrder: [Author, Book, Publisher]\n * }),\n * ...opts,\n * });\n * }\n * ```\n */\nexport function maybeNewPoly<T extends Entity, NewT extends T = T>(\n ifNewCstr: EntityConstructor<NewT>,\n opts?: {\n ifNewOpts?: ActualFactoryOpts<NewT>;\n existingSearchOrder?: MaybeAbstractEntityConstructor<T>[];\n },\n): FactoryEntityOpt<NewT> {\n // Return a marker that resolveFactoryOpt will look for\n return new MaybeNew<T>((opts?.ifNewOpts || {}) as any, opts?.existingSearchOrder ?? [ifNewCstr]) as any;\n}\n\nclass MaybeNew<T extends Entity> {\n constructor(\n public opts: FactoryOpts<T>,\n public polyRefPreferredOrder: MaybeAbstractEntityConstructor<T>[] = [],\n ) {}\n}\n\n/**\n * Returns a unique-ish test index for putting in `name` fields.\n *\n * Note that `testIndex` is easier to just include in a string, because it doesn't require passing\n * the `EntityManger` and `type`. But if a factory really wants the test index as a number, they can\n * call this method.\n *\n * Despite the name, these are 1-based, i.e. the first `Author` is `a1`.\n */\nexport function getTestIndex<T extends Entity>(em: EntityManager, type: MaybeAbstractEntityConstructor<T>): number {\n const existing = em.getEntities(type);\n return existing.length + 1;\n}\n\n/** Returns the stable `a#1` factory id for em.create-d entities, using the createId assigned at creation time. */\nfunction getTestId<T extends Entity>(em: EntityManager, entity: T): string | undefined {\n const meta = getMetadata(entity);\n const createId = getInstanceData(entity).createId;\n return createId ? `${meta.tagName}#${createId}` : undefined;\n}\n\n// We keep a local copy of `global.Date`, in case a faking library\n// like @sinonjs/fake-timers is used and rewrites `global.Date` to\n// their own `ClockDate`, which would make our `===` check below fail.\nconst globalDate = global.Date;\n\nfunction defaultValueForField(em: EntityManager, cstr: EntityConstructor<any>, field: PrimitiveField): unknown {\n if (field.serde.columns[0].isArray) return [];\n if (field.type === \"string\") {\n if (field.fieldName === \"name\") {\n return `${cstr.name} ${getTestIndex(em, cstr)}`;\n }\n return field.fieldName;\n } else if (field.type === \"number\") {\n return 0;\n } else if (field.type === \"bigint\") {\n return 0n;\n } else if (field.type === globalDate) {\n return testDate;\n } else if (field.type === \"boolean\") {\n return false;\n } else if (field.type === \"Object\") {\n // A required jsonb column, i.e. so factories can satisfy a required (possibly `lazy`) column.\n return {};\n } else if (Temporal) {\n if (field.type === Temporal.PlainDate) {\n return testPlainDate;\n } else if (field.type === Temporal.PlainDateTime) {\n return testPlainDateTime;\n } else if (field.type === Temporal.ZonedDateTime) {\n return testZonedDateTime;\n }\n }\n\n return null;\n}\n\n// Utility type to destructure T out of T | undefined\ntype DefinedOr<T> = T | undefined | null;\n\ntype DeepPartialOpts<T extends Entity> = AllowRelationsOrPartials<OptsOf<T>>;\n\n/** What a factory can accept for a given entity. */\nexport type FactoryEntityOpt<T extends Entity> =\n | T\n // The ability to use an id, like `newAuthor(em, { publisher: \"p:1\" })` is not necessarily\n // on purpose, but the AuthorOpts already have `publisher: Publisher | PublisherId` in them,\n // so `newTestInstance` has to handle this typing anyway, unless we explicitly go out of our\n // way to remove the `PublisherId` from the Opts type.\n | IdOf<T>\n | (ActualFactoryOpts<T> & { useFactoryDefaults?: boolean | \"none\" });\n\ntype AllowRelationsOrPartials<T> = {\n [P in keyof T]?: T[P] extends DefinedOr<infer U>\n ? U extends Array<infer V>\n ? V extends Entity\n ? Array<FactoryEntityOpt<V>>\n : T[P]\n : U extends Entity\n ? FactoryEntityOpt<U>\n : T[P]\n : T[P];\n};\n\n// Map of constructor --> [\n// default entity,\n// | \"testOpts\" === explicitly passed into the top-level `newFactory` that creates the UseMap\n// | \"useOpt\" === explicitly passed in as a `use` flag\n// | \"diffBranch\" == created internally within the current factory call, but a different branch of children\n// | \"sameBranch\" === created internally within the current factory call, in the current branch of entities\n// ]\nexport type UseMapSource = \"testOpts\" | \"useOpt\" | \"sameBranch\" | \"diffBranch\";\ntype UseMapValue = [Entity, UseMapSource];\ntype UseMap = Map<Function, UseMapValue>;\n\n// Do a one-time conversion of the user's `use` array into a map for internal use, which we'll\n// then re-use across all `newTestInstance` calls within a given `new<Entity>` call.\nfunction getOrCreateUseMap(opts: FactoryOpts<any>): UseMap {\n const use: Entity | Entity[] | UseMap | undefined = opts.use;\n let map: UseMap;\n\n if (use instanceof Map) {\n // it's already a map\n map = use;\n } else {\n map = new Map();\n if (use instanceof Array) {\n // it's a top-level `newAuthor` with a user-passed `use: array`\n use.forEach((e) => addToUseMap(map, e, \"useOpt\"));\n } else if (use) {\n // it's a top-level `newAuthor` w/o a `use: entity` param\n addToUseMap(map, use, \"useOpt\");\n }\n // Scan opts for entities to add to the map, i.e. if the user calls `newAuthor(em, { book: b1 })`,\n // we'll use `b1` for any other books we might happen to create.\n const todo = [opts];\n while (todo.length > 0) {\n const opts = todo.pop();\n for (const opt of Object.values(opts || {})) {\n if (isEntity(opt) && !map.has(opt.constructor)) {\n addToUseMap(map, opt, \"testOpts\");\n } else if (opt instanceof Array) {\n // Push the array as-is, because it will be `Object.value`-d on the next iteration\n todo.push(opt);\n } else if (isPlainObject(opt)) {\n todo.push(opt);\n }\n }\n }\n }\n // Store our potentially-massaged map back into opts i.e. in case resolveFactoryOpt needs it.\n // Use as any b/c UseMap is our internal impl detail and not public.\n (opts as any).use = map;\n return map;\n}\n\n// If e is a subtype like SmallPublisher, register it for the base Publisher as well\nfunction addToUseMap(map: UseMap, e: Entity, source: UseMapSource) {\n logger?.logAddToUseMap(e, source);\n const meta = getMetadata(e);\n if (meta.baseType || meta.subTypes.length) {\n getBaseAndSelfMetas(meta).forEach((m) => {\n // console.log(`Putting ${e.toString()} into ${objectId(map)} as ${source}`);\n map.set(m.cstr, [e, source]);\n });\n } else {\n // console.log(`Putting ${e.toString()} into ${objectId(map)} as ${source}`);\n map.set(meta.cstr, [e, source]);\n }\n}\n\n/** Merge the factory's opts and the test's opts so that `{ age: 40 }` and `{ firstName: \"b1\" }` get merged. */\nfunction mergeOpts(meta: EntityMetadata, testOpts: Record<string, any>, factoryOpts: Record<string, any>): object {\n // Merge the factory's opts and the test's opts so that `{ age: 40 }` and `{ firstName: \"b1\" }` get merged\n if (testOpts.useFactoryDefaults === false || testOpts.useFactoryDefaults === \"none\") {\n return testOpts;\n }\n\n const opts: any = { ...testOpts };\n Object.entries(factoryOpts).forEach(([key, factoryValue]) => {\n // Skip special opts\n if (key === \"useExisting\") return;\n const testValue = testOpts[key];\n if (testOpts[key] === undefined) {\n // If the test doesn't define an opt, we have nothing to merge...unless\n // they literally passed `foo: undefined`, in which case they win.\n if (!(key in testOpts)) {\n opts[key] = factoryValue;\n }\n } else if (isPlainObject(factoryValue) && isPlainObject(testValue)) {\n // Should this deep merge? Probably?\n opts[key] = mergeOpts(meta, testValue, factoryValue);\n } else if (factoryValue instanceof MaybeNew && isPlainObject(testValue)) {\n opts[key] = mergeOpts(meta, testValue, factoryValue.opts);\n } else if (factoryValue instanceof MaybeNew && testValue instanceof MaybeNew) {\n opts[key] = new MaybeNew<any>(\n mergeOpts(meta, testValue.opts, factoryValue.opts),\n testValue.polyRefPreferredOrder ?? factoryValue.polyRefPreferredOrder,\n );\n }\n // This seemed like a good idea\n if (opts[key]?.[branchValueSym]) {\n const field = meta.allFields[key];\n if (field.kind === \"m2o\") {\n const use = testOpts.use as UseMap;\n const inTree = use?.get(field.otherMetadata().cstr);\n if (inTree && (inTree[1] === \"sameBranch\" || inTree[1] === \"testOpts\")) {\n // console.log(`Putting ${field.fieldName} to`, inTree[0]);\n opts[key] = inTree[0];\n }\n } else {\n throw new Error(`branchValue is not implemented for ${field.kind}`);\n }\n delete opts[key]?.[branchValueSym];\n }\n });\n return opts;\n}\n\n// As we branch out to children, going down the tree, give each branch its own playground of entities\nfunction withBranchMap(opts: object): object {\n const oldMap = (opts as any).use;\n const newMap = new CopyMap(oldMap);\n return { ...opts, use: newMap };\n}\n\n/** Writes new entities into our branch's map (this map), as well as the root we came from. */\nclass CopyMap extends Map<Function, UseMapValue> {\n constructor(private readonly root: UseMap) {\n super(root);\n }\n set(k: Function, v: UseMapValue): this {\n // Purposefully downgrade this to source=diffBranch so that it will not be used by `branchValue()`\n // calls that override `{}`, but can still be used to in-fan, i.e. if making multiple books by\n // default they get the same author.\n // ...also use `root?` because the `super(root)` will call `set` while copying the other map\n // but our `this.root` has not been set yet; which is fine, we want to ignore those anyway.\n this.root?.set(k, [v[0], \"diffBranch\"]);\n return super.set(k, v);\n }\n}\n\n// const objectId = (() => {\n// let currentId = 0;\n// const map = new WeakMap();\n// return (object: object): number => {\n// if (!map.has(object)) {\n// map.set(object, ++currentId);\n// }\n// return map.get(object)!;\n// };\n// })();\n/** Enables factory logging for all factories. */\nexport function setFactoryLogging(enabled: boolean): void {\n logger = enabled ? new FactoryLogger() : undefined;\n}\n\n/** Marker for tests setting derived values during test setup. */\nexport class FactoryInitialValue {\n constructor(public readonly value: any) {}\n}\n\nexport function isFactoryCreation(entity: Entity): boolean {\n return factoryCreated.has(entity);\n}\n\nexport function resetFactoryCreated(): void {\n factoryCreated = new WeakSet<Entity>();\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,IAAI,SAAoC,KAAA;AAGxC,IAAI,iCAAiB,IAAI,QAAQ;AAGjC,IAAI;AAEJ,MAAM,kBAAkB;;;;;;;;;;;;;;AAexB,MAAa,YAAiC,IAAI,MAAM,OAAO,OAAO,IAAI,GAAG,EAC3E,IAAI,SAAS,MAAM;CACjB,IAAI,OAAO,SAAS,UAAU,OAAO,KAAA;CACrC,MAAM,QAAQ,KAAK,MAAM,eAAe;CACxC,IAAI,CAAC,OAAO,MAAM,IAAI,MAAM,eAAe,KAAK,yBAAyB;CACzE,MAAM,GAAG,KAAK,MAAM;CACpB,IAAI,CAAC,eAAe,MAAM,IAAI,MAAM,qEAAqE;CACzG,MAAM,SAAS,GAAG,IAAI,GAAG;CACzB,MAAM,SAAS,cAAc,SAAS,MAAM,MAAM,UAAU,eAAgB,CAAC,MAAM,MAAM;CACzF,IAAI,CAAC,QAAQ,MAAM,IAAI,MAAM,gCAAgC,OAAO,EAAE;CACtE,OAAO;AACT,EACF,CAAC;AA2BD,MAAa,WAAW,IADP,KAAK,MAAM,GAAG,CACP;AACxB,MAAM,WAAW,qBAAqB,CAAC,EAAE;AACzC,MAAa,gBAAgB,UAAU,UAAU,KAAK,YAAY;AAClE,MAAa,oBAAoB,eAAe,gBAAgB,UAAU;AAC1E,MAAa,oBAAoB,eAAe,gBAAgB,KAAK;AAErE,MAAM,eAAe;CAAC;CAAM;CAAO;CAAc;CAAoB;AAAoB;;;;;;;;;AAUzF,SAAgB,gBACd,IACA,MAEA,WAA2B,CAAC,GAE5B,cAEI,CA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AAA,OAAA;CAE7B;CACA,IAAI,GAAa,GAAsB;EAMrC,KAAK,MAAM,IAAI,GAAG,CAAC,EAAE,IAAI,YAAY,CAAC;EACtC,OAAO,MAAM,IAAI,GAAG,CAAC;CACvB;AACF;;AAaA,SAAgB,kBAAkB,SAAwB;CACxD,SAAS,UAAU,IAAI,cAAc,IAAI,KAAA;AAC3C;;AAGA,IAAa,sBAAb,MAAiC;CACH;CAA5B,YAAY,OAA4B;EAAZ,KAAA,QAAA;CAAa;AAC3C;AAEA,SAAgB,kBAAkB,QAAyB;CACzD,OAAO,eAAe,IAAI,MAAM;AAClC;AAEA,SAAgB,sBAA4B;CAC1C,iCAAiB,IAAI,QAAgB;AACvC"}
1
+ {"version":3,"file":"newTestInstance.js","names":[],"sources":["../src/newTestInstance.ts"],"sourcesContent":["import { isPlainObject } from \"joist-utils\";\nimport { getInstanceData } from \"src/BaseEntity.ts\";\nimport { hasDefaultValue, setAsyncDefaultsSynchronously } from \"src/defaults.ts\";\nimport { type Entity, isEntity } from \"src/Entity.ts\";\nimport {\n type EntityConstructor,\n type EntityManager,\n type IdOf,\n type MaybeAbstractEntityConstructor,\n isId,\n} from \"src/EntityManager.ts\";\nimport {\n type EntityMetadata,\n type ManyToManyField,\n type ManyToOneField,\n type OneToManyField,\n type OneToOneField,\n type PolymorphicField,\n type PrimitiveField,\n getBaseAndSelfMetas,\n getBaseSelfAndSubMetas,\n getMetadata,\n isManyToOneField,\n isOneToOneField,\n} from \"src/EntityMetadata.ts\";\nimport { type DeepNew, type FactoryExtrasOf, type New } from \"src/index.ts\";\nimport { FactoryLogger } from \"src/logging/FactoryLogger.ts\";\nimport { maybeRequireTemporal } from \"src/serde/temporal.ts\";\nimport { type ActualFactoryOpts, type OptsOf } from \"src/typeMap.ts\";\nimport { assertNever } from \"src/utils.ts\";\n\nlet logger: FactoryLogger | undefined = undefined;\n\n// Maybe we should scope this per-em, but assuming tests are single-threaded for now\nlet factoryCreated = new WeakSet();\n\n// The last EntityManager used in a factory call, for the `factories` proxy to resolve entities\nlet lastFactoryEm: EntityManager | undefined;\n\nconst factoryKeyRegex = /^([a-zA-Z]+)(\\d+)$/;\n\n/**\n * A proxy that allows accessing factory-created entities by their factory id.\n *\n * For example, after creating entities with `as` keys:\n *\n * ```ts\n * newAuthor(em, { books: [{ is: \"b#1\" }, { is: \"b#2\", prequel: \"b#1\" }] });\n * const { b1, b2 } = factories;\n * ```\n *\n * The proxy parses property names like `b1` into `b#1` and looks up the entity\n * in the most recently used EntityManager.\n */\nexport const factories: Record<string, any> = new Proxy(Object.create(null), {\n get(_target, prop) {\n if (typeof prop !== \"string\") return undefined;\n const match = prop.match(factoryKeyRegex);\n if (!match) throw new Error(`Invalid id '${prop}', expected 'b1' or 'a2'`);\n const [, tag, id] = match;\n if (!lastFactoryEm) throw new Error(\"No EntityManager available; call a factory like newAuthor(em) first\");\n const testId = `${tag}#${id}`;\n const entity = lastFactoryEm.entities.find((e) => getTestId(lastFactoryEm!, e) === testId);\n if (!entity) throw new Error(`No factory entity found for '${testId}'`);\n return entity;\n },\n});\n\n/**\n * DeepPartial-esque type specific to our `newTestInstance` factory.\n *\n * Specifically (vs using DeepPartial directly) this:\n *\n * 1. Adds a `use` tag of `Entity | Entity[]` that will be checked for existing\n * entities before creating new ones (i.e. \"if `newTestInstance` needs a `Book`,\n * use the one in `use` instead of making a new one).\n *\n * 2. Works specifically against the constructor/entity opts fields.\n */\nexport type FactoryOpts<T extends Entity> = DeepPartialOpts<T> & {\n is?: string;\n use?: Entity | Entity[];\n useFactoryDefaults?: boolean | \"none\";\n useExistingCheck?: boolean;\n useLogging?: boolean;\n} & {\n // We use a mapped type here with an explicit `?`, instead of just `FactoryExtrasOf<T>`,\n // so that tsc knows that `{}` is a valid default opts value.\n [K in keyof FactoryExtrasOf<T>]?: FactoryExtrasOf<T>[K];\n};\n\n// Chosen b/c it's a monday https://www.timeanddate.com/calendar/monthly.html?year=2018&month=1&country=1\nconst jan1 = new Date(2018, 0, 1);\nexport const testDate = jan1;\nconst Temporal = maybeRequireTemporal()?.Temporal;\nexport const testPlainDate = Temporal?.PlainDate.from(\"2018-01-01\");\nexport const testPlainDateTime = testPlainDate?.toPlainDateTime(\"00:00:00\");\nexport const testZonedDateTime = testPlainDate?.toZonedDateTime(\"UTC\");\n\nconst knownUseKeys = [\"is\", \"use\", \"useLogging\", \"useExistingCheck\", \"useFactoryDefaults\"];\n\n/**\n * Creates a test instance of `T`.\n *\n * If the factory code passes factoryOpts.useExisting, they can \"intercept\" the `em.create`\n * to try and resolve \"already created\" / singleton instances. The `useExisting` callback is\n * useful b/c the `opts` will be the \"resolved-to-entity\" opts, and not the raw \"maybe object\n * literal, maybe object instance\" opts that tests pass into the factory.\n */\nexport function newTestInstance<T extends Entity>(\n em: EntityManager,\n cstr: EntityConstructor<T>,\n /** The test's test-specific override opts. */\n testOpts: FactoryOpts<T> = {},\n /** The factory file's default opts. */\n factoryOpts: FactoryOpts<T> & {\n useExisting?: (opts: OptsOf<T>, existing: DeepNew<T>) => boolean;\n } = {},\n): DeepNew<T> {\n // Remember the em so the `factories` proxy can look up entities\n lastFactoryEm = em;\n\n // The first factory that is asked to debug, without one in place, will create+unset the logger.\n let ownsTheLogger = !logger && testOpts.useLogging;\n if (ownsTheLogger) logger = new FactoryLogger();\n\n logger?.logCreating(cstr);\n logger?.indent();\n\n const meta = getMetadata(cstr);\n const opts = mergeOpts(meta, testOpts, factoryOpts);\n const use = getOrCreateUseMap(opts);\n\n const selfFields: string[] = [];\n\n // Create just the primitive and m2o fields 1st, so we can create a minimal/valid\n // instance of the entity. We'll do the o2m/other fields as a second pass.\n const initialOpts = Object.values(meta.allFields)\n .map((field) => {\n const { fieldName } = field;\n\n // Don't fill in required fields if told not to\n const ignoreAllDefaults = \"useFactoryDefaults\" in opts && opts.useFactoryDefaults === \"none\";\n // If the field has a default value, don't force fill it, even if passed `author: undefined`\n const required = field.required && !ignoreAllDefaults && !hasDefaultValue(meta, fieldName);\n\n // Use the opts value if they passed one in\n if (fieldName in opts && (opts as any)[fieldName] !== defaultValueMarker) {\n const optValue = (opts as any)[fieldName];\n // We don't explicitly support null (callers should pass undefined), but we accept it\n // because the factory might have done `const { author, ... } = opts` and is accidentally\n // passing an `author: undefined` without meaning too.\n const shouldRespectUndefined = !required;\n if (optValue === null || (optValue === undefined && shouldRespectUndefined)) {\n return [];\n }\n switch (field.kind) {\n case \"m2o\":\n case \"poly\":\n return [fieldName, resolveFactoryOpt(em, opts, field, optValue, undefined, undefined)];\n case \"o2o\":\n case \"o2m\":\n case \"m2m\":\n // We do these in the 2nd pass after `entity` exists (see additionalOpts)\n return [];\n case \"m2mEnum\":\n // Enum codes have no entity identity, so pass them straight through.\n return [fieldName, optValue];\n case \"lo2m\":\n // If a child is passing themselves into a parent that is a large collection, just ignore it\n return [];\n case \"primitive\":\n case \"enum\":\n case \"primaryKey\":\n // Look for strings that want to use the test index\n if (typeof optValue === \"string\" && optValue.includes(testIndexString)) {\n const actualIndex = getTestIndex(em, meta.cstr);\n const value = optValue.replace(testIndexString, String(actualIndex));\n return [fieldName, value];\n } else if (typeof optValue === \"number\" && optValue === testIndex) {\n const actualIndex = getTestIndex(em, meta.cstr);\n return [fieldName, actualIndex];\n }\n // Otherwise just use the user's opt value as-is\n return [fieldName, optValue];\n default:\n return assertNever(field);\n }\n }\n\n if (\n field.kind === \"primitive\" &&\n (required || (opts as any)[fieldName] === defaultValueMarker) &&\n !field.derived &&\n !field.protected\n ) {\n return [fieldName, defaultValueForField(em, cstr, field)];\n } else if (field.kind === \"m2o\" && !field.derived) {\n // If neither the user nor the factory (i.e. for an explicit \"fan out\" case) set this field,\n // then look in `use` and for an \"obvious\" there-is-only-one default (even for optional fields)\n const [existing, loggerKey] = getObviousDefault(em, field.otherMetadata(), use);\n // If this is a m2o pointing to an o2o, i.e. that as a unique constraint, make sure the\n // existing entity we found isn't already claimed\n const isUniqueAndAlreadyUsed =\n existing &&\n isOneToOneField(field.otherMetadata().allFields[field.otherFieldName]) &&\n (existing as any)[field.otherFieldName].isLoaded &&\n (existing as any)[field.otherFieldName].isSet;\n if (existing && !isUniqueAndAlreadyUsed && !ignoreAllDefaults) {\n logger?.[loggerKey](fieldName, existing);\n return [fieldName, existing];\n }\n // Otherwise, only make a new entity only if the field is required\n if (required) {\n // ...unless this is a self-referential key, in which case avoid infinite looping.\n if (field.otherMetadata() === meta) {\n selfFields.push(fieldName);\n return [];\n } else {\n return [fieldName, resolveFactoryOpt(em, opts, field, undefined, undefined, undefined)];\n }\n }\n } else if (field.kind === \"enum\" && required && !field.derived) {\n return [fieldName, field.enumDetailType.getValues()[0]];\n } else if (field.kind === \"poly\" && required) {\n return [fieldName, resolveFactoryOpt(em, opts, field, undefined, undefined, undefined)];\n }\n\n return [];\n })\n .filter((t) => t.length > 0);\n\n const createOpts = Object.fromEntries(initialOpts);\n\n if (factoryOpts.useExisting && testOpts.useExistingCheck !== false) {\n const existing = em.entities\n .filter((e) => e instanceof meta.cstr)\n .find((e) => factoryOpts.useExisting!(createOpts as OptsOf<T>, e as DeepNew<T>));\n if (existing) {\n logger?.logFoundExisting(existing);\n logger?.dedent();\n if (ownsTheLogger) logger = undefined;\n return existing as DeepNew<T>;\n }\n }\n\n const entity = em.create(cstr, createOpts) as New<T>;\n\n // Verify the `as` assertion if provided\n if ((opts as any).is) {\n const expected = (opts as any).is;\n const actual = getTestId(em, entity);\n if (actual !== expected) {\n throw new Error(`Test used 'is: ${expected}' but the entity is actually ${actual}`);\n }\n }\n\n // Report this as factory-created until the next em.flush\n factoryCreated.add(entity);\n\n // If the type we just made doesn't exist in `use` yet, remember it. This works better than\n // looking at the values in `fullOpts`, because instead of waiting until the end of the\n // `build fullOpts` loop, we're also invoking `newTestInstance` as we go through the loop itself,\n // creating each test instance within nested/recursive `newTestInstance` calls.\n if (!use.has(entity.constructor) || use.get(entity.constructor)![1] === \"diffBranch\") {\n addToUseMap(use, entity, \"sameBranch\");\n } else {\n // The `addToUseMap` does its own 'created & added to scope'\n logger?.logCreated(entity);\n }\n\n // Now that we've got the entity, do a 2nd pass for o2m/m2m where we pass\n // `{ parent: entity }` down to children (i.e. to replace our original\n // null marker approach).\n const additionalOpts = Object.entries(opts).map(([fieldName, optValue]) => {\n const field = meta.allFields[fieldName];\n // Look for `use` / etc\n if (knownUseKeys.includes(fieldName)) return [];\n if (!field) {\n // Look for extra/derived fields\n if (fieldName.startsWith(\"with\")) {\n const realName = fieldName[4].toLowerCase() + fieldName.substring(5);\n const realField = meta.allFields[realName];\n if (realField && \"derived\" in realField && realField.derived === \"async\") {\n return [realName, new FactoryInitialValue(optValue)];\n }\n // Fields with `config.transitions`/`onTransition`s accept a trusted created value, like ReactiveFields\n if (realField?.kind === \"enum\" && meta.transitions!.has(realName)) {\n return [realName, new FactoryInitialValue(optValue)];\n }\n }\n throw new Error(`Unknown field ${fieldName}`);\n }\n if (optValue === null || optValue === undefined) return [];\n if (field.kind === \"o2m\") {\n // If this is a list of children, i.e. book.authors, handle partials to newTestInstance'd\n return [\n fieldName,\n (optValue as Array<any>).map((opt, i) => {\n // console.log(`${field.fieldName}`, i);\n return resolveFactoryOpt(em, withBranchMap(opts), field, opt, entity, i);\n }),\n ];\n } else if (field.kind == \"m2m\") {\n return [\n fieldName,\n (optValue as Array<any>).map((opt, i) =>\n resolveFactoryOpt(em, withBranchMap(opts), field, opt, [entity] as any, i),\n ),\n ];\n } else if (field.kind === \"o2o\") {\n const otherField = field.otherMetadata().allFields[field.otherFieldName];\n const isReactiveReference = \"derived\" in otherField && otherField.derived === \"async\";\n if (isReactiveReference) return [];\n // If this is an o2o, i.e. author.image, just pass the optValue (i.e. it won't be a list)\n return [fieldName, resolveFactoryOpt(em, opts, field, optValue as any, entity, undefined)];\n } else {\n return []; // Assume createOpts handled this\n }\n });\n\n for (const fieldName of selfFields) {\n additionalOpts.push([fieldName, entity]);\n }\n\n entity.set(Object.fromEntries(additionalOpts.filter((t) => t.length > 0)));\n\n // em.create applied synchronous defaults automatically; since we're a factory with likely\n // deeply-loaded instances, go ahead and synchronously invoke the async defaults, at least\n // the ones that just use load hints + a synchronous lambda.\n // (...would be nice to log these in the setFactoryLogging output)\n setAsyncDefaultsSynchronously(em.ctx, entity);\n\n // Set it back to undefined\n logger?.dedent();\n if (ownsTheLogger) logger = undefined;\n\n return entity as DeepNew<T>;\n}\n\n/**\n * Resolves a `FactoryEntityOpt` (i.e. maybe an existing entity, maybe an id, maybe a hash of opts) to an entity.\n *\n * If `opt` is `undefined`, then the usual factory semantics of \"check use\", \"look for only one instance\" are\n * checked before finally creating a brand new entity.\n *\n * We also accept an optional `otherFieldName` so that, if we do create a new entity, we pass along the null\n * marker for them to know not to create their own version of us.\n *\n * (This was originally intended to be a public API, but the use case ended up being handled\n * by the more-ergonomic `maybeNew` feature; we could explore making this public if another\n * similar use case comes up in the future.)\n */\nfunction resolveFactoryOpt<T extends Entity>(\n em: EntityManager,\n opts: FactoryOpts<any>,\n field: OneToManyField | ManyToOneField | OneToOneField | ManyToManyField | PolymorphicField,\n opt: FactoryEntityOpt<any> | undefined,\n maybeEntity: T | undefined,\n fieldIndex: number | undefined,\n): T | IdOf<T> {\n const use = getOrCreateUseMap(opts);\n const { meta, otherFieldName } = metaFromFieldAndOpt(field, opt);\n // const meta = field.kind === \"poly\" ? field.components[0].otherMetadata() : field.otherMetadata();\n // const otherFieldName = field.kind === \"poly\" ? field.components[0].otherFieldName : field.otherFieldName;\n const fieldWithIndex = `${field.fieldName}${fieldIndex !== undefined ? `[${fieldIndex}]` : \"\"}`;\n if (isEntity(opt)) {\n logger?.logFoundOpt(fieldWithIndex, opt);\n return opt as T;\n } else if (isId(opt)) {\n // Try finding the entity in the UoW, otherwise fallback on just setting it as the id (which we support that now)\n const found = (em.entities.find((e) => e.idTaggedMaybe === opt || getTestId(em, e) === opt) as T) || opt;\n logger?.logFoundOpt(fieldWithIndex, found);\n return found;\n } else if (opt && !isPlainObject(opt) && !(opt instanceof MaybeNew)) {\n // If opt isn't a POJO, assume this is a completely-custom factory\n logger?.logNotFoundAndCreating(fieldWithIndex, meta);\n return meta.factory(em, opt);\n } else {\n // Look for an obvious default\n if (opt === undefined || opt instanceof MaybeNew) {\n if (\n field.kind === \"poly\" ||\n (field.otherMetadata().subTypes.length > 0 && opt instanceof MaybeNew && opt.polyRefPreferredOrder.length > 0)\n ) {\n // We have a polymorphic maybeNew to sort through\n const [existing, loggerKey] = (opt instanceof MaybeNew\n ? opt.polyRefPreferredOrder.map((cstr) => getMetadata(cstr))\n : field.kind === \"poly\"\n ? field.components.map((c) => c.otherMetadata())\n : [meta]\n )\n .map((meta) => getObviousDefault(em, meta, use))\n .find((existing) => !!existing[0]) || [undefined, undefined];\n if (existing) {\n logger?.[loggerKey](fieldWithIndex, existing);\n return existing as T;\n }\n } else {\n // Otherwise fall though to making a new entity via the factory\n const [existing, loggerKey] = getObviousDefault(em, meta, use);\n if (existing) {\n logger?.[loggerKey](fieldWithIndex, existing);\n return existing as T;\n }\n }\n }\n // If this is image.author (m2o) but the other-side is an o2o, pass null instead of []\n maybeEntity ??= (meta.allFields[otherFieldName].kind === \"o2o\" ? null : []) as any;\n logger?.logNotFoundAndCreating(fieldWithIndex, meta);\n return meta.factory(em, {\n // Because of the `!isPlainObject` above, opt will either be undefined or an object here\n ...applyUse((opt as any) || {}, use, meta),\n ...(opt instanceof MaybeNew && opt.opts),\n [otherFieldName]: maybeEntity,\n });\n }\n}\n\n/** Determines the metadata and otherFieldName to use in resolveFactoryOpt to account for polymorphic fields */\nfunction metaFromFieldAndOpt<T extends Entity>(\n field: OneToManyField | ManyToOneField | OneToOneField | ManyToManyField | PolymorphicField,\n opt: FactoryEntityOpt<T> | undefined,\n): { meta: EntityMetadata; otherFieldName: string } {\n if (field.kind === \"poly\") {\n let componentToUse =\n // Otherwise, we check if the `opt` specifies a particular component to use, and if not fall back to the first one\n field.components.find(\n (component) =>\n opt instanceof MaybeNew &&\n getBaseSelfAndSubMetas(component.otherMetadata())\n .map((m) => m.cstr)\n .includes(opt.polyRefPreferredOrder[0]),\n ) ?? field.components[0];\n return { meta: componentToUse.otherMetadata(), otherFieldName: componentToUse.otherFieldName };\n } else if (\n field.otherMetadata().subTypes.length > 0 &&\n opt instanceof MaybeNew &&\n opt.polyRefPreferredOrder.length > 0\n ) {\n const otherMeta = field.otherMetadata();\n const types = getBaseSelfAndSubMetas(otherMeta);\n const typeToUse = types.find((subType) => subType.cstr === opt.polyRefPreferredOrder[0]) ?? otherMeta;\n return { meta: typeToUse, otherFieldName: field.otherFieldName };\n } else {\n // If it isn't a poly field, then the field itself can tell us everything we need to know\n return { meta: field.otherMetadata(), otherFieldName: field.otherFieldName };\n }\n}\n\n/** We look for `use`-cached entities, which are either those we created, or had \"if-only-one\" defaults. */\nfunction getObviousDefault<T extends Entity>(\n em: EntityManager,\n metadata: EntityMetadata,\n use: UseMap,\n): [T, \"logFoundInUseMap\" | \"logFoundSingleEntity\"] | [undefined, undefined] {\n if (use.has(metadata.cstr)) {\n return [use.get(metadata.cstr)![0] as T, \"logFoundInUseMap\"];\n }\n // If there is a single existing instance of this type, assume the caller is fine with that.\n // ...in theory seeding our `use` map with the only-one entities was supposed to prevent the\n // need for doing this (the entities would already be in the use map that we just checked),\n // but that approach doesn't catch created-as-side-effect entities.\n const existing = em.getEntities(metadata.cstr);\n if (existing.length === 1) {\n return [existing[0] as T, \"logFoundSingleEntity\"];\n }\n return [undefined, undefined];\n}\n\n// When a factory is called, i.e. `newAuthor`, opts will:\n//\n// - Have values explicitly passed by the user/other factories\n// - Have values from the user's explicit `use` parameter\n// - NOT have guessed (i.e. \"only existing entity\") or an implicitly-created `use` parameter\n//\n// This allows the factory to \"fan out\" by default, i.e. newInternalUser creating its own User\n// and Market creating its own ProductAttribute, which originally we couldn't do when\n// guessed/implicit opts were passed directly to `newAuthor`.\n//\n// Now, if the `newAuthor` factory doesn't explicitly \"fan out\" (by passing `user: {}` to\n// `newTestInstance`), we still \"fan in\" by having `newTestInstance` sneak in the guessed/implicit\n// opts of only-one-existing or factory-created instances.\n\n/** Given we're going to call a factory, make sure any `use`s are put into `opts`. */\nfunction applyUse(optsMaybeNew: object, use: UseMap, metadata: EntityMetadata): object {\n const opts = optsMaybeNew instanceof MaybeNew ? optsMaybeNew.opts : optsMaybeNew;\n // Find any unset fields\n Object.values(metadata.fields)\n .filter((f) => !(f.fieldName in opts))\n .forEach((f) => {\n // And set them to the current `use` entity for their type, if it exists\n if (((isManyToOneField(f) && !f.derived) || isOneToOneField(f)) && use.has(f.otherMetadata().cstr)) {\n const def = use.get(f.otherMetadata().cstr)!;\n // Only pass explicit/user-defined `use` entities, so that factories can \"fan out\" if they want,\n // and not see other factory-created entities look like user-specific values.\n if (def[1] === \"useOpt\") {\n (opts as any)[f.fieldName] = def[0];\n }\n }\n });\n // Make a copy so that we don't leak `use` onto opts that tests might later use in assertions.\n return { ...opts, use };\n}\n\n/**\n * A marker value for later replacement with the test instance's \"unique-ish\" index.\n *\n * This is meant to just be a helpful identifier in fields like entity names/descriptions for\n * debugging purposes.\n */\nexport const testIndex: number = -1_111_111_222;\n\nconst testIndexString = String(testIndex);\n\nconst defaultValueMarker: any = {};\nconst branchValueSym = Symbol(\"branchValue\");\n\n/**\n * A marker value for the default `newTestInstance` behavior.\n *\n * Useful for passing arguments to `newTestInstance` where you sometimes want to\n * provide a specific value, and other times ask for the \"pick a default\" behavior\n * (i.e. you don't want to pass `undefined` b/c that means explicitly \"leave this\n * key unset\").\n *\n * Note that this is a function so that we can infer the return type as basically\n * `any` without really using `any` (which would disable type-checking in the rest\n * of the expression).\n */\nexport function defaultValue<T>(): T {\n return defaultValueMarker;\n}\n\n/**\n * A marker value to never set a field, even if it's required.\n *\n * The factories treat `{ author: undefined }` as \"still set the author\", because of how easy\n * it is for destructuring/restructuring opts to implicitly set `undefined` values.\n *\n * If you want to force a field to not be set, you can use `{ author: noValue() }`.\n */\nexport function noValue<T>(): T {\n return null as T;\n}\n\n/**\n * A marker value to accept values only if explicitly created-or-passed within the current,\n * unique \"branch\" of a factory call.\n *\n * This is useful for \"diamond-shape\" entity models like:\n *\n * ```\n * ParentGroup <-- ParentItem\n * | |\n * ChildGroup <-- ChildItem\n * ```\n *\n * Where it's important that the `ChildItem -> ParentItem -> ParentGroup` path matches\n * the `ChildItem -> ChildGroup -> ParentGroup` path.\n *\n * This can be hard to achieve in normal factory behavior, i.e. for a call like:\n *\n * ```ts\n * const c = newChild(em, {\n * groups: [\n * { childItems: [{}, {}] },\n * { childItems: [{}, {}] },\n * ],\n * });\n * ```\n *\n * The first `ChildGroup` will create a new `ParentGroup` that is used by everything, which\n * is not our intent, as both `ChildGroup`s, and all four `ParentItem`s, will live in a single\n * `ParentGroup`.\n *\n * An initial idea is to pass `parentGroup: {}` in the factories, because that turns off \"reusing\n * existing instances\", but for this problem the `{}` approach is \"too good\" at creating new\n * instances, b/c the above diamond pattern will be disconnected.\n *\n * So `branchValue` provides a middle ground, where _usually_ it will be a new entity, unless\n * it was explicitly created within the same \"branch\" of a factory call.\n */\nexport function maybeBranchValue<T>(opts?: ActualFactoryOpts<T>): T {\n // opts get mutated, so we have to return a new value\n return { [branchValueSym]: true, ...(opts ? opts : undefined) } as any;\n}\n\n/**\n * Allows a factory to declare that an optional relation should be filled in with an\n * \"obvious default\", or a new entity if one doesn't exist.\n *\n * This \"obvious default or new entity\" is what Joist already does for _required_ relations,\n * and so `maybeNew` lets the factory tell Joist to apply the same behavior to an optional\n * field.\n *\n * I.e.:\n *\n * ```typescript\n * export function newAuthor(em: Entity, opts: FactoryOpts<Author>) {\n * return newTestInstance(em, Author, {\n * // this always make a new publisher, unless explicitly overridden by the test,\n * // i.e. when each author really needs \"their own\" publisher.\n * publisher: {},\n * // this will make a new publisher but first looks for \"good defaults\" in the\n * // test, i.e. an already-created publisher. This is the default behavior of\n * // required fields (\"look for a good default\"), and `maybeNew` lets you tell\n * // Joist to invoke that same \"maybe new\" behavior for an optional field.\n * publisher: maybeNew<Publisher>({}),\n * ...opts,\n * });\n * }\n * ```\n */\nexport function maybeNew<T extends Entity>(opts?: ActualFactoryOpts<T>): FactoryEntityOpt<T> {\n // Return a marker that resolveFactoryOpt will look for\n return new MaybeNew<T>((opts || {}) as any) as any;\n}\n\n/**\n * Similar to `maybeNew` in behaviour/use but with enhancements to support polymorphic fields:\n * 1) Allows you to specify which entity type to create, if it is found a new one is needed\n * 2) Allows you to prioritize which existing entities to select\n *\n * For example below, we are specifying that an Author should be created if needed (and optionally it's default opts\n * in the `ifNewOpts` field), and also that the priority order for choosing existing entities is Author, Book, and then Publisher.\n * Note since BookReview is excluded from `existingSearchOrder`, an existing BookReview will never be chosen.\n *\n * ```typescript\n * export function newComment(em: EntityManager, opts: FactoryOpts<Comment> = {}): New<Comment> {\n * return newTestInstance(em, Comment, {\n * parent: maybeNewPoly<CommentParent, Author>(\n * Author, {\n * ifNewOpts: { firstName: \"optional\"},\n * existingSearchOrder: [Author, Book, Publisher]\n * }),\n * ...opts,\n * });\n * }\n * ```\n */\nexport function maybeNewPoly<T extends Entity, NewT extends T = T>(\n ifNewCstr: EntityConstructor<NewT>,\n opts?: {\n ifNewOpts?: ActualFactoryOpts<NewT>;\n existingSearchOrder?: MaybeAbstractEntityConstructor<T>[];\n },\n): FactoryEntityOpt<NewT> {\n // Return a marker that resolveFactoryOpt will look for\n return new MaybeNew<T>((opts?.ifNewOpts || {}) as any, opts?.existingSearchOrder ?? [ifNewCstr]) as any;\n}\n\nclass MaybeNew<T extends Entity> {\n constructor(\n public opts: FactoryOpts<T>,\n public polyRefPreferredOrder: MaybeAbstractEntityConstructor<T>[] = [],\n ) {}\n}\n\n/**\n * Returns a unique-ish test index for putting in `name` fields.\n *\n * Note that `testIndex` is easier to just include in a string, because it doesn't require passing\n * the `EntityManger` and `type`. But if a factory really wants the test index as a number, they can\n * call this method.\n *\n * Despite the name, these are 1-based, i.e. the first `Author` is `a1`.\n */\nexport function getTestIndex<T extends Entity>(em: EntityManager, type: MaybeAbstractEntityConstructor<T>): number {\n const existing = em.getEntities(type);\n return existing.length + 1;\n}\n\n/** Returns the stable `a#1` factory id for em.create-d entities, using the createId assigned at creation time. */\nfunction getTestId<T extends Entity>(em: EntityManager, entity: T): string | undefined {\n const meta = getMetadata(entity);\n const createId = getInstanceData(entity).createId;\n return createId ? `${meta.tagName}#${createId}` : undefined;\n}\n\n// We keep a local copy of `global.Date`, in case a faking library\n// like @sinonjs/fake-timers is used and rewrites `global.Date` to\n// their own `ClockDate`, which would make our `===` check below fail.\nconst globalDate = global.Date;\n\nfunction defaultValueForField(em: EntityManager, cstr: EntityConstructor<any>, field: PrimitiveField): unknown {\n if (field.serde.columns[0].isArray) return [];\n if (field.type === \"string\") {\n if (field.fieldName === \"name\") {\n return `${cstr.name} ${getTestIndex(em, cstr)}`;\n }\n return field.fieldName;\n } else if (field.type === \"number\") {\n return 0;\n } else if (field.type === \"bigint\") {\n return 0n;\n } else if (field.type === globalDate) {\n return testDate;\n } else if (field.type === \"boolean\") {\n return false;\n } else if (field.type === \"Object\") {\n // A required jsonb column, i.e. so factories can satisfy a required (possibly `lazy`) column.\n return {};\n } else if (Temporal) {\n if (field.type === Temporal.PlainDate) {\n return testPlainDate;\n } else if (field.type === Temporal.PlainDateTime) {\n return testPlainDateTime;\n } else if (field.type === Temporal.ZonedDateTime) {\n return testZonedDateTime;\n }\n }\n\n return null;\n}\n\n// Utility type to destructure T out of T | undefined\ntype DefinedOr<T> = T | undefined | null;\n\ntype DeepPartialOpts<T extends Entity> = AllowRelationsOrPartials<OptsOf<T>>;\n\n/** What a factory can accept for a given entity. */\nexport type FactoryEntityOpt<T extends Entity> =\n | T\n // The ability to use an id, like `newAuthor(em, { publisher: \"p:1\" })` is not necessarily\n // on purpose, but the AuthorOpts already have `publisher: Publisher | PublisherId` in them,\n // so `newTestInstance` has to handle this typing anyway, unless we explicitly go out of our\n // way to remove the `PublisherId` from the Opts type.\n | IdOf<T>\n | (ActualFactoryOpts<T> & { useFactoryDefaults?: boolean | \"none\" });\n\ntype AllowRelationsOrPartials<T> = {\n [P in keyof T]?: T[P] extends DefinedOr<infer U>\n ? U extends Array<infer V>\n ? V extends Entity\n ? Array<FactoryEntityOpt<V>>\n : T[P]\n : U extends Entity\n ? FactoryEntityOpt<U>\n : T[P]\n : T[P];\n};\n\n// Map of constructor --> [\n// default entity,\n// | \"testOpts\" === explicitly passed into the top-level `newFactory` that creates the UseMap\n// | \"useOpt\" === explicitly passed in as a `use` flag\n// | \"diffBranch\" == created internally within the current factory call, but a different branch of children\n// | \"sameBranch\" === created internally within the current factory call, in the current branch of entities\n// ]\nexport type UseMapSource = \"testOpts\" | \"useOpt\" | \"sameBranch\" | \"diffBranch\";\ntype UseMapValue = [Entity, UseMapSource];\ntype UseMap = Map<Function, UseMapValue>;\n\n// Do a one-time conversion of the user's `use` array into a map for internal use, which we'll\n// then re-use across all `newTestInstance` calls within a given `new<Entity>` call.\nfunction getOrCreateUseMap(opts: FactoryOpts<any>): UseMap {\n const use: Entity | Entity[] | UseMap | undefined = opts.use;\n let map: UseMap;\n\n if (use instanceof Map) {\n // it's already a map\n map = use;\n } else {\n map = new Map();\n if (use instanceof Array) {\n // it's a top-level `newAuthor` with a user-passed `use: array`\n use.forEach((e) => addToUseMap(map, e, \"useOpt\"));\n } else if (use) {\n // it's a top-level `newAuthor` w/o a `use: entity` param\n addToUseMap(map, use, \"useOpt\");\n }\n // Scan opts for entities to add to the map, i.e. if the user calls `newAuthor(em, { book: b1 })`,\n // we'll use `b1` for any other books we might happen to create.\n const todo = [opts];\n while (todo.length > 0) {\n const opts = todo.pop();\n for (const opt of Object.values(opts || {})) {\n if (isEntity(opt) && !map.has(opt.constructor)) {\n addToUseMap(map, opt, \"testOpts\");\n } else if (opt instanceof Array) {\n // Push the array as-is, because it will be `Object.value`-d on the next iteration\n todo.push(opt);\n } else if (isPlainObject(opt)) {\n todo.push(opt);\n }\n }\n }\n }\n // Store our potentially-massaged map back into opts i.e. in case resolveFactoryOpt needs it.\n // Use as any b/c UseMap is our internal impl detail and not public.\n (opts as any).use = map;\n return map;\n}\n\n// If e is a subtype like SmallPublisher, register it for the base Publisher as well\nfunction addToUseMap(map: UseMap, e: Entity, source: UseMapSource) {\n logger?.logAddToUseMap(e, source);\n const meta = getMetadata(e);\n if (meta.baseType || meta.subTypes.length) {\n getBaseAndSelfMetas(meta).forEach((m) => {\n // console.log(`Putting ${e.toString()} into ${objectId(map)} as ${source}`);\n map.set(m.cstr, [e, source]);\n });\n } else {\n // console.log(`Putting ${e.toString()} into ${objectId(map)} as ${source}`);\n map.set(meta.cstr, [e, source]);\n }\n}\n\n/** Merge the factory's opts and the test's opts so that `{ age: 40 }` and `{ firstName: \"b1\" }` get merged. */\nfunction mergeOpts(meta: EntityMetadata, testOpts: Record<string, any>, factoryOpts: Record<string, any>): object {\n // Merge the factory's opts and the test's opts so that `{ age: 40 }` and `{ firstName: \"b1\" }` get merged\n if (testOpts.useFactoryDefaults === false || testOpts.useFactoryDefaults === \"none\") {\n return testOpts;\n }\n\n const opts: any = { ...testOpts };\n Object.entries(factoryOpts).forEach(([key, factoryValue]) => {\n // Skip special opts\n if (key === \"useExisting\") return;\n const testValue = testOpts[key];\n if (testOpts[key] === undefined) {\n // If the test doesn't define an opt, we have nothing to merge...unless\n // they literally passed `foo: undefined`, in which case they win.\n if (!(key in testOpts)) {\n opts[key] = factoryValue;\n }\n } else if (isPlainObject(factoryValue) && isPlainObject(testValue)) {\n // Should this deep merge? Probably?\n opts[key] = mergeOpts(meta, testValue, factoryValue);\n } else if (factoryValue instanceof MaybeNew && isPlainObject(testValue)) {\n opts[key] = mergeOpts(meta, testValue, factoryValue.opts);\n } else if (factoryValue instanceof MaybeNew && testValue instanceof MaybeNew) {\n opts[key] = new MaybeNew<any>(\n mergeOpts(meta, testValue.opts, factoryValue.opts),\n testValue.polyRefPreferredOrder ?? factoryValue.polyRefPreferredOrder,\n );\n }\n // This seemed like a good idea\n if (opts[key]?.[branchValueSym]) {\n const field = meta.allFields[key];\n if (field.kind === \"m2o\") {\n const use = testOpts.use as UseMap;\n const inTree = use?.get(field.otherMetadata().cstr);\n if (inTree && (inTree[1] === \"sameBranch\" || inTree[1] === \"testOpts\")) {\n // console.log(`Putting ${field.fieldName} to`, inTree[0]);\n opts[key] = inTree[0];\n }\n } else {\n throw new Error(`branchValue is not implemented for ${field.kind}`);\n }\n delete opts[key]?.[branchValueSym];\n }\n });\n return opts;\n}\n\n// As we branch out to children, going down the tree, give each branch its own playground of entities\nfunction withBranchMap(opts: object): object {\n const oldMap = (opts as any).use;\n const newMap = new CopyMap(oldMap);\n return { ...opts, use: newMap };\n}\n\n/** Writes new entities into our branch's map (this map), as well as the root we came from. */\nclass CopyMap extends Map<Function, UseMapValue> {\n constructor(private readonly root: UseMap) {\n super(root);\n }\n set(k: Function, v: UseMapValue): this {\n // Purposefully downgrade this to source=diffBranch so that it will not be used by `branchValue()`\n // calls that override `{}`, but can still be used to in-fan, i.e. if making multiple books by\n // default they get the same author.\n // ...also use `root?` because the `super(root)` will call `set` while copying the other map\n // but our `this.root` has not been set yet; which is fine, we want to ignore those anyway.\n this.root?.set(k, [v[0], \"diffBranch\"]);\n return super.set(k, v);\n }\n}\n\n// const objectId = (() => {\n// let currentId = 0;\n// const map = new WeakMap();\n// return (object: object): number => {\n// if (!map.has(object)) {\n// map.set(object, ++currentId);\n// }\n// return map.get(object)!;\n// };\n// })();\n/** Enables factory logging for all factories. */\nexport function setFactoryLogging(enabled: boolean): void {\n logger = enabled ? new FactoryLogger() : undefined;\n}\n\n/** Marker for tests setting derived values during test setup. */\nexport class FactoryInitialValue {\n constructor(public readonly value: any) {}\n}\n\nexport function isFactoryCreation(entity: Entity): boolean {\n return factoryCreated.has(entity);\n}\n\nexport function resetFactoryCreated(): void {\n factoryCreated = new WeakSet<Entity>();\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,IAAI,SAAoC,KAAA;AAGxC,IAAI,iCAAiB,IAAI,QAAQ;AAGjC,IAAI;AAEJ,MAAM,kBAAkB;;;;;;;;;;;;;;AAexB,MAAa,YAAiC,IAAI,MAAM,OA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C;AAEA,SAAgB,kBAAkB,QAAyB;CACzD,OAAO,eAAe,IAAI,MAAM;AAClC;AAEA,SAAgB,sBAA4B;CAC1C,iCAAiB,IAAI,QAAgB;AACvC"}
@@ -1,8 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_normalizeHints = require("../normalizeHints.cjs");
3
2
  const require_relations_ReactiveReference = require("../relations/ReactiveReference.cjs");
4
3
  require("../relations/index.cjs");
5
4
  const require_getProperties = require("../getProperties.cjs");
5
+ const require_normalizeHints = require("../normalizeHints.cjs");
6
6
  require("../EntityMetadata.cjs");
7
7
  const require_preloading_canPreload = require("./canPreload.cjs");
8
8
  //#region src/preloading/partitionHint.ts
@@ -1,7 +1,7 @@
1
- import { deepNormalizeHint, normalizeHint } from "../normalizeHints.js";
2
1
  import { ReactiveReferenceImpl } from "../relations/ReactiveReference.js";
3
2
  import "../relations/index.js";
4
3
  import { getProperties } from "../getProperties.js";
4
+ import { deepNormalizeHint, normalizeHint } from "../normalizeHints.js";
5
5
  import "../EntityMetadata.js";
6
6
  import { canPreload } from "./canPreload.js";
7
7
  //#region src/preloading/partitionHint.ts
@@ -23,7 +23,7 @@ function isMutation(arg) {
23
23
  * An undefined plan represents a validated standalone empty VALUES array, not DEFAULT VALUES.
24
24
  */
25
25
  function parseStatement(arg) {
26
- if (!isMutation(arg)) return require_queries_sql_query.parseUserQuery(arg);
26
+ if (!isMutation(arg)) return require_queries_sql_query.parseRootQuery(arg);
27
27
  const statement = arg;
28
28
  const roots = [
29
29
  "insert",
@@ -32,7 +32,7 @@ function parseStatement(arg) {
32
32
  ].filter((key) => key in statement);
33
33
  if (roots.length !== 1) require_utils.fail("A mutation requires exactly one insert, update, or delete root");
34
34
  const operation = roots[0];
35
- checkPojo(statement, operation === "insert" ? [
35
+ const allowed = operation === "insert" ? [
36
36
  "insert",
37
37
  "values",
38
38
  "from",
@@ -46,28 +46,26 @@ function parseStatement(arg) {
46
46
  "returning",
47
47
  "with",
48
48
  ...operation === "update" ? ["set"] : []
49
- ], `SQL ${operation}`);
50
- const target = statement[operation];
51
- if (!require_queries_sql_Tables.isTable(target)) require_utils.fail("A mutation target must be a table");
52
- const mgmt = require_queries_sql_Tables.getTableMgmt(target);
53
- const meta = require_queries_sql_Tables.isEntityTable(target) ? require_queries_sql_Tables.getTableMgmt(target).meta : void 0;
54
- const custom = require_queries_sql_Tables.isCustomTable(target) ? require_queries_sql_Tables.getTableMgmt(target) : void 0;
49
+ ];
50
+ require_queries_sql_query.checkPojoKeys(statement, allowed, `SQL ${operation}`);
51
+ const target = mutationTarget(statement[operation]);
52
+ const { meta } = target;
55
53
  if (meta) {
56
54
  if (meta.inheritanceType || meta.baseType || meta.baseTypes.length || meta.subTypes.length) require_utils.fail("SQL mutations do not support CTI/STI targets or inherited table families");
57
55
  if (meta.supportsEmExecute !== true) require_utils.fail(`SQL mutations require supported physical metadata for ${meta.type}; run codegen`);
58
- for (const field of Object.values(meta.columns)) requireColumnMetadata(meta, field);
56
+ for (const column of Object.values(meta.columns)) requireColumnMetadata(target, column);
59
57
  } else if (statement.softDeletes !== void 0) require_utils.fail("Custom table mutations do not support softDeletes");
60
- const fields = Object.entries(meta?.columns ?? custom.columns);
58
+ const fields = Object.entries(target.columns);
61
59
  const assigner = new require_queries_sql_AliasAssigner.AliasAssigner();
62
60
  const withCtx = new require_queries_sql_query.Ctx(assigner, void 0);
63
61
  const ctes = require_queries_sql_query.registerCtes(statement, withCtx, assigner);
64
62
  const refs = [];
65
63
  const ctx = new require_queries_sql_query.Ctx(assigner, withCtx);
66
- const alias = assigner.getAlias(mgmt.tableName);
67
- ctx.register(mgmt, alias);
64
+ const alias = assigner.getAlias(target.mgmt.tableName);
65
+ ctx.register(target.mgmt, alias);
68
66
  const returning = statement.returning === void 0 ? void 0 : require_queries_sql_query.projectionToSql(statement.returning, ctx);
69
67
  if (returning) for (const select of returning.selects) refs.push(...select.refs);
70
- let sql = `${operation === "delete" ? "DELETE FROM" : operation.toUpperCase() + (operation === "insert" ? " INTO" : "")} ${require_queries_sql_Tables.tableSqlName(mgmt)} AS ${require_queries_sql_keywords.kq(alias)}`;
68
+ let sql = `${operation === "delete" ? "DELETE FROM" : operation.toUpperCase() + (operation === "insert" ? " INTO" : "")} ${require_queries_sql_Tables.tableSqlName(target.mgmt)} AS ${require_queries_sql_keywords.kq(alias)}`;
71
69
  const bindings = [];
72
70
  if (operation === "insert") {
73
71
  if ("values" in statement === "from" in statement) require_utils.fail("INSERT requires exactly one of values or from");
@@ -76,8 +74,8 @@ function parseStatement(arg) {
76
74
  if (!Array.isArray(statement.values)) require_utils.fail("INSERT values must be an array of field POJOs");
77
75
  const rows = statement.values;
78
76
  const valuesCtx = new require_queries_sql_query.Ctx(assigner, withCtx);
79
- const entries = rows.map((row) => meta ? assignments(meta, row, "insert") : customAssignments(custom, row, "insert"));
80
- for (const row of entries) for (const [key] of required) if (!row.some((entry) => entry[0] === key)) require_utils.fail(`INSERT requires ${meta?.type ?? custom.tableName}.${key}`);
77
+ const entries = rows.map((row) => assignments(target, row, "insert"));
78
+ for (const row of entries) for (const [key] of required) if (!row.some((entry) => entry[0] === key)) require_utils.fail(`INSERT requires ${target.name}.${key}`);
81
79
  if (rows.length === 0) return void 0;
82
80
  const keys = fields.filter(([key]) => entries.some((row) => row.some((entry) => entry[0] === key))).map(([key, field]) => [key, field.columnName]);
83
81
  sql += ` (${keys.map(([, column]) => require_queries_sql_keywords.kq(column)).join(", ")}) VALUES `;
@@ -85,7 +83,7 @@ function parseStatement(arg) {
85
83
  return `(${keys.map(([key]) => {
86
84
  const entry = row.find((entry) => entry[0] === key);
87
85
  if (!entry) return "DEFAULT";
88
- const cell = meta ? assignmentToSql(meta, writableField(meta, key, "insert"), entry[1], valuesCtx) : customAssignmentToSql(custom, customWritableField(custom, key, "insert"), entry[1], valuesCtx);
86
+ const cell = assignmentToSql(target, writableField(target, key, "insert"), entry[1], valuesCtx);
89
87
  bindings.push(...cell.bindings);
90
88
  refs.push(...cell.refs);
91
89
  return cell.sql;
@@ -95,13 +93,13 @@ function parseStatement(arg) {
95
93
  const source = require_queries_sql_query.parseNestedQuery(statement.from, withCtx, assigner);
96
94
  if (source.output.kind !== "pojo") require_utils.fail("INSERT SELECT requires named POJO output columns");
97
95
  const columns = source.output.columns;
98
- for (const [key] of required) if (!columns.some((column) => column[0] === key)) require_utils.fail(`INSERT requires ${meta?.type ?? custom.tableName}.${key}`);
96
+ for (const [key] of required) if (!columns.some((column) => column[0] === key)) require_utils.fail(`INSERT requires ${target.name}.${key}`);
99
97
  for (const [key, expr] of columns) {
100
- const field = meta ? writableField(meta, key, "insert") : customWritableField(custom, key, "insert");
98
+ const field = writableField(target, key, "insert");
101
99
  const left = field.outputType;
102
100
  const right = expr.outputType;
103
- if (!left || !right || left.dbType !== right.dbType || left.domain !== right.domain || left.idMeta !== right.idMeta) require_utils.fail(`INSERT SELECT ${meta?.type ?? custom.tableName}.${key} has incompatible or unknown storage codecs`);
104
- if (!field.sqlNullable && expr.sqlNullable === true) require_utils.fail(`INSERT SELECT ${meta?.type ?? custom.tableName}.${key} cannot accept a nullable output`);
101
+ if (!left || !right || left.dbType !== right.dbType || left.domain !== right.domain || left.idMeta !== right.idMeta) require_utils.fail(`INSERT SELECT ${target.name}.${key} has incompatible or unknown storage codecs`);
102
+ if (!field.sqlNullable && expr.sqlNullable === true) require_utils.fail(`INSERT SELECT ${target.name}.${key} cannot accept a nullable output`);
105
103
  }
106
104
  const keys = fields.filter(([key]) => columns.some((column) => column[0] === key)).map(([key, field]) => [key, field.columnName]);
107
105
  const sourceAlias = require_queries_sql_keywords.safeKq(assigner.getLiteralAlias("sq"));
@@ -115,11 +113,11 @@ function parseStatement(arg) {
115
113
  const whereCondition = mutationCondition(statement.where, ctx);
116
114
  if (Object.hasOwn(statement, "where") && !whereCondition && statement.allowAll !== true) require_utils.fail("UPDATE and DELETE require allowAll: true when a supplied where is undefined or fully pruned");
117
115
  if (operation === "update") {
118
- const entries = meta ? assignments(meta, statement.set, "update") : customAssignments(custom, statement.set, "update");
116
+ const entries = assignments(target, statement.set, "update");
119
117
  sql += " SET " + entries.map((entry) => {
120
118
  const [key, value] = entry;
121
- const field = meta ? writableField(meta, key, "update") : customWritableField(custom, key, "update");
122
- const cell = meta ? assignmentToSql(meta, field, value, ctx) : customAssignmentToSql(custom, field, value, ctx);
119
+ const field = writableField(target, key, "update");
120
+ const cell = assignmentToSql(target, field, value, ctx);
123
121
  bindings.push(...cell.bindings);
124
122
  refs.push(...cell.refs);
125
123
  return `${require_queries_sql_keywords.kq(field.columnName)} = ${cell.sql}`;
@@ -141,15 +139,10 @@ function parseStatement(arg) {
141
139
  sql += ` RETURNING ${returning.selects.map((select) => select.sql).join(", ")}`;
142
140
  for (const select of returning.selects) bindings.push(...select.bindings);
143
141
  }
144
- const keptCtes = require_queries_sql_query.pruneCtes(ctes, new Set(refs));
145
- if (keptCtes.length > 0) {
146
- const clause = require_queries_sql_query.withFragment(keptCtes);
147
- sql = clause.sql + sql;
148
- bindings.unshift(...clause.bindings);
149
- }
142
+ const withCtes = require_queries_sql_query.prependCtes(ctes, new Set(refs), sql, bindings);
150
143
  return {
151
- sql,
152
- bindings,
144
+ sql: withCtes.sql,
145
+ bindings: withCtes.bindings,
153
146
  outerRefs: [],
154
147
  output: returning?.output ?? {
155
148
  kind: "pojo",
@@ -166,55 +159,66 @@ function decodeStatementResult(em, plan, result) {
166
159
  rows: plan.decodeRows(em, result.rows)
167
160
  };
168
161
  }
162
+ /** Reads the writable columns from either kind of table handle, so the compiler has one target shape. */
163
+ function mutationTarget(target) {
164
+ if (require_queries_sql_Tables.isEntityTable(target)) {
165
+ const mgmt = require_queries_sql_Tables.getTableMgmt(target);
166
+ return {
167
+ mgmt,
168
+ name: mgmt.meta.type,
169
+ columns: mgmt.meta.columns,
170
+ meta: mgmt.meta
171
+ };
172
+ }
173
+ if (require_queries_sql_Tables.isCustomTable(target)) {
174
+ const mgmt = require_queries_sql_Tables.getTableMgmt(target);
175
+ return {
176
+ mgmt,
177
+ name: mgmt.tableName,
178
+ columns: mgmt.columns,
179
+ meta: void 0
180
+ };
181
+ }
182
+ return require_utils.fail("A mutation target must be a table");
183
+ }
169
184
  /** SQL mutations require complete physical metadata. */
170
- function requireColumnMetadata(meta, column) {
171
- if (typeof column.sqlNullable !== "boolean" || typeof column.hasDefault !== "boolean" || typeof column.isGenerated !== "boolean") require_utils.fail(`Missing physical metadata for ${meta.type}.${column.columnName}; run codegen`);
185
+ function requireColumnMetadata(target, column) {
186
+ if (typeof column.sqlNullable !== "boolean" || typeof column.hasDefault !== "boolean" || typeof column.isGenerated !== "boolean") require_utils.fail(`Missing physical metadata for ${target.name}.${column.columnName}; run codegen`);
172
187
  }
173
188
  /** Validates every supplied key, including undefined fields, before pruning omitted values. */
174
- function assignments(meta, value, operation) {
189
+ function assignments(target, value, operation) {
175
190
  if (!value || typeof value !== "object" || Array.isArray(value) || require_queries_sql_Expr.isExpr(value) || require_Entity.isEntity(value)) require_utils.fail(`${operation} assignments must be a field POJO`);
176
191
  const entries = Object.entries(value);
177
- for (const [key] of entries) writableField(meta, key, operation);
178
- checkPojo(value, Object.keys(meta.columns), `${operation} assignments`);
192
+ for (const [key] of entries) writableField(target, key, operation);
193
+ require_queries_sql_query.checkPojoKeys(value, Object.keys(target.columns), `${operation} assignments`);
179
194
  const defined = entries.filter((entry) => entry[1] !== void 0);
180
195
  if (!defined.length) require_utils.fail(`${operation} requires at least one defined field; empty rows/sets are not DEFAULT VALUES`);
181
196
  return defined;
182
197
  }
183
- /** Validates assignment keys against a custom table's declared writable columns. */
184
- function customAssignments(table, value, operation) {
185
- if (!value || typeof value !== "object" || Array.isArray(value) || require_queries_sql_Expr.isExpr(value) || require_Entity.isEntity(value)) require_utils.fail(`${operation} assignments must be a field POJO`);
186
- const entries = Object.entries(value);
187
- for (const [key] of entries) customWritableField(table, key, operation);
188
- checkPojo(value, Object.keys(table.columns), `${operation} assignments`);
189
- const defined = entries.filter((entry) => entry[1] !== void 0);
190
- if (!defined.length) require_utils.fail(`${operation} requires at least one defined field; empty rows/sets are not DEFAULT VALUES`);
191
- return defined;
192
- }
193
- /** Applies physical write restrictions declared by `declareTable`. */
194
- function customWritableField(table, key, operation) {
195
- const column = Object.hasOwn(table.columns, key) ? table.columns[key] : void 0;
196
- if (!column) require_utils.fail(`Unsupported SQL mutation field ${table.tableName}.${key}`);
197
- if (operation === "update" ? !column.update : column.insert === "never") require_utils.fail(`Unsupported SQL mutation field ${table.tableName}.${key}`);
198
- return column;
199
- }
200
- /** Applies physical write restrictions, not ORM-derived, protected, or business-immutable flags. */
201
- function writableField(meta, key, operation) {
202
- const column = Object.hasOwn(meta.columns, key) ? meta.columns[key] : void 0;
203
- if (!column) require_utils.fail(`Unsupported SQL mutation field ${meta.type}.${key}`);
204
- requireColumnMetadata(meta, column);
205
- if (operation === "update" && key === "id") require_utils.fail("UPDATE primary-key assignments are not supported");
206
- if (column.isGenerated) require_utils.fail(`Generated field ${meta.type}.${key} is omit-only`);
207
- if (operation === "update" ? !column.update : column.insert === "never") require_utils.fail(`Unsupported SQL mutation field ${meta.type}.${key}`);
198
+ /**
199
+ * Applies physical write restrictions, not ORM-derived, protected, or business-immutable flags.
200
+ *
201
+ * The primary-key and generated checks only sharpen the message: `Column` already denies both through
202
+ * `insert: "never"` and `update: false`, for declared custom columns as well as generated ones.
203
+ */
204
+ function writableField(target, key, operation) {
205
+ const column = Object.hasOwn(target.columns, key) ? target.columns[key] : void 0;
206
+ if (!column) require_utils.fail(`Unsupported SQL mutation field ${target.name}.${key}`);
207
+ if (operation === "update" && column.columnName === "id") require_utils.fail("UPDATE primary-key assignments are not supported");
208
+ if (column.isGenerated) require_utils.fail(`Generated field ${target.name}.${key} is omit-only`);
209
+ if (operation === "update" ? !column.update : column.insert === "never") require_utils.fail(`Unsupported SQL mutation field ${target.name}.${key}`);
208
210
  return column;
209
211
  }
210
212
  /**
211
213
  * Classifies SQL expressions and SQL NULL before invoking the column's entity-independent write codec.
212
214
  * Normalizes public PK/FK ids to internal tagged ids using the target entity's idType.
215
+ *
216
+ * A custom table's columns never carry `idMetadata`, so they take the literal path below unchanged.
213
217
  */
214
- function assignmentToSql(meta, column, value, ctx) {
218
+ function assignmentToSql(target, column, value, ctx) {
215
219
  if (require_queries_sql_Expr.isExpr(value)) return require_queries_sql_Expr.asNode(value).toSql(ctx);
216
220
  if (value === null) {
217
- if (!column.sqlNullable) require_utils.fail(`${meta.type}.${column.columnName} is physically NOT NULL`);
221
+ if (!column.sqlNullable) require_utils.fail(`${target.name}.${column.columnName} is physically NOT NULL`);
218
222
  return {
219
223
  sql: "NULL",
220
224
  bindings: [],
@@ -230,24 +234,7 @@ function assignmentToSql(meta, column, value, ctx) {
230
234
  } else if (typeof value !== (other.idType === "number" ? "number" : "string")) require_utils.fail(`Expected a persisted ${other.type} or its ID; nested creation is not supported`);
231
235
  else value = other.idType === "untagged-string" ? require_keys.keyToTaggedId(other, value) : require_keys.toTaggedId(other, value);
232
236
  }
233
- if (!column.codec.mapToDbValue) require_utils.fail(`The codec for ${meta.type}.${column.columnName} does not support SQL value writes`);
234
- return {
235
- sql: "?",
236
- bindings: [column.mapToDbValue(value)],
237
- refs: []
238
- };
239
- }
240
- /** Encodes a custom-table literal through its declared primitive codec. */
241
- function customAssignmentToSql(table, column, value, ctx) {
242
- if (require_queries_sql_Expr.isExpr(value)) return require_queries_sql_Expr.asNode(value).toSql(ctx);
243
- if (value === null) {
244
- if (!column.sqlNullable) require_utils.fail(`${table.tableName}.${column.columnName} is physically NOT NULL`);
245
- return {
246
- sql: "NULL",
247
- bindings: [],
248
- refs: []
249
- };
250
- }
237
+ if (!column.codec.mapToDbValue) require_utils.fail(`The codec for ${target.name}.${column.columnName} does not support SQL value writes`);
251
238
  return {
252
239
  sql: "?",
253
240
  bindings: [column.mapToDbValue(value)],
@@ -260,14 +247,6 @@ function mutationCondition(value, ctx) {
260
247
  if (Array.isArray(value)) return require_queries_sql_query.conditionToSql({ and: value }, ctx, true);
261
248
  return require_queries_sql_query.conditionToSql(value, ctx, true);
262
249
  }
263
- /** Only own enumerable POJO clauses count as input or explicit full-table consent. */
264
- function checkPojo(value, allowed, description) {
265
- if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) require_utils.fail(`${description} must be a plain POJO`);
266
- for (const key of Reflect.ownKeys(value)) {
267
- if (!allowed.includes(key)) require_utils.fail(`${description} does not support '${String(key)}'`);
268
- if (typeof key === "string" && !Object.prototype.propertyIsEnumerable.call(value, key)) require_utils.fail(`${description} requires enumerable fields`);
269
- }
270
- }
271
250
  //#endregion
272
251
  exports.decodeStatementResult = decodeStatementResult;
273
252
  exports.isMutation = isMutation;