@fjell/lib-sequelize 4.4.52 → 4.4.54

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -623,10 +623,11 @@ var removeEvents = (item) => {
623
623
  // src/processing/ReferenceBuilder.ts
624
624
  var buildSequelizeReference = async (item, referenceDefinition, registry, context) => {
625
625
  const libLogger = logger_default.get("processing", "ReferenceBuilder");
626
+ const isCompositeItem = referenceDefinition.kta.length > 1;
626
627
  const primaryKeyType = referenceDefinition.kta[0];
627
- if (referenceDefinition.kta.length > 1) {
628
+ if (isCompositeItem) {
628
629
  libLogger.debug(
629
- "Using multikey reference with PriKey assumption",
630
+ "Detected composite item reference - will use ComKey with empty loc array",
630
631
  {
631
632
  kta: referenceDefinition.kta,
632
633
  primaryKeyType,
@@ -634,10 +635,6 @@ var buildSequelizeReference = async (item, referenceDefinition, registry, contex
634
635
  column: referenceDefinition.column
635
636
  }
636
637
  );
637
- libLogger.debug(
638
- 'ASSUMPTION: The primary key for key type "%s" is unique and can be used to retrieve composite items',
639
- primaryKeyType
640
- );
641
638
  }
642
639
  if (!registry) {
643
640
  throw new Error(
@@ -655,38 +652,91 @@ var buildSequelizeReference = async (item, referenceDefinition, registry, contex
655
652
  item[referenceDefinition.property] = null;
656
653
  return item;
657
654
  }
658
- const priKey = {
659
- kt: primaryKeyType,
660
- pk: columnValue
661
- };
655
+ let itemKey;
656
+ if (!isCompositeItem) {
657
+ itemKey = {
658
+ kt: primaryKeyType,
659
+ pk: columnValue
660
+ };
661
+ } else if (referenceDefinition.locationColumns && referenceDefinition.locationColumns.length > 0) {
662
+ const locationTypes = referenceDefinition.kta.slice(1);
663
+ const loc = [];
664
+ for (let i = 0; i < referenceDefinition.locationColumns.length; i++) {
665
+ const columnName = referenceDefinition.locationColumns[i];
666
+ const locValue = item[columnName];
667
+ if (locValue == null) {
668
+ libLogger.warning(
669
+ `Location column '${columnName}' is null/undefined for reference '${referenceDefinition.property}'. Falling back to empty loc array search.`
670
+ );
671
+ itemKey = {
672
+ kt: primaryKeyType,
673
+ pk: columnValue,
674
+ loc: []
675
+ };
676
+ break;
677
+ }
678
+ loc.push({
679
+ kt: locationTypes[i],
680
+ lk: locValue
681
+ });
682
+ }
683
+ if (!itemKey) {
684
+ itemKey = {
685
+ kt: primaryKeyType,
686
+ pk: columnValue,
687
+ loc
688
+ };
689
+ libLogger.debug("Built full ComKey with location context", {
690
+ itemKey,
691
+ locationColumns: referenceDefinition.locationColumns,
692
+ property: referenceDefinition.property
693
+ });
694
+ }
695
+ } else {
696
+ itemKey = {
697
+ kt: primaryKeyType,
698
+ pk: columnValue,
699
+ loc: []
700
+ };
701
+ libLogger.debug("Using empty loc array for composite item reference", {
702
+ kta: referenceDefinition.kta,
703
+ property: referenceDefinition.property
704
+ });
705
+ }
706
+ libLogger.debug("Created reference key", {
707
+ itemKey,
708
+ isCompositeItem,
709
+ hasLocationColumns: !!referenceDefinition.locationColumns,
710
+ property: referenceDefinition.property
711
+ });
662
712
  let referencedItem;
663
713
  if (context) {
664
- if (context.isCached(priKey)) {
665
- libLogger.debug("Using cached reference", { priKey, property: referenceDefinition.property });
666
- referencedItem = context.getCached(priKey);
667
- } else if (context.isInProgress(priKey)) {
714
+ if (context.isCached(itemKey)) {
715
+ libLogger.debug("Using cached reference", { itemKey, property: referenceDefinition.property });
716
+ referencedItem = context.getCached(itemKey);
717
+ } else if (context.isInProgress(itemKey)) {
668
718
  libLogger.debug("Circular dependency detected, creating reference placeholder", {
669
- priKey,
719
+ itemKey,
670
720
  property: referenceDefinition.property
671
721
  });
672
722
  referencedItem = {
673
- key: priKey
723
+ key: itemKey
674
724
  // Add any other minimal properties that might be needed
675
725
  // This prevents infinite loops while still providing the key for identification
676
726
  };
677
727
  } else {
678
- context.markInProgress(priKey);
728
+ context.markInProgress(itemKey);
679
729
  try {
680
- referencedItem = await library.operations.get(priKey);
681
- context.setCached(priKey, referencedItem);
730
+ referencedItem = await library.operations.get(itemKey);
731
+ context.setCached(itemKey, referencedItem);
682
732
  } catch (error) {
683
733
  throw error;
684
734
  } finally {
685
- context.markComplete(priKey);
735
+ context.markComplete(itemKey);
686
736
  }
687
737
  }
688
738
  } else {
689
- referencedItem = await library.operations.get(priKey);
739
+ referencedItem = await library.operations.get(itemKey);
690
740
  }
691
741
  item[referenceDefinition.property] = referencedItem;
692
742
  return item;
@@ -1141,10 +1191,16 @@ var getGetOperation = (models, definition, registry) => {
1141
1191
  item = await model.findByPk(itemKey.pk);
1142
1192
  } else if (isComKey3(itemKey)) {
1143
1193
  const comKey = itemKey;
1144
- const queryOptions = processCompositeKey(comKey, model, kta);
1145
- logger11.default("Composite key query", { queryOptions });
1146
- logger11.trace(`[GET] Executing ${model.name}.findOne() with options: ${stringifyJSON(queryOptions)}`);
1147
- item = await model.findOne(queryOptions);
1194
+ if (comKey.loc.length === 0) {
1195
+ logger11.debug(`[GET] Empty loc array detected - finding by primary key across all locations: ${comKey.pk}`);
1196
+ logger11.trace(`[GET] Executing ${model.name}.findByPk() with pk: ${comKey.pk}`);
1197
+ item = await model.findByPk(comKey.pk);
1198
+ } else {
1199
+ const queryOptions = processCompositeKey(comKey, model, kta);
1200
+ logger11.default("Composite key query", { queryOptions });
1201
+ logger11.trace(`[GET] Executing ${model.name}.findOne() with options: ${stringifyJSON(queryOptions)}`);
1202
+ item = await model.findOne(queryOptions);
1203
+ }
1148
1204
  }
1149
1205
  if (!item) {
1150
1206
  throw new NotFoundError("get", coordinate, key);
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/Options.ts", "../src/logger.ts", "../src/Coordinate.ts", "../src/Definition.ts", "../src/SequelizeLibrary.ts", "../src/ops/all.ts", "../src/QueryBuilder.ts", "../src/util/general.ts", "../src/validation/LocationKeyValidator.ts", "../src/util/relationshipUtils.ts", "../src/KeyMaster.ts", "../src/RowProcessor.ts", "../src/EventCoordinator.ts", "../src/processing/ReferenceBuilder.ts", "../src/ops/create.ts", "../src/ops/find.ts", "../src/ops/get.ts", "../src/ops/one.ts", "../src/ops/remove.ts", "../src/ops/update.ts", "../src/ops/upsert.ts", "../src/Operations.ts", "../src/SequelizeLibraryFactory.ts", "../src/contained/index.ts", "../src/contained/SequelizeLibrary.ts", "../src/primary/index.ts", "../src/primary/SequelizeLibrary.ts"],
4
- "sourcesContent": ["import * as Library from '@fjell/lib';\nimport { ComKey, Item, LocKeyArray, PriKey } from '@fjell/core';\nimport { SequelizeReferenceDefinition } from './processing/ReferenceBuilder';\n\n// Re-export AggregationDefinition from @fjell/lib for backwards compatibility\nexport type { AggregationDefinition } from '@fjell/lib';\n\n// Export Sequelize-specific reference definition\nexport type { SequelizeReferenceDefinition } from './processing/ReferenceBuilder';\n\n/**\n * Sequelize-specific Options that uses SequelizeReferenceDefinition\n * instead of the generic ReferenceDefinition\n */\nexport interface Options<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> {\n hooks?: {\n preCreate?: (\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n options?:\n {\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n locations?: never;\n } | {\n key?: never;\n locations: LocKeyArray<L1, L2, L3, L4, L5>,\n }\n ) => Promise<Partial<Item<S, L1, L2, L3, L4, L5>>>;\n postCreate?: (\n item: V,\n ) => Promise<V>;\n preUpdate?: (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n ) => Promise<Partial<Item<S, L1, L2, L3, L4, L5>>>;\n postUpdate?: (\n item: V,\n ) => Promise<V>;\n preRemove?: (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n ) => Promise<Partial<Item<S, L1, L2, L3, L4, L5>>>;\n postRemove?: (\n item: V,\n ) => Promise<V>;\n },\n validators?: {\n onCreate?: (\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n options?:\n {\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n locations?: never;\n } | {\n key?: never;\n locations: LocKeyArray<L1, L2, L3, L4, L5>,\n }\n ) => Promise<boolean>;\n onUpdate?: (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n ) => Promise<boolean>;\n onRemove?: (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n ) => Promise<boolean>;\n },\n finders?: Record<string, Library.FinderMethod<V, S, L1, L2, L3, L4, L5>>,\n actions?: Record<string, Library.ActionMethod<V, S, L1, L2, L3, L4, L5>>,\n facets?: Record<string, Library.FacetMethod<V, S, L1, L2, L3, L4, L5>>,\n allActions?: Record<string, Library.AllActionMethod<V, S, L1, L2, L3, L4, L5>>,\n allFacets?: Record<string, Library.AllFacetMethod<L1, L2, L3, L4, L5>>,\n references?: SequelizeReferenceDefinition[], // Sequelize-specific!\n aggregations?: Library.AggregationDefinition[],\n deleteOnRemove?: boolean; // Sequelize-specific option\n}\n\nexport const createOptions = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(sequelizeOptions?: Options<V, S, L1, L2, L3, L4, L5>): Options<V, S, L1, L2, L3, L4, L5> => {\n // Convert Sequelize options to Library options (excluding references which have different types)\n const { references, deleteOnRemove, ...libCompatibleOptions } = sequelizeOptions || {};\n \n // Create base options from Library\n const baseOptions = Library.createOptions(libCompatibleOptions as Library.Options<V, S, L1, L2, L3, L4, L5>);\n\n // Return Sequelize options with Sequelize-specific references, aggregations, and deleteOnRemove\n return {\n ...baseOptions,\n references: references ?? [], // Keep Sequelize-specific references\n aggregations: baseOptions.aggregations ?? [], // Ensure aggregations is always present\n deleteOnRemove: deleteOnRemove ?? false, // Sequelize-specific option\n } as Options<V, S, L1, L2, L3, L4, L5>;\n}\n", "import Logging from '@fjell/logging';\n\nconst LibLogger = Logging.getLogger('@fjell/lib-sequelize');\n\nexport default LibLogger;\n", "import { ItemTypeArray } from '@fjell/core';\nimport { Coordinate, createCoordinate as createBaseCoordinate } from '@fjell/registry';\nimport LibLogger from './logger';\n\nconst logger = LibLogger.get('Coordinate');\n\nexport const SCOPE_SEQUELIZE = 'sequelize';\n\nexport const createCoordinate = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(kta: ItemTypeArray<S, L1, L2, L3, L4, L5>, scopes?: string[]): Coordinate<S, L1, L2, L3, L4, L5> => {\n logger.debug('createCoordinate', { kta, scopes });\n const coordinate = createBaseCoordinate(kta, [SCOPE_SEQUELIZE, ...(scopes || [])]);\n return coordinate;\n};\n\n// Re-export the Coordinate type\nexport type { Coordinate } from '@fjell/registry';\n", "import { Item, ItemTypeArray } from '@fjell/core';\nimport { createOptions, Options } from './Options';\nimport LibLogger from './logger';\nimport { createCoordinate } from './Coordinate';\n\nconst logger = LibLogger.get('lib-sequelize', 'Definition');\n\nexport interface Definition<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> {\n coordinate: import('@fjell/registry').Coordinate<S, L1, L2, L3, L4, L5>;\n options: Options<V, S, L1, L2, L3, L4, L5>;\n}\n\nexport const createDefinition = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n kta: ItemTypeArray<S, L1, L2, L3, L4, L5>,\n scopes: string[],\n libOptions?: Partial<Options<V, S, L1, L2, L3, L4, L5>>,\n ): Definition<V, S, L1, L2, L3, L4, L5> => {\n logger.debug('createDefinition', { kta, scopes, libOptions });\n const coordinate = createCoordinate(kta, scopes);\n const options = createOptions<V, S, L1, L2, L3, L4, L5>(libOptions);\n\n return {\n coordinate,\n options,\n }\n}\n", "\nimport * as Library from '@fjell/lib';\nimport { Item } from '@fjell/core';\nimport { Coordinate } from '@fjell/registry';\nimport { Registry } from './Registry';\nimport { createOperations } from './Operations';\nimport { ModelStatic } from 'sequelize';\nimport { Options } from './Options';\nimport SequelizeLogger from './logger';\n\nconst logger = SequelizeLogger.get(\"SequelizeLibrary\");\n\n/**\n * The SequelizeLibrary interface extends the fjell-lib Library\n * and adds Sequelize-specific functionality:\n * - models: Array of Sequelize model classes for this library\n *\n * @template V - The type of the data model item, extending Item\n * @template S - The string literal type representing the model's key type\n * @template L1-L5 - Optional string literal types for location hierarchy levels\n */\nexport interface SequelizeLibrary<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> extends Library.Library<V, S, L1, L2, L3, L4, L5> {\n /** Array of Sequelize model classes associated with this library */\n models: ModelStatic<any>[];\n}\n\n/**\n * Creates a new SequelizeLibrary that extends the fjell-lib Library\n * with Sequelize-specific functionality\n */\nexport const createSequelizeLibrary = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n registry: Registry,\n coordinate: Coordinate<S, L1, L2, L3, L4, L5>,\n models: ModelStatic<any>[],\n options: Options<V, S, L1, L2, L3, L4, L5>\n ): SequelizeLibrary<V, S, L1, L2, L3, L4, L5> => {\n logger.debug(\"createSequelizeLibrary\", { coordinate, models, registry, options });\n\n // Create Sequelize-specific operations\n const operations = createOperations<V, S, L1, L2, L3, L4, L5>(models, coordinate, registry, options);\n\n // Wrap operations with validation and hooks from base library\n const wrappedOperations = Library.wrapOperations(operations, options, coordinate, registry);\n\n // Create the base fjell-lib library\n const libLibrary = Library.createLibrary(registry, coordinate, wrappedOperations, options);\n\n return {\n ...libLibrary,\n models,\n };\n}\n\n/**\n * Type guard to check if an object is a SequelizeLibrary\n */\nexport const isSequelizeLibrary = (library: any): library is SequelizeLibrary<any, any, any, any, any, any, any> => {\n return library != null &&\n library.coordinate != null &&\n library.operations != null &&\n library.options != null &&\n library.registry != null &&\n library.models != null &&\n Array.isArray(library.models);\n}\n", "/* eslint-disable no-undefined */\n/* eslint-disable indent */\nimport { validateKeys } from \"@fjell/core\";\n\nimport { buildQuery } from \"../QueryBuilder\";\n\nimport { Definition } from \"../Definition\";\nimport { validateLocations } from \"../validation/LocationKeyValidator\";\nimport LibLogger from '../logger';\nimport * as Library from \"@fjell/lib\";\nimport { processRow } from \"../RowProcessor\";\nimport { Item, ItemQuery, LocKeyArray } from \"@fjell/core\";\nimport { ModelStatic, Op } from \"sequelize\";\nimport { buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { contextManager } from \"../RowProcessor\";\n\nimport { stringifyJSON } from \"../util/general\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'all');\n\n// Helper function to merge includes avoiding duplicates\nconst mergeIncludes = (existingIncludes: any[], newIncludes: any[]): any[] => {\n const mergedIncludes = [...existingIncludes];\n\n for (const newInclude of newIncludes) {\n const existingIndex = mergedIncludes.findIndex(\n (existing: any) => existing.as === newInclude.as && existing.model === newInclude.model\n );\n if (existingIndex === -1) {\n mergedIncludes.push(newInclude);\n } else if (newInclude.include && mergedIncludes[existingIndex].include) {\n mergedIncludes[existingIndex].include = [\n ...mergedIncludes[existingIndex].include,\n ...newInclude.include\n ];\n } else if (newInclude.include) {\n mergedIncludes[existingIndex].include = newInclude.include;\n }\n }\n\n return mergedIncludes;\n};\n\nexport const getAllOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: Array<ModelStatic<any>>,\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n) => {\n\n const { coordinate, options: { references, aggregations } } = definition;\n\n //#region Query\n const all = async (\n itemQuery: ItemQuery,\n locations?: LocKeyArray<L1, L2, L3, L4, L5> | [] | undefined\n ): Promise<V[]> => {\n logger.debug(`ALL operation called on ${models[0].name} with ${locations?.length || 0} location filters: ${locations?.map(loc => `${loc.kt}=${loc.lk}`).join(', ') || 'none'}`);\n\n // Validate location key order\n validateLocations(locations, coordinate, 'all');\n\n const loc: LocKeyArray<L1, L2, L3, L4, L5> | [] = locations || [];\n\n // @ts-ignore\n const model = models[0];\n\n // Build base query from itemQuery\n const options = buildQuery(itemQuery, model);\n\n // Handle location keys if present\n if (loc.length > 0) {\n const { kta } = coordinate;\n const directLocations: Array<{ kt: string; lk: any }> = [];\n const hierarchicalLocations: Array<{ kt: string; lk: any }> = [];\n const additionalIncludes: any[] = [];\n\n // Categorize location keys as direct or hierarchical\n for (const locKey of loc) {\n const relationshipInfo = buildRelationshipPath(model, locKey.kt, kta, true);\n\n if (!relationshipInfo.found) {\n const errorMessage = `Location key '${locKey.kt}' cannot be resolved on model '${model.name}' or through its relationships.`;\n logger.error(errorMessage, { locations: loc, kta });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.isDirect) {\n directLocations.push(locKey);\n } else {\n hierarchicalLocations.push(locKey);\n }\n }\n\n // Handle direct location keys (simple foreign key constraints)\n for (const locKey of directLocations) {\n if (locKey.lk === undefined || locKey.lk == null || locKey.lk === '' || (typeof locKey.lk === 'object' && Object.keys(locKey.lk).length === 0)) {\n logger.error(`Location key '${locKey.kt}' has invalid lk value: ${stringifyJSON(locKey.lk)}`, { locKey, locations: loc });\n throw new Error(`Location key '${locKey.kt}' has invalid lk value: ${stringifyJSON(locKey.lk)}`);\n }\n const foreignKeyField = locKey.kt + 'Id';\n\n // Check if this field already has a condition from the itemQuery\n if (options.where[foreignKeyField]) {\n logger.debug(`[ALL] Field ${foreignKeyField} already constrained by itemQuery, skipping location constraint to avoid conflicts`);\n continue; // Skip this location constraint to avoid conflicts\n }\n\n logger.trace(`[ALL] Setting direct location where clause: ${foreignKeyField} = ${stringifyJSON(locKey.lk)} (type: ${typeof locKey.lk})`);\n options.where[foreignKeyField] = {\n [Op.eq]: locKey.lk\n };\n }\n\n // Handle hierarchical location keys (requires relationship traversal)\n for (const locKey of hierarchicalLocations) {\n if (locKey.lk === undefined || locKey.lk == null || locKey.lk === '' || (typeof locKey.lk === 'object' && Object.keys(locKey.lk).length === 0)) {\n logger.error(`Hierarchical location key '${locKey.kt}' has invalid lk value: ${stringifyJSON(locKey.lk)}`, { locKey, locations: loc });\n throw new Error(`Hierarchical location key '${locKey.kt}' has invalid lk value: ${stringifyJSON(locKey.lk)}`);\n }\n const relationshipInfo = buildRelationshipPath(model, locKey.kt, kta);\n\n if (relationshipInfo.found && relationshipInfo.path) {\n // Check if this field already has a condition from the itemQuery\n if (options.where[relationshipInfo.path]) {\n logger.debug(`[ALL] Field ${relationshipInfo.path} already constrained by itemQuery, skipping hierarchical location constraint to avoid conflicts`);\n continue; // Skip this location constraint to avoid conflicts\n }\n\n // Add the relationship constraint using the path\n logger.trace(`[ALL] Setting hierarchical location where clause: ${relationshipInfo.path} = ${stringifyJSON(locKey.lk)} (type: ${typeof locKey.lk})`);\n options.where[relationshipInfo.path] = {\n [Op.eq]: locKey.lk\n };\n\n // Add necessary includes for the relationship traversal\n if (relationshipInfo.includes) {\n additionalIncludes.push(...relationshipInfo.includes);\n }\n }\n }\n\n // Merge additional includes with existing includes\n if (additionalIncludes.length > 0) {\n const existingIncludes = options.include || [];\n options.include = mergeIncludes(existingIncludes, additionalIncludes);\n }\n }\n\n logger.default(`All query configured for ${model.name} with where fields: ${options.where ? Object.keys(options.where).join(', ') : 'none'}, includes: ${options.include?.length || 0}`);\n\n try {\n logger.trace(`[ALL] Executing ${model.name}.findAll() with options: ${JSON.stringify(options, null, 2)}`);\n } catch {\n // Fallback for cases where JSON.stringify fails on Sequelize operators\n logger.trace(`[ALL] Executing ${model.name}.findAll() with options containing non-serializable operators (${Object.keys(options.where || {}).length} where conditions)`);\n }\n const matchingItems = await model.findAll(options);\n\n // this.logger.default('Matching Items', { matchingItems });\n\n // Pass null as context to let processRow create a new context for each top-level operation\n // This prevents circular dependency false positives between concurrent operations\n // while still detecting legitimate circular references within the same operation\n\n // TODO: Move this Up!\n const currentContext = contextManager.getCurrentContext();\n const results = (await Promise.all(matchingItems.map(async (row: any) => {\n // Each row in an all() operation should get its own context to prevent interference\n const processedRow = await processRow(row, coordinate.kta, references || [], aggregations || [], registry, currentContext);\n return validateKeys(processedRow, coordinate.kta);\n }))) as V[];\n\n logger.debug(`[ALL] Returning ${results.length} ${model.name} records`);\n return results;\n }\n\n return all;\n\n}\n", "/* eslint-disable max-len */\nimport {\n CompoundCondition,\n Condition,\n EventQuery,\n isComKey,\n isCondition,\n isPriKey,\n ItemQuery,\n OrderBy,\n PriKey,\n References\n} from '@fjell/core';\n\nimport { Association, ModelStatic, Op } from 'sequelize';\nimport LibLogger from './logger';\nimport { stringifyJSON } from './util/general';\n\nconst logger = LibLogger.get('sequelize', 'QueryBuilder');\n\nexport type QueryOptions = {\n where: Record<string, any>;\n limit?: number;\n offset?: number;\n order?: Array<[string, string]>;\n include?: Array<any>;\n}\n\nconst addDeleteQuery = (options: QueryOptions, model: ModelStatic<any>): QueryOptions => {\n logger.default(`QueryBuilder adding delete query with options: ${stringifyJSON(options)}`);\n if (model.getAttributes().deletedAt) {\n options.where['deletedAt'] = {\n [Op.eq]: null\n }\n } else if (model.getAttributes().isDeleted) {\n options.where['isDeleted'] = {\n [Op.eq]: false\n }\n }\n\n return options;\n}\n\nconst addEventQueries = (\n options: QueryOptions, events: Record<string, EventQuery>, model: ModelStatic<any>): QueryOptions => {\n logger.default(`QueryBuilder adding event queries with options: ${stringifyJSON(options)}, events: ${stringifyJSON(events)}`);\n Object.keys(events).forEach((key: string) => {\n\n if (!model.getAttributes()[`${key}At`]) {\n throw new Error(`Event ${key} is not supported on model '${model.name}', column '${key}At' not found. Available columns: [${Object.keys(model.getAttributes()).join(', ')}]. Event query: ${stringifyJSON(events[key])}`);\n }\n\n let whereClauses = {};\n\n const event = events[key];\n if (event.start) {\n whereClauses = { ...whereClauses, [Op.gte]: new Date(event.start) };\n }\n if (event.end) {\n whereClauses = { ...whereClauses, [Op.lt]: new Date(event.end) };\n }\n\n if (event.by) {\n if (!model.getAttributes()[`${key}By`]) {\n throw new Error(`Event ${key} is not supported on model '${model.name}', column '${key}By' not found. Available columns: [${Object.keys(model.getAttributes()).join(', ')}]. Event query: ${stringifyJSON(events[key])}`);\n }\n whereClauses = { ...whereClauses, [Op.eq]: event.by };\n }\n\n options.where[`${key}At`] = whereClauses;\n\n });\n return options;\n}\n\n// Add the references to the query\nconst addReferenceQueries = (options: any, references: References, model: ModelStatic<any>): any => {\n logger.default(`QueryBuilder adding reference queries with options: ${stringifyJSON(options)}, references: ${stringifyJSON(references)}`);\n\n Object.keys(references).forEach((key: string) => {\n logger.default(`QueryBuilder adding reference query for key: ${key}, references: ${stringifyJSON(references)}`);\n\n if (!model.getAttributes()[`${key}Id`]) {\n throw new Error(`Reference ${key} is not supported on model '${model.name}', column '${key}Id' not found. Available columns: [${Object.keys(model.getAttributes()).join(', ')}]. Reference query: ${stringifyJSON(references[key])}`);\n }\n\n const refValue = references[key];\n const keyValue = (refValue as any).key || refValue;\n \n if (isPriKey(keyValue)) {\n const priKey: PriKey<string> = keyValue as PriKey<string>;\n\n if (priKey.pk == null || priKey.pk === '' || (typeof priKey.pk === 'object' && Object.keys(priKey.pk).length === 0)) {\n logger.error(`Reference key '${key}' has invalid pk value: ${stringifyJSON(priKey.pk)}`, { priKey, references });\n throw new Error(`Reference key '${key}' has invalid pk value: ${stringifyJSON(priKey.pk)}. Model: '${model.name}', Key type: '${priKey.kt}', Full reference: ${stringifyJSON(references[key])}`);\n }\n\n logger.trace(`[QueryBuilder] Setting reference where clause: ${key}Id = ${stringifyJSON(priKey.pk)} (type: ${typeof priKey.pk})`);\n options.where[`${key}Id`] = {\n [Op.eq]: priKey.pk\n }\n } else if (isComKey(references[key])) {\n throw new Error(`ComKeys are not supported in Sequelize. Reference key: '${key}', Model: '${model.name}', ComKey: ${stringifyJSON(references[key])}`);\n }\n });\n return options;\n}\n\nexport const addCompoundCondition = (options: any, compoundCondition: CompoundCondition, model: ModelStatic<any>) => {\n // Ensure options.where exists\n options.where = options.where || {};\n\n let compoundOp: symbol;\n const compoundType = compoundCondition.compoundType;\n if (compoundType === \"AND\") {\n compoundOp = Op.and;\n } else {\n compoundOp = Op.or;\n };\n\n let conditions: Record<string, any> = {};\n compoundCondition.conditions.forEach((condition: Condition | CompoundCondition) => {\n if (isCondition(condition)) {\n conditions = addCondition(conditions, condition, model);\n } else {\n throw new Error(`Nested Compound conditions not supported. Model: '${model.name}', Compound condition: ${stringifyJSON(compoundCondition)}, Nested condition: ${stringifyJSON(condition)}`);\n }\n });\n\n // Merge with existing where conditions instead of replacing\n if (Object.keys(options.where).length > 0) {\n // If there are existing conditions, wrap everything in an AND\n options.where = {\n [Op.and]: [\n options.where,\n { [compoundOp]: conditions }\n ]\n };\n } else {\n // If no existing conditions, just set the compound condition\n options.where[compoundOp] = conditions;\n }\n\n return options;\n}\n\nconst getSequelizeOperator = (operator: string): symbol => {\n if (operator === '==') {\n return Op.eq;\n } else if (operator === '<') {\n return Op.lt;\n } else if (operator === '>') {\n return Op.gt;\n } else if (operator === '<=') {\n return Op.lte;\n } else if (operator === '>=') {\n return Op.gte;\n } else if (operator === 'in') {\n return Op.in;\n } else {\n throw new Error(`Operator ${operator} not supported`);\n }\n};\n\nconst addAssociationCondition = (\n conditions: Record<string, any>,\n condition: Condition,\n model: ModelStatic<any>\n): Record<string, any> => {\n const [associationName, attributeName] = condition.column.split('.', 2);\n\n // Check if the association exists on the model\n if (!model.associations || !model.associations[associationName]) {\n throw new Error(`Association ${associationName} not found on model ${model.name}`);\n }\n\n const association: Association<any, any> = model.associations[associationName];\n const associatedModel = association.target;\n\n // Check if the attribute exists on the associated model\n if (!associatedModel.getAttributes()[attributeName]) {\n throw new Error(`Attribute ${attributeName} not found on associated model ${associatedModel.name} for association ${associationName}`);\n }\n\n // Use Sequelize's $association.attribute$ syntax for querying associated models\n const sequelizeAssociationColumn = `$${associationName}.${attributeName}$`;\n\n // Handle null values with proper SQL IS NULL / IS NOT NULL syntax\n if (condition.value === null) {\n if (condition.operator === '==' || !condition.operator) {\n // Use Op.is for IS NULL\n logger.trace(`[QueryBuilder] Setting association condition: ${sequelizeAssociationColumn} IS NULL`);\n conditions[sequelizeAssociationColumn] = {\n [Op.is]: null\n };\n } else if (condition.operator === '!=') {\n // Use Op.not for IS NOT NULL\n logger.trace(`[QueryBuilder] Setting association condition: ${sequelizeAssociationColumn} IS NOT NULL`);\n conditions[sequelizeAssociationColumn] = {\n [Op.not]: null\n };\n } else {\n logger.error(`Operator ${condition.operator} cannot be used with null value on association`, { condition });\n throw new Error(`Operator ${condition.operator} cannot be used with null value. Use '==' for IS NULL or '!=' for IS NOT NULL.`);\n }\n return conditions;\n }\n\n const conditionOp = getSequelizeOperator(condition.operator);\n\n logger.trace(`[QueryBuilder] Setting association condition: ${sequelizeAssociationColumn} = ${stringifyJSON(condition.value)} (type: ${typeof condition.value})`);\n conditions[sequelizeAssociationColumn] = {\n [conditionOp]: condition.value\n };\n\n return conditions;\n};\n\nconst addAttributeCondition = (\n conditions: Record<string, any>,\n condition: Condition,\n model: ModelStatic<any>\n): Record<string, any> => {\n const conditionColumn = condition.column;\n\n if (!model.getAttributes()[conditionColumn]) {\n throw new Error(`Condition column ${conditionColumn} not found on model ${model.name}`);\n }\n\n // Handle null values with proper SQL IS NULL / IS NOT NULL syntax\n if (condition.value === null) {\n if (condition.operator === '==' || !condition.operator) {\n // Use Op.is for IS NULL\n logger.trace(`[QueryBuilder] Setting attribute condition: ${conditionColumn} IS NULL`);\n conditions[conditionColumn] = {\n [Op.is]: null\n };\n } else if (condition.operator === '!=') {\n // Use Op.not for IS NOT NULL\n logger.trace(`[QueryBuilder] Setting attribute condition: ${conditionColumn} IS NOT NULL`);\n conditions[conditionColumn] = {\n [Op.not]: null\n };\n } else {\n logger.error(`Operator ${condition.operator} cannot be used with null value`, { condition });\n throw new Error(`Operator ${condition.operator} cannot be used with null value. Use '==' for IS NULL or '!=' for IS NOT NULL.`);\n }\n return conditions;\n }\n\n const conditionOp = getSequelizeOperator(condition.operator);\n\n logger.trace(`[QueryBuilder] Setting attribute condition: ${conditionColumn} = ${stringifyJSON(condition.value)} (type: ${typeof condition.value})`);\n conditions[conditionColumn] = {\n [conditionOp]: condition.value\n };\n\n return conditions;\n};\n\nexport const addCondition = (conditions: Record<string, any>, condition: Condition, model: ModelStatic<any>) => {\n const conditionColumn: string = condition.column;\n\n // Check if this is an association query (contains a dot)\n if (conditionColumn.includes('.')) {\n return addAssociationCondition(conditions, condition, model);\n }\n\n // Handle regular column queries\n return addAttributeCondition(conditions, condition, model);\n}\n\nconst collectAssociationsFromConditions = (conditions: any): Set<string> => {\n const associations = new Set<string>();\n\n const processObject = (obj: any) => {\n if (typeof obj === 'object' && obj !== null) {\n // Check string keys\n Object.keys(obj).forEach(key => {\n // Check if this is an association reference ($association.attribute$)\n if (typeof key === 'string' && key.startsWith('$') && key.endsWith('$') && key.includes('.')) {\n const associationName = key.substring(1, key.indexOf('.'));\n associations.add(associationName);\n }\n\n // Recursively process nested objects\n if (typeof obj[key] === 'object') {\n processObject(obj[key]);\n }\n });\n\n // Also check Symbol keys (for compound conditions like Op.and, Op.or)\n Object.getOwnPropertySymbols(obj).forEach(symbol => {\n if (typeof obj[symbol] === 'object') {\n processObject(obj[symbol]);\n }\n });\n }\n\n // Handle arrays (for compound conditions that might be arrays)\n if (Array.isArray(obj)) {\n obj.forEach(item => {\n if (typeof item === 'object') {\n processObject(item);\n }\n });\n }\n };\n\n processObject(conditions);\n return associations;\n};\n\nconst addAssociationIncludes = (options: any, model: ModelStatic<any>): any => {\n // Collect all association names used in conditions\n const referencedAssociations = collectAssociationsFromConditions(options.where);\n\n if (referencedAssociations.size > 0) {\n options.include = options.include || [];\n\n // Add each referenced association to the include array\n referencedAssociations.forEach(associationName => {\n // Check if this association is already included\n const alreadyIncluded = options.include.some((inc: any) =>\n (typeof inc === 'string' && inc === associationName) ||\n (typeof inc === 'object' && inc.association === associationName)\n );\n\n if (!alreadyIncluded && model.associations && model.associations[associationName]) {\n options.include.push({\n model: model.associations[associationName].target,\n as: associationName,\n required: false // Use LEFT JOIN so records without associations are still returned\n });\n }\n });\n }\n\n return options;\n};\n\nexport const buildQuery = (\n itemQuery: ItemQuery,\n model: ModelStatic<any>\n): any => {\n logger.default(`QueryBuilder build called with itemQuery: ${stringifyJSON(itemQuery)}`);\n\n let options: any = {\n where: {},\n };\n\n if (itemQuery.compoundCondition) {\n logger.default(`QueryBuilder adding conditions: ${stringifyJSON(itemQuery.compoundCondition)}`);\n options = addCompoundCondition(options, itemQuery.compoundCondition, model);\n }\n\n // If the model has a deletedAt column, we need to add a delete query\n if (model.getAttributes().deletedAt || model.getAttributes().isDeleted) {\n options = addDeleteQuery(options, model);\n }\n\n if (itemQuery.refs) {\n options = addReferenceQueries(options, itemQuery.refs, model);\n }\n if (itemQuery.events) {\n options = addEventQueries(options, itemQuery.events, model);\n }\n\n // TODO: Once we start to support Aggs on the server-side, we'll need to parse agg queries\n\n // Apply a limit to the result set\n if (itemQuery.limit) {\n logger.default(`QueryBuilder applying limit: ${itemQuery.limit}`);\n options.limit = itemQuery.limit;\n }\n\n // Apply an offset to the result set\n if (itemQuery.offset) {\n options.offset = itemQuery.offset;\n }\n\n // Add orderBy to the query\n if (itemQuery.orderBy) {\n itemQuery.orderBy.forEach((orderBy: OrderBy) => {\n if (!model.getAttributes()[orderBy.field]) {\n throw new Error(`Order by field ${orderBy.field} not found on model ${model.name}`);\n }\n options.order = [\n [orderBy.field, orderBy.direction]\n ];\n });\n }\n\n // Add includes for any associations referenced in conditions\n options = addAssociationIncludes(options, model);\n\n return options;\n}\n", "\n/* eslint-disable */\nexport const clean = (obj: any) => {\n return Object.fromEntries(\n Object.entries(obj).filter(([_, v]) => v !== undefined)\n );\n}\n\n//Recursive implementation of jSON.stringify;\nexport const stringifyJSON = function (obj: any, visited: Set<any> = new Set()): string {\n const arrOfKeyVals: string[] = [];\n const arrVals: string[] = [];\n let objKeys: string[] = [];\n\n /*********CHECK FOR PRIMITIVE TYPES**********/\n if (typeof obj === 'number' || typeof obj === 'boolean' || obj === null)\n return '' + obj;\n else if (typeof obj === 'string')\n return '\"' + obj + '\"';\n\n /*********DETECT CIRCULAR REFERENCES**********/\n if (obj instanceof Object && visited.has(obj)) {\n return '\"(circular)\"';\n }\n\n /*********CHECK FOR ARRAY**********/\n else if (Array.isArray(obj)) {\n //check for empty array\n if (obj.length === 0)\n return '[]';\n else {\n // Add array to visited before processing its elements\n visited.add(obj);\n obj.forEach(function (el) {\n arrVals.push(stringifyJSON(el, visited));\n });\n // Remove from visited after processing to allow arrays at different levels\n visited.delete(obj);\n return '[' + arrVals + ']';\n }\n }\n /*********CHECK FOR OBJECT**********/\n else if (obj instanceof Object) {\n // Add object to visited before processing its properties\n visited.add(obj);\n //get object keys\n objKeys = Object.keys(obj);\n //set key output;\n objKeys.forEach(function (key) {\n const keyOut = '\"' + key + '\":';\n const keyValOut = obj[key];\n //skip functions and undefined properties\n if (keyValOut instanceof Function || keyValOut === undefined)\n return; // Skip this entry entirely instead of pushing an empty string\n else if (typeof keyValOut === 'string')\n arrOfKeyVals.push(keyOut + '\"' + keyValOut + '\"');\n else if (typeof keyValOut === 'boolean' || typeof keyValOut === 'number' || keyValOut === null)\n arrOfKeyVals.push(keyOut + keyValOut);\n //check for nested objects, call recursively until no more objects\n else if (keyValOut instanceof Object) {\n arrOfKeyVals.push(keyOut + stringifyJSON(keyValOut, visited));\n }\n });\n // Remove from visited after processing to allow objects at different levels\n visited.delete(obj);\n return '{' + arrOfKeyVals + '}';\n }\n return '';\n};\n", "import { LocKey, LocKeyArray } from \"@fjell/core\";\nimport { Coordinate } from \"@fjell/registry\";\nimport LibLogger from \"../logger\";\n\nconst logger = LibLogger.get('LocationKeyValidator');\n\n/**\n * Validates that location keys in a LocKeyArray are in the correct hierarchical order\n * based on the entity's coordinate definition.\n *\n * @param locations - The location key array to validate\n * @param coordinate - The coordinate defining the expected hierarchy\n * @param operation - The name of the operation being performed (for error messages)\n * @throws Error if location keys are not in the correct order or if the array is invalid\n */\nexport const validateLocations = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n locations: LocKeyArray<L1, L2, L3, L4, L5> | [] | undefined,\n coordinate: Coordinate<S, L1, L2, L3, L4, L5>,\n operation: string\n ): void => {\n if (!locations || locations.length === 0) {\n return;\n }\n\n const keyTypeArray = coordinate.kta;\n const expectedLocationTypes = keyTypeArray.slice(1); // Skip the first element (primary key type)\n const actualLocationTypes = (locations as Array<LocKey<L1 | L2 | L3 | L4 | L5>>).map(loc => loc.kt);\n\n logger.debug(`Validating locations for ${operation}`, {\n expected: expectedLocationTypes,\n actual: actualLocationTypes,\n coordinate: keyTypeArray\n });\n\n // Check if too many location keys were provided\n if (actualLocationTypes.length > expectedLocationTypes.length) {\n logger.error('Location key array has too many elements', {\n expected: expectedLocationTypes.length,\n actual: actualLocationTypes.length,\n expectedTypes: expectedLocationTypes,\n actualTypes: actualLocationTypes,\n coordinate,\n operation\n });\n throw new Error(\n `Invalid location key array for ${operation}: ` +\n `Expected at most ${expectedLocationTypes.length} location keys ` +\n `(hierarchy: [${expectedLocationTypes.join(', ')}]), ` +\n `but received ${actualLocationTypes.length} ` +\n `(types: [${actualLocationTypes.join(', ')}])`\n );\n }\n\n // Validate that each location key is in the correct hierarchical position\n for (let i = 0; i < actualLocationTypes.length; i++) {\n if (expectedLocationTypes[i] !== actualLocationTypes[i]) {\n logger.error('Location key array order mismatch', {\n position: i,\n expected: expectedLocationTypes[i],\n actual: actualLocationTypes[i],\n expectedHierarchy: expectedLocationTypes,\n actualOrder: actualLocationTypes,\n coordinate,\n operation\n });\n throw new Error(\n `Invalid location key array order for ${operation}: ` +\n `At position ${i}, expected key type \"${expectedLocationTypes[i]}\" ` +\n `but received \"${actualLocationTypes[i]}\". ` +\n `Location keys must be ordered according to the hierarchy: [${expectedLocationTypes.join(', ')}]. ` +\n `Received order: [${actualLocationTypes.join(', ')}]`\n );\n }\n }\n\n logger.debug(`Location key array validation passed for ${operation}`, { locations });\n};\n\n", "/* eslint-disable indent */\nimport { ModelStatic } from 'sequelize';\n\nexport interface RelationshipChainResult {\n success: boolean;\n path?: string;\n includes?: any[];\n}\n\nexport interface RelationshipPathResult {\n found: boolean;\n path?: string;\n includes?: any[];\n isDirect?: boolean;\n}\n\n/**\n * Helper function to build relationship chain includes\n */\nexport const buildRelationshipChain = (\n targetModel: ModelStatic<any>,\n kta: string[],\n currentIndex: number,\n targetIndex: number\n): RelationshipChainResult => {\n // Build the association path and validate relationships exist\n const associationParts: string[] = [];\n const modelChain: ModelStatic<any>[] = [targetModel];\n let currentModel = targetModel;\n\n // Validate that all associations exist and build model chain\n for (let i = currentIndex + 1; i <= targetIndex; i++) {\n const intermediateType = kta[i];\n const associationName = intermediateType;\n\n if (!currentModel.associations || !currentModel.associations[associationName]) {\n return { success: false };\n }\n\n associationParts.push(associationName);\n currentModel = currentModel.associations[associationName].target;\n modelChain.push(currentModel);\n }\n\n // Build the full association path for the target field\n const targetPrimaryKey = currentModel.primaryKeyAttribute || 'id';\n const associationPath = `$${associationParts.join('.')}.${targetPrimaryKey}$`;\n\n // Build nested includes structure iteratively (clearer than recursion)\n let deepestInclude: any = null;\n\n // Build from the deepest level back to the root\n for (let i = targetIndex; i > currentIndex; i--) {\n const currentType = kta[i];\n const modelIndex = i - currentIndex;\n\n const includeObj: any = {\n model: modelChain[modelIndex],\n as: currentType,\n required: true\n };\n\n if (deepestInclude) {\n includeObj.include = [deepestInclude];\n }\n\n deepestInclude = includeObj;\n }\n\n const includes = deepestInclude ? [deepestInclude] : [];\n\n return { success: true, path: associationPath, includes };\n};\n\n/**\n * Helper function to build relationship path for a locator\n * @param includeIsDirect Whether to include the isDirect flag in the result\n */\nexport const buildRelationshipPath = (\n targetModel: ModelStatic<any>,\n locatorType: string,\n kta: string[],\n includeIsDirect: boolean = false\n): RelationshipPathResult => {\n\n // First check if the field exists directly\n const directFieldName = `${locatorType}Id`;\n const attributes = targetModel.getAttributes();\n if (attributes && attributes[directFieldName]) {\n const result: RelationshipPathResult = { found: true };\n if (includeIsDirect) {\n result.isDirect = true;\n }\n return result;\n }\n\n // If not direct, look for relationship path\n const targetIndex = kta.indexOf(locatorType);\n if (targetIndex === -1) {\n const result: RelationshipPathResult = { found: false };\n if (includeIsDirect) {\n result.isDirect = false;\n }\n return result;\n }\n\n const currentIndex = 0; // We're always looking from the base model\n\n if (targetIndex <= currentIndex) {\n const result: RelationshipPathResult = { found: false };\n if (includeIsDirect) {\n result.isDirect = false;\n }\n return result;\n }\n\n const chainResult = buildRelationshipChain(targetModel, kta, currentIndex, targetIndex);\n if (chainResult.success) {\n const result: RelationshipPathResult = {\n found: true,\n path: chainResult.path,\n includes: chainResult.includes\n };\n if (includeIsDirect) {\n result.isDirect = false;\n }\n return result;\n }\n\n const result: RelationshipPathResult = { found: false };\n if (includeIsDirect) {\n result.isDirect = false;\n }\n return result;\n};\n", "/* eslint-disable max-len */\n/* eslint-disable indent */\nimport {\n AllItemTypeArrays,\n Item,\n} from '@fjell/core';\n\nimport LibLogger from './logger';\nimport { Model, ModelStatic } from 'sequelize';\nimport { buildRelationshipPath } from './util/relationshipUtils';\n\nconst logger = LibLogger.get('sequelize', 'KeyMaster');\n\n// Helper function to extract location key value from item\nconst extractLocationKeyValue = (\n model: ModelStatic<any>,\n item: any,\n locatorType: string,\n kta: string[]\n): any => {\n logger.default('Extracting location key value', { locatorType, kta });\n\n const relationshipInfo = buildRelationshipPath(model, locatorType, kta, true);\n\n if (!relationshipInfo.found) {\n throw new Error(`Location key '${locatorType}' cannot be resolved on model '${model.name}' or through its relationships. Key type array: [${kta.join(', ')}]. Available associations: [${Object.keys(model.associations || {}).join(', ')}]`);\n }\n\n if (relationshipInfo.isDirect) {\n // Direct foreign key field\n const foreignKeyField = `${locatorType}Id`;\n const value = item[foreignKeyField];\n if (typeof value === 'undefined' || value === null) {\n throw new Error(`Direct foreign key field '${foreignKeyField}' is missing or null in item. Model: '${model.name}', Locator type: '${locatorType}', Available item properties: [${Object.keys(item || {}).join(', ')}]`);\n }\n return value;\n } else {\n // Need to traverse relationship hierarchy\n // Find the path through the key type array\n const locatorIndex = kta.indexOf(locatorType);\n if (locatorIndex === -1) {\n throw new Error(`Locator type '${locatorType}' not found in key type array. Model: '${model.name}', Key type array: [${kta.join(', ')}]`);\n }\n\n // Start from the current item (index 0 in kta)\n let currentObject = item;\n\n // Traverse through each intermediate relationship to reach the target\n for (let i = 1; i < locatorIndex; i++) {\n const intermediateType = kta[i];\n\n // Check if the intermediate relationship object is loaded\n if (currentObject[intermediateType] && typeof currentObject[intermediateType] === 'object') {\n currentObject = currentObject[intermediateType];\n } else {\n // Try the foreign key approach if the relationship object isn't loaded\n const foreignKeyField = `${intermediateType}Id`;\n if (typeof currentObject[foreignKeyField] !== 'undefined' && currentObject[foreignKeyField] !== null) {\n // We have the foreign key but not the loaded object, we can't traverse further\n throw new Error(`Intermediate relationship '${intermediateType}' is not loaded. Cannot traverse to '${locatorType}'. Model: '${model.name}', Available item properties: [${Object.keys(currentObject || {}).join(', ')}]. Either include the relationship in your query or ensure it's loaded.`);\n }\n throw new Error(`Intermediate relationship '${intermediateType}' is missing in the relationship chain. Model: '${model.name}', Expected path: ${kta.slice(0, locatorIndex + 1).join(' \u2192 ')}, Available item properties: [${Object.keys(currentObject || {}).join(', ')}]`);\n }\n }\n\n // Now extract the target locator value from the current object\n // First try to get it from the loaded relationship object\n if (currentObject[locatorType] && typeof currentObject[locatorType] === 'object' && typeof currentObject[locatorType].id !== 'undefined') {\n return currentObject[locatorType].id;\n }\n\n // If the relationship object isn't loaded, try the foreign key field\n const foreignKeyField = `${locatorType}Id`;\n if (typeof currentObject[foreignKeyField] !== 'undefined' && currentObject[foreignKeyField] !== null) {\n return currentObject[foreignKeyField];\n }\n\n const traversalPath = kta.slice(0, locatorIndex + 1).join(' \u2192 ');\n throw new Error(\n `Unable to extract location key for '${locatorType}'. ` +\n `Neither the relationship object nor direct foreign key is available. ` +\n `Traversal path: ${traversalPath}`\n );\n }\n};\n\nexport const removeKey = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Removing Key', { item });\n delete item.key;\n return item;\n}\n\n// export const populateKey = <\n// S extends string,\n// L1 extends string = never,\n// L2 extends string = never,\n// L3 extends string = never,\n// L4 extends string = never,\n// L5 extends string = never\n// >(\n// item: ItemProperties<S, L1, L2, L3, L4, L5>,\n// keyTypes: AllItemTypeArrays<S, L1, L2, L3, L4, L5>\n// ): ItemProperties<S, L1, L2, L3, L4, L5> => {\n// if (keyTypes.length === 1) {\n// item.key = { kt: keyTypes[0], pk: item.id };\n// delete item.id;\n// } else if (keyTypes.length === 2) {\n// item.key = {\n// kt: keyTypes[0], pk: item.id,\n// // TODO: Shouldn't this be inspecting the model to get the primary key type?\n// loc: [{ kt: keyTypes[1], lk: item[keyTypes[1] + 'Id'] }],\n// };\n// delete item.id;\n// delete item[keyTypes[1] + 'Id'];\n// } else {\n// throw new Error('Not implemented');\n// }\n// return item;\n// }\n\nexport const addKey = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n model: Model<any, any>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n keyTypes: AllItemTypeArrays<S, L1, L2, L3, L4, L5>\n): Item<S, L1, L2, L3, L4, L5> => {\n logger.default('Adding Key', { item });\n const key = {};\n const modelClass = model.constructor as ModelStatic<any>;\n const primaryKeyAttr = modelClass.primaryKeyAttribute;\n\n if (Array.isArray(keyTypes) && keyTypes.length > 1) {\n const type = [...keyTypes];\n const pkType = type.shift();\n Object.assign(key, { kt: pkType, pk: item[primaryKeyAttr] });\n\n // Build location keys for composite key\n const locationKeys = [];\n for (const locatorType of type) {\n try {\n const lk = extractLocationKeyValue(modelClass, item, locatorType, keyTypes as string[]);\n locationKeys.push({ kt: locatorType, lk });\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error(`Failed to extract location key for '${locatorType}'`, { error: errorMessage, item, keyTypes });\n throw error;\n }\n }\n\n Object.assign(key, { loc: locationKeys });\n } else {\n Object.assign(key, { kt: keyTypes[0], pk: item[primaryKeyAttr] });\n }\n Object.assign(item, { key });\n return item as Item<S, L1, L2, L3, L4, L5>;\n};\n", "/* eslint-disable indent */\n\nimport { AllItemTypeArrays, Item } from \"@fjell/core\";\nimport { Model } from \"sequelize\";\n\nimport LibLogger from \"./logger\";\nimport { addKey } from \"./KeyMaster\";\nimport { AggregationDefinition, SequelizeReferenceDefinition } from \"./Options\";\nimport * as Library from \"@fjell/lib\";\nimport {\n buildAggregation,\n contextManager,\n createOperationContext,\n OperationContext\n} from \"@fjell/lib\";\nimport { stringifyJSON } from \"./util/general\";\nimport { populateEvents } from \"./EventCoordinator\";\nimport { buildSequelizeReference } from \"./processing/ReferenceBuilder\";\n\nconst logger = LibLogger.get('sequelize', 'RowProcessor');\n\n// Re-export types and functions from @fjell/lib for backwards compatibility\nexport type { OperationContext };\nexport { createOperationContext, contextManager };\n\nexport const processRow = async <S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never>(\n row: Model<any, any>,\n keyTypes: AllItemTypeArrays<S, L1, L2, L3, L4, L5>,\n referenceDefinitions: SequelizeReferenceDefinition[],\n aggregationDefinitions: AggregationDefinition[],\n registry: Library.Registry,\n context?: OperationContext\n ): Promise<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Processing Row', { row });\n\n // Use provided context or create new one\n const operationContext = context || createOperationContext();\n\n // Process the row within the context to ensure all operations share the same context\n return contextManager.withContext(operationContext, async () => {\n let item = row.get({ plain: true }) as any;\n logger.default('Adding Key to Item with Key Types: %s', stringifyJSON(keyTypes));\n item = addKey(row, item, keyTypes);\n item = populateEvents(item);\n logger.default('Key Added to Item: %s', stringifyJSON(item.key));\n\n // Mark this item as in progress to detect circular references\n operationContext.markInProgress(item.key);\n\n try {\n if (referenceDefinitions && referenceDefinitions.length > 0) {\n for (const referenceDefinition of referenceDefinitions) {\n logger.default('Processing Reference for %s to %s', item.key.kt, stringifyJSON(referenceDefinition.kta));\n item = await buildSequelizeReference(item, referenceDefinition, registry, operationContext);\n }\n }\n if (aggregationDefinitions && aggregationDefinitions.length > 0) {\n for (const aggregationDefinition of aggregationDefinitions) {\n logger.default('Processing Aggregation for %s from %s', item.key.kt, stringifyJSON(aggregationDefinition.kta));\n item = await buildAggregation(item, aggregationDefinition, registry, operationContext);\n }\n }\n\n // Cache the fully processed item\n operationContext.setCached(item.key, item);\n } finally {\n // Mark this item as complete\n operationContext.markComplete(item.key);\n }\n\n logger.default('Processed Row: %j', stringifyJSON(item));\n return item as Item<S, L1, L2, L3, L4, L5>;\n });\n};\n", "import {\n Evented,\n Item,\n ManagedEvents\n} from '@fjell/core';\nimport deepmerge from 'deepmerge';\n\nimport LibLogger from './logger';\n\nconst logger = LibLogger.get(\"sequelize\", \"EventCoordinator\");\n\nexport const createEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>):\n Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Creating Events', { item });\n const currentDate = new Date();\n\n let events = item.events;\n\n if (events) {\n if (!events.created) {\n events = deepmerge(events, { created: { at: currentDate } });\n }\n if (!events.updated) {\n events = deepmerge(events, { updated: { at: currentDate } });\n }\n if (!events.deleted) {\n events = deepmerge(events, { deleted: { at: null } });\n }\n\n } else {\n events = {\n created: { at: currentDate },\n updated: { at: currentDate },\n deleted: { at: null },\n };\n }\n\n return deepmerge(item, { events }) as Partial<Item<S, L1, L2, L3, L4, L5>>;\n}\n\nexport const updateEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>):\n Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Updating Events', { item });\n const currentDate = new Date();\n const events: Evented = {\n updated: { at: currentDate },\n };\n\n // TODO: This is clean-up code, we should remove it\n // If the event lacks a created data, let's just insert it here...\n if (!item.events || !item.events.created || !item.events.created.at) {\n events.created = { at: currentDate };\n }\n\n return deepmerge(item, { events }) as Partial<Item<S, L1, L2, L3, L4, L5>>;\n}\n//#endregion\n\nexport const populateEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n const events: ManagedEvents = {\n created: { at: item.createdAt || null },\n updated: { at: item.updatedAt || null },\n deleted: { at: null }\n };\n item.events = events;\n return item;\n}\n\nexport const extractEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Extracting Events to database fields', { item });\n\n if (item.events) {\n if (item.events.created?.at) {\n item.createdAt = item.events.created.at;\n }\n if (item.events.updated?.at) {\n item.updatedAt = item.events.updated.at;\n }\n if (item.events.deleted?.at) {\n item.deletedAt = item.events.deleted.at;\n }\n }\n\n return item;\n}\n\nexport const removeEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Removing Events', { item });\n delete item.events;\n return item;\n}\n", "import { Item, PriKey } from \"@fjell/core\";\nimport type { Registry } from \"@fjell/lib\";\nimport { OperationContext } from \"@fjell/lib\";\nimport logger from \"../logger\";\n\n/**\n * Sequelize-specific definition for a reference relationship.\n * References in Sequelize are stored as foreign key columns (e.g., \"authorId\")\n * and populated into properties on the item.\n */\nexport interface SequelizeReferenceDefinition {\n /** Column name containing the foreign key value (e.g., \"authorId\") */\n column: string;\n /** Key type array of the referenced item */\n kta: string[];\n /** Property name to populate with the referenced item (e.g., \"author\") */\n property: string;\n}\n\n/**\n * Build a reference by looking up a related item by its key from a column value.\n * The referenced item will be populated directly into a property on the item.\n *\n * @param item - The item to populate with reference data\n * @param referenceDefinition - Sequelize-specific definition of what to reference\n * @param registry - Registry to look up library instances\n * @param context - Optional operation context for caching and cycle detection\n * @returns The item with the reference property populated\n */\nexport const buildSequelizeReference = async (\n item: any,\n referenceDefinition: SequelizeReferenceDefinition,\n registry: Registry,\n context?: OperationContext\n) => {\n const libLogger = logger.get('processing', 'ReferenceBuilder');\n \n // For multikey references, we assume that the primary key of the first key type is unique\n // and can be used to retrieve the composite item with just a PriKey<S>\n const primaryKeyType = referenceDefinition.kta[0];\n\n if (referenceDefinition.kta.length > 1) {\n libLogger.debug(\n 'Using multikey reference with PriKey assumption',\n {\n kta: referenceDefinition.kta,\n primaryKeyType,\n property: referenceDefinition.property,\n column: referenceDefinition.column\n }\n );\n\n // TODO: Add validation to check if the target model has a unique primary key\n libLogger.debug(\n 'ASSUMPTION: The primary key for key type \"%s\" is unique and can be used to retrieve composite items',\n primaryKeyType\n );\n }\n\n // Check if dependencies exist\n if (!registry) {\n throw new Error(\n `This model definition has a reference definition, but the registry is not present. ` +\n `Reference property: '${referenceDefinition.property}', ` +\n `key types: [${referenceDefinition.kta.join(', ')}], column: '${referenceDefinition.column}'`\n );\n }\n\n // Find the Library.Instance for the key type\n const library: any = registry.get(referenceDefinition.kta as any);\n if (!library) {\n throw new Error(\n `This model definition has a reference definition, but the dependency is not present in registry. ` +\n `Reference property: '${referenceDefinition.property}', ` +\n `missing key type: '${primaryKeyType}', column: '${referenceDefinition.column}'`\n );\n }\n\n // Check if the column value is null - if so, skip the reference\n const columnValue = item[referenceDefinition.column];\n if (columnValue == null) {\n item[referenceDefinition.property] = null;\n return item;\n }\n\n // Create a PriKey using the column value from item\n // For multikey references, we use the primary key type (first in the kta array)\n const priKey: PriKey<string> = {\n kt: primaryKeyType,\n pk: columnValue\n };\n\n let referencedItem;\n\n if (context) {\n // Check if we already have this item cached\n if (context.isCached(priKey)) {\n libLogger.debug('Using cached reference', { priKey, property: referenceDefinition.property });\n referencedItem = context.getCached(priKey);\n }\n // Check if this item is currently being loaded (circular dependency)\n else if (context.isInProgress(priKey)) {\n libLogger.debug('Circular dependency detected, creating reference placeholder', {\n priKey,\n property: referenceDefinition.property\n });\n\n // Create a minimal reference object with just the key to break the cycle\n referencedItem = {\n key: priKey,\n // Add any other minimal properties that might be needed\n // This prevents infinite loops while still providing the key for identification\n };\n }\n else {\n // Mark this key as in progress before loading\n context.markInProgress(priKey);\n try {\n // Get the referenced item using the Library.Operations get method (context now managed internally)\n referencedItem = await library!.operations.get(priKey);\n\n // Cache the result\n context.setCached(priKey, referencedItem);\n } catch (error: any) {\n throw error; // Re-throw to maintain original behavior\n } finally {\n // Always mark as complete, even if there was an error\n context.markComplete(priKey);\n }\n }\n } else {\n // Fallback to original behavior if no context provided\n referencedItem = await library!.operations.get(priKey);\n }\n\n // Store the result in the property on item (Sequelize style - direct property)\n item[referenceDefinition.property] = referencedItem;\n\n return item;\n};\n\n/**\n * Strip populated reference properties from item before writing to database.\n * This ensures we only store the foreign key columns, not the full populated items.\n *\n * @param item - The item to strip references from\n * @param referenceDefinitions - Array of reference definitions to strip\n * @returns The item with only foreign key values (no populated items)\n */\nexport const stripSequelizeReferenceItems = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n referenceDefinitions: SequelizeReferenceDefinition[]\n ): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n const result = { ...item };\n\n // Remove populated reference properties but keep the foreign key columns\n for (const refDef of referenceDefinitions) {\n // Delete the populated property (e.g., delete item.author)\n // Keep the foreign key column (e.g., keep item.authorId)\n delete result[refDef.property as keyof typeof result];\n }\n\n return result;\n};\n\n", "/* eslint-disable indent */\nimport { ComKey, isComKey, isPriKey, Item, LocKeyArray, PriKey, validateKeys } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport { validateLocations } from \"../validation/LocationKeyValidator\";\nimport LibLogger from '../logger';\nimport { processRow } from \"../RowProcessor\";\nimport * as Library from \"@fjell/lib\";\nimport { ModelStatic } from \"sequelize\";\nimport { extractEvents, removeEvents } from \"../EventCoordinator\";\nimport { buildRelationshipChain, buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { stringifyJSON } from \"../util/general\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'create');\n\n// Helper function to translate PostgreSQL errors to meaningful messages\nfunction translateDatabaseError(error: any, itemData: any, modelName: string): Error {\n const originalMessage = error.message || '';\n const errorCode = error.original?.code;\n const constraint = error.original?.constraint;\n const detail = error.original?.detail;\n\n logger.error('Database error during create operation', {\n errorCode,\n constraint,\n detail,\n originalMessage,\n modelName,\n itemData: JSON.stringify(itemData, null, 2)\n });\n\n // Handle specific PostgreSQL error codes\n switch (errorCode) {\n case '23505': // unique_violation\n if (constraint) {\n return new Error(`Duplicate value violates unique constraint '${constraint}'. ${detail || ''}`);\n }\n return new Error(`Duplicate value detected. This record already exists. ${detail || ''}`);\n\n case '23503': // foreign_key_violation\n if (constraint) {\n return new Error(`Foreign key constraint '${constraint}' violated. Referenced record does not exist. ${detail || ''}`);\n }\n return new Error(`Referenced record does not exist. Check that all related records are valid. ${detail || ''}`);\n\n case '23502': // not_null_violation\n const column = error.original?.column;\n if (column) {\n return new Error(`Required field '${column}' cannot be null`);\n }\n return new Error(`Required field is missing or null`);\n\n case '23514': // check_violation\n if (constraint) {\n return new Error(`Check constraint '${constraint}' violated. ${detail || ''}`);\n }\n return new Error(`Data validation failed. Check constraint violated. ${detail || ''}`);\n\n case '22001': // string_data_right_truncation\n return new Error(`Data too long for field. Check string lengths. ${detail || ''}`);\n\n case '22003': // numeric_value_out_of_range\n return new Error(`Numeric value out of range. Check number values. ${detail || ''}`);\n\n case '42703': // undefined_column\n const undefinedColumn = error.original?.column;\n if (undefinedColumn) {\n return new Error(`Column '${undefinedColumn}' does not exist in table '${modelName}'`);\n }\n return new Error(`Referenced column does not exist`);\n\n case '42P01': // undefined_table\n return new Error(`Table '${modelName}' does not exist`);\n\n default:\n // Handle SQLite-specific errors that don't have error codes\n if (originalMessage.includes('notNull Violation')) {\n const fieldMatches = originalMessage.match(/([a-zA-Z]+\\.[a-zA-Z]+) cannot be null/g);\n if (fieldMatches) {\n const fields = fieldMatches.map((match: string) => {\n const parts = match.split('.');\n return parts[1]?.split(' ')[0]; // Extract field name like 'code' from 'WidgetType.code'\n }).filter(Boolean);\n if (fields.length > 0) {\n return new Error(`Required field${fields.length > 1 ? 's' : ''} ${fields.join(', ')} cannot be null`);\n }\n }\n return new Error('Required fields are missing');\n }\n\n // For unknown errors, provide the original message with context\n return new Error(`Database error in ${modelName}.create(): ${originalMessage}. Item data: ${JSON.stringify(itemData, null, 2)}`);\n }\n}\n\n// Helper function to validate hierarchical chain exists\nasync function validateHierarchicalChain(\n models: ModelStatic<any>[],\n locKey: { kt: string; lk: any },\n kta: string[]\n): Promise<void> {\n try {\n // Find the direct parent model that contains this locator\n const locatorIndex = kta.indexOf(locKey.kt);\n if (locatorIndex === -1) {\n throw new Error(`Locator type '${locKey.kt}' not found in kta array`);\n }\n\n // Get the model for this locator\n const locatorModel = models[locatorIndex] || models[0]; // Fallback to primary model\n\n // Build a query to validate the chain exists\n const chainResult = buildRelationshipChain(locatorModel, kta, locatorIndex, kta.length - 1);\n\n if (!chainResult.success) {\n // If we can't build a chain, just validate the record exists\n const record = await locatorModel.findByPk(locKey.lk);\n if (!record) {\n throw new Error(`Referenced ${locKey.kt} with id ${locKey.lk} does not exist`);\n }\n return;\n }\n\n // Validate that the chain exists\n const queryOptions: any = {\n where: { id: locKey.lk }\n };\n\n if (chainResult.includes && chainResult.includes.length > 0) {\n queryOptions.include = chainResult.includes;\n }\n\n const record = await locatorModel.findOne(queryOptions);\n if (!record) {\n throw new Error(`Referenced ${locKey.kt} with id ${locKey.lk} does not exist or chain is invalid`);\n }\n } catch (error: any) {\n // Add context to validation errors\n if (error.original) {\n throw translateDatabaseError(error, { locKey, kta }, locKey.kt);\n }\n throw error;\n }\n}\n\nexport const getCreateOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n\n registry: Library.Registry\n) => {\n\n const create = async (\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n options?: {\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n locations?: never;\n } | {\n key?: never;\n locations: LocKeyArray<L1, L2, L3, L4, L5>,\n },\n ): Promise<V> => {\n const constraints = options?.key\n ? `key: pk=${options.key.pk}, loc=[${isComKey(options.key)\n ? (options.key as ComKey<S, L1, L2, L3, L4, L5>).loc.map((l: any) => `${l.kt}=${l.lk}`).join(', ')\n : ''}]`\n : options?.locations\n ? `locations: ${options.locations.map(loc => `${loc.kt}=${loc.lk}`).join(', ')}`\n : 'no constraints';\n logger.debug(`CREATE operation called on ${models[0].name} with ${constraints}`);\n logger.default(`Create configured for ${models[0].name} with ${Object.keys(item).length} item fields`);\n\n const { coordinate, options: { references, aggregations } } = definition;\n const { kta } = coordinate;\n\n // Validate location key order from options\n if (options?.locations) {\n validateLocations(options.locations, coordinate, 'create');\n }\n if (options?.key && isComKey(options.key)) {\n validateLocations((options.key as ComKey<S, L1, L2, L3, L4, L5>).loc, coordinate, 'create');\n }\n\n // Get the primary model (first model in array)\n const model = models[0];\n const modelAttributes = model.getAttributes();\n\n // Validate that all item attributes exist on the model\n let itemData = { ...item } as any;\n\n // TODO: We need the opposite of processRow, something to step down from fjell to database.\n itemData = extractEvents(itemData);\n itemData = removeEvents(itemData);\n\n // Validate that all item attributes exist on the model\n const invalidAttributes: string[] = [];\n for (const key of Object.keys(itemData)) {\n if (!modelAttributes[key]) {\n invalidAttributes.push(key);\n }\n }\n\n if (invalidAttributes.length > 0) {\n const availableAttributes = Object.keys(modelAttributes).join(', ');\n throw new Error(\n `Invalid attributes for model '${model.name}': [${invalidAttributes.join(', ')}]. ` +\n `Available attributes: [${availableAttributes}]. ` +\n `Item data: ${JSON.stringify(itemData, null, 2)}`\n );\n }\n\n // Handle key options\n // If a key is supplied, assume its contents are to be assigned to the appropriate ids.\n // For most cases this will be null as key generation is often through autoIncrement.\n // If this is a CItem then the locations will be present.\n if (options?.key) {\n const key = options.key;\n if (isPriKey(key)) {\n // Set the primary key\n itemData.id = key.pk;\n } else if (isComKey(key)) {\n // Set primary key\n itemData.id = key.pk;\n\n // Process location keys - only set direct foreign keys, validate hierarchical chains\n const comKey = key as ComKey<S, L1, L2, L3, L4, L5>;\n const directLocations: Array<{ kt: string; lk: any }> = [];\n const hierarchicalLocations: Array<{ kt: string; lk: any }> = [];\n\n // Categorize location keys as direct or hierarchical\n for (const locKey of comKey.loc) {\n const relationshipInfo = buildRelationshipPath(model, locKey.kt, kta, true);\n\n if (!relationshipInfo.found) {\n const associations = model.associations ? Object.keys(model.associations) : [];\n const errorMessage = `Composite key locator '${locKey.kt}' cannot be resolved on model '${model.name}' or through its relationships. ` +\n `Available associations: [${associations.join(', ')}]. ` +\n `KTA: [${kta.join(', ')}]. ` +\n `Composite key: ${JSON.stringify(comKey, null, 2)}`;\n logger.error(errorMessage, { key: comKey, kta, associations });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.isDirect) {\n directLocations.push(locKey);\n } else {\n hierarchicalLocations.push(locKey);\n }\n }\n\n // Set direct foreign keys\n for (const locKey of directLocations) {\n if (locKey.lk == null || locKey.lk === '') {\n logger.error(`Composite key location '${locKey.kt}' has undefined/null lk value`, { locKey, key: comKey });\n throw new Error(`Composite key location '${locKey.kt}' has undefined/null lk value`);\n }\n const foreignKeyField = locKey.kt + 'Id';\n itemData[foreignKeyField] = locKey.lk;\n }\n\n // Validate hierarchical chains exist\n for (const locKey of hierarchicalLocations) {\n await validateHierarchicalChain(models, locKey, kta);\n }\n }\n }\n\n // Handle locations options\n // This is the most frequent way relationship ids will be set\n if (options?.locations) {\n const directLocations: Array<{ kt: string; lk: any }> = [];\n const hierarchicalLocations: Array<{ kt: string; lk: any }> = [];\n\n // Categorize location keys as direct or hierarchical\n for (const locKey of options.locations) {\n const relationshipInfo = buildRelationshipPath(model, locKey.kt, kta, true);\n\n if (!relationshipInfo.found) {\n const associations = model.associations ? Object.keys(model.associations) : [];\n const errorMessage = `Location key '${locKey.kt}' cannot be resolved on model '${model.name}' or through its relationships. ` +\n `Available associations: [${associations.join(', ')}]. ` +\n `KTA: [${kta.join(', ')}]. ` +\n `Locations: ${JSON.stringify(options.locations, null, 2)}`;\n logger.error(errorMessage, { locations: options.locations, kta, associations });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.isDirect) {\n directLocations.push(locKey);\n } else {\n hierarchicalLocations.push(locKey);\n }\n }\n\n // Set direct foreign keys\n for (const locKey of directLocations) {\n if (locKey.lk == null || locKey.lk === '') {\n logger.error(`Location option '${locKey.kt}' has undefined/null lk value`, { locKey, locations: options.locations });\n throw new Error(`Location option '${locKey.kt}' has undefined/null lk value`);\n }\n const foreignKeyField = locKey.kt + 'Id';\n itemData[foreignKeyField] = locKey.lk;\n }\n\n // Validate hierarchical chains exist\n for (const locKey of hierarchicalLocations) {\n await validateHierarchicalChain(models, locKey, kta);\n }\n }\n\n // Create the record\n try {\n logger.trace(`[CREATE] Executing ${model.name}.create() with data: ${stringifyJSON(itemData)}`);\n const createdRecord = await model.create(itemData);\n\n // Add key and events\n // Create operations get their own context since they're top-level operations\n const processedRecord = await processRow(createdRecord, kta, references || [], aggregations || [], registry);\n const result = validateKeys(processedRecord, kta) as V;\n\n logger.debug(`[CREATE] Created ${model.name} with key: ${(result as any).key ? JSON.stringify((result as any).key) : `id=${createdRecord.id}`}`);\n return result;\n } catch (error: any) {\n throw translateDatabaseError(error, itemData, model.name);\n }\n }\n\n return create;\n}\n", "/* eslint-disable indent */\nimport { Item, LocKeyArray, validateKeys } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport { validateLocations } from \"../validation/LocationKeyValidator\";\nimport LibLogger from '../logger';\nimport { ModelStatic } from \"sequelize\";\nimport { processRow } from \"../RowProcessor\";\nimport * as Library from \"@fjell/lib\";\nimport { stringifyJSON } from \"../util/general\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'find');\n\nexport const getFindOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n) => {\n\n const { options: { finders, references, aggregations } } = definition;\n\n const find = async (\n finder: string,\n finderParams: Record<string, string | number | boolean | Date | Array<string | number | boolean | Date>>,\n locations?: LocKeyArray<L1, L2, L3, L4, L5> | [],\n\n ): Promise<V[]> => {\n const locationFilters = locations?.map(loc => `${loc.kt}=${loc.lk}`).join(', ') || 'none';\n logger.debug(\n `FIND operation called on ${models[0].name} with finder '${finder}' ` +\n `and ${locations?.length || 0} location filters: ${locationFilters}`\n );\n logger.default(`Find configured for ${models[0].name} using finder '${finder}' with ${Object.keys(finderParams).length} params`);\n\n // Validate location key order\n validateLocations(locations, definition.coordinate, 'find');\n\n // Note that we execute the createFinders function here because we want to make sure we're always getting the\n // most up to date methods.\n if (finders && finders[finder]) {\n const finderMethod = finders[finder];\n if (finderMethod) {\n logger.trace(`[FIND] Executing finder '${finder}' on ${models[0].name} with params: ${stringifyJSON(finderParams)}, locations: ${stringifyJSON(locations)}`);\n const results = await finderMethod(finderParams, locations);\n if (results && results.length > 0) {\n const processedResults = (await Promise.all(results.map(async (row: any) => {\n // Each found row gets its own context to prevent interference between concurrent processing\n const processedRow = await processRow(row, definition.coordinate.kta, references || [], aggregations || [], registry);\n return validateKeys(processedRow, definition.coordinate.kta);\n })) as V[]);\n\n logger.debug(`[FIND] Found ${processedResults.length} ${models[0].name} records using finder '${finder}'`);\n return processedResults;\n } else {\n logger.debug(`[FIND] Found 0 ${models[0].name} records using finder '${finder}'`);\n return [];\n }\n } else {\n logger.error(`Finder %s not found`, finder);\n throw new Error(`Finder ${finder} not found`);\n }\n } else {\n logger.error(`No finders have been defined for this lib`);\n throw new Error(`No finders found`);\n }\n }\n\n return find;\n}\n", "/* eslint-disable max-len */\n/* eslint-disable indent */\nimport {\n ComKey,\n isComKey,\n isPriKey,\n isValidItemKey,\n Item,\n PriKey,\n validateKeys\n} from '@fjell/core';\n\nimport LibLogger from '../logger';\nimport { ModelStatic } from 'sequelize';\nimport { processRow } from '../RowProcessor';\nimport { Definition } from '../Definition';\nimport { NotFoundError } from '@fjell/lib';\nimport * as Library from \"@fjell/lib\";\nimport { buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { contextManager } from \"../RowProcessor\";\nimport { stringifyJSON } from \"../util/general\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'get');\n\n// Helper function to process composite key and build query options\nconst processCompositeKey = (\n comKey: ComKey<any, any, any, any, any, any>,\n model: ModelStatic<any>,\n kta: string[]\n): { where: { [key: string]: any }; include?: any[] } => {\n const where: { [key: string]: any } = { id: comKey.pk };\n const includes: any[] = [];\n\n for (const locator of comKey.loc) {\n const relationshipInfo = buildRelationshipPath(model, locator.kt, kta);\n\n if (!relationshipInfo.found) {\n const errorMessage = `Composite key locator '${locator.kt}' cannot be resolved on model '${model.name}' or through its relationships. Key type array: [${kta.join(', ')}], Composite key: ${stringifyJSON(comKey)}, Available associations: [${Object.keys(model.associations || {}).join(', ')}]`;\n logger.error(errorMessage, { key: comKey, kta });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.path) {\n // This requires a relationship traversal\n where[relationshipInfo.path] = locator.lk;\n if (relationshipInfo.includes) {\n includes.push(...relationshipInfo.includes);\n }\n } else {\n // This is a direct field\n const fieldName = `${locator.kt}Id`;\n where[fieldName] = locator.lk;\n }\n }\n\n const result: { where: { [key: string]: any }; include?: any[] } = { where };\n if (includes.length > 0) {\n result.include = includes;\n }\n\n return result;\n};\n\nexport const getGetOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: Array<ModelStatic<any>>,\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n) => {\n\n const { coordinate, options: { references, aggregations } } = definition;\n const { kta } = coordinate;\n\n const get = async (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>\n ): Promise<V> => {\n if (!isValidItemKey(key)) {\n logger.error('Key for Get is not a valid ItemKey: %j', key);\n throw new Error('Key for Get is not a valid ItemKey');\n }\n\n const keyDescription = isPriKey(key)\n ? `primary key: pk=${key.pk}`\n : `composite key: pk=${key.pk}, loc=[${(key as ComKey<S, L1, L2, L3, L4, L5>).loc.map((l: any) => `${l.kt}=${l.lk}`).join(', ')}]`;\n logger.debug(`GET operation called on ${models[0].name} with ${keyDescription}`);\n logger.default(`Get configured for ${models[0].name} with ${isPriKey(key) ? 'primary' : 'composite'} key`);\n\n const itemKey = key;\n\n // @ts-ignore\n const model = models[0];\n\n let item;\n\n if (isPriKey(itemKey)) {\n // This is the easy case because we can just find the item by its primary key\n logger.trace(`[GET] Executing ${model.name}.findByPk() with pk: ${(itemKey as PriKey<S>).pk}`);\n item = await model.findByPk((itemKey as PriKey<S>).pk);\n } else if (isComKey(itemKey)) {\n // This is a composite key, so we need to build a where clause based on the composite key's locators\n const comKey = itemKey as ComKey<S, L1, L2, L3, L4, L5>;\n const queryOptions = processCompositeKey(comKey, model, kta);\n\n logger.default('Composite key query', { queryOptions });\n logger.trace(`[GET] Executing ${model.name}.findOne() with options: ${stringifyJSON(queryOptions)}`);\n item = await model.findOne(queryOptions);\n }\n\n if (!item) {\n throw new NotFoundError<S, L1, L2, L3, L4, L5>('get', coordinate, key);\n } else {\n // Use current context if available (prevents infinite recursion in reference loading)\n // This ensures proper circular dependency detection within the same operation\n const currentContext = contextManager.getCurrentContext();\n const result = validateKeys(await processRow(item, kta, references || [], aggregations || [], registry, currentContext), kta) as V;\n\n logger.debug(`[GET] Retrieved ${model.name} with key: ${(result as any).key ? JSON.stringify((result as any).key) : `id=${item.id}`}`);\n return result;\n }\n }\n\n return get;\n}\n", "/* eslint-disable indent */\nimport { Item, ItemQuery, LocKeyArray } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport { validateLocations } from \"../validation/LocationKeyValidator\";\nimport LibLogger from '../logger';\nimport { ModelStatic } from \"sequelize\";\nimport { getAllOperation } from \"./all\";\nimport * as Library from \"@fjell/lib\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'one');\n\nexport const getOneOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n) => {\n const one = async (\n itemQuery: ItemQuery,\n locations: LocKeyArray<L1, L2, L3, L4, L5> | [] = [],\n ): Promise<V | null> => {\n logger.debug(`ONE operation called on ${models[0].name} with ${locations.length} location filters: ${locations.map(loc => `${loc.kt}=${loc.lk}`).join(', ') || 'none'}`);\n logger.default(`One configured for ${models[0].name} delegating to all operation`);\n\n // Validate location key order\n validateLocations(locations, definition.coordinate, 'one');\n\n const items = await getAllOperation(models, definition, registry)(itemQuery, locations);\n if (items.length > 0) {\n const result = items[0] as V;\n logger.debug(`[ONE] Found ${models[0].name} record with key: ${(result as any).key ? JSON.stringify((result as any).key) : 'unknown'}`);\n return result;\n } else {\n logger.debug(`[ONE] No ${models[0].name} record found`);\n return null;\n }\n }\n\n return one;\n}", "/* eslint-disable */\nimport { ComKey, isValidItemKey, PriKey } from \"@fjell/core\";\n\nimport { abbrevIK, isComKey, isPriKey, Item } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport { populateEvents } from \"../EventCoordinator\";\nimport { addKey } from \"../KeyMaster\";\nimport LibLogger from '../logger';\nimport { ModelStatic } from \"sequelize\";\nimport { buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { stringifyJSON } from \"../util/general\";\nimport { NotFoundError } from \"@fjell/lib\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'remove');\n\n// Helper function to process composite key and build query options\nconst processCompositeKey = (\n comKey: ComKey<any, any, any, any, any, any>,\n model: ModelStatic<any>,\n kta: string[]\n): { where: { [key: string]: any }; include?: any[] } => {\n const where: { [key: string]: any } = { id: comKey.pk };\n const includes: any[] = [];\n\n for (const locator of comKey.loc) {\n const relationshipInfo = buildRelationshipPath(model, locator.kt, kta);\n\n if (!relationshipInfo.found) {\n const errorMessage = `Composite key locator '${locator.kt}' cannot be resolved on model '${model.name}' or through its relationships.`;\n logger.error(errorMessage, { key: comKey, kta });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.path) {\n // This requires a relationship traversal\n where[relationshipInfo.path] = locator.lk;\n if (relationshipInfo.includes) {\n includes.push(...relationshipInfo.includes);\n }\n } else {\n // This is a direct field\n const fieldName = `${locator.kt}Id`;\n where[fieldName] = locator.lk;\n }\n }\n\n const result: { where: { [key: string]: any }; include?: any[] } = { where };\n if (includes.length > 0) {\n result.include = includes;\n }\n\n return result;\n};\n\nexport const getRemoveOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n _registry: import('@fjell/lib').Registry\n) => {\n const { coordinate, options } = definition;\n const { kta } = coordinate;\n\n const remove = async (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n ): Promise<V> => {\n if (!isValidItemKey(key)) {\n logger.error('Key for Remove is not a valid ItemKey: %j', key);\n throw new Error('Key for Remove is not a valid ItemKey');\n }\n\n const keyDescription = isPriKey(key)\n ? `primary key: pk=${key.pk}`\n : `composite key: pk=${key.pk}, loc=[${(key as ComKey<S, L1, L2, L3, L4, L5>).loc.map((l: any) => `${l.kt}=${l.lk}`).join(', ')}]`;\n logger.debug(`REMOVE operation called on ${models[0].name} with ${keyDescription}`);\n logger.default(`Remove configured for ${models[0].name} with ${isPriKey(key) ? 'primary' : 'composite'} key`);\n\n // @ts-ignore\n const model = models[0];\n\n let item;\n let returnItem;\n\n logger.debug('remove: %s', abbrevIK(key));\n if (isPriKey(key)) {\n logger.debug(`[REMOVE] Executing ${model.name}.findByPk() with pk: ${(key as PriKey<S>).pk}`);\n item = await model.findByPk((key as PriKey<S>).pk);\n } else if (isComKey(key)) {\n // This is a composite key, so we need to build a where clause based on the composite key's locators\n const comKey = key as ComKey<S, L1, L2, L3, L4, L5>;\n const queryOptions = processCompositeKey(comKey, model, kta);\n\n logger.default(`Remove composite key query for ${model.name} with where fields: ${queryOptions.where ? Object.keys(queryOptions.where).join(', ') : 'none'}`);\n logger.debug(`[REMOVE] Executing ${model.name}.findOne() with options: ${stringifyJSON(queryOptions)}`);\n item = await model.findOne(queryOptions);\n }\n\n if (!item) {\n throw new NotFoundError<S, L1, L2, L3, L4, L5>('remove', coordinate, key);\n }\n\n const isDeletedAttribute = model.getAttributes().isDeleted;\n const deletedAtAttribute = model.getAttributes().deletedAt;\n\n if (isDeletedAttribute || deletedAtAttribute) {\n if (model.getAttributes().isDeleted) {\n item.isDeleted = true;\n }\n\n if (model.getAttributes().deletedAt) {\n item.deletedAt = new Date();\n }\n\n // Save the object\n logger.debug(`[REMOVE] Executing ${model.name}.save() for soft delete`);\n await item?.save();\n returnItem = item?.get({ plain: true }) as Partial<Item<S, L1, L2, L3, L4, L5>>;\n returnItem = addKey(item, returnItem as any, kta);\n returnItem = populateEvents(returnItem);\n } else if (options.deleteOnRemove) {\n logger.debug(`[REMOVE] Executing ${model.name}.destroy() for hard delete`);\n await item?.destroy();\n returnItem = item?.get({ plain: true }) as Partial<Item<S, L1, L2, L3, L4, L5>>;\n returnItem = addKey(item, returnItem as any, kta);\n returnItem = populateEvents(returnItem);\n } else {\n throw new Error('No deletedAt or isDeleted attribute found in model, and deleteOnRemove is not set');\n }\n\n logger.debug(`[REMOVE] Removed ${model.name} with key: ${(returnItem as any).key ? JSON.stringify((returnItem as any).key) : `id=${item.id}`}`);\n return returnItem as V;\n }\n\n return remove;\n}\n", "/* eslint-disable indent */\nimport { abbrevIK, isComKey, validateKeys } from \"@fjell/core\";\n\nimport { isPriKey } from \"@fjell/core\";\n\nimport { ComKey, Item, PriKey } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport { extractEvents, removeEvents } from \"../EventCoordinator\";\nimport { removeKey } from \"../KeyMaster\";\nimport LibLogger from '../logger';\nimport { processRow } from \"../RowProcessor\";\n\nimport * as Library from \"@fjell/lib\";\nimport { NotFoundError } from \"@fjell/lib\";\nimport { ModelStatic, Op } from \"sequelize\";\nimport { buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { stringifyJSON } from \"../util/general\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'update');\n\n// Helper function to merge includes avoiding duplicates\nconst mergeIncludes = (existingIncludes: any[], newIncludes: any[]): any[] => {\n const mergedIncludes = [...existingIncludes];\n\n for (const newInclude of newIncludes) {\n const existingIndex = mergedIncludes.findIndex(\n (existing: any) => existing.as === newInclude.as && existing.model === newInclude.model\n );\n if (existingIndex === -1) {\n mergedIncludes.push(newInclude);\n } else if (newInclude.include && mergedIncludes[existingIndex].include) {\n mergedIncludes[existingIndex].include = [\n ...mergedIncludes[existingIndex].include,\n ...newInclude.include\n ];\n } else if (newInclude.include) {\n mergedIncludes[existingIndex].include = newInclude.include;\n }\n }\n\n return mergedIncludes;\n};\n\nexport const getUpdateOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n\n registry: Library.Registry\n) => {\n\n const { options: { references, aggregations } } = definition;\n\n const update = async (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n ): Promise<V> => {\n const keyDescription = isPriKey(key)\n ? `primary key: pk=${key.pk}`\n : `composite key: pk=${key.pk}, loc=[${(key as ComKey<S, L1, L2, L3, L4, L5>).loc.map((l: any) => `${l.kt}=${l.lk}`).join(', ')}]`;\n logger.debug(`UPDATE operation called on ${models[0].name} with ${keyDescription}`);\n const { coordinate } = definition;\n const { kta } = coordinate;\n\n logger.debug('update: %s, %j', abbrevIK(key), item);\n // Find the object we're updating\n // @ts-ignore\n const model = models[0];\n\n let response;\n\n if (isPriKey(key)) {\n // Find the model by using the PK\n const priKey = key as PriKey<S>;\n logger.trace(`[UPDATE] Executing ${model.name}.findByPk() with pk: ${priKey.pk}`);\n response = await model.findByPk(priKey.pk);\n } else if (isComKey(key)) {\n const comKey = key as ComKey<S, L1, L2, L3, L4, L5>;\n\n // Build query options for composite key with multiple location keys\n const where: { [key: string]: any } = { id: comKey.pk };\n const additionalIncludes: any[] = [];\n\n // Process all location keys in the composite key\n for (const locator of comKey.loc) {\n const relationshipInfo = buildRelationshipPath(model, locator.kt, kta, true);\n\n if (!relationshipInfo.found) {\n const errorMessage = `Composite key locator '${locator.kt}' cannot be resolved on model '${model.name}' or through its relationships.`;\n logger.error(errorMessage, { key: comKey, kta });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.isDirect) {\n // Direct foreign key field\n const fieldName = `${locator.kt}Id`;\n where[fieldName] = locator.lk;\n } else if (relationshipInfo.path) {\n // Hierarchical relationship requiring traversal\n where[relationshipInfo.path] = {\n [Op.eq]: locator.lk\n };\n\n // Add necessary includes for relationship traversal\n if (relationshipInfo.includes) {\n additionalIncludes.push(...relationshipInfo.includes);\n }\n }\n }\n\n // Build final query options\n const queryOptions: any = { where };\n if (additionalIncludes.length > 0) {\n queryOptions.include = mergeIncludes([], additionalIncludes);\n }\n\n logger.default(`Update composite key query for ${model.name} with where fields: ${queryOptions.where ? Object.keys(queryOptions.where).join(', ') : 'none'}`);\n logger.trace(`[UPDATE] Executing ${model.name}.findOne() with options: ${stringifyJSON(queryOptions)}`);\n response = await model.findOne(queryOptions);\n }\n\n if (response) {\n\n // Remove the key and events\n let updateProps = removeKey(item)\n // TODO: We need the opposite of processRow, something to step down from fjell to database.\n updateProps = extractEvents(updateProps);\n updateProps = removeEvents(updateProps);\n\n logger.default(`Update found ${model.name} record to modify`);\n logger.default(`Update properties configured: ${Object.keys(updateProps).join(', ')}`);\n\n // Update the object\n logger.trace(`[UPDATE] Executing ${model.name}.update() with properties: ${stringifyJSON(updateProps)}`);\n response = await response.update(updateProps);\n\n // Populate the key and events\n // Update operations get their own context since they're top-level operations\n const processedItem = await processRow(response, kta, references || [], aggregations || [], registry);\n const returnItem = validateKeys(processedItem, kta);\n\n logger.debug(`[UPDATE] Updated ${model.name} with key: ${(returnItem as any).key ? JSON.stringify((returnItem as any).key) : `id=${response.id}`}`);\n return returnItem as V;\n } else {\n throw new NotFoundError<S, L1, L2, L3, L4, L5>('update', coordinate, key);\n }\n\n }\n\n return update;\n}\n", "/* eslint-disable indent */\nimport { ComKey, isValidItemKey, Item, PriKey } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport LibLogger from '../logger';\nimport * as Library from \"@fjell/lib\";\nimport { ModelStatic } from \"sequelize\";\nimport { getGetOperation } from \"./get\";\nimport { getUpdateOperation } from \"./update\";\nimport { getCreateOperation } from \"./create\";\nimport { stringifyJSON } from \"../util/general\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'upsert');\n\nexport const getUpsertOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: Array<ModelStatic<any>>,\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n) => {\n\n // Get the individual operations we'll use\n const get = getGetOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n const update = getUpdateOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n const create = getCreateOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n\n const upsert = async (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>\n ): Promise<V> => {\n\n if (!isValidItemKey(key)) {\n logger.error('Key for Upsert is not a valid ItemKey: %j', key);\n throw new Error(`Key for Upsert is not a valid ItemKey: ${stringifyJSON(key)}`);\n }\n\n logger.debug(`[UPSERT] Attempting upsert with key: ${stringifyJSON(key)}`);\n\n try {\n // Try to get the existing item first\n const existingItem = await get(key);\n if (existingItem) {\n logger.debug(`[UPSERT] Item exists, updating with key: ${stringifyJSON(key)}`);\n // Item exists, update it\n return await update(key, item);\n }\n } catch {\n // Item doesn't exist (get threw NotFoundError), fall through to create\n logger.debug(`[UPSERT] Item not found, creating new item with key: ${stringifyJSON(key)}`);\n }\n\n // Item doesn't exist, create it\n return await create(item, { key });\n }\n\n return upsert;\n}\n", "/* eslint-disable indent */\nimport { Item } from \"@fjell/core\";\n\nimport * as Library from \"@fjell/lib\";\nimport { Registry } from \"./Registry\";\nimport { getAllOperation } from \"./ops/all\";\nimport { getCreateOperation } from \"./ops/create\";\nimport { getFindOperation } from \"./ops/find\";\nimport { getGetOperation } from \"./ops/get\";\nimport { getOneOperation } from \"./ops/one\";\nimport { getRemoveOperation } from \"./ops/remove\";\nimport { getUpdateOperation } from \"./ops/update\";\nimport { getUpsertOperation } from \"./ops/upsert\";\nimport { ModelStatic } from \"sequelize\";\nimport { Coordinate } from \"@fjell/registry\";\n\nexport const createOperations = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never,\n>(\n models: Array<ModelStatic<any>>,\n coordinate: Coordinate<S, L1, L2, L3, L4, L5>,\n registry: Registry,\n options: import('./Options').Options<V, S, L1, L2, L3, L4, L5>\n): Library.Operations<V, S, L1, L2, L3, L4, L5> => {\n\n const operations = {} as Library.Operations<V, S, L1, L2, L3, L4, L5>;\n\n // Create a definition-like object for backward compatibility with existing operation functions\n const definition = { coordinate, options };\n\n operations.all = getAllOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n operations.one = getOneOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n operations.create = getCreateOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n operations.update = getUpdateOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n operations.get = getGetOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n operations.remove = getRemoveOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n operations.find = getFindOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n operations.upsert = getUpsertOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n operations.allFacet = async (): Promise<any> => { };\n operations.allAction = async (): Promise<any> => { };\n operations.action = async (): Promise<any> => { };\n operations.facet = async (): Promise<any> => { };\n\n operations.finders = { ...(options.finders || {}) };\n operations.actions = { ...(options.actions || {}) };\n operations.facets = { ...(options.facets || {}) };\n operations.allActions = { ...(options.allActions || {}) };\n operations.allFacets = { ...(options.allFacets || {}) };\n\n return operations;\n}\n", "import { Item } from \"@fjell/core\";\nimport { Options } from \"./Options\";\nimport { Registry as LocalRegistry } from \"./Registry\";\nimport { InstanceFactory as BaseInstanceFactory, Registry as BaseRegistry, Coordinate, RegistryHub } from \"@fjell/registry\";\nimport { createSequelizeLibrary, SequelizeLibrary } from \"./SequelizeLibrary\";\nimport { ModelStatic } from \"sequelize\";\nimport SequelizeLogger from \"./logger\";\n\nconst logger = SequelizeLogger.get(\"InstanceFactory\");\n\n/**\n * Sequelize Library Factory type that extends the base factory\n * to include Sequelize-specific models parameter\n */\nexport type SequelizeLibraryFactory<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> = (\n models: ModelStatic<any>[],\n options: Options<V, S, L1, L2, L3, L4, L5>\n) => BaseInstanceFactory<S, L1, L2, L3, L4, L5>;\n\n/**\n * Factory function for creating Sequelize libraries\n * This extends the fjell-lib pattern by adding Sequelize-specific models\n */\nexport const createSequelizeLibraryFactory = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n options: Options<V, S, L1, L2, L3, L4, L5>\n ): BaseInstanceFactory<S, L1, L2, L3, L4, L5> => {\n return (coordinate: Coordinate<S, L1, L2, L3, L4, L5>, context: { registry: BaseRegistry, registryHub?: RegistryHub }) => {\n logger.debug(\"Creating Sequelize instance\", {\n coordinate,\n registry: context.registry,\n models: models.map(m => m.name),\n options\n });\n\n return createSequelizeLibrary<V, S, L1, L2, L3, L4, L5>(\n context.registry as LocalRegistry,\n coordinate,\n models,\n options\n ) as SequelizeLibrary<V, S, L1, L2, L3, L4, L5>;\n };\n};\n", "export * from './SequelizeLibrary';\n", "\nimport { SequelizeLibrary as AbstractSequelizeLibrary } from '../SequelizeLibrary';\nimport { Item, ItemTypeArray } from '@fjell/core';\nimport { Contained } from '@fjell/lib';\nimport * as Library from '@fjell/lib';\nimport { createOperations } from '../Operations';\nimport { ModelStatic } from 'sequelize';\nimport { Registry } from '../Registry';\nimport { createOptions, Options } from '../Options';\nimport { Coordinate, createCoordinate } from '../Coordinate';\n\nexport interface SequelizeLibrary<\n V extends Item<S>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> extends AbstractSequelizeLibrary<V, S, L1, L2, L3, L4, L5> {\n coordinate: Coordinate<S, L1, L2, L3, L4, L5>;\n registry: Registry;\n operations: Library.Operations<V, S, L1, L2, L3, L4, L5>;\n options: Options<V, S, L1, L2, L3, L4, L5>;\n models: ModelStatic<any>[];\n}\n\nexport function createSequelizeLibrary<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n keyTypes: ItemTypeArray<S, L1, L2, L3, L4, L5>,\n models: ModelStatic<any>[],\n libOptions: Partial<Options<V, S, L1, L2, L3, L4, L5>> = {},\n scopes: string[] = [],\n registry: Registry\n): SequelizeLibrary<V, S, L1, L2, L3, L4, L5> {\n\n // Create coordinate and options separately following new pattern\n const coordinate = createCoordinate(keyTypes, scopes);\n const options = createOptions(libOptions);\n\n // Create operations with the new signature\n const operations = createOperations<V, S, L1, L2, L3, L4, L5>(models, coordinate, registry, options);\n\n // Wrap operations for contained pattern\n const wrappedOperations = Contained.wrapOperations(operations, options as any, coordinate, registry);\n\n return {\n coordinate,\n registry,\n operations: wrappedOperations,\n options,\n models,\n } as unknown as SequelizeLibrary<V, S, L1, L2, L3, L4, L5>;\n}\n", "export * from './SequelizeLibrary';\n", "\nimport { SequelizeLibrary as AbstractSequelizeLibrary } from '../SequelizeLibrary';\nimport { Item } from '@fjell/core';\nimport { Primary } from '@fjell/lib';\nimport * as Library from '@fjell/lib';\nimport { createOperations } from '../Operations';\nimport { ModelStatic } from 'sequelize';\nimport { createOptions, Options } from '../Options';\nimport { Registry } from '../Registry';\nimport { Coordinate, createCoordinate } from '../Coordinate';\n\nimport LibLogger from '../logger';\n\nconst logger = LibLogger.get('lib-sequelize', 'primary', 'library');\n\nexport interface SequelizeLibrary<\n V extends Item<S>,\n S extends string\n> extends AbstractSequelizeLibrary<V, S> {\n coordinate: Coordinate<S>;\n registry: Registry;\n operations: Library.Operations<V, S>;\n options: Options<V, S>;\n models: ModelStatic<any>[];\n}\n\nexport function createSequelizeLibrary<\n V extends Item<S>,\n S extends string\n>(\n keyType: S,\n models: ModelStatic<any>[],\n libOptions: Partial<Options<V, S>> = {},\n scopes: string[] = [],\n registry: Registry\n): SequelizeLibrary<V, S> {\n logger.debug('createSequelizeLibrary', { keyType, models, libOptions, scopes });\n\n // Create coordinate and options separately following new pattern\n const coordinate = createCoordinate([keyType], scopes);\n const options = createOptions(libOptions);\n\n // Create operations with the new signature\n const operations = createOperations<V, S>(models, coordinate, registry, options);\n\n // Wrap operations for primary pattern\n const wrappedOperations = Primary.wrapOperations(operations, options as any, coordinate, registry);\n\n return {\n coordinate,\n registry,\n operations: wrappedOperations,\n options,\n models,\n } as unknown as SequelizeLibrary<V, S>;\n}\n"],
5
- "mappings": ";;;;;;;AAAA,YAAY,aAAa;AAkFlB,IAAMA,iBAAgB,CAQ3B,qBAA4F;AAE5F,QAAM,EAAE,YAAY,gBAAgB,GAAG,qBAAqB,IAAI,oBAAoB,CAAC;AAGrF,QAAM,cAAsB,sBAAc,oBAAiE;AAG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,YAAY,SAAgB,YAAY,QAAQ;AAEjG,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import * as Library from '@fjell/lib';\nimport { ComKey, Item, LocKeyArray, PriKey } from '@fjell/core';\nimport { SequelizeReferenceDefinition } from './processing/ReferenceBuilder';\n\n// Re-export AggregationDefinition from @fjell/lib for backwards compatibility\nexport type { AggregationDefinition } from '@fjell/lib';\n\n// Export Sequelize-specific reference definition\nexport type { SequelizeReferenceDefinition } from './processing/ReferenceBuilder';\n\n/**\n * Sequelize-specific Options that uses SequelizeReferenceDefinition\n * instead of the generic ReferenceDefinition\n */\nexport interface Options<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> {\n hooks?: {\n preCreate?: (\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n options?:\n {\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n locations?: never;\n } | {\n key?: never;\n locations: LocKeyArray<L1, L2, L3, L4, L5>,\n }\n ) => Promise<Partial<Item<S, L1, L2, L3, L4, L5>>>;\n postCreate?: (\n item: V,\n ) => Promise<V>;\n preUpdate?: (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n ) => Promise<Partial<Item<S, L1, L2, L3, L4, L5>>>;\n postUpdate?: (\n item: V,\n ) => Promise<V>;\n preRemove?: (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n ) => Promise<Partial<Item<S, L1, L2, L3, L4, L5>>>;\n postRemove?: (\n item: V,\n ) => Promise<V>;\n },\n validators?: {\n onCreate?: (\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n options?:\n {\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n locations?: never;\n } | {\n key?: never;\n locations: LocKeyArray<L1, L2, L3, L4, L5>,\n }\n ) => Promise<boolean>;\n onUpdate?: (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n ) => Promise<boolean>;\n onRemove?: (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n ) => Promise<boolean>;\n },\n finders?: Record<string, Library.FinderMethod<V, S, L1, L2, L3, L4, L5>>,\n actions?: Record<string, Library.ActionMethod<V, S, L1, L2, L3, L4, L5>>,\n facets?: Record<string, Library.FacetMethod<V, S, L1, L2, L3, L4, L5>>,\n allActions?: Record<string, Library.AllActionMethod<V, S, L1, L2, L3, L4, L5>>,\n allFacets?: Record<string, Library.AllFacetMethod<L1, L2, L3, L4, L5>>,\n references?: SequelizeReferenceDefinition[], // Sequelize-specific!\n aggregations?: Library.AggregationDefinition[],\n deleteOnRemove?: boolean; // Sequelize-specific option\n}\n\nexport const createOptions = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(sequelizeOptions?: Options<V, S, L1, L2, L3, L4, L5>): Options<V, S, L1, L2, L3, L4, L5> => {\n // Convert Sequelize options to Library options (excluding references which have different types)\n const { references, deleteOnRemove, ...libCompatibleOptions } = sequelizeOptions || {};\n \n // Create base options from Library\n const baseOptions = Library.createOptions(libCompatibleOptions as Library.Options<V, S, L1, L2, L3, L4, L5>);\n\n // Return Sequelize options with Sequelize-specific references, aggregations, and deleteOnRemove\n return {\n ...baseOptions,\n references: references ?? [], // Keep Sequelize-specific references\n aggregations: baseOptions.aggregations ?? [], // Ensure aggregations is always present\n deleteOnRemove: deleteOnRemove ?? false, // Sequelize-specific option\n } as Options<V, S, L1, L2, L3, L4, L5>;\n}\n", "import Logging from '@fjell/logging';\n\nconst LibLogger = Logging.getLogger('@fjell/lib-sequelize');\n\nexport default LibLogger;\n", "import { ItemTypeArray } from '@fjell/core';\nimport { Coordinate, createCoordinate as createBaseCoordinate } from '@fjell/registry';\nimport LibLogger from './logger';\n\nconst logger = LibLogger.get('Coordinate');\n\nexport const SCOPE_SEQUELIZE = 'sequelize';\n\nexport const createCoordinate = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(kta: ItemTypeArray<S, L1, L2, L3, L4, L5>, scopes?: string[]): Coordinate<S, L1, L2, L3, L4, L5> => {\n logger.debug('createCoordinate', { kta, scopes });\n const coordinate = createBaseCoordinate(kta, [SCOPE_SEQUELIZE, ...(scopes || [])]);\n return coordinate;\n};\n\n// Re-export the Coordinate type\nexport type { Coordinate } from '@fjell/registry';\n", "import { Item, ItemTypeArray } from '@fjell/core';\nimport { createOptions, Options } from './Options';\nimport LibLogger from './logger';\nimport { createCoordinate } from './Coordinate';\n\nconst logger = LibLogger.get('lib-sequelize', 'Definition');\n\nexport interface Definition<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> {\n coordinate: import('@fjell/registry').Coordinate<S, L1, L2, L3, L4, L5>;\n options: Options<V, S, L1, L2, L3, L4, L5>;\n}\n\nexport const createDefinition = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n kta: ItemTypeArray<S, L1, L2, L3, L4, L5>,\n scopes: string[],\n libOptions?: Partial<Options<V, S, L1, L2, L3, L4, L5>>,\n ): Definition<V, S, L1, L2, L3, L4, L5> => {\n logger.debug('createDefinition', { kta, scopes, libOptions });\n const coordinate = createCoordinate(kta, scopes);\n const options = createOptions<V, S, L1, L2, L3, L4, L5>(libOptions);\n\n return {\n coordinate,\n options,\n }\n}\n", "\nimport * as Library from '@fjell/lib';\nimport { Item } from '@fjell/core';\nimport { Coordinate } from '@fjell/registry';\nimport { Registry } from './Registry';\nimport { createOperations } from './Operations';\nimport { ModelStatic } from 'sequelize';\nimport { Options } from './Options';\nimport SequelizeLogger from './logger';\n\nconst logger = SequelizeLogger.get(\"SequelizeLibrary\");\n\n/**\n * The SequelizeLibrary interface extends the fjell-lib Library\n * and adds Sequelize-specific functionality:\n * - models: Array of Sequelize model classes for this library\n *\n * @template V - The type of the data model item, extending Item\n * @template S - The string literal type representing the model's key type\n * @template L1-L5 - Optional string literal types for location hierarchy levels\n */\nexport interface SequelizeLibrary<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> extends Library.Library<V, S, L1, L2, L3, L4, L5> {\n /** Array of Sequelize model classes associated with this library */\n models: ModelStatic<any>[];\n}\n\n/**\n * Creates a new SequelizeLibrary that extends the fjell-lib Library\n * with Sequelize-specific functionality\n */\nexport const createSequelizeLibrary = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n registry: Registry,\n coordinate: Coordinate<S, L1, L2, L3, L4, L5>,\n models: ModelStatic<any>[],\n options: Options<V, S, L1, L2, L3, L4, L5>\n ): SequelizeLibrary<V, S, L1, L2, L3, L4, L5> => {\n logger.debug(\"createSequelizeLibrary\", { coordinate, models, registry, options });\n\n // Create Sequelize-specific operations\n const operations = createOperations<V, S, L1, L2, L3, L4, L5>(models, coordinate, registry, options);\n\n // Wrap operations with validation and hooks from base library\n const wrappedOperations = Library.wrapOperations(operations, options, coordinate, registry);\n\n // Create the base fjell-lib library\n const libLibrary = Library.createLibrary(registry, coordinate, wrappedOperations, options);\n\n return {\n ...libLibrary,\n models,\n };\n}\n\n/**\n * Type guard to check if an object is a SequelizeLibrary\n */\nexport const isSequelizeLibrary = (library: any): library is SequelizeLibrary<any, any, any, any, any, any, any> => {\n return library != null &&\n library.coordinate != null &&\n library.operations != null &&\n library.options != null &&\n library.registry != null &&\n library.models != null &&\n Array.isArray(library.models);\n}\n", "/* eslint-disable no-undefined */\n/* eslint-disable indent */\nimport { validateKeys } from \"@fjell/core\";\n\nimport { buildQuery } from \"../QueryBuilder\";\n\nimport { Definition } from \"../Definition\";\nimport { validateLocations } from \"../validation/LocationKeyValidator\";\nimport LibLogger from '../logger';\nimport * as Library from \"@fjell/lib\";\nimport { processRow } from \"../RowProcessor\";\nimport { Item, ItemQuery, LocKeyArray } from \"@fjell/core\";\nimport { ModelStatic, Op } from \"sequelize\";\nimport { buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { contextManager } from \"../RowProcessor\";\n\nimport { stringifyJSON } from \"../util/general\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'all');\n\n// Helper function to merge includes avoiding duplicates\nconst mergeIncludes = (existingIncludes: any[], newIncludes: any[]): any[] => {\n const mergedIncludes = [...existingIncludes];\n\n for (const newInclude of newIncludes) {\n const existingIndex = mergedIncludes.findIndex(\n (existing: any) => existing.as === newInclude.as && existing.model === newInclude.model\n );\n if (existingIndex === -1) {\n mergedIncludes.push(newInclude);\n } else if (newInclude.include && mergedIncludes[existingIndex].include) {\n mergedIncludes[existingIndex].include = [\n ...mergedIncludes[existingIndex].include,\n ...newInclude.include\n ];\n } else if (newInclude.include) {\n mergedIncludes[existingIndex].include = newInclude.include;\n }\n }\n\n return mergedIncludes;\n};\n\nexport const getAllOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: Array<ModelStatic<any>>,\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n) => {\n\n const { coordinate, options: { references, aggregations } } = definition;\n\n //#region Query\n const all = async (\n itemQuery: ItemQuery,\n locations?: LocKeyArray<L1, L2, L3, L4, L5> | [] | undefined\n ): Promise<V[]> => {\n logger.debug(`ALL operation called on ${models[0].name} with ${locations?.length || 0} location filters: ${locations?.map(loc => `${loc.kt}=${loc.lk}`).join(', ') || 'none'}`);\n\n // Validate location key order\n validateLocations(locations, coordinate, 'all');\n\n const loc: LocKeyArray<L1, L2, L3, L4, L5> | [] = locations || [];\n\n // @ts-ignore\n const model = models[0];\n\n // Build base query from itemQuery\n const options = buildQuery(itemQuery, model);\n\n // Handle location keys if present\n if (loc.length > 0) {\n const { kta } = coordinate;\n const directLocations: Array<{ kt: string; lk: any }> = [];\n const hierarchicalLocations: Array<{ kt: string; lk: any }> = [];\n const additionalIncludes: any[] = [];\n\n // Categorize location keys as direct or hierarchical\n for (const locKey of loc) {\n const relationshipInfo = buildRelationshipPath(model, locKey.kt, kta, true);\n\n if (!relationshipInfo.found) {\n const errorMessage = `Location key '${locKey.kt}' cannot be resolved on model '${model.name}' or through its relationships.`;\n logger.error(errorMessage, { locations: loc, kta });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.isDirect) {\n directLocations.push(locKey);\n } else {\n hierarchicalLocations.push(locKey);\n }\n }\n\n // Handle direct location keys (simple foreign key constraints)\n for (const locKey of directLocations) {\n if (locKey.lk === undefined || locKey.lk == null || locKey.lk === '' || (typeof locKey.lk === 'object' && Object.keys(locKey.lk).length === 0)) {\n logger.error(`Location key '${locKey.kt}' has invalid lk value: ${stringifyJSON(locKey.lk)}`, { locKey, locations: loc });\n throw new Error(`Location key '${locKey.kt}' has invalid lk value: ${stringifyJSON(locKey.lk)}`);\n }\n const foreignKeyField = locKey.kt + 'Id';\n\n // Check if this field already has a condition from the itemQuery\n if (options.where[foreignKeyField]) {\n logger.debug(`[ALL] Field ${foreignKeyField} already constrained by itemQuery, skipping location constraint to avoid conflicts`);\n continue; // Skip this location constraint to avoid conflicts\n }\n\n logger.trace(`[ALL] Setting direct location where clause: ${foreignKeyField} = ${stringifyJSON(locKey.lk)} (type: ${typeof locKey.lk})`);\n options.where[foreignKeyField] = {\n [Op.eq]: locKey.lk\n };\n }\n\n // Handle hierarchical location keys (requires relationship traversal)\n for (const locKey of hierarchicalLocations) {\n if (locKey.lk === undefined || locKey.lk == null || locKey.lk === '' || (typeof locKey.lk === 'object' && Object.keys(locKey.lk).length === 0)) {\n logger.error(`Hierarchical location key '${locKey.kt}' has invalid lk value: ${stringifyJSON(locKey.lk)}`, { locKey, locations: loc });\n throw new Error(`Hierarchical location key '${locKey.kt}' has invalid lk value: ${stringifyJSON(locKey.lk)}`);\n }\n const relationshipInfo = buildRelationshipPath(model, locKey.kt, kta);\n\n if (relationshipInfo.found && relationshipInfo.path) {\n // Check if this field already has a condition from the itemQuery\n if (options.where[relationshipInfo.path]) {\n logger.debug(`[ALL] Field ${relationshipInfo.path} already constrained by itemQuery, skipping hierarchical location constraint to avoid conflicts`);\n continue; // Skip this location constraint to avoid conflicts\n }\n\n // Add the relationship constraint using the path\n logger.trace(`[ALL] Setting hierarchical location where clause: ${relationshipInfo.path} = ${stringifyJSON(locKey.lk)} (type: ${typeof locKey.lk})`);\n options.where[relationshipInfo.path] = {\n [Op.eq]: locKey.lk\n };\n\n // Add necessary includes for the relationship traversal\n if (relationshipInfo.includes) {\n additionalIncludes.push(...relationshipInfo.includes);\n }\n }\n }\n\n // Merge additional includes with existing includes\n if (additionalIncludes.length > 0) {\n const existingIncludes = options.include || [];\n options.include = mergeIncludes(existingIncludes, additionalIncludes);\n }\n }\n\n logger.default(`All query configured for ${model.name} with where fields: ${options.where ? Object.keys(options.where).join(', ') : 'none'}, includes: ${options.include?.length || 0}`);\n\n try {\n logger.trace(`[ALL] Executing ${model.name}.findAll() with options: ${JSON.stringify(options, null, 2)}`);\n } catch {\n // Fallback for cases where JSON.stringify fails on Sequelize operators\n logger.trace(`[ALL] Executing ${model.name}.findAll() with options containing non-serializable operators (${Object.keys(options.where || {}).length} where conditions)`);\n }\n const matchingItems = await model.findAll(options);\n\n // this.logger.default('Matching Items', { matchingItems });\n\n // Pass null as context to let processRow create a new context for each top-level operation\n // This prevents circular dependency false positives between concurrent operations\n // while still detecting legitimate circular references within the same operation\n\n // TODO: Move this Up!\n const currentContext = contextManager.getCurrentContext();\n const results = (await Promise.all(matchingItems.map(async (row: any) => {\n // Each row in an all() operation should get its own context to prevent interference\n const processedRow = await processRow(row, coordinate.kta, references || [], aggregations || [], registry, currentContext);\n return validateKeys(processedRow, coordinate.kta);\n }))) as V[];\n\n logger.debug(`[ALL] Returning ${results.length} ${model.name} records`);\n return results;\n }\n\n return all;\n\n}\n", "/* eslint-disable max-len */\nimport {\n CompoundCondition,\n Condition,\n EventQuery,\n isComKey,\n isCondition,\n isPriKey,\n ItemQuery,\n OrderBy,\n PriKey,\n References\n} from '@fjell/core';\n\nimport { Association, ModelStatic, Op } from 'sequelize';\nimport LibLogger from './logger';\nimport { stringifyJSON } from './util/general';\n\nconst logger = LibLogger.get('sequelize', 'QueryBuilder');\n\nexport type QueryOptions = {\n where: Record<string, any>;\n limit?: number;\n offset?: number;\n order?: Array<[string, string]>;\n include?: Array<any>;\n}\n\nconst addDeleteQuery = (options: QueryOptions, model: ModelStatic<any>): QueryOptions => {\n logger.default(`QueryBuilder adding delete query with options: ${stringifyJSON(options)}`);\n if (model.getAttributes().deletedAt) {\n options.where['deletedAt'] = {\n [Op.eq]: null\n }\n } else if (model.getAttributes().isDeleted) {\n options.where['isDeleted'] = {\n [Op.eq]: false\n }\n }\n\n return options;\n}\n\nconst addEventQueries = (\n options: QueryOptions, events: Record<string, EventQuery>, model: ModelStatic<any>): QueryOptions => {\n logger.default(`QueryBuilder adding event queries with options: ${stringifyJSON(options)}, events: ${stringifyJSON(events)}`);\n Object.keys(events).forEach((key: string) => {\n\n if (!model.getAttributes()[`${key}At`]) {\n throw new Error(`Event ${key} is not supported on model '${model.name}', column '${key}At' not found. Available columns: [${Object.keys(model.getAttributes()).join(', ')}]. Event query: ${stringifyJSON(events[key])}`);\n }\n\n let whereClauses = {};\n\n const event = events[key];\n if (event.start) {\n whereClauses = { ...whereClauses, [Op.gte]: new Date(event.start) };\n }\n if (event.end) {\n whereClauses = { ...whereClauses, [Op.lt]: new Date(event.end) };\n }\n\n if (event.by) {\n if (!model.getAttributes()[`${key}By`]) {\n throw new Error(`Event ${key} is not supported on model '${model.name}', column '${key}By' not found. Available columns: [${Object.keys(model.getAttributes()).join(', ')}]. Event query: ${stringifyJSON(events[key])}`);\n }\n whereClauses = { ...whereClauses, [Op.eq]: event.by };\n }\n\n options.where[`${key}At`] = whereClauses;\n\n });\n return options;\n}\n\n// Add the references to the query\nconst addReferenceQueries = (options: any, references: References, model: ModelStatic<any>): any => {\n logger.default(`QueryBuilder adding reference queries with options: ${stringifyJSON(options)}, references: ${stringifyJSON(references)}`);\n\n Object.keys(references).forEach((key: string) => {\n logger.default(`QueryBuilder adding reference query for key: ${key}, references: ${stringifyJSON(references)}`);\n\n if (!model.getAttributes()[`${key}Id`]) {\n throw new Error(`Reference ${key} is not supported on model '${model.name}', column '${key}Id' not found. Available columns: [${Object.keys(model.getAttributes()).join(', ')}]. Reference query: ${stringifyJSON(references[key])}`);\n }\n\n const refValue = references[key];\n const keyValue = (refValue as any).key || refValue;\n \n if (isPriKey(keyValue)) {\n const priKey: PriKey<string> = keyValue as PriKey<string>;\n\n if (priKey.pk == null || priKey.pk === '' || (typeof priKey.pk === 'object' && Object.keys(priKey.pk).length === 0)) {\n logger.error(`Reference key '${key}' has invalid pk value: ${stringifyJSON(priKey.pk)}`, { priKey, references });\n throw new Error(`Reference key '${key}' has invalid pk value: ${stringifyJSON(priKey.pk)}. Model: '${model.name}', Key type: '${priKey.kt}', Full reference: ${stringifyJSON(references[key])}`);\n }\n\n logger.trace(`[QueryBuilder] Setting reference where clause: ${key}Id = ${stringifyJSON(priKey.pk)} (type: ${typeof priKey.pk})`);\n options.where[`${key}Id`] = {\n [Op.eq]: priKey.pk\n }\n } else if (isComKey(references[key])) {\n throw new Error(`ComKeys are not supported in Sequelize. Reference key: '${key}', Model: '${model.name}', ComKey: ${stringifyJSON(references[key])}`);\n }\n });\n return options;\n}\n\nexport const addCompoundCondition = (options: any, compoundCondition: CompoundCondition, model: ModelStatic<any>) => {\n // Ensure options.where exists\n options.where = options.where || {};\n\n let compoundOp: symbol;\n const compoundType = compoundCondition.compoundType;\n if (compoundType === \"AND\") {\n compoundOp = Op.and;\n } else {\n compoundOp = Op.or;\n };\n\n let conditions: Record<string, any> = {};\n compoundCondition.conditions.forEach((condition: Condition | CompoundCondition) => {\n if (isCondition(condition)) {\n conditions = addCondition(conditions, condition, model);\n } else {\n throw new Error(`Nested Compound conditions not supported. Model: '${model.name}', Compound condition: ${stringifyJSON(compoundCondition)}, Nested condition: ${stringifyJSON(condition)}`);\n }\n });\n\n // Merge with existing where conditions instead of replacing\n if (Object.keys(options.where).length > 0) {\n // If there are existing conditions, wrap everything in an AND\n options.where = {\n [Op.and]: [\n options.where,\n { [compoundOp]: conditions }\n ]\n };\n } else {\n // If no existing conditions, just set the compound condition\n options.where[compoundOp] = conditions;\n }\n\n return options;\n}\n\nconst getSequelizeOperator = (operator: string): symbol => {\n if (operator === '==') {\n return Op.eq;\n } else if (operator === '<') {\n return Op.lt;\n } else if (operator === '>') {\n return Op.gt;\n } else if (operator === '<=') {\n return Op.lte;\n } else if (operator === '>=') {\n return Op.gte;\n } else if (operator === 'in') {\n return Op.in;\n } else {\n throw new Error(`Operator ${operator} not supported`);\n }\n};\n\nconst addAssociationCondition = (\n conditions: Record<string, any>,\n condition: Condition,\n model: ModelStatic<any>\n): Record<string, any> => {\n const [associationName, attributeName] = condition.column.split('.', 2);\n\n // Check if the association exists on the model\n if (!model.associations || !model.associations[associationName]) {\n throw new Error(`Association ${associationName} not found on model ${model.name}`);\n }\n\n const association: Association<any, any> = model.associations[associationName];\n const associatedModel = association.target;\n\n // Check if the attribute exists on the associated model\n if (!associatedModel.getAttributes()[attributeName]) {\n throw new Error(`Attribute ${attributeName} not found on associated model ${associatedModel.name} for association ${associationName}`);\n }\n\n // Use Sequelize's $association.attribute$ syntax for querying associated models\n const sequelizeAssociationColumn = `$${associationName}.${attributeName}$`;\n\n // Handle null values with proper SQL IS NULL / IS NOT NULL syntax\n if (condition.value === null) {\n if (condition.operator === '==' || !condition.operator) {\n // Use Op.is for IS NULL\n logger.trace(`[QueryBuilder] Setting association condition: ${sequelizeAssociationColumn} IS NULL`);\n conditions[sequelizeAssociationColumn] = {\n [Op.is]: null\n };\n } else if (condition.operator === '!=') {\n // Use Op.not for IS NOT NULL\n logger.trace(`[QueryBuilder] Setting association condition: ${sequelizeAssociationColumn} IS NOT NULL`);\n conditions[sequelizeAssociationColumn] = {\n [Op.not]: null\n };\n } else {\n logger.error(`Operator ${condition.operator} cannot be used with null value on association`, { condition });\n throw new Error(`Operator ${condition.operator} cannot be used with null value. Use '==' for IS NULL or '!=' for IS NOT NULL.`);\n }\n return conditions;\n }\n\n const conditionOp = getSequelizeOperator(condition.operator);\n\n logger.trace(`[QueryBuilder] Setting association condition: ${sequelizeAssociationColumn} = ${stringifyJSON(condition.value)} (type: ${typeof condition.value})`);\n conditions[sequelizeAssociationColumn] = {\n [conditionOp]: condition.value\n };\n\n return conditions;\n};\n\nconst addAttributeCondition = (\n conditions: Record<string, any>,\n condition: Condition,\n model: ModelStatic<any>\n): Record<string, any> => {\n const conditionColumn = condition.column;\n\n if (!model.getAttributes()[conditionColumn]) {\n throw new Error(`Condition column ${conditionColumn} not found on model ${model.name}`);\n }\n\n // Handle null values with proper SQL IS NULL / IS NOT NULL syntax\n if (condition.value === null) {\n if (condition.operator === '==' || !condition.operator) {\n // Use Op.is for IS NULL\n logger.trace(`[QueryBuilder] Setting attribute condition: ${conditionColumn} IS NULL`);\n conditions[conditionColumn] = {\n [Op.is]: null\n };\n } else if (condition.operator === '!=') {\n // Use Op.not for IS NOT NULL\n logger.trace(`[QueryBuilder] Setting attribute condition: ${conditionColumn} IS NOT NULL`);\n conditions[conditionColumn] = {\n [Op.not]: null\n };\n } else {\n logger.error(`Operator ${condition.operator} cannot be used with null value`, { condition });\n throw new Error(`Operator ${condition.operator} cannot be used with null value. Use '==' for IS NULL or '!=' for IS NOT NULL.`);\n }\n return conditions;\n }\n\n const conditionOp = getSequelizeOperator(condition.operator);\n\n logger.trace(`[QueryBuilder] Setting attribute condition: ${conditionColumn} = ${stringifyJSON(condition.value)} (type: ${typeof condition.value})`);\n conditions[conditionColumn] = {\n [conditionOp]: condition.value\n };\n\n return conditions;\n};\n\nexport const addCondition = (conditions: Record<string, any>, condition: Condition, model: ModelStatic<any>) => {\n const conditionColumn: string = condition.column;\n\n // Check if this is an association query (contains a dot)\n if (conditionColumn.includes('.')) {\n return addAssociationCondition(conditions, condition, model);\n }\n\n // Handle regular column queries\n return addAttributeCondition(conditions, condition, model);\n}\n\nconst collectAssociationsFromConditions = (conditions: any): Set<string> => {\n const associations = new Set<string>();\n\n const processObject = (obj: any) => {\n if (typeof obj === 'object' && obj !== null) {\n // Check string keys\n Object.keys(obj).forEach(key => {\n // Check if this is an association reference ($association.attribute$)\n if (typeof key === 'string' && key.startsWith('$') && key.endsWith('$') && key.includes('.')) {\n const associationName = key.substring(1, key.indexOf('.'));\n associations.add(associationName);\n }\n\n // Recursively process nested objects\n if (typeof obj[key] === 'object') {\n processObject(obj[key]);\n }\n });\n\n // Also check Symbol keys (for compound conditions like Op.and, Op.or)\n Object.getOwnPropertySymbols(obj).forEach(symbol => {\n if (typeof obj[symbol] === 'object') {\n processObject(obj[symbol]);\n }\n });\n }\n\n // Handle arrays (for compound conditions that might be arrays)\n if (Array.isArray(obj)) {\n obj.forEach(item => {\n if (typeof item === 'object') {\n processObject(item);\n }\n });\n }\n };\n\n processObject(conditions);\n return associations;\n};\n\nconst addAssociationIncludes = (options: any, model: ModelStatic<any>): any => {\n // Collect all association names used in conditions\n const referencedAssociations = collectAssociationsFromConditions(options.where);\n\n if (referencedAssociations.size > 0) {\n options.include = options.include || [];\n\n // Add each referenced association to the include array\n referencedAssociations.forEach(associationName => {\n // Check if this association is already included\n const alreadyIncluded = options.include.some((inc: any) =>\n (typeof inc === 'string' && inc === associationName) ||\n (typeof inc === 'object' && inc.association === associationName)\n );\n\n if (!alreadyIncluded && model.associations && model.associations[associationName]) {\n options.include.push({\n model: model.associations[associationName].target,\n as: associationName,\n required: false // Use LEFT JOIN so records without associations are still returned\n });\n }\n });\n }\n\n return options;\n};\n\nexport const buildQuery = (\n itemQuery: ItemQuery,\n model: ModelStatic<any>\n): any => {\n logger.default(`QueryBuilder build called with itemQuery: ${stringifyJSON(itemQuery)}`);\n\n let options: any = {\n where: {},\n };\n\n if (itemQuery.compoundCondition) {\n logger.default(`QueryBuilder adding conditions: ${stringifyJSON(itemQuery.compoundCondition)}`);\n options = addCompoundCondition(options, itemQuery.compoundCondition, model);\n }\n\n // If the model has a deletedAt column, we need to add a delete query\n if (model.getAttributes().deletedAt || model.getAttributes().isDeleted) {\n options = addDeleteQuery(options, model);\n }\n\n if (itemQuery.refs) {\n options = addReferenceQueries(options, itemQuery.refs, model);\n }\n if (itemQuery.events) {\n options = addEventQueries(options, itemQuery.events, model);\n }\n\n // TODO: Once we start to support Aggs on the server-side, we'll need to parse agg queries\n\n // Apply a limit to the result set\n if (itemQuery.limit) {\n logger.default(`QueryBuilder applying limit: ${itemQuery.limit}`);\n options.limit = itemQuery.limit;\n }\n\n // Apply an offset to the result set\n if (itemQuery.offset) {\n options.offset = itemQuery.offset;\n }\n\n // Add orderBy to the query\n if (itemQuery.orderBy) {\n itemQuery.orderBy.forEach((orderBy: OrderBy) => {\n if (!model.getAttributes()[orderBy.field]) {\n throw new Error(`Order by field ${orderBy.field} not found on model ${model.name}`);\n }\n options.order = [\n [orderBy.field, orderBy.direction]\n ];\n });\n }\n\n // Add includes for any associations referenced in conditions\n options = addAssociationIncludes(options, model);\n\n return options;\n}\n", "\n/* eslint-disable */\nexport const clean = (obj: any) => {\n return Object.fromEntries(\n Object.entries(obj).filter(([_, v]) => v !== undefined)\n );\n}\n\n//Recursive implementation of jSON.stringify;\nexport const stringifyJSON = function (obj: any, visited: Set<any> = new Set()): string {\n const arrOfKeyVals: string[] = [];\n const arrVals: string[] = [];\n let objKeys: string[] = [];\n\n /*********CHECK FOR PRIMITIVE TYPES**********/\n if (typeof obj === 'number' || typeof obj === 'boolean' || obj === null)\n return '' + obj;\n else if (typeof obj === 'string')\n return '\"' + obj + '\"';\n\n /*********DETECT CIRCULAR REFERENCES**********/\n if (obj instanceof Object && visited.has(obj)) {\n return '\"(circular)\"';\n }\n\n /*********CHECK FOR ARRAY**********/\n else if (Array.isArray(obj)) {\n //check for empty array\n if (obj.length === 0)\n return '[]';\n else {\n // Add array to visited before processing its elements\n visited.add(obj);\n obj.forEach(function (el) {\n arrVals.push(stringifyJSON(el, visited));\n });\n // Remove from visited after processing to allow arrays at different levels\n visited.delete(obj);\n return '[' + arrVals + ']';\n }\n }\n /*********CHECK FOR OBJECT**********/\n else if (obj instanceof Object) {\n // Add object to visited before processing its properties\n visited.add(obj);\n //get object keys\n objKeys = Object.keys(obj);\n //set key output;\n objKeys.forEach(function (key) {\n const keyOut = '\"' + key + '\":';\n const keyValOut = obj[key];\n //skip functions and undefined properties\n if (keyValOut instanceof Function || keyValOut === undefined)\n return; // Skip this entry entirely instead of pushing an empty string\n else if (typeof keyValOut === 'string')\n arrOfKeyVals.push(keyOut + '\"' + keyValOut + '\"');\n else if (typeof keyValOut === 'boolean' || typeof keyValOut === 'number' || keyValOut === null)\n arrOfKeyVals.push(keyOut + keyValOut);\n //check for nested objects, call recursively until no more objects\n else if (keyValOut instanceof Object) {\n arrOfKeyVals.push(keyOut + stringifyJSON(keyValOut, visited));\n }\n });\n // Remove from visited after processing to allow objects at different levels\n visited.delete(obj);\n return '{' + arrOfKeyVals + '}';\n }\n return '';\n};\n", "import { LocKey, LocKeyArray } from \"@fjell/core\";\nimport { Coordinate } from \"@fjell/registry\";\nimport LibLogger from \"../logger\";\n\nconst logger = LibLogger.get('LocationKeyValidator');\n\n/**\n * Validates that location keys in a LocKeyArray are in the correct hierarchical order\n * based on the entity's coordinate definition.\n *\n * @param locations - The location key array to validate\n * @param coordinate - The coordinate defining the expected hierarchy\n * @param operation - The name of the operation being performed (for error messages)\n * @throws Error if location keys are not in the correct order or if the array is invalid\n */\nexport const validateLocations = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n locations: LocKeyArray<L1, L2, L3, L4, L5> | [] | undefined,\n coordinate: Coordinate<S, L1, L2, L3, L4, L5>,\n operation: string\n ): void => {\n if (!locations || locations.length === 0) {\n return;\n }\n\n const keyTypeArray = coordinate.kta;\n const expectedLocationTypes = keyTypeArray.slice(1); // Skip the first element (primary key type)\n const actualLocationTypes = (locations as Array<LocKey<L1 | L2 | L3 | L4 | L5>>).map(loc => loc.kt);\n\n logger.debug(`Validating locations for ${operation}`, {\n expected: expectedLocationTypes,\n actual: actualLocationTypes,\n coordinate: keyTypeArray\n });\n\n // Check if too many location keys were provided\n if (actualLocationTypes.length > expectedLocationTypes.length) {\n logger.error('Location key array has too many elements', {\n expected: expectedLocationTypes.length,\n actual: actualLocationTypes.length,\n expectedTypes: expectedLocationTypes,\n actualTypes: actualLocationTypes,\n coordinate,\n operation\n });\n throw new Error(\n `Invalid location key array for ${operation}: ` +\n `Expected at most ${expectedLocationTypes.length} location keys ` +\n `(hierarchy: [${expectedLocationTypes.join(', ')}]), ` +\n `but received ${actualLocationTypes.length} ` +\n `(types: [${actualLocationTypes.join(', ')}])`\n );\n }\n\n // Validate that each location key is in the correct hierarchical position\n for (let i = 0; i < actualLocationTypes.length; i++) {\n if (expectedLocationTypes[i] !== actualLocationTypes[i]) {\n logger.error('Location key array order mismatch', {\n position: i,\n expected: expectedLocationTypes[i],\n actual: actualLocationTypes[i],\n expectedHierarchy: expectedLocationTypes,\n actualOrder: actualLocationTypes,\n coordinate,\n operation\n });\n throw new Error(\n `Invalid location key array order for ${operation}: ` +\n `At position ${i}, expected key type \"${expectedLocationTypes[i]}\" ` +\n `but received \"${actualLocationTypes[i]}\". ` +\n `Location keys must be ordered according to the hierarchy: [${expectedLocationTypes.join(', ')}]. ` +\n `Received order: [${actualLocationTypes.join(', ')}]`\n );\n }\n }\n\n logger.debug(`Location key array validation passed for ${operation}`, { locations });\n};\n\n", "/* eslint-disable indent */\nimport { ModelStatic } from 'sequelize';\n\nexport interface RelationshipChainResult {\n success: boolean;\n path?: string;\n includes?: any[];\n}\n\nexport interface RelationshipPathResult {\n found: boolean;\n path?: string;\n includes?: any[];\n isDirect?: boolean;\n}\n\n/**\n * Helper function to build relationship chain includes\n */\nexport const buildRelationshipChain = (\n targetModel: ModelStatic<any>,\n kta: string[],\n currentIndex: number,\n targetIndex: number\n): RelationshipChainResult => {\n // Build the association path and validate relationships exist\n const associationParts: string[] = [];\n const modelChain: ModelStatic<any>[] = [targetModel];\n let currentModel = targetModel;\n\n // Validate that all associations exist and build model chain\n for (let i = currentIndex + 1; i <= targetIndex; i++) {\n const intermediateType = kta[i];\n const associationName = intermediateType;\n\n if (!currentModel.associations || !currentModel.associations[associationName]) {\n return { success: false };\n }\n\n associationParts.push(associationName);\n currentModel = currentModel.associations[associationName].target;\n modelChain.push(currentModel);\n }\n\n // Build the full association path for the target field\n const targetPrimaryKey = currentModel.primaryKeyAttribute || 'id';\n const associationPath = `$${associationParts.join('.')}.${targetPrimaryKey}$`;\n\n // Build nested includes structure iteratively (clearer than recursion)\n let deepestInclude: any = null;\n\n // Build from the deepest level back to the root\n for (let i = targetIndex; i > currentIndex; i--) {\n const currentType = kta[i];\n const modelIndex = i - currentIndex;\n\n const includeObj: any = {\n model: modelChain[modelIndex],\n as: currentType,\n required: true\n };\n\n if (deepestInclude) {\n includeObj.include = [deepestInclude];\n }\n\n deepestInclude = includeObj;\n }\n\n const includes = deepestInclude ? [deepestInclude] : [];\n\n return { success: true, path: associationPath, includes };\n};\n\n/**\n * Helper function to build relationship path for a locator\n * @param includeIsDirect Whether to include the isDirect flag in the result\n */\nexport const buildRelationshipPath = (\n targetModel: ModelStatic<any>,\n locatorType: string,\n kta: string[],\n includeIsDirect: boolean = false\n): RelationshipPathResult => {\n\n // First check if the field exists directly\n const directFieldName = `${locatorType}Id`;\n const attributes = targetModel.getAttributes();\n if (attributes && attributes[directFieldName]) {\n const result: RelationshipPathResult = { found: true };\n if (includeIsDirect) {\n result.isDirect = true;\n }\n return result;\n }\n\n // If not direct, look for relationship path\n const targetIndex = kta.indexOf(locatorType);\n if (targetIndex === -1) {\n const result: RelationshipPathResult = { found: false };\n if (includeIsDirect) {\n result.isDirect = false;\n }\n return result;\n }\n\n const currentIndex = 0; // We're always looking from the base model\n\n if (targetIndex <= currentIndex) {\n const result: RelationshipPathResult = { found: false };\n if (includeIsDirect) {\n result.isDirect = false;\n }\n return result;\n }\n\n const chainResult = buildRelationshipChain(targetModel, kta, currentIndex, targetIndex);\n if (chainResult.success) {\n const result: RelationshipPathResult = {\n found: true,\n path: chainResult.path,\n includes: chainResult.includes\n };\n if (includeIsDirect) {\n result.isDirect = false;\n }\n return result;\n }\n\n const result: RelationshipPathResult = { found: false };\n if (includeIsDirect) {\n result.isDirect = false;\n }\n return result;\n};\n", "/* eslint-disable max-len */\n/* eslint-disable indent */\nimport {\n AllItemTypeArrays,\n Item,\n} from '@fjell/core';\n\nimport LibLogger from './logger';\nimport { Model, ModelStatic } from 'sequelize';\nimport { buildRelationshipPath } from './util/relationshipUtils';\n\nconst logger = LibLogger.get('sequelize', 'KeyMaster');\n\n// Helper function to extract location key value from item\nconst extractLocationKeyValue = (\n model: ModelStatic<any>,\n item: any,\n locatorType: string,\n kta: string[]\n): any => {\n logger.default('Extracting location key value', { locatorType, kta });\n\n const relationshipInfo = buildRelationshipPath(model, locatorType, kta, true);\n\n if (!relationshipInfo.found) {\n throw new Error(`Location key '${locatorType}' cannot be resolved on model '${model.name}' or through its relationships. Key type array: [${kta.join(', ')}]. Available associations: [${Object.keys(model.associations || {}).join(', ')}]`);\n }\n\n if (relationshipInfo.isDirect) {\n // Direct foreign key field\n const foreignKeyField = `${locatorType}Id`;\n const value = item[foreignKeyField];\n if (typeof value === 'undefined' || value === null) {\n throw new Error(`Direct foreign key field '${foreignKeyField}' is missing or null in item. Model: '${model.name}', Locator type: '${locatorType}', Available item properties: [${Object.keys(item || {}).join(', ')}]`);\n }\n return value;\n } else {\n // Need to traverse relationship hierarchy\n // Find the path through the key type array\n const locatorIndex = kta.indexOf(locatorType);\n if (locatorIndex === -1) {\n throw new Error(`Locator type '${locatorType}' not found in key type array. Model: '${model.name}', Key type array: [${kta.join(', ')}]`);\n }\n\n // Start from the current item (index 0 in kta)\n let currentObject = item;\n\n // Traverse through each intermediate relationship to reach the target\n for (let i = 1; i < locatorIndex; i++) {\n const intermediateType = kta[i];\n\n // Check if the intermediate relationship object is loaded\n if (currentObject[intermediateType] && typeof currentObject[intermediateType] === 'object') {\n currentObject = currentObject[intermediateType];\n } else {\n // Try the foreign key approach if the relationship object isn't loaded\n const foreignKeyField = `${intermediateType}Id`;\n if (typeof currentObject[foreignKeyField] !== 'undefined' && currentObject[foreignKeyField] !== null) {\n // We have the foreign key but not the loaded object, we can't traverse further\n throw new Error(`Intermediate relationship '${intermediateType}' is not loaded. Cannot traverse to '${locatorType}'. Model: '${model.name}', Available item properties: [${Object.keys(currentObject || {}).join(', ')}]. Either include the relationship in your query or ensure it's loaded.`);\n }\n throw new Error(`Intermediate relationship '${intermediateType}' is missing in the relationship chain. Model: '${model.name}', Expected path: ${kta.slice(0, locatorIndex + 1).join(' \u2192 ')}, Available item properties: [${Object.keys(currentObject || {}).join(', ')}]`);\n }\n }\n\n // Now extract the target locator value from the current object\n // First try to get it from the loaded relationship object\n if (currentObject[locatorType] && typeof currentObject[locatorType] === 'object' && typeof currentObject[locatorType].id !== 'undefined') {\n return currentObject[locatorType].id;\n }\n\n // If the relationship object isn't loaded, try the foreign key field\n const foreignKeyField = `${locatorType}Id`;\n if (typeof currentObject[foreignKeyField] !== 'undefined' && currentObject[foreignKeyField] !== null) {\n return currentObject[foreignKeyField];\n }\n\n const traversalPath = kta.slice(0, locatorIndex + 1).join(' \u2192 ');\n throw new Error(\n `Unable to extract location key for '${locatorType}'. ` +\n `Neither the relationship object nor direct foreign key is available. ` +\n `Traversal path: ${traversalPath}`\n );\n }\n};\n\nexport const removeKey = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Removing Key', { item });\n delete item.key;\n return item;\n}\n\n// export const populateKey = <\n// S extends string,\n// L1 extends string = never,\n// L2 extends string = never,\n// L3 extends string = never,\n// L4 extends string = never,\n// L5 extends string = never\n// >(\n// item: ItemProperties<S, L1, L2, L3, L4, L5>,\n// keyTypes: AllItemTypeArrays<S, L1, L2, L3, L4, L5>\n// ): ItemProperties<S, L1, L2, L3, L4, L5> => {\n// if (keyTypes.length === 1) {\n// item.key = { kt: keyTypes[0], pk: item.id };\n// delete item.id;\n// } else if (keyTypes.length === 2) {\n// item.key = {\n// kt: keyTypes[0], pk: item.id,\n// // TODO: Shouldn't this be inspecting the model to get the primary key type?\n// loc: [{ kt: keyTypes[1], lk: item[keyTypes[1] + 'Id'] }],\n// };\n// delete item.id;\n// delete item[keyTypes[1] + 'Id'];\n// } else {\n// throw new Error('Not implemented');\n// }\n// return item;\n// }\n\nexport const addKey = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n model: Model<any, any>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n keyTypes: AllItemTypeArrays<S, L1, L2, L3, L4, L5>\n): Item<S, L1, L2, L3, L4, L5> => {\n logger.default('Adding Key', { item });\n const key = {};\n const modelClass = model.constructor as ModelStatic<any>;\n const primaryKeyAttr = modelClass.primaryKeyAttribute;\n\n if (Array.isArray(keyTypes) && keyTypes.length > 1) {\n const type = [...keyTypes];\n const pkType = type.shift();\n Object.assign(key, { kt: pkType, pk: item[primaryKeyAttr] });\n\n // Build location keys for composite key\n const locationKeys = [];\n for (const locatorType of type) {\n try {\n const lk = extractLocationKeyValue(modelClass, item, locatorType, keyTypes as string[]);\n locationKeys.push({ kt: locatorType, lk });\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error(`Failed to extract location key for '${locatorType}'`, { error: errorMessage, item, keyTypes });\n throw error;\n }\n }\n\n Object.assign(key, { loc: locationKeys });\n } else {\n Object.assign(key, { kt: keyTypes[0], pk: item[primaryKeyAttr] });\n }\n Object.assign(item, { key });\n return item as Item<S, L1, L2, L3, L4, L5>;\n};\n", "/* eslint-disable indent */\n\nimport { AllItemTypeArrays, Item } from \"@fjell/core\";\nimport { Model } from \"sequelize\";\n\nimport LibLogger from \"./logger\";\nimport { addKey } from \"./KeyMaster\";\nimport { AggregationDefinition, SequelizeReferenceDefinition } from \"./Options\";\nimport * as Library from \"@fjell/lib\";\nimport {\n buildAggregation,\n contextManager,\n createOperationContext,\n OperationContext\n} from \"@fjell/lib\";\nimport { stringifyJSON } from \"./util/general\";\nimport { populateEvents } from \"./EventCoordinator\";\nimport { buildSequelizeReference } from \"./processing/ReferenceBuilder\";\n\nconst logger = LibLogger.get('sequelize', 'RowProcessor');\n\n// Re-export types and functions from @fjell/lib for backwards compatibility\nexport type { OperationContext };\nexport { createOperationContext, contextManager };\n\nexport const processRow = async <S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never>(\n row: Model<any, any>,\n keyTypes: AllItemTypeArrays<S, L1, L2, L3, L4, L5>,\n referenceDefinitions: SequelizeReferenceDefinition[],\n aggregationDefinitions: AggregationDefinition[],\n registry: Library.Registry,\n context?: OperationContext\n ): Promise<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Processing Row', { row });\n\n // Use provided context or create new one\n const operationContext = context || createOperationContext();\n\n // Process the row within the context to ensure all operations share the same context\n return contextManager.withContext(operationContext, async () => {\n let item = row.get({ plain: true }) as any;\n logger.default('Adding Key to Item with Key Types: %s', stringifyJSON(keyTypes));\n item = addKey(row, item, keyTypes);\n item = populateEvents(item);\n logger.default('Key Added to Item: %s', stringifyJSON(item.key));\n\n // Mark this item as in progress to detect circular references\n operationContext.markInProgress(item.key);\n\n try {\n if (referenceDefinitions && referenceDefinitions.length > 0) {\n for (const referenceDefinition of referenceDefinitions) {\n logger.default('Processing Reference for %s to %s', item.key.kt, stringifyJSON(referenceDefinition.kta));\n item = await buildSequelizeReference(item, referenceDefinition, registry, operationContext);\n }\n }\n if (aggregationDefinitions && aggregationDefinitions.length > 0) {\n for (const aggregationDefinition of aggregationDefinitions) {\n logger.default('Processing Aggregation for %s from %s', item.key.kt, stringifyJSON(aggregationDefinition.kta));\n item = await buildAggregation(item, aggregationDefinition, registry, operationContext);\n }\n }\n\n // Cache the fully processed item\n operationContext.setCached(item.key, item);\n } finally {\n // Mark this item as complete\n operationContext.markComplete(item.key);\n }\n\n logger.default('Processed Row: %j', stringifyJSON(item));\n return item as Item<S, L1, L2, L3, L4, L5>;\n });\n};\n", "import {\n Evented,\n Item,\n ManagedEvents\n} from '@fjell/core';\nimport deepmerge from 'deepmerge';\n\nimport LibLogger from './logger';\n\nconst logger = LibLogger.get(\"sequelize\", \"EventCoordinator\");\n\nexport const createEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>):\n Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Creating Events', { item });\n const currentDate = new Date();\n\n let events = item.events;\n\n if (events) {\n if (!events.created) {\n events = deepmerge(events, { created: { at: currentDate } });\n }\n if (!events.updated) {\n events = deepmerge(events, { updated: { at: currentDate } });\n }\n if (!events.deleted) {\n events = deepmerge(events, { deleted: { at: null } });\n }\n\n } else {\n events = {\n created: { at: currentDate },\n updated: { at: currentDate },\n deleted: { at: null },\n };\n }\n\n return deepmerge(item, { events }) as Partial<Item<S, L1, L2, L3, L4, L5>>;\n}\n\nexport const updateEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>):\n Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Updating Events', { item });\n const currentDate = new Date();\n const events: Evented = {\n updated: { at: currentDate },\n };\n\n // TODO: This is clean-up code, we should remove it\n // If the event lacks a created data, let's just insert it here...\n if (!item.events || !item.events.created || !item.events.created.at) {\n events.created = { at: currentDate };\n }\n\n return deepmerge(item, { events }) as Partial<Item<S, L1, L2, L3, L4, L5>>;\n}\n//#endregion\n\nexport const populateEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n const events: ManagedEvents = {\n created: { at: item.createdAt || null },\n updated: { at: item.updatedAt || null },\n deleted: { at: null }\n };\n item.events = events;\n return item;\n}\n\nexport const extractEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Extracting Events to database fields', { item });\n\n if (item.events) {\n if (item.events.created?.at) {\n item.createdAt = item.events.created.at;\n }\n if (item.events.updated?.at) {\n item.updatedAt = item.events.updated.at;\n }\n if (item.events.deleted?.at) {\n item.deletedAt = item.events.deleted.at;\n }\n }\n\n return item;\n}\n\nexport const removeEvents = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(item: Partial<Item<S, L1, L2, L3, L4, L5>>): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n logger.default('Removing Events', { item });\n delete item.events;\n return item;\n}\n", "import { ComKey, Item, PriKey } from \"@fjell/core\";\nimport type { Registry } from \"@fjell/lib\";\nimport { OperationContext } from \"@fjell/lib\";\nimport logger from \"../logger\";\n\n/**\n * Sequelize-specific definition for a reference relationship.\n * References in Sequelize are stored as foreign key columns (e.g., \"authorId\")\n * and populated into properties on the item.\n */\nexport interface SequelizeReferenceDefinition {\n /** Column name containing the foreign key value (e.g., \"authorId\") */\n column: string;\n /** Key type array of the referenced item */\n kta: string[];\n /** Property name to populate with the referenced item (e.g., \"author\") */\n property: string;\n /**\n * Optional: Column names for location keys when referencing composite items.\n * If provided, will construct a full ComKey with location context.\n * If omitted for composite items, uses empty loc array to search across all locations.\n *\n * Example: ['phaseId'] for a step reference where you have both stepId and phaseId columns\n */\n locationColumns?: string[];\n}\n\n/**\n * Build a reference by looking up a related item by its key from a column value.\n * The referenced item will be populated directly into a property on the item.\n *\n * @param item - The item to populate with reference data\n * @param referenceDefinition - Sequelize-specific definition of what to reference\n * @param registry - Registry to look up library instances\n * @param context - Optional operation context for caching and cycle detection\n * @returns The item with the reference property populated\n */\nexport const buildSequelizeReference = async (\n item: any,\n referenceDefinition: SequelizeReferenceDefinition,\n registry: Registry,\n context?: OperationContext\n) => {\n const libLogger = logger.get('processing', 'ReferenceBuilder');\n \n // Check if this is a composite item reference (has location hierarchy)\n const isCompositeItem = referenceDefinition.kta.length > 1;\n const primaryKeyType = referenceDefinition.kta[0];\n\n if (isCompositeItem) {\n libLogger.debug(\n 'Detected composite item reference - will use ComKey with empty loc array',\n {\n kta: referenceDefinition.kta,\n primaryKeyType,\n property: referenceDefinition.property,\n column: referenceDefinition.column\n }\n );\n }\n\n // Check if dependencies exist\n if (!registry) {\n throw new Error(\n `This model definition has a reference definition, but the registry is not present. ` +\n `Reference property: '${referenceDefinition.property}', ` +\n `key types: [${referenceDefinition.kta.join(', ')}], column: '${referenceDefinition.column}'`\n );\n }\n\n // Find the Library.Instance for the key type\n const library: any = registry.get(referenceDefinition.kta as any);\n if (!library) {\n throw new Error(\n `This model definition has a reference definition, but the dependency is not present in registry. ` +\n `Reference property: '${referenceDefinition.property}', ` +\n `missing key type: '${primaryKeyType}', column: '${referenceDefinition.column}'`\n );\n }\n\n // Check if the column value is null - if so, skip the reference\n const columnValue = item[referenceDefinition.column];\n if (columnValue == null) {\n item[referenceDefinition.property] = null;\n return item;\n }\n\n // Create the appropriate key type based on whether this is a composite item\n let itemKey: PriKey<string> | ComKey<string>;\n \n if (!isCompositeItem) {\n // Primary item: use PriKey\n itemKey = {\n kt: primaryKeyType,\n pk: columnValue\n };\n } else if (referenceDefinition.locationColumns && referenceDefinition.locationColumns.length > 0) {\n // Composite item with location columns provided: build full ComKey\n const locationTypes = referenceDefinition.kta.slice(1); // Skip primary key type\n const loc: Array<{kt: string, lk: any}> = [];\n \n for (let i = 0; i < referenceDefinition.locationColumns.length; i++) {\n const columnName = referenceDefinition.locationColumns[i];\n const locValue = item[columnName];\n \n if (locValue == null) {\n libLogger.warning(\n `Location column '${columnName}' is null/undefined for reference '${referenceDefinition.property}'. ` +\n `Falling back to empty loc array search.`\n );\n // Fall back to empty loc array if any location column is missing\n itemKey = {\n kt: primaryKeyType,\n pk: columnValue,\n loc: []\n };\n break;\n }\n \n loc.push({\n kt: locationTypes[i],\n lk: locValue\n });\n }\n \n // Only set itemKey if we haven't already (fallback case)\n if (!itemKey) {\n itemKey = {\n kt: primaryKeyType,\n pk: columnValue,\n loc: loc as any\n };\n \n libLogger.debug('Built full ComKey with location context', {\n itemKey,\n locationColumns: referenceDefinition.locationColumns,\n property: referenceDefinition.property\n });\n }\n } else {\n // Composite item without location columns: use empty loc array\n // This signals \"find this item by primary key across all location contexts\"\n itemKey = {\n kt: primaryKeyType,\n pk: columnValue,\n loc: []\n };\n \n libLogger.debug('Using empty loc array for composite item reference', {\n kta: referenceDefinition.kta,\n property: referenceDefinition.property\n });\n }\n\n libLogger.debug('Created reference key', {\n itemKey,\n isCompositeItem,\n hasLocationColumns: !!referenceDefinition.locationColumns,\n property: referenceDefinition.property\n });\n\n let referencedItem;\n\n if (context) {\n // Check if we already have this item cached\n if (context.isCached(itemKey)) {\n libLogger.debug('Using cached reference', { itemKey, property: referenceDefinition.property });\n referencedItem = context.getCached(itemKey);\n }\n // Check if this item is currently being loaded (circular dependency)\n else if (context.isInProgress(itemKey)) {\n libLogger.debug('Circular dependency detected, creating reference placeholder', {\n itemKey,\n property: referenceDefinition.property\n });\n\n // Create a minimal reference object with just the key to break the cycle\n referencedItem = {\n key: itemKey,\n // Add any other minimal properties that might be needed\n // This prevents infinite loops while still providing the key for identification\n };\n }\n else {\n // Mark this key as in progress before loading\n context.markInProgress(itemKey);\n try {\n // Get the referenced item using the Library.Operations get method (context now managed internally)\n referencedItem = await library!.operations.get(itemKey);\n\n // Cache the result\n context.setCached(itemKey, referencedItem);\n } catch (error: any) {\n throw error; // Re-throw to maintain original behavior\n } finally {\n // Always mark as complete, even if there was an error\n context.markComplete(itemKey);\n }\n }\n } else {\n // Fallback to original behavior if no context provided\n referencedItem = await library!.operations.get(itemKey);\n }\n\n // Store the result in the property on item (Sequelize style - direct property)\n item[referenceDefinition.property] = referencedItem;\n\n return item;\n};\n\n/**\n * Strip populated reference properties from item before writing to database.\n * This ensures we only store the foreign key columns, not the full populated items.\n *\n * @param item - The item to strip references from\n * @param referenceDefinitions - Array of reference definitions to strip\n * @returns The item with only foreign key values (no populated items)\n */\nexport const stripSequelizeReferenceItems = <\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n referenceDefinitions: SequelizeReferenceDefinition[]\n ): Partial<Item<S, L1, L2, L3, L4, L5>> => {\n const result = { ...item };\n\n // Remove populated reference properties but keep the foreign key columns\n for (const refDef of referenceDefinitions) {\n // Delete the populated property (e.g., delete item.author)\n // Keep the foreign key column (e.g., keep item.authorId)\n delete result[refDef.property as keyof typeof result];\n }\n\n return result;\n};\n\n", "/* eslint-disable indent */\nimport { ComKey, isComKey, isPriKey, Item, LocKeyArray, PriKey, validateKeys } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport { validateLocations } from \"../validation/LocationKeyValidator\";\nimport LibLogger from '../logger';\nimport { processRow } from \"../RowProcessor\";\nimport * as Library from \"@fjell/lib\";\nimport { ModelStatic } from \"sequelize\";\nimport { extractEvents, removeEvents } from \"../EventCoordinator\";\nimport { buildRelationshipChain, buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { stringifyJSON } from \"../util/general\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'create');\n\n// Helper function to translate PostgreSQL errors to meaningful messages\nfunction translateDatabaseError(error: any, itemData: any, modelName: string): Error {\n const originalMessage = error.message || '';\n const errorCode = error.original?.code;\n const constraint = error.original?.constraint;\n const detail = error.original?.detail;\n\n logger.error('Database error during create operation', {\n errorCode,\n constraint,\n detail,\n originalMessage,\n modelName,\n itemData: JSON.stringify(itemData, null, 2)\n });\n\n // Handle specific PostgreSQL error codes\n switch (errorCode) {\n case '23505': // unique_violation\n if (constraint) {\n return new Error(`Duplicate value violates unique constraint '${constraint}'. ${detail || ''}`);\n }\n return new Error(`Duplicate value detected. This record already exists. ${detail || ''}`);\n\n case '23503': // foreign_key_violation\n if (constraint) {\n return new Error(`Foreign key constraint '${constraint}' violated. Referenced record does not exist. ${detail || ''}`);\n }\n return new Error(`Referenced record does not exist. Check that all related records are valid. ${detail || ''}`);\n\n case '23502': // not_null_violation\n const column = error.original?.column;\n if (column) {\n return new Error(`Required field '${column}' cannot be null`);\n }\n return new Error(`Required field is missing or null`);\n\n case '23514': // check_violation\n if (constraint) {\n return new Error(`Check constraint '${constraint}' violated. ${detail || ''}`);\n }\n return new Error(`Data validation failed. Check constraint violated. ${detail || ''}`);\n\n case '22001': // string_data_right_truncation\n return new Error(`Data too long for field. Check string lengths. ${detail || ''}`);\n\n case '22003': // numeric_value_out_of_range\n return new Error(`Numeric value out of range. Check number values. ${detail || ''}`);\n\n case '42703': // undefined_column\n const undefinedColumn = error.original?.column;\n if (undefinedColumn) {\n return new Error(`Column '${undefinedColumn}' does not exist in table '${modelName}'`);\n }\n return new Error(`Referenced column does not exist`);\n\n case '42P01': // undefined_table\n return new Error(`Table '${modelName}' does not exist`);\n\n default:\n // Handle SQLite-specific errors that don't have error codes\n if (originalMessage.includes('notNull Violation')) {\n const fieldMatches = originalMessage.match(/([a-zA-Z]+\\.[a-zA-Z]+) cannot be null/g);\n if (fieldMatches) {\n const fields = fieldMatches.map((match: string) => {\n const parts = match.split('.');\n return parts[1]?.split(' ')[0]; // Extract field name like 'code' from 'WidgetType.code'\n }).filter(Boolean);\n if (fields.length > 0) {\n return new Error(`Required field${fields.length > 1 ? 's' : ''} ${fields.join(', ')} cannot be null`);\n }\n }\n return new Error('Required fields are missing');\n }\n\n // For unknown errors, provide the original message with context\n return new Error(`Database error in ${modelName}.create(): ${originalMessage}. Item data: ${JSON.stringify(itemData, null, 2)}`);\n }\n}\n\n// Helper function to validate hierarchical chain exists\nasync function validateHierarchicalChain(\n models: ModelStatic<any>[],\n locKey: { kt: string; lk: any },\n kta: string[]\n): Promise<void> {\n try {\n // Find the direct parent model that contains this locator\n const locatorIndex = kta.indexOf(locKey.kt);\n if (locatorIndex === -1) {\n throw new Error(`Locator type '${locKey.kt}' not found in kta array`);\n }\n\n // Get the model for this locator\n const locatorModel = models[locatorIndex] || models[0]; // Fallback to primary model\n\n // Build a query to validate the chain exists\n const chainResult = buildRelationshipChain(locatorModel, kta, locatorIndex, kta.length - 1);\n\n if (!chainResult.success) {\n // If we can't build a chain, just validate the record exists\n const record = await locatorModel.findByPk(locKey.lk);\n if (!record) {\n throw new Error(`Referenced ${locKey.kt} with id ${locKey.lk} does not exist`);\n }\n return;\n }\n\n // Validate that the chain exists\n const queryOptions: any = {\n where: { id: locKey.lk }\n };\n\n if (chainResult.includes && chainResult.includes.length > 0) {\n queryOptions.include = chainResult.includes;\n }\n\n const record = await locatorModel.findOne(queryOptions);\n if (!record) {\n throw new Error(`Referenced ${locKey.kt} with id ${locKey.lk} does not exist or chain is invalid`);\n }\n } catch (error: any) {\n // Add context to validation errors\n if (error.original) {\n throw translateDatabaseError(error, { locKey, kta }, locKey.kt);\n }\n throw error;\n }\n}\n\nexport const getCreateOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n\n registry: Library.Registry\n) => {\n\n const create = async (\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n options?: {\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n locations?: never;\n } | {\n key?: never;\n locations: LocKeyArray<L1, L2, L3, L4, L5>,\n },\n ): Promise<V> => {\n const constraints = options?.key\n ? `key: pk=${options.key.pk}, loc=[${isComKey(options.key)\n ? (options.key as ComKey<S, L1, L2, L3, L4, L5>).loc.map((l: any) => `${l.kt}=${l.lk}`).join(', ')\n : ''}]`\n : options?.locations\n ? `locations: ${options.locations.map(loc => `${loc.kt}=${loc.lk}`).join(', ')}`\n : 'no constraints';\n logger.debug(`CREATE operation called on ${models[0].name} with ${constraints}`);\n logger.default(`Create configured for ${models[0].name} with ${Object.keys(item).length} item fields`);\n\n const { coordinate, options: { references, aggregations } } = definition;\n const { kta } = coordinate;\n\n // Validate location key order from options\n if (options?.locations) {\n validateLocations(options.locations, coordinate, 'create');\n }\n if (options?.key && isComKey(options.key)) {\n validateLocations((options.key as ComKey<S, L1, L2, L3, L4, L5>).loc, coordinate, 'create');\n }\n\n // Get the primary model (first model in array)\n const model = models[0];\n const modelAttributes = model.getAttributes();\n\n // Validate that all item attributes exist on the model\n let itemData = { ...item } as any;\n\n // TODO: We need the opposite of processRow, something to step down from fjell to database.\n itemData = extractEvents(itemData);\n itemData = removeEvents(itemData);\n\n // Validate that all item attributes exist on the model\n const invalidAttributes: string[] = [];\n for (const key of Object.keys(itemData)) {\n if (!modelAttributes[key]) {\n invalidAttributes.push(key);\n }\n }\n\n if (invalidAttributes.length > 0) {\n const availableAttributes = Object.keys(modelAttributes).join(', ');\n throw new Error(\n `Invalid attributes for model '${model.name}': [${invalidAttributes.join(', ')}]. ` +\n `Available attributes: [${availableAttributes}]. ` +\n `Item data: ${JSON.stringify(itemData, null, 2)}`\n );\n }\n\n // Handle key options\n // If a key is supplied, assume its contents are to be assigned to the appropriate ids.\n // For most cases this will be null as key generation is often through autoIncrement.\n // If this is a CItem then the locations will be present.\n if (options?.key) {\n const key = options.key;\n if (isPriKey(key)) {\n // Set the primary key\n itemData.id = key.pk;\n } else if (isComKey(key)) {\n // Set primary key\n itemData.id = key.pk;\n\n // Process location keys - only set direct foreign keys, validate hierarchical chains\n const comKey = key as ComKey<S, L1, L2, L3, L4, L5>;\n const directLocations: Array<{ kt: string; lk: any }> = [];\n const hierarchicalLocations: Array<{ kt: string; lk: any }> = [];\n\n // Categorize location keys as direct or hierarchical\n for (const locKey of comKey.loc) {\n const relationshipInfo = buildRelationshipPath(model, locKey.kt, kta, true);\n\n if (!relationshipInfo.found) {\n const associations = model.associations ? Object.keys(model.associations) : [];\n const errorMessage = `Composite key locator '${locKey.kt}' cannot be resolved on model '${model.name}' or through its relationships. ` +\n `Available associations: [${associations.join(', ')}]. ` +\n `KTA: [${kta.join(', ')}]. ` +\n `Composite key: ${JSON.stringify(comKey, null, 2)}`;\n logger.error(errorMessage, { key: comKey, kta, associations });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.isDirect) {\n directLocations.push(locKey);\n } else {\n hierarchicalLocations.push(locKey);\n }\n }\n\n // Set direct foreign keys\n for (const locKey of directLocations) {\n if (locKey.lk == null || locKey.lk === '') {\n logger.error(`Composite key location '${locKey.kt}' has undefined/null lk value`, { locKey, key: comKey });\n throw new Error(`Composite key location '${locKey.kt}' has undefined/null lk value`);\n }\n const foreignKeyField = locKey.kt + 'Id';\n itemData[foreignKeyField] = locKey.lk;\n }\n\n // Validate hierarchical chains exist\n for (const locKey of hierarchicalLocations) {\n await validateHierarchicalChain(models, locKey, kta);\n }\n }\n }\n\n // Handle locations options\n // This is the most frequent way relationship ids will be set\n if (options?.locations) {\n const directLocations: Array<{ kt: string; lk: any }> = [];\n const hierarchicalLocations: Array<{ kt: string; lk: any }> = [];\n\n // Categorize location keys as direct or hierarchical\n for (const locKey of options.locations) {\n const relationshipInfo = buildRelationshipPath(model, locKey.kt, kta, true);\n\n if (!relationshipInfo.found) {\n const associations = model.associations ? Object.keys(model.associations) : [];\n const errorMessage = `Location key '${locKey.kt}' cannot be resolved on model '${model.name}' or through its relationships. ` +\n `Available associations: [${associations.join(', ')}]. ` +\n `KTA: [${kta.join(', ')}]. ` +\n `Locations: ${JSON.stringify(options.locations, null, 2)}`;\n logger.error(errorMessage, { locations: options.locations, kta, associations });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.isDirect) {\n directLocations.push(locKey);\n } else {\n hierarchicalLocations.push(locKey);\n }\n }\n\n // Set direct foreign keys\n for (const locKey of directLocations) {\n if (locKey.lk == null || locKey.lk === '') {\n logger.error(`Location option '${locKey.kt}' has undefined/null lk value`, { locKey, locations: options.locations });\n throw new Error(`Location option '${locKey.kt}' has undefined/null lk value`);\n }\n const foreignKeyField = locKey.kt + 'Id';\n itemData[foreignKeyField] = locKey.lk;\n }\n\n // Validate hierarchical chains exist\n for (const locKey of hierarchicalLocations) {\n await validateHierarchicalChain(models, locKey, kta);\n }\n }\n\n // Create the record\n try {\n logger.trace(`[CREATE] Executing ${model.name}.create() with data: ${stringifyJSON(itemData)}`);\n const createdRecord = await model.create(itemData);\n\n // Add key and events\n // Create operations get their own context since they're top-level operations\n const processedRecord = await processRow(createdRecord, kta, references || [], aggregations || [], registry);\n const result = validateKeys(processedRecord, kta) as V;\n\n logger.debug(`[CREATE] Created ${model.name} with key: ${(result as any).key ? JSON.stringify((result as any).key) : `id=${createdRecord.id}`}`);\n return result;\n } catch (error: any) {\n throw translateDatabaseError(error, itemData, model.name);\n }\n }\n\n return create;\n}\n", "/* eslint-disable indent */\nimport { Item, LocKeyArray, validateKeys } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport { validateLocations } from \"../validation/LocationKeyValidator\";\nimport LibLogger from '../logger';\nimport { ModelStatic } from \"sequelize\";\nimport { processRow } from \"../RowProcessor\";\nimport * as Library from \"@fjell/lib\";\nimport { stringifyJSON } from \"../util/general\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'find');\n\nexport const getFindOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n) => {\n\n const { options: { finders, references, aggregations } } = definition;\n\n const find = async (\n finder: string,\n finderParams: Record<string, string | number | boolean | Date | Array<string | number | boolean | Date>>,\n locations?: LocKeyArray<L1, L2, L3, L4, L5> | [],\n\n ): Promise<V[]> => {\n const locationFilters = locations?.map(loc => `${loc.kt}=${loc.lk}`).join(', ') || 'none';\n logger.debug(\n `FIND operation called on ${models[0].name} with finder '${finder}' ` +\n `and ${locations?.length || 0} location filters: ${locationFilters}`\n );\n logger.default(`Find configured for ${models[0].name} using finder '${finder}' with ${Object.keys(finderParams).length} params`);\n\n // Validate location key order\n validateLocations(locations, definition.coordinate, 'find');\n\n // Note that we execute the createFinders function here because we want to make sure we're always getting the\n // most up to date methods.\n if (finders && finders[finder]) {\n const finderMethod = finders[finder];\n if (finderMethod) {\n logger.trace(`[FIND] Executing finder '${finder}' on ${models[0].name} with params: ${stringifyJSON(finderParams)}, locations: ${stringifyJSON(locations)}`);\n const results = await finderMethod(finderParams, locations);\n if (results && results.length > 0) {\n const processedResults = (await Promise.all(results.map(async (row: any) => {\n // Each found row gets its own context to prevent interference between concurrent processing\n const processedRow = await processRow(row, definition.coordinate.kta, references || [], aggregations || [], registry);\n return validateKeys(processedRow, definition.coordinate.kta);\n })) as V[]);\n\n logger.debug(`[FIND] Found ${processedResults.length} ${models[0].name} records using finder '${finder}'`);\n return processedResults;\n } else {\n logger.debug(`[FIND] Found 0 ${models[0].name} records using finder '${finder}'`);\n return [];\n }\n } else {\n logger.error(`Finder %s not found`, finder);\n throw new Error(`Finder ${finder} not found`);\n }\n } else {\n logger.error(`No finders have been defined for this lib`);\n throw new Error(`No finders found`);\n }\n }\n\n return find;\n}\n", "/* eslint-disable max-len */\n/* eslint-disable indent */\nimport {\n ComKey,\n isComKey,\n isPriKey,\n isValidItemKey,\n Item,\n PriKey,\n validateKeys\n} from '@fjell/core';\n\nimport LibLogger from '../logger';\nimport { ModelStatic } from 'sequelize';\nimport { processRow } from '../RowProcessor';\nimport { Definition } from '../Definition';\nimport { NotFoundError } from '@fjell/lib';\nimport * as Library from \"@fjell/lib\";\nimport { buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { contextManager } from \"../RowProcessor\";\nimport { stringifyJSON } from \"../util/general\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'get');\n\n// Helper function to process composite key and build query options\nconst processCompositeKey = (\n comKey: ComKey<any, any, any, any, any, any>,\n model: ModelStatic<any>,\n kta: string[]\n): { where: { [key: string]: any }; include?: any[] } => {\n const where: { [key: string]: any } = { id: comKey.pk };\n const includes: any[] = [];\n\n for (const locator of comKey.loc) {\n const relationshipInfo = buildRelationshipPath(model, locator.kt, kta);\n\n if (!relationshipInfo.found) {\n const errorMessage = `Composite key locator '${locator.kt}' cannot be resolved on model '${model.name}' or through its relationships. Key type array: [${kta.join(', ')}], Composite key: ${stringifyJSON(comKey)}, Available associations: [${Object.keys(model.associations || {}).join(', ')}]`;\n logger.error(errorMessage, { key: comKey, kta });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.path) {\n // This requires a relationship traversal\n where[relationshipInfo.path] = locator.lk;\n if (relationshipInfo.includes) {\n includes.push(...relationshipInfo.includes);\n }\n } else {\n // This is a direct field\n const fieldName = `${locator.kt}Id`;\n where[fieldName] = locator.lk;\n }\n }\n\n const result: { where: { [key: string]: any }; include?: any[] } = { where };\n if (includes.length > 0) {\n result.include = includes;\n }\n\n return result;\n};\n\nexport const getGetOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: Array<ModelStatic<any>>,\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n) => {\n\n const { coordinate, options: { references, aggregations } } = definition;\n const { kta } = coordinate;\n\n const get = async (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>\n ): Promise<V> => {\n if (!isValidItemKey(key)) {\n logger.error('Key for Get is not a valid ItemKey: %j', key);\n throw new Error('Key for Get is not a valid ItemKey');\n }\n\n const keyDescription = isPriKey(key)\n ? `primary key: pk=${key.pk}`\n : `composite key: pk=${key.pk}, loc=[${(key as ComKey<S, L1, L2, L3, L4, L5>).loc.map((l: any) => `${l.kt}=${l.lk}`).join(', ')}]`;\n logger.debug(`GET operation called on ${models[0].name} with ${keyDescription}`);\n logger.default(`Get configured for ${models[0].name} with ${isPriKey(key) ? 'primary' : 'composite'} key`);\n\n const itemKey = key;\n\n // @ts-ignore\n const model = models[0];\n\n let item;\n\n if (isPriKey(itemKey)) {\n // This is the easy case because we can just find the item by its primary key\n logger.trace(`[GET] Executing ${model.name}.findByPk() with pk: ${(itemKey as PriKey<S>).pk}`);\n item = await model.findByPk((itemKey as PriKey<S>).pk);\n } else if (isComKey(itemKey)) {\n const comKey = itemKey as ComKey<S, L1, L2, L3, L4, L5>;\n \n // Empty loc array is a special case: find by primary key across all locations\n // This is used for foreign key references to composite items where location context is unknown\n if (comKey.loc.length === 0) {\n logger.debug(`[GET] Empty loc array detected - finding by primary key across all locations: ${comKey.pk}`);\n logger.trace(`[GET] Executing ${model.name}.findByPk() with pk: ${comKey.pk}`);\n item = await model.findByPk(comKey.pk);\n } else {\n // This is a composite key with location context, build a where clause based on the locators\n const queryOptions = processCompositeKey(comKey, model, kta);\n\n logger.default('Composite key query', { queryOptions });\n logger.trace(`[GET] Executing ${model.name}.findOne() with options: ${stringifyJSON(queryOptions)}`);\n item = await model.findOne(queryOptions);\n }\n }\n\n if (!item) {\n throw new NotFoundError<S, L1, L2, L3, L4, L5>('get', coordinate, key);\n } else {\n // Use current context if available (prevents infinite recursion in reference loading)\n // This ensures proper circular dependency detection within the same operation\n const currentContext = contextManager.getCurrentContext();\n const result = validateKeys(await processRow(item, kta, references || [], aggregations || [], registry, currentContext), kta) as V;\n\n logger.debug(`[GET] Retrieved ${model.name} with key: ${(result as any).key ? JSON.stringify((result as any).key) : `id=${item.id}`}`);\n return result;\n }\n }\n\n return get;\n}\n", "/* eslint-disable indent */\nimport { Item, ItemQuery, LocKeyArray } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport { validateLocations } from \"../validation/LocationKeyValidator\";\nimport LibLogger from '../logger';\nimport { ModelStatic } from \"sequelize\";\nimport { getAllOperation } from \"./all\";\nimport * as Library from \"@fjell/lib\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'one');\n\nexport const getOneOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n) => {\n const one = async (\n itemQuery: ItemQuery,\n locations: LocKeyArray<L1, L2, L3, L4, L5> | [] = [],\n ): Promise<V | null> => {\n logger.debug(`ONE operation called on ${models[0].name} with ${locations.length} location filters: ${locations.map(loc => `${loc.kt}=${loc.lk}`).join(', ') || 'none'}`);\n logger.default(`One configured for ${models[0].name} delegating to all operation`);\n\n // Validate location key order\n validateLocations(locations, definition.coordinate, 'one');\n\n const items = await getAllOperation(models, definition, registry)(itemQuery, locations);\n if (items.length > 0) {\n const result = items[0] as V;\n logger.debug(`[ONE] Found ${models[0].name} record with key: ${(result as any).key ? JSON.stringify((result as any).key) : 'unknown'}`);\n return result;\n } else {\n logger.debug(`[ONE] No ${models[0].name} record found`);\n return null;\n }\n }\n\n return one;\n}", "/* eslint-disable */\nimport { ComKey, isValidItemKey, PriKey } from \"@fjell/core\";\n\nimport { abbrevIK, isComKey, isPriKey, Item } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport { populateEvents } from \"../EventCoordinator\";\nimport { addKey } from \"../KeyMaster\";\nimport LibLogger from '../logger';\nimport { ModelStatic } from \"sequelize\";\nimport { buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { stringifyJSON } from \"../util/general\";\nimport { NotFoundError } from \"@fjell/lib\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'remove');\n\n// Helper function to process composite key and build query options\nconst processCompositeKey = (\n comKey: ComKey<any, any, any, any, any, any>,\n model: ModelStatic<any>,\n kta: string[]\n): { where: { [key: string]: any }; include?: any[] } => {\n const where: { [key: string]: any } = { id: comKey.pk };\n const includes: any[] = [];\n\n for (const locator of comKey.loc) {\n const relationshipInfo = buildRelationshipPath(model, locator.kt, kta);\n\n if (!relationshipInfo.found) {\n const errorMessage = `Composite key locator '${locator.kt}' cannot be resolved on model '${model.name}' or through its relationships.`;\n logger.error(errorMessage, { key: comKey, kta });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.path) {\n // This requires a relationship traversal\n where[relationshipInfo.path] = locator.lk;\n if (relationshipInfo.includes) {\n includes.push(...relationshipInfo.includes);\n }\n } else {\n // This is a direct field\n const fieldName = `${locator.kt}Id`;\n where[fieldName] = locator.lk;\n }\n }\n\n const result: { where: { [key: string]: any }; include?: any[] } = { where };\n if (includes.length > 0) {\n result.include = includes;\n }\n\n return result;\n};\n\nexport const getRemoveOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n _registry: import('@fjell/lib').Registry\n) => {\n const { coordinate, options } = definition;\n const { kta } = coordinate;\n\n const remove = async (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n ): Promise<V> => {\n if (!isValidItemKey(key)) {\n logger.error('Key for Remove is not a valid ItemKey: %j', key);\n throw new Error('Key for Remove is not a valid ItemKey');\n }\n\n const keyDescription = isPriKey(key)\n ? `primary key: pk=${key.pk}`\n : `composite key: pk=${key.pk}, loc=[${(key as ComKey<S, L1, L2, L3, L4, L5>).loc.map((l: any) => `${l.kt}=${l.lk}`).join(', ')}]`;\n logger.debug(`REMOVE operation called on ${models[0].name} with ${keyDescription}`);\n logger.default(`Remove configured for ${models[0].name} with ${isPriKey(key) ? 'primary' : 'composite'} key`);\n\n // @ts-ignore\n const model = models[0];\n\n let item;\n let returnItem;\n\n logger.debug('remove: %s', abbrevIK(key));\n if (isPriKey(key)) {\n logger.debug(`[REMOVE] Executing ${model.name}.findByPk() with pk: ${(key as PriKey<S>).pk}`);\n item = await model.findByPk((key as PriKey<S>).pk);\n } else if (isComKey(key)) {\n // This is a composite key, so we need to build a where clause based on the composite key's locators\n const comKey = key as ComKey<S, L1, L2, L3, L4, L5>;\n const queryOptions = processCompositeKey(comKey, model, kta);\n\n logger.default(`Remove composite key query for ${model.name} with where fields: ${queryOptions.where ? Object.keys(queryOptions.where).join(', ') : 'none'}`);\n logger.debug(`[REMOVE] Executing ${model.name}.findOne() with options: ${stringifyJSON(queryOptions)}`);\n item = await model.findOne(queryOptions);\n }\n\n if (!item) {\n throw new NotFoundError<S, L1, L2, L3, L4, L5>('remove', coordinate, key);\n }\n\n const isDeletedAttribute = model.getAttributes().isDeleted;\n const deletedAtAttribute = model.getAttributes().deletedAt;\n\n if (isDeletedAttribute || deletedAtAttribute) {\n if (model.getAttributes().isDeleted) {\n item.isDeleted = true;\n }\n\n if (model.getAttributes().deletedAt) {\n item.deletedAt = new Date();\n }\n\n // Save the object\n logger.debug(`[REMOVE] Executing ${model.name}.save() for soft delete`);\n await item?.save();\n returnItem = item?.get({ plain: true }) as Partial<Item<S, L1, L2, L3, L4, L5>>;\n returnItem = addKey(item, returnItem as any, kta);\n returnItem = populateEvents(returnItem);\n } else if (options.deleteOnRemove) {\n logger.debug(`[REMOVE] Executing ${model.name}.destroy() for hard delete`);\n await item?.destroy();\n returnItem = item?.get({ plain: true }) as Partial<Item<S, L1, L2, L3, L4, L5>>;\n returnItem = addKey(item, returnItem as any, kta);\n returnItem = populateEvents(returnItem);\n } else {\n throw new Error('No deletedAt or isDeleted attribute found in model, and deleteOnRemove is not set');\n }\n\n logger.debug(`[REMOVE] Removed ${model.name} with key: ${(returnItem as any).key ? JSON.stringify((returnItem as any).key) : `id=${item.id}`}`);\n return returnItem as V;\n }\n\n return remove;\n}\n", "/* eslint-disable indent */\nimport { abbrevIK, isComKey, validateKeys } from \"@fjell/core\";\n\nimport { isPriKey } from \"@fjell/core\";\n\nimport { ComKey, Item, PriKey } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport { extractEvents, removeEvents } from \"../EventCoordinator\";\nimport { removeKey } from \"../KeyMaster\";\nimport LibLogger from '../logger';\nimport { processRow } from \"../RowProcessor\";\n\nimport * as Library from \"@fjell/lib\";\nimport { NotFoundError } from \"@fjell/lib\";\nimport { ModelStatic, Op } from \"sequelize\";\nimport { buildRelationshipPath } from \"../util/relationshipUtils\";\nimport { stringifyJSON } from \"../util/general\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'update');\n\n// Helper function to merge includes avoiding duplicates\nconst mergeIncludes = (existingIncludes: any[], newIncludes: any[]): any[] => {\n const mergedIncludes = [...existingIncludes];\n\n for (const newInclude of newIncludes) {\n const existingIndex = mergedIncludes.findIndex(\n (existing: any) => existing.as === newInclude.as && existing.model === newInclude.model\n );\n if (existingIndex === -1) {\n mergedIncludes.push(newInclude);\n } else if (newInclude.include && mergedIncludes[existingIndex].include) {\n mergedIncludes[existingIndex].include = [\n ...mergedIncludes[existingIndex].include,\n ...newInclude.include\n ];\n } else if (newInclude.include) {\n mergedIncludes[existingIndex].include = newInclude.include;\n }\n }\n\n return mergedIncludes;\n};\n\nexport const getUpdateOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n\n registry: Library.Registry\n) => {\n\n const { options: { references, aggregations } } = definition;\n\n const update = async (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>,\n ): Promise<V> => {\n const keyDescription = isPriKey(key)\n ? `primary key: pk=${key.pk}`\n : `composite key: pk=${key.pk}, loc=[${(key as ComKey<S, L1, L2, L3, L4, L5>).loc.map((l: any) => `${l.kt}=${l.lk}`).join(', ')}]`;\n logger.debug(`UPDATE operation called on ${models[0].name} with ${keyDescription}`);\n const { coordinate } = definition;\n const { kta } = coordinate;\n\n logger.debug('update: %s, %j', abbrevIK(key), item);\n // Find the object we're updating\n // @ts-ignore\n const model = models[0];\n\n let response;\n\n if (isPriKey(key)) {\n // Find the model by using the PK\n const priKey = key as PriKey<S>;\n logger.trace(`[UPDATE] Executing ${model.name}.findByPk() with pk: ${priKey.pk}`);\n response = await model.findByPk(priKey.pk);\n } else if (isComKey(key)) {\n const comKey = key as ComKey<S, L1, L2, L3, L4, L5>;\n\n // Build query options for composite key with multiple location keys\n const where: { [key: string]: any } = { id: comKey.pk };\n const additionalIncludes: any[] = [];\n\n // Process all location keys in the composite key\n for (const locator of comKey.loc) {\n const relationshipInfo = buildRelationshipPath(model, locator.kt, kta, true);\n\n if (!relationshipInfo.found) {\n const errorMessage = `Composite key locator '${locator.kt}' cannot be resolved on model '${model.name}' or through its relationships.`;\n logger.error(errorMessage, { key: comKey, kta });\n throw new Error(errorMessage);\n }\n\n if (relationshipInfo.isDirect) {\n // Direct foreign key field\n const fieldName = `${locator.kt}Id`;\n where[fieldName] = locator.lk;\n } else if (relationshipInfo.path) {\n // Hierarchical relationship requiring traversal\n where[relationshipInfo.path] = {\n [Op.eq]: locator.lk\n };\n\n // Add necessary includes for relationship traversal\n if (relationshipInfo.includes) {\n additionalIncludes.push(...relationshipInfo.includes);\n }\n }\n }\n\n // Build final query options\n const queryOptions: any = { where };\n if (additionalIncludes.length > 0) {\n queryOptions.include = mergeIncludes([], additionalIncludes);\n }\n\n logger.default(`Update composite key query for ${model.name} with where fields: ${queryOptions.where ? Object.keys(queryOptions.where).join(', ') : 'none'}`);\n logger.trace(`[UPDATE] Executing ${model.name}.findOne() with options: ${stringifyJSON(queryOptions)}`);\n response = await model.findOne(queryOptions);\n }\n\n if (response) {\n\n // Remove the key and events\n let updateProps = removeKey(item)\n // TODO: We need the opposite of processRow, something to step down from fjell to database.\n updateProps = extractEvents(updateProps);\n updateProps = removeEvents(updateProps);\n\n logger.default(`Update found ${model.name} record to modify`);\n logger.default(`Update properties configured: ${Object.keys(updateProps).join(', ')}`);\n\n // Update the object\n logger.trace(`[UPDATE] Executing ${model.name}.update() with properties: ${stringifyJSON(updateProps)}`);\n response = await response.update(updateProps);\n\n // Populate the key and events\n // Update operations get their own context since they're top-level operations\n const processedItem = await processRow(response, kta, references || [], aggregations || [], registry);\n const returnItem = validateKeys(processedItem, kta);\n\n logger.debug(`[UPDATE] Updated ${model.name} with key: ${(returnItem as any).key ? JSON.stringify((returnItem as any).key) : `id=${response.id}`}`);\n return returnItem as V;\n } else {\n throw new NotFoundError<S, L1, L2, L3, L4, L5>('update', coordinate, key);\n }\n\n }\n\n return update;\n}\n", "/* eslint-disable indent */\nimport { ComKey, isValidItemKey, Item, PriKey } from \"@fjell/core\";\n\nimport { Definition } from \"../Definition\";\nimport LibLogger from '../logger';\nimport * as Library from \"@fjell/lib\";\nimport { ModelStatic } from \"sequelize\";\nimport { getGetOperation } from \"./get\";\nimport { getUpdateOperation } from \"./update\";\nimport { getCreateOperation } from \"./create\";\nimport { stringifyJSON } from \"../util/general\";\n\nconst logger = LibLogger.get('sequelize', 'ops', 'upsert');\n\nexport const getUpsertOperation = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: Array<ModelStatic<any>>,\n definition: Definition<V, S, L1, L2, L3, L4, L5>,\n registry: Library.Registry\n) => {\n\n // Get the individual operations we'll use\n const get = getGetOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n const update = getUpdateOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n const create = getCreateOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n\n const upsert = async (\n key: PriKey<S> | ComKey<S, L1, L2, L3, L4, L5>,\n item: Partial<Item<S, L1, L2, L3, L4, L5>>\n ): Promise<V> => {\n\n if (!isValidItemKey(key)) {\n logger.error('Key for Upsert is not a valid ItemKey: %j', key);\n throw new Error(`Key for Upsert is not a valid ItemKey: ${stringifyJSON(key)}`);\n }\n\n logger.debug(`[UPSERT] Attempting upsert with key: ${stringifyJSON(key)}`);\n\n try {\n // Try to get the existing item first\n const existingItem = await get(key);\n if (existingItem) {\n logger.debug(`[UPSERT] Item exists, updating with key: ${stringifyJSON(key)}`);\n // Item exists, update it\n return await update(key, item);\n }\n } catch {\n // Item doesn't exist (get threw NotFoundError), fall through to create\n logger.debug(`[UPSERT] Item not found, creating new item with key: ${stringifyJSON(key)}`);\n }\n\n // Item doesn't exist, create it\n return await create(item, { key });\n }\n\n return upsert;\n}\n", "/* eslint-disable indent */\nimport { Item } from \"@fjell/core\";\n\nimport * as Library from \"@fjell/lib\";\nimport { Registry } from \"./Registry\";\nimport { getAllOperation } from \"./ops/all\";\nimport { getCreateOperation } from \"./ops/create\";\nimport { getFindOperation } from \"./ops/find\";\nimport { getGetOperation } from \"./ops/get\";\nimport { getOneOperation } from \"./ops/one\";\nimport { getRemoveOperation } from \"./ops/remove\";\nimport { getUpdateOperation } from \"./ops/update\";\nimport { getUpsertOperation } from \"./ops/upsert\";\nimport { ModelStatic } from \"sequelize\";\nimport { Coordinate } from \"@fjell/registry\";\n\nexport const createOperations = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never,\n>(\n models: Array<ModelStatic<any>>,\n coordinate: Coordinate<S, L1, L2, L3, L4, L5>,\n registry: Registry,\n options: import('./Options').Options<V, S, L1, L2, L3, L4, L5>\n): Library.Operations<V, S, L1, L2, L3, L4, L5> => {\n\n const operations = {} as Library.Operations<V, S, L1, L2, L3, L4, L5>;\n\n // Create a definition-like object for backward compatibility with existing operation functions\n const definition = { coordinate, options };\n\n operations.all = getAllOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n operations.one = getOneOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n operations.create = getCreateOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n operations.update = getUpdateOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n operations.get = getGetOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n operations.remove = getRemoveOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n operations.find = getFindOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n operations.upsert = getUpsertOperation<V, S, L1, L2, L3, L4, L5>(models, definition, registry);\n operations.allFacet = async (): Promise<any> => { };\n operations.allAction = async (): Promise<any> => { };\n operations.action = async (): Promise<any> => { };\n operations.facet = async (): Promise<any> => { };\n\n operations.finders = { ...(options.finders || {}) };\n operations.actions = { ...(options.actions || {}) };\n operations.facets = { ...(options.facets || {}) };\n operations.allActions = { ...(options.allActions || {}) };\n operations.allFacets = { ...(options.allFacets || {}) };\n\n return operations;\n}\n", "import { Item } from \"@fjell/core\";\nimport { Options } from \"./Options\";\nimport { Registry as LocalRegistry } from \"./Registry\";\nimport { InstanceFactory as BaseInstanceFactory, Registry as BaseRegistry, Coordinate, RegistryHub } from \"@fjell/registry\";\nimport { createSequelizeLibrary, SequelizeLibrary } from \"./SequelizeLibrary\";\nimport { ModelStatic } from \"sequelize\";\nimport SequelizeLogger from \"./logger\";\n\nconst logger = SequelizeLogger.get(\"InstanceFactory\");\n\n/**\n * Sequelize Library Factory type that extends the base factory\n * to include Sequelize-specific models parameter\n */\nexport type SequelizeLibraryFactory<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> = (\n models: ModelStatic<any>[],\n options: Options<V, S, L1, L2, L3, L4, L5>\n) => BaseInstanceFactory<S, L1, L2, L3, L4, L5>;\n\n/**\n * Factory function for creating Sequelize libraries\n * This extends the fjell-lib pattern by adding Sequelize-specific models\n */\nexport const createSequelizeLibraryFactory = <\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n models: ModelStatic<any>[],\n options: Options<V, S, L1, L2, L3, L4, L5>\n ): BaseInstanceFactory<S, L1, L2, L3, L4, L5> => {\n return (coordinate: Coordinate<S, L1, L2, L3, L4, L5>, context: { registry: BaseRegistry, registryHub?: RegistryHub }) => {\n logger.debug(\"Creating Sequelize instance\", {\n coordinate,\n registry: context.registry,\n models: models.map(m => m.name),\n options\n });\n\n return createSequelizeLibrary<V, S, L1, L2, L3, L4, L5>(\n context.registry as LocalRegistry,\n coordinate,\n models,\n options\n ) as SequelizeLibrary<V, S, L1, L2, L3, L4, L5>;\n };\n};\n", "export * from './SequelizeLibrary';\n", "\nimport { SequelizeLibrary as AbstractSequelizeLibrary } from '../SequelizeLibrary';\nimport { Item, ItemTypeArray } from '@fjell/core';\nimport { Contained } from '@fjell/lib';\nimport * as Library from '@fjell/lib';\nimport { createOperations } from '../Operations';\nimport { ModelStatic } from 'sequelize';\nimport { Registry } from '../Registry';\nimport { createOptions, Options } from '../Options';\nimport { Coordinate, createCoordinate } from '../Coordinate';\n\nexport interface SequelizeLibrary<\n V extends Item<S>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n> extends AbstractSequelizeLibrary<V, S, L1, L2, L3, L4, L5> {\n coordinate: Coordinate<S, L1, L2, L3, L4, L5>;\n registry: Registry;\n operations: Library.Operations<V, S, L1, L2, L3, L4, L5>;\n options: Options<V, S, L1, L2, L3, L4, L5>;\n models: ModelStatic<any>[];\n}\n\nexport function createSequelizeLibrary<\n V extends Item<S, L1, L2, L3, L4, L5>,\n S extends string,\n L1 extends string = never,\n L2 extends string = never,\n L3 extends string = never,\n L4 extends string = never,\n L5 extends string = never\n>(\n keyTypes: ItemTypeArray<S, L1, L2, L3, L4, L5>,\n models: ModelStatic<any>[],\n libOptions: Partial<Options<V, S, L1, L2, L3, L4, L5>> = {},\n scopes: string[] = [],\n registry: Registry\n): SequelizeLibrary<V, S, L1, L2, L3, L4, L5> {\n\n // Create coordinate and options separately following new pattern\n const coordinate = createCoordinate(keyTypes, scopes);\n const options = createOptions(libOptions);\n\n // Create operations with the new signature\n const operations = createOperations<V, S, L1, L2, L3, L4, L5>(models, coordinate, registry, options);\n\n // Wrap operations for contained pattern\n const wrappedOperations = Contained.wrapOperations(operations, options as any, coordinate, registry);\n\n return {\n coordinate,\n registry,\n operations: wrappedOperations,\n options,\n models,\n } as unknown as SequelizeLibrary<V, S, L1, L2, L3, L4, L5>;\n}\n", "export * from './SequelizeLibrary';\n", "\nimport { SequelizeLibrary as AbstractSequelizeLibrary } from '../SequelizeLibrary';\nimport { Item } from '@fjell/core';\nimport { Primary } from '@fjell/lib';\nimport * as Library from '@fjell/lib';\nimport { createOperations } from '../Operations';\nimport { ModelStatic } from 'sequelize';\nimport { createOptions, Options } from '../Options';\nimport { Registry } from '../Registry';\nimport { Coordinate, createCoordinate } from '../Coordinate';\n\nimport LibLogger from '../logger';\n\nconst logger = LibLogger.get('lib-sequelize', 'primary', 'library');\n\nexport interface SequelizeLibrary<\n V extends Item<S>,\n S extends string\n> extends AbstractSequelizeLibrary<V, S> {\n coordinate: Coordinate<S>;\n registry: Registry;\n operations: Library.Operations<V, S>;\n options: Options<V, S>;\n models: ModelStatic<any>[];\n}\n\nexport function createSequelizeLibrary<\n V extends Item<S>,\n S extends string\n>(\n keyType: S,\n models: ModelStatic<any>[],\n libOptions: Partial<Options<V, S>> = {},\n scopes: string[] = [],\n registry: Registry\n): SequelizeLibrary<V, S> {\n logger.debug('createSequelizeLibrary', { keyType, models, libOptions, scopes });\n\n // Create coordinate and options separately following new pattern\n const coordinate = createCoordinate([keyType], scopes);\n const options = createOptions(libOptions);\n\n // Create operations with the new signature\n const operations = createOperations<V, S>(models, coordinate, registry, options);\n\n // Wrap operations for primary pattern\n const wrappedOperations = Primary.wrapOperations(operations, options as any, coordinate, registry);\n\n return {\n coordinate,\n registry,\n operations: wrappedOperations,\n options,\n models,\n } as unknown as SequelizeLibrary<V, S>;\n}\n"],
5
+ "mappings": ";;;;;;;AAAA,YAAY,aAAa;AAkFlB,IAAMA,iBAAgB,CAQ3B,qBAA4F;AAE5F,QAAM,EAAE,YAAY,gBAAgB,GAAG,qBAAqB,IAAI,oBAAoB,CAAC;AAGrF,QAAM,cAAsB,sBAAc,oBAAiE;AAG3G,SAAO;AAAA,IACL,GAAG;AAAA,IACH,YAAY,cAAc,CAAC;AAAA;AAAA,IAC3B,cAAc,YAAY,gBAAgB,CAAC;AAAA;AAAA,IAC3C,gBAAgB,kBAAkB;AAAA;AAAA,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AAQ;AAEjG,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,EACF;AACF;",
6
6
  "names": ["createOptions", "logger", "createOptions", "Library", "logger", "logger", "result", "logger", "foreignKeyField", "logger", "logger", "logger", "logger", "Op", "logger", "loc", "Op", "isComKey", "isPriKey", "validateKeys", "logger", "record", "isComKey", "isPriKey", "validateKeys", "validateKeys", "logger", "validateKeys", "isComKey", "isPriKey", "validateKeys", "logger", "isPriKey", "isComKey", "validateKeys", "logger", "isValidItemKey", "isComKey", "isPriKey", "NotFoundError", "logger", "processCompositeKey", "isValidItemKey", "isPriKey", "isComKey", "abbrevIK", "isComKey", "validateKeys", "isPriKey", "NotFoundError", "Op", "logger", "mergeIncludes", "isPriKey", "abbrevIK", "isComKey", "Op", "validateKeys", "NotFoundError", "isValidItemKey", "logger", "isValidItemKey", "logger", "logger", "createSequelizeLibrary", "createSequelizeLibrary", "createOptions", "createSequelizeLibrary", "logger", "createSequelizeLibrary", "createOptions"]
7
7
  }
@@ -1 +1 @@
1
- {"version":3,"file":"get.d.ts","sourceRoot":"","sources":["../../src/ops/get.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,MAAM,EAIN,IAAI,EACJ,MAAM,EAEP,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAExC,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,OAAO,KAAK,OAAO,MAAM,YAAY,CAAC;AA8CtC,eAAO,MAAM,eAAe,GAC1B,CAAC,SAAS,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EACrC,CAAC,SAAS,MAAM,EAChB,EAAE,SAAS,MAAM,GAAG,KAAK,EACzB,EAAE,SAAS,MAAM,GAAG,KAAK,EACzB,EAAE,SAAS,MAAM,GAAG,KAAK,EACzB,EAAE,SAAS,MAAM,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AM,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,KAC7C,OAAO,CAAC,CAAC,CAwDb,CAAA"}
@@ -13,6 +13,14 @@ export interface SequelizeReferenceDefinition {
13
13
  kta: string[];
14
14
  /** Property name to populate with the referenced item (e.g., "author") */
15
15
  property: string;
16
+ /**
17
+ * Optional: Column names for location keys when referencing composite items.
18
+ * If provided, will construct a full ComKey with location context.
19
+ * If omitted for composite items, uses empty loc array to search across all locations.
20
+ *
21
+ * Example: ['phaseId'] for a step reference where you have both stepId and phaseId columns
22
+ */
23
+ locationColumns?: string[];
16
24
  }
17
25
  /**
18
26
  * Build a reference by looking up a related item by its key from a column value.
@@ -1 +1 @@
1
- {"version":3,"file":"ReferenceBuilder.d.ts","sourceRoot":"","sources":["../../src/processing/ReferenceBuilder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAU,MAAM,aAAa,CAAC;AAC3C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAG9C;;;;GAIG;AACH,MAAM,WAAW,4BAA4B;IAC3C,sEAAsE;IACtE,MAAM,EAAE,MAAM,CAAC;IACf,4CAA4C;IAC5C,GAAG,EAAE,MAAM,EAAE,CAAC;IACd,0EAA0E;IAC1E,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,uBAAuB,GAClC,MAAM,GAAG,EACT,qBAAqB,4BAA4B,EACjD,UAAU,QAAQ,EAClB,UAAU,gBAAgB,iBA0G3B,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,4BAA4B,GACvC,CAAC,SAAS,MAAM,EAChB,EAAE,SAAS,MAAM,GAAG,KAAK,EACzB,EAAE,SAAS,MAAM,GAAG,KAAK,EACzB,EAAE,SAAS,MA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K,EAEvB,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,EAC1C,sBAAsB,4BAA4B,EAAE,KACnD,OAAO,CAAC,IAAI,CAAC,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,CAWvC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fjell/lib-sequelize",
3
- "version": "4.4.52",
3
+ "version": "4.4.54",
4
4
  "license": "Apache-2.0",
5
5
  "keywords": [
6
6
  "library",
@@ -41,10 +41,10 @@
41
41
  "docs:test": "cd docs && npm run test"
42
42
  },
43
43
  "dependencies": {
44
- "@fjell/core": "^4.4.46",
45
- "@fjell/lib": "^4.4.54",
44
+ "@fjell/core": "^4.4.48",
45
+ "@fjell/lib": "^4.4.56",
46
46
  "@fjell/logging": "^4.4.47",
47
- "@fjell/registry": "^4.4.48",
47
+ "@fjell/registry": "^4.4.50",
48
48
  "dayjs": "^1.11.13",
49
49
  "deepmerge": "^4.3.1",
50
50
  "sequelize": "^6.37.7",