Global

Members

# ASSISTANT_GREETING_MESSAGE

Assistant greeting message to the user

View Source config/env.js, line 85

# AUTH_GRPC_HOST

Authentication gRPC service hostname

View Source config/env.js, line 50

# AUTH_GRPC_PORT

Authentication gRPC service port

View Source config/env.js, line 55

# constant AUTOGEN_RANDOM_BYTES

Number of random bytes used to generate a unique subLink suffix.

View Source types/urls/constants.js, line 8

# constant AssistantSchema

Embedded schema representing assistant responses in the chat history.

View Source models/Chat.model.js, line 17

# CACHE_DURATION_DEFAULT

Cache Configuration

View Source config/env.js, line 92

# CACHE_DURATION_LONG

Cache duration long

View Source config/env.js, line 110

# CACHE_DURATION_SHORT

Cache duration short

View Source config/env.js, line 101

# CORS_ALLOWED_DOMAIN

CORS allowed domain (e.g., ".aaic.dev" to allow all subdomains)

View Source config/env.js, line 147

# constant CURRICULUM_SORT_EXPR

MongoDB expression for curriculum sorting (empty → "zzz" to sort last)

View Source utils/investigation/mongo-aggregation.js, line 79

# constant Chat

Chat model used to persist conversation history.

View Source models/Chat.model.js, line 48

# constant ChatHistorySchema

Chat history entry schema combining user and assistant messages.

View Source models/Chat.model.js, line 28

# constant ChatSchema

Root schema representing a chat session and associated investigation reference.

View Source models/Chat.model.js, line 38

# constant DEFAULT_CURRICULUM

Default values and constants for investigation utilities

View Source utils/investigation/constants.js, line 5

# constant DEFAULT_HISTORY_LIMIT

Default number of history entries to return

View Source types/investigation/dto.utils.js, line 7

string

# DatabaseOperation

Database Operation Enum - For database operations

View Source types/enums.js, line 12

# ENV_PREFIX

Environment prefix for GCS paths (qa, dev, etc.)

View Source config/env.js, line 193

# constant EditableFieldSchema

General EditableField Schema - Base schema for all editable fields This schema provides the common structure for AI-generated and human-editable content

View Source models/investigation/schema-definition.js, line 20

# constant EditableVector3Schema

Vector3 Schema - 3D vector with x, y, z coordinates

View Source models/investigation/schema-definition.js, line 89

string

# ErrorCode

Error Code Enum - Application error codes

View Source types/enums.js, line 24

# constant FIELD_HISTORY_LIMIT_MIN

Pagination limit constants for field history endpoint

View Source types/investigation/constants.js, line 24

# constant FieldHistoryEntrySchema

Field History Entry Schema - Schema for a single history entry

View Source models/investigation/schema-definition.js, line 10

# GCS_BUCKET_NAME

Google Cloud Storage Configuration

View Source config/env.js, line 187

# constant GCS_PATHS

Google Cloud Storage path constants Centralized path definitions for GCS storage organization

View Source constants/gcs.constants.js, line 6

# constant GRADE_MIN

Grade range constants Defines the minimum and maximum grade values allowed in the system

View Source types/investigation/constants.js, line 10

# constant GRADE_SORT_EMPTY

Sort value for empty/missing grades

View Source utils/investigation/constants.js, line 42

# constant GRADE_SORT_FIELD

MongoDB expression for grade sorting. Converts grade to numeric: K=0, 1-12=1-12, P=13, B=14, C=15, other=99, empty=999

View Source utils/investigation/mongo-aggregation.js, line 48

# constant GRADE_SORT_UNKNOWN

Sort value for unknown/unrecognized grades

View Source utils/investigation/constants.js, line 40

# constant GRADE_SORT_VALUES

Grade sort values for non-numeric grades. Numeric grades (1-12) use their own values. Order: K=0, [1-12], P=13, B=14, C=15, unknown=99, empty=999

View Source utils/investigation/constants.js, line 33

# GRPC_HTTP2_PING_INTERVAL_MS

gRPC HTTP2 ping interval

View Source config/env.js, line 128

# GRPC_KEEPALIVE_TIME_MS

gRPC Configuration

View Source config/env.js, line 119

# constant INVESTIGATIONS_FETCH_ALL_LIMIT

Hard cap for fetchAll requests to prevent memory/performance issues

View Source types/investigation/constants.js, line 20

# constant INVESTIGATIONS_LIST_LIMIT_MIN

Pagination limit constants for investigations list endpoint

View Source types/investigation/constants.js, line 15

# INVESTIGATION_INACTIVITY_TIMEOUT_MS

Investigation inactivity timeout in milliseconds

View Source config/env.js, line 137

# constant INVESTIGATION_VERSIONS_LIMIT_MIN

Pagination limit constants for investigation versions endpoint

View Source types/investigation/constants.js, line 29

string

# Intents

AI Assistant's Intents Enum - For Assistant process message

View Source types/intent/enums.js, line 6

# constant Investigation

Investigation Model This is the main model file that assembles all components

View Source models/investigation/investigation.model.js, line 8

string

# InvestigationGroupType

Investigation List Group Type Enum Defines sub-grouping options within sections

View Source types/investigation/enums.js, line 40

# constant InvestigationMetadataSchema

Investigation Metadata Schema - Metadata for an investigation

View Source models/investigation/schema-definition.js, line 313

# constant InvestigationSchema

Investigation Schema Definition This file contains the main mongoose schema definition for investigations

View Source models/investigation/schema-definition.js, line 359

string

# InvestigationSectionType

Investigation List Section Type Enum Defines how investigations are grouped in the main list view

View Source types/investigation/enums.js, line 26

string

# InvestigationSortBy

Investigation Sort By Field Enum Defines which field to sort investigations by

View Source types/investigation/enums.js, line 52

string

# InvestigationStatus

Investigation Status Enum

View Source types/investigation/enums.js, line 11

# constant LESSON_SORT_FIELDS

MongoDB expressions for lesson-based group sorting (extends unit sorting)

View Source utils/investigation/mongo-aggregation.js, line 261

# LinkKey

Link key - logical destination / page type for the URL

View Source types/urls/enums.js, line 20

# constant MAX_UNIQUE_RETRIES

Max attempts to find a unique subLink before falling back to timestamp-based slug.

View Source types/urls/constants.js, line 10

# MONGO_URI

MongoDB connection URI - must be provided

View Source config/env.js, line 35

# constant Metadata

Metadata model exposing catalog metadata persistence APIs.

View Source models/Metadata.model.js, line 81

# constant MetadataSchema

Metadata schema describing investigation catalog entries.

View Source models/Metadata.model.js, line 6

string

# ModifyInvestigationIntents

AI Assistant's Modify InvestigationIntents Enum - For Assistant investigation modification

View Source types/intent/enums.js, line 22

# NODE_ENV

Node.js environment (development, production, test)

View Source config/env.js, line 30

# OBJECT_IMAGE_SIZE

Object Image Processing Configuration

View Source config/env.js, line 198

# OPENAI_API_KEY

OpenAI Key

View Source config/env.js, line 60

# OPENAI_MODEL

OpenAI LLM model

View Source config/env.js, line 75

# OPENAI_MODEL_TEMPERATURE

OpenAI LLM model temperature

View Source config/env.js, line 80

# constant ObjectIdParamSchema

Zod validation schemas for URL/link endpoints

View Source schemas/url.validation.js, line 7

# constant ObjectSchema

Object Schema - 3D object with position, rotation, size, view and components

View Source models/investigation/schema-definition.js, line 260

# PHYSICS_ENGINE_AMQP_PASSWORD

Physics service RabbitMQ password

View Source config/env.js, line 234

# PHYSICS_ENGINE_AMQP_PORT

Physics service RabbitMQ AMQP port

View Source config/env.js, line 224

# PHYSICS_ENGINE_AMQP_USER

Physics service RabbitMQ username

View Source config/env.js, line 229

# PHYSICS_ENGINE_COMMAND_QUEUE

RabbitMQ queue name for physics commands (request). Chrono must consume with prefetch(1) so only one command is processed at a time (waiting = queued, running = unacked).

View Source config/env.js, line 240

# PHYSICS_ENGINE_HEARTBEAT

RabbitMQ connection heartbeat in seconds. Keeps connection alive over unstable networks.

View Source config/env.js, line 260

# PHYSICS_ENGINE_HOST

Physics service (RabbitMQ) host

View Source config/env.js, line 219

# PHYSICS_ENGINE_REPLY_QUEUE

RabbitMQ queue name for physics command replies (RPC). Per-connection queues use this as prefix + connectionId.

View Source config/env.js, line 245

# PHYSICS_ENGINE_STATE_EXCHANGE

RabbitMQ topic exchange name for physics state broadcasts

View Source config/env.js, line 250

# PHYSICS_ENGINE_STATE_QUEUE

RabbitMQ queue name prefix for state broadcasts. Per-connection queue name is {prefix}_{connectionId}.

View Source config/env.js, line 255

# PHYSICS_GATEWAY_CLEANUP_DELAY_MS

Delay in ms before closing physics gateway (replies/state queues) after socket disconnect. Use 60000 (60s) or 300000 (300s) for stable reconnects on poor user internet.

View Source config/env.js, line 266

# PHYSICS_GATEWAY_RECONNECT_ATTEMPTS

Max reconnection attempts for physics gateway (connection/channel drops).

View Source config/env.js, line 271

# PHYSICS_GATEWAY_RECONNECT_DELAY_MS

Base delay in ms between reconnection attempts. Backoff may increase on repeated failures.

View Source config/env.js, line 276

# PORT

HTTP server port

View Source config/env.js, line 15

# constant Prompt

Prompt model providing access to reusable LLM prompt templates.

View Source models/Prompt.model.js, line 22

# constant PromptSchema

Prompt Schema

View Source models/Prompt.model.js, line 6

number

# ProtoUserRole

Proto UserRole enum values for gRPC communication with Auth Service

View Source types/auth/enums.js, line 17

# RATE_LIMIT_GENERAL_WINDOW_MS

Rate Limiting Configuration

View Source config/env.js, line 207

# REDIS_DB_INDEX

Redis database index

View Source config/env.js, line 45

# REDIS_URI

Redis connection URI - must be provided

View Source config/env.js, line 40

# REPLICATE_API_TOKEN

Replicate Key

View Source config/env.js, line 70

# SOCKET_PORT

Socket IO server port

View Source config/env.js, line 20

# constant SORT_FIELD_MAP

Map of sortBy enum values to MongoDB field paths

View Source utils/investigation/mongo-aggregation.js, line 10

# constant STATUS_DISPLAY_MAP

Map of status codes to human-readable display names

View Source utils/investigation/constants.js, line 14

# constant SUBJECT_ORDER

Subject sort order: Physics → Biology → Chemistry

View Source utils/investigation/constants.js, line 23

# constant SUBJECT_SORT_FIELDS

MongoDB expressions for subject-based group sorting. Order: Physics (1) → Biology (2) → Chemistry (3) → other (50) → N/A (99)

View Source utils/investigation/mongo-aggregation.js, line 98

Max length of an autogenerated subLink slug (from title).

View Source types/urls/constants.js, line 6

string

# SortOrder

Sort Order Enum Defines the sort direction

View Source types/investigation/enums.js, line 68

# constant StepSchema

Step Schema - Individual step in an investigation Each field is now wrapped with EditableFieldSchema for AI/human editing capabilities

View Source models/investigation/schema-definition.js, line 59

# TOGETHER_API_KEY

TogetherAI APR key (this is for future)

View Source config/env.js, line 65

# constant UNIT_IDENTIFIER_EXPR

Helper expression to extract unit identifier: " Unit 8.1: Title " → "8.1"

View Source utils/investigation/mongo-aggregation.js, line 155

# constant UNIT_SORT_FIELDS

MongoDB expressions for unit-based group sorting

View Source utils/investigation/mongo-aggregation.js, line 182

# constant URL_LOOKUP_STAGES

MongoDB aggregation stages for looking up URL data and computing views/completions

View Source utils/investigation/mongo-aggregation.js, line 25

# constant Url

URL model used to persist short links associated with investigations.

View Source models/urls/url.model.js, line 7

# constant UrlCountersSchema

URL Counters Schema - Mongoose schema for UrlCounters This is a subdocument schema with no _id

View Source models/urls/schema-definition.js, line 8

string

# UrlOrigin

URL Origin Enum - Indicates how the URL was created

View Source types/urls/enums.js, line 11

# constant UrlSchema

URL Schema Definition This file contains the main mongoose schema definition for URLs

View Source models/urls/schema-definition.js, line 25

string

# UserRole

User role enumeration - matches Auth Service definition Only admin and SME (Subject Matter Expert) roles are supported

View Source types/auth/enums.js, line 7

# constant UserSchema

Embedded schema representing a user entry in the chat history.

View Source models/Chat.model.js, line 8

# VAULT_API_VERSION

HashiCorp Vault API version

View Source config/env.js, line 182

# VAULT_KV_KEY

HashiCorp Vault KV key

View Source config/env.js, line 177

# VAULT_MOUNT_PATH

HashiCorp Vault secrets engine mount path

View Source config/env.js, line 172

# VAULT_ROLE_ID

HashiCorp Vault role ID for AppRole auth

View Source config/env.js, line 162

# VAULT_SECRET_ID

HashiCorp Vault secret ID for AppRole auth

View Source config/env.js, line 167

# VAULT_TOKEN

HashiCorp Vault authentication token

View Source config/env.js, line 157

# VAULT_URL

HashiCorp Vault Configuration

View Source config/env.js, line 152

# constant Vector3Schema

Vector3 validation schema

View Source schemas/investigation.validation.js, line 14

# WS_PORT

WebSocket server port (for Unity WebGL and other platforms)

View Source config/env.js, line 25

# constant apiKeyLimiter

Rate limiter for API key-based requests More lenient for authenticated API access

View Source config/rate-limit.js, line 41

# constant asyncHandler

Wraps an async function to catch any rejections and forward them to the next middleware. This allows you to use async/await in route handlers without manually wrapping them in try-catch blocks.

View Source utils/asyncHandler.js, line 28

Example
```typescript
// Instead of:
app.get('/users', async (req, res, next) => {
  try {
    const users = await userService.getUsers();
    res.json(users);
  } catch (error) {
    next(error);
  }
});

// You can do:
app.get('/users', asyncHandler(async (req, res) => {
  const users = await userService.getUsers();
  res.json(users);
}));
```

# constant authLimiter

Strict rate limiter for authentication endpoints Used to prevent brute-force attacks on login/auth endpoints

View Source config/rate-limit.js, line 24

# constant env

Parsed and validated environment variables.

View Source config/env.js, line 282

# constant envSchema

Environment variables schema and validation.

View Source config/env.js, line 10

# fetchAll

When true, fetches all matching investigations up to INVESTIGATIONS_FETCH_ALL_LIMIT. This is required for proper sectioning/grouping - without full data, sections would be incomplete and split across pages (e.g., "Grade 8" appearing on multiple pages with different items). When fetchAll is true, limit/offset are ignored.

View Source schemas/investigation.validation.js, line 252

# constant generalLimiter

General rate limiter for all API endpoints

View Source config/rate-limit.js, line 7

# constant mockInvestigations

Pre-defined mock investigation items for common test scenarios

View Source utils/__tests__/mocks/investigation.mocks.js, line 47

# constant mockPhysicsGatewayService

Mock the physics gateway service

View Source tests/unit/socket-physics-handler.test.js, line 8

# constant mongoOptions

MongoDB connection options used for the service-level connection pool.

View Source database/mongo.connection.js, line 8

# constant redisUtils

Convenience helpers for interacting with Redis commands.

View Source database/redis.client.js, line 136

# constant requireAuthenticated

Create middleware that requires authentication (admin or SME role)

View Source middlewares/auth.js, line 202

# constant router

REST endpoints that manage investigations.

View Source routes/investigation.routes.js, line 13

# constant router

Link routes (public resolve + protected investigation-scoped list/create).

  • GET/POST /investigation/:id require auth.
  • GET /:key/:subLink is public (resolve).

View Source routes/link.routes.js, line 13

# constant router

Swagger documentation routes

View Source routes/swagger.routes.js, line 8

# constant subjectsFactory

Maps subject codes to their corresponding full names.

View Source utils/subjectsFactory.js, line 5

# constant swaggerOptions

Swagger configuration for API documentation

View Source config/swagger.js, line 6

# constant uploadLimiter

Stricter rate limiter for file upload endpoints

View Source config/rate-limit.js, line 61

Methods

# addContradictionInPlace(investigation, contradiction) → {Partial.<IInvestigation>}

Adds a contradiction to a specific field in an investigation.

Parameters:
Name Type Description
investigation Partial.<IInvestigation>

The investigation object to update.

contradiction IContradictionInput

The details of the contradiction to add.

View Source services/investigation/contradictions.js, line 10

  • If the field is not found in the investigation.
Error
  • The investigation object with the updated contradiction.
Partial.<IInvestigation>

# assertNotInDevelopment(investigation, message) → {void}

Throws when investigation is in development state.

Parameters:
Name Type Description
investigation IInvestigation

Investigation to validate.

message string

Error message to throw.

View Source services/investigation/crud.js, line 234

No return value.

void

# batchFetchUserProfiles(userIds, grpcClient) → {Promise.<Map.<string, IUserProfile>>}

Batch fetch multiple user profiles efficiently using a single gRPC call. Uses Redis mget for batch cache lookup, then fetches missing profiles via batch gRPC.

Parameters:
Name Type Description
userIds Array.<string>

Array of user IDs to fetch.

grpcClient AuthGrpcService

The gRPC client used to fetch users.

View Source utils/user-profile.utils.js, line 131

Map of userId to profile.

Promise.<Map.<string, IUserProfile>>

# buildGroupSortFields(group) → {Array.<SectionSortAddFieldsStage>}

Builds MongoDB $addFields stages for group sorting

Parameters:
Name Type Description
group GroupType | null

The group type to build sort fields for

View Source utils/investigation/mongo-aggregation.js, line 332

Array of MongoDB $addFields stages

Array.<SectionSortAddFieldsStage>

# buildInvestigationQuery(searchDto) → {Object}

Builds MongoDB query from search filters

Parameters:
Name Type Description
searchDto IInvestigationSearchDto

The search and filter parameters

View Source services/investigation/listing.js, line 196

Query object and search metadata

Object

# buildInvestigationSnapshot(investigation) → {Record.<string, unknown>}

Builds a plain JSON snapshot of the investigation state for versioning.

Parameters:
Name Type Description
investigation IInvestigation

Investigation document to snapshot.

View Source services/investigation/versioning-helpers.js, line 221

Snapshot of the investigation without versioning metadata.

Record.<string, unknown>

# buildRelevanceScoreStage(escapedSearchTerm) → {object}

Builds MongoDB aggregation stage for relevance scoring with priorities Priority order: Title (highest) > Curriculum/Unit/Lesson/Grade > Objectives/Goals/AnalyticalFacts/NGSS > Day/Steps/Objects Exact matches score higher than partial matches

Parameters:
Name Type Description
escapedSearchTerm string

Escaped search term for regex matching

View Source services/investigation/listing.js, line 16

MongoDB $addFields stage with relevanceScore calculation

object

# buildSectionSortFields(section, currentUserIdopt, sortedAuthorIdsopt) → {Array.<SectionSortAddFieldsStage>}

Builds MongoDB $addFields stages for section sorting

Parameters:
Name Type Attributes Description
section SectionType | null

The section type to build sort fields for

currentUserId string <optional>

Optional current user ID for author sorting

sortedAuthorIds Array.<Types.ObjectId> <optional>

Optional pre-sorted author IDs

View Source utils/investigation/mongo-aggregation.js, line 351

Array of MongoDB $addFields stages

Array.<SectionSortAddFieldsStage>

# buildSortSpec(sortBy, sortOrder, hasSearch, section, hasSortedAuthorIds, group) → {Record.<string, number>}

Builds MongoDB sort specification with section/group-aware sorting

Parameters:
Name Type Description
sortBy InvestigationSortBy | undefined

The field to sort by

sortOrder SortOrder | undefined

The sort order (ASC or DESC)

hasSearch boolean

Whether a search term is present

section SectionType | null

Optional section type for section-aware sorting

hasSortedAuthorIds boolean

Whether pre-sorted author IDs are available

group GroupType | null

Optional group type for group-aware sorting

View Source utils/investigation/mongo-aggregation.js, line 429

MongoDB sort specification object

Record.<string, number>

# checkAndUnlockStaleLocks() → {Promise.<number>}

Check and unlock stale locks (investigations locked for more than 5 minutes).

View Source services/investigation/locks.js, line 91

Number of investigations unlocked.

Promise.<number>

# cloneInvestigation(investigationId, userIdopt) → {Promise.<IInvestigation>}

Clones the current investigation by adding a "copy_N" postfix to its identifier.

Parameters:
Name Type Attributes Description
investigationId string

The ID of the current investigation to clone.

userId string <optional>

The ID of the user cloning the investigation (will be set as the new author).

View Source services/investigation/clone.js, line 15

  • If an error occurs during the cloning process.
Error
  • The cloned investigation object.
Promise.<IInvestigation>

# closeDatabaseConnection() → {Promise.<void>}

Close the active MongoDB connection if one exists.

View Source database/mongo.connection.js, line 101

Resolves after the connection is terminated.

Promise.<void>

# closeDatabases() → {Promise.<void>}

Close database connections.

View Source database/index.js, line 31

Propagates shutdown errors.

unknown

Resolves when MongoDB and Redis connections are closed.

Promise.<void>

# closeRedisConnection() → {Promise.<void>}

Gracefully close the Redis connection if active.

View Source database/redis.client.js, line 95

Resolves when the connection quits.

Promise.<void>

# closeVault() → {void}

Closes the Vault service.

View Source vault/index.js, line 31

  • If the Vault service cannot be closed.
Error
  • Closes the Vault service.
void

# connectToDatabase() → {Promise.<void>}

Connect to MongoDB using the configured connection options.

View Source database/mongo.connection.js, line 32

Propagates connection errors once the retry budget is exhausted.

unknown

Resolves when the connection is established.

Promise.<void>

# connectToRedis() → {Promise.<Redis>}

Establish Redis connection for caching and pub/sub use cases.

View Source database/redis.client.js, line 12

Propagates connection errors/timeouts.

unknown

Resolves with a ready Redis client.

Promise.<Redis>

# convertEditableFieldToSimple(investigation) → {function}

Creates a helper function to extract a simplified version of an EditableField from an investigation object.

The returned function allows retrieving a specific field by name and converts it into a plain IEditableFieldSimple object, providing default values for missing properties.

Parameters:
Name Type Description
investigation IInvestigation

The investigation object containing EditableField properties.

View Source utils/step-conversion.utils.js, line 152

  • A function that accepts:
    • fieldName: The key of the field to extract.
    • defaultValue: The fallback value if the field's value is missing (default: ""). Returns IEditableFieldSimple or null if the field does not exist.
function

# convertInvestigationFromModel(investigation) → {ICreateInvestigationDto}

Converts an investigation from the database/model format to a simple DTO format suitable for API input or further processing.

Parameters:
Name Type Description
investigation IInvestigation

The investigation in the model format.

View Source helpers/investigation.js, line 9

The investigation converted to a simple ICreateInvestigationDto format.

ICreateInvestigationDto

# convertObjectsToInputFormat(objects, withCoordinates) → {Array.<object>}

Converts an array of IObjectBase objects with EditableField structures into a plain input format suitable for API requests or other processing.

Extracts the value from each editable field and provides default fallbacks:

  • Empty string for name and objectId
  • 0 for position and rotation coordinates
  • null for size if not defined
Parameters:
Name Type Description
objects Array.<IObjectBase>

Array of objects with EditableField properties.

withCoordinates boolean

If true, it converts with coordinates fields(position, rotation, size), otherwise converts without them.

View Source utils/step-conversion.utils.js, line 36

  • Array of plain objects with name, objectId, position, rotation, and size.
Array.<object>

# convertObjectsToSimple(objects) → {Array.<object>}

Convert database objects (IObject[]) to simple objects (ISimpleObject[]) for API response

Parameters:
Name Type Description
objects Array.<IObjectBase>

Database objects with EditableField structure

View Source utils/step-conversion.utils.js, line 73

  • Simple objects for API response with default values instead of null/undefined
Array.<object>

# convertObjectsToUpdateFormat(objects) → {Array.<IUpdateObjectDto>}

Converts an array of simple objects (from AI response or plain format) to IUpdateObjectDto format. This is the reverse of convertObjectsToInputFormat - it converts from simple format to update DTO format.

Parameters:
Name Type Description
objects Array.<ISimpleObject> | Array.<ISimpleResponseObject>

Array of simple objects with plain values.

View Source utils/step-conversion.utils.js, line 113

  • Array of objects in IUpdateObjectDto format suitable for update requests.
Array.<IUpdateObjectDto>

# convertStepsToSimple(steps) → {Array.<IStep>}

Convert database steps (IStep[]) to simple steps (ISimpleStep[]) for API response

Parameters:
Name Type Description
steps Array.<IInvestigationBaseStepModel>

Database steps with EditableField structure

View Source utils/step-conversion.utils.js, line 13

  • Simple steps for API response with empty strings instead of undefined
Array.<IStep>

# createAuthMiddleware(options) → {function}

Create authentication middleware for Express routes

Parameters:
Name Type Description
options IAuthMiddlewareOptions

Configuration options for the middleware

View Source middlewares/auth.js, line 25

Express middleware function

function

# createEmptyEditableField(defaultValue) → {IEditableFieldResponse.<T>}

Creates an empty editable field response with default value

Parameters:
Name Type Description
defaultValue T

The default value to use for the empty field

View Source types/investigation/dto.utils.js, line 30

Empty editable field response with the default value

IEditableFieldResponse.<T>

# createInvestigation(createDto) → {Promise.<IInvestigation>}

Creates a new investigation.

Parameters:
Name Type Description
createDto ICreateInvestigationDto

The data required to create the investigation.

View Source services/investigation/crud.js, line 13

  • The created investigation.
Promise.<IInvestigation>

Create a new link for an investigation. If subLink is provided: validate uniqueness and set origin HUMAN. If subLink is omitted: autogenerate from investigation title (or random), set origin AUTO.

Parameters:
Name Type Attributes Description
investigationId Types.ObjectId

Investigation to attach the link to

options object

Link options

key string

Link key (e.g. "physical-tool")

subLink string <optional>

Custom slug; if omitted, one is generated

description string <optional>

Optional description

createdBy Types.ObjectId | null

User ID who created the link (or null)

View Source services/url.service.js, line 53

404 if investigation not found

ApiError

409 if subLink is provided and already exists for this key

ApiError

The saved URL document

Promise.<IUrl>

# createMockInvestigationItem(overrides) → {IInvestigationListItemDto}

Creates a mock investigation list item with default or overridden values

Parameters:
Name Type Description
overrides Partial.<IInvestigationListItemDto>

Properties to override defaults

View Source utils/__tests__/mocks/investigation.mocks.js, line 7

Mock investigation item

IInvestigationListItemDto

# createMockSearchDto(overrides) → {IInvestigationSearchDto}

Creates a mock search DTO with default or overridden values

Parameters:
Name Type Description
overrides Partial.<IInvestigationSearchDto>

Properties to override defaults

View Source utils/__tests__/mocks/investigation.mocks.js, line 37

Mock search DTO

IInvestigationSearchDto

# createRangeValidation(fromField, toField) → {function}

Helper function to create a range validation refine Validates that a "from" field is less than or equal to a "to" field

Parameters:
Name Type Description
fromField string

Name of the "from" field

toField string

Name of the "to" field

View Source schemas/investigation.validation.js, line 223

Zod refine function that validates the range

function

# createSampleInvestigation() → {IInvestigation}

Create a sample investigation based on the Galileo Cloud interface

View Source scripts/seed-investigation.js, line 20

The sample investigation

IInvestigation

# createVersionEntry(investigation, updatedBy, isAiGeneratedopt) → {IInvestigationVersionEntryModel}

Creates a new version entry from the current investigation state.

Parameters:
Name Type Attributes Description
investigation IInvestigation

Investigation document to version.

updatedBy Types.ObjectId | null

User id who made the change (null when not available).

isAiGenerated boolean <optional>

Whether the versioned state was AI-generated (defaults to false).

View Source services/investigation/versioning-helpers.js, line 247

Version entry containing snapshot and metadata.

IInvestigationVersionEntryModel

# createWebSocketServer(httpServer) → {WebSocketServer}

Create a general-purpose WebSocket server for Unity WebGL and other platforms

Parameters:
Name Type Description
httpServer HTTPServer

HTTP server instance to attach WebSocket server to

View Source socket/websocket-server.js, line 9

WebSocketServer instance

WebSocketServer

# deleteInvestigationById(investigationId) → {Promise.<IDeleteInvestigationByIdResponse>}

Permanently deletes an investigation and its related chat history.

Parameters:
Name Type Description
investigationId string

The ID of the investigation to delete.

View Source services/investigation/delete.js, line 53

  • If an error occurs during the deletion process.
Error
  • An object summarizing the deletion status of the investigation and related chats.
Promise.<IDeleteInvestigationByIdResponse>

# deleteInvestigationData(investigation) → {IInvestigation}

Deletes the data of a given investigation.

Parameters:
Name Type Description
investigation IInvestigation

The investigation to clear.

View Source services/investigation/delete.js, line 13

  • If an error occurs during the deletion process.
Error
  • The investigation object with its values emptied.
IInvestigation

# emitInvestigationUpdated(investigationId, payload)

Emit an "investigation:updated" event to all subscribers of the given investigation room.

Parameters:
Name Type Description
investigationId string

Investigation identifier used as room name.

payload object

Arbitrary payload to send with the event.

updatedBy string | null

The ID of the user who updated the investigation.

updatedAt string | null

The date and time the investigation was updated.

updatedFields unknown

The fields that were updated.

View Source utils/socket-events.js, line 28

# enrichInvestigationResponse(investigation, dto, grpcClient) → {Promise.<void>}

Enriches an investigation response DTO with detailed author and editor profile information.

Fetches user profiles from the Auth gRPC service using batch fetch and populates the metadata.author and metadata.editorsDetailed fields with user details such as name, email, and avatar.

Parameters:
Name Type Description
investigation IInvestigation

The investigation object containing metadata.

dto IInvestigationResponseDto

The investigation response DTO to enrich.

grpcClient AuthGrpcService

The Auth gRPC client used to fetch user profiles.

View Source utils/investigation-response.utils.js, line 14

  • Enriches the dto object in-place.
Promise.<void>

# async enrichItemsWithProfiles(items, grpcClientopt) → {Promise.<Array.<IInvestigationListItemDto>>}

Enriches investigation list items with author profile information.

Parameters:
Name Type Attributes Description
items Array.<IInvestigationListItemDto>

The investigation items to enrich.

grpcClient AuthGrpcService <optional>

Optional gRPC client for fetching user profiles.

View Source services/investigation/listing.js, line 306

  • Items enriched with author profiles.
Promise.<Array.<IInvestigationListItemDto>>

# enrichUserItems(items, grpcClient) → {Promise.<IUserProfile>}

Enriches items that have an id field with user profile information (name, email, avatar). Commonly used for enriching authors/editors lists in filter metadata.

Parameters:
Name Type Description
items Array

Array of items with id, name, email, optional avatar fields

grpcClient AuthGrpcService | undefined

gRPC client for fetching profiles (if undefined, returns items unchanged)

View Source utils/user-profile.utils.js, line 15

Promise resolving to items with populated name, email, and avatar fields

Promise.<IUserProfile>

# ensureInvestigationAuthor(investigationId, authorId) → {Promise.<(IInvestigation|null)>}

Ensures that the author of a given investigation is set.

If the investigation exists and does not already have a valid author, this method sets the author to the provided authorId and updates the dateModified field.

Parameters:
Name Type Description
investigationId string

The ID of the investigation to check.

authorId Types.ObjectId

The ObjectId of the author to set.

View Source services/investigation/author.js, line 15

If there is an error during the process of fetching or saving the investigation.

Error
  • The updated investigation object, or null if the investigation does not exist or already has a valid author.
Promise.<(IInvestigation|null)>

# errorHandler(error, req, res, _next) → {void}

Error Handler Middleware

Parameters:
Name Type Description
error IApiError

The error object

req Request

The request object

res Response

The response object

_next NextFunction

The next function

View Source middlewares/errorHandler.js, line 12

void

Check if a (key, subLink) pair already exists in the URLs collection.

Parameters:
Name Type Description
key string

Link key (e.g. "physical-tool")

subLink string

Slug (normalized to lowercase)

View Source services/url.service.js, line 34

True if a URL document exists with this key and subLink

Promise.<boolean>

# fetchUserProfile(userId, profileCache, grpcClient) → {Promise.<IUserProfile>}

Fetches a user profile using a multi-layered caching strategy.

Parameters:
Name Type Description
userId string

The ID of the user whose profile is being fetched.

profileCache Map.<string, (IUserProfile|Promise.<IUserProfile>)> | undefined

Optional memoization cache to prevent duplicate fetches.

grpcClient AuthGrpcService

The gRPC client used to fetch the user if cache misses.

View Source utils/user-profile.utils.js, line 54

The resolved user profile with name, avatar, and email fields (nullable if unavailable).

Promise.<IUserProfile>

# formatHistory(chatHistory) → {Array.<IFormattedHistory>}

Formats chat history into the OpenAI message format for LLM requests.

Parameters:
Name Type Description
chatHistory Array.<IChatHistory>

Chat exchanges between the user and assistant.

View Source helpers/history.js, line 7

Array of formatted messages ready for LLM consumption.

Array.<IFormattedHistory>

# fromEditableField(field, defaultValue, historyLimit) → {IEditableFieldResponse.<T>}

Convert editable field to response DTO format

Parameters:
Name Type Description
field IEditableField.<T> | null | undefined

The editable field to convert

defaultValue T

The default value to use if the field is null or undefined

historyLimit number

Maximum number of history entries to return

View Source types/investigation/dto.utils.js, line 48

The formatted editable field response

IEditableFieldResponse.<T>

# generateInvestigation(aiProcessor, message, history, investigationMetadata) → {Promise.<(IAssistantInvestigationFormat|null)>}

Generates an entire investigation based on the provided metadata. If the investigation is not found, it throws an error.

Parameters:
Name Type Description
aiProcessor AIProcessor

AI processor instance.

message string

The user's message from which the lesson must be detected.

history FormattedHistory

The chat history between the user and the assistant.

investigationMetadata IMetadataDocument

The metadata of the investigation.

View Source services/investigation/ai-generate.js, line 186

  • If the investigation is not found.
Error
  • The generated investigation.
Promise.<(IAssistantInvestigationFormat|null)>

# generateInvestigationObjects(aiProcessor, message, history, investigationMetadata, investigation) → {Promise.<(IAssistantInvestigationFormat|null)>}

Generates objects of investigation based on the provided metadata and plain investigation. If the objects are not found, it throws an error.

Parameters:
Name Type Description
aiProcessor AIProcessor

AI processor instance.

message string

The user's message from which the lesson must be detected.

history string

The chat history between the user and the assistant.

investigationMetadata string

The metadata of the investigation.

investigation string

The plain investigation without steps and objects with yaml format.

View Source services/investigation/ai-generate.js, line 85

  • If the objects are not found.
Error
  • The generated objects of the provided investigation.
Promise.<(IAssistantInvestigationFormat|null)>

# generateInvestigationSteps(aiProcessor, message, history, investigationMetadata, investigation) → {Promise.<(IAssistantInvestigationFormat|null)>}

Generates steps of investigation based on the provided metadata and the provided investigation. If the steps are not found, it throws an error.

Parameters:
Name Type Description
aiProcessor AIProcessor

AI processor instance.

message string

The user's message from which the lesson must be detected.

history string

The chat history between the user and the assistant.

investigationMetadata string

The metadata of the investigation.

investigation string

The provided investigation without steps with yaml format.

View Source services/investigation/ai-generate.js, line 136

  • If the steps are not found.
Error
  • The generated steps of the provided investigation.
Promise.<(IAssistantInvestigationFormat|null)>

# generateInvestigationWithoutStepsAndObjects(aiProcessor, message, history, investigationMetadata) → {Promise.<(IAssistantInvestigationFormat|null)>}

Generates an investigation without steps and objects based on the provided metadata. If the investigation is not found, it throws an error.

Parameters:
Name Type Description
aiProcessor AIProcessor

AI processor instance.

message string

The user's message from which the lesson must be detected.

history string

The chat history between the user and the assistant.

investigationMetadata string

The metadata of the investigation.

View Source services/investigation/ai-generate.js, line 16

  • If the investigation is not found.
Error
  • The generated investigation without steps and objects.
Promise.<(IAssistantInvestigationFormat|null)>

# getDatabaseStatus() → {object}

Snapshot of the current MongoDB connection state.

View Source database/mongo.connection.js, line 124

Connection metadata.

object

# getDefaultSortOrder(sortBy) → {SortOrder}

Determines the default sort order based on the sort field

Parameters:
Name Type Description
sortBy InvestigationSortBy | undefined

The field to sort by

View Source utils/investigation/mongo-aggregation.js, line 313

The default sort order for the field

SortOrder

# getFieldHistory(investigationId, fieldPath, limit) → {Promise.<{fieldPath: string, history: Array.<unknown>, totalCount: number}>}

Gets the history for a specific field in an investigation.

Parameters:
Name Type Description
investigationId string

The ID of the investigation.

fieldPath string

The path to the field (e.g., "title", "steps.0.title", "objects.0.name").

limit number

Maximum number of history entries to return (default: 50).

View Source services/investigation/versions.js, line 15

If the investigation is not found.

Error

The field history.

Promise.<{fieldPath: string, history: Array.<unknown>, totalCount: number}>

# getFieldOrEmpty(shouldBeEmpty, field, defaultValue, historyLimit) → {IEditableFieldResponse.<T>}

Returns either an empty field or converts from editable field based on condition

Parameters:
Name Type Description
shouldBeEmpty boolean

Whether to return an empty field

field IEditableField.<T> | null | undefined

The editable field to convert if not empty

defaultValue T

The default value to use

historyLimit number

Maximum number of history entries to return

View Source types/investigation/dto.utils.js, line 67

Empty or populated editable field response

IEditableFieldResponse.<T>

# getFilterMetadata() → {Promise.<IInvestigationFilterMetadataDto>}

Retrieves filter metadata for investigations list. Returns available filter options with counts for status, curriculum, grade, authors, and editors. Uses MongoDB $facet aggregation to compute all counts in a single query.

View Source services/investigation/listing.js, line 519

  • Filter metadata with counts for each dimension.
Promise.<IInvestigationFilterMetadataDto>

# getInvestigationById(investigationId) → {Promise.<IInvestigation>}

Retrieves a single investigation by its ID.

Parameters:
Name Type Description
investigationId string

The ID of the investigation to retrieve.

View Source services/investigation/crud.js, line 40

If the investigation is not found.

Error
  • The investigation data.
Promise.<IInvestigation>

# getInvestigationVersions(investigationId, limit) → {Promise.<IInvestigationVersionListResponse>}

Gets the versions of an investigation.

Parameters:
Name Type Description
investigationId string

The ID of the investigation.

limit number

The number of versions to return (default: 20).

View Source services/investigation/versions.js, line 65

If the investigation is not found.

Error
  • The investigation versions.
Promise.<IInvestigationVersionListResponse>

# getInvestigations(searchDto, grpcClientopt) → {Promise.<IInvestigationListResponseDto>}

Retrieves investigations with filtering, sorting, and grouping.

Parameters:
Name Type Attributes Description
searchDto IInvestigationSearchDto

The search and pagination parameters.

grpcClient AuthGrpcService <optional>

Optional gRPC client for enriching user profiles.

View Source services/investigation/listing.js, line 326

  • The investigations with sections/items.
Promise.<IInvestigationListResponseDto>

# getLessonData(unit, hasInvestigation) → {Promise.<string>}

Retrieves lesson metadata for a given unit and formats it as a string.

Can optionally filter lessons based on whether they have an associated investigation. The returned string includes the unit name and a list of lessons with their numbers, titles, and optionally whether they have an investigation.

Parameters:
Name Type Description
unit string

The unit identifier to fetch lessons for.

hasInvestigation boolean | null

Optional filter to only include lessons that do (true) or do not (false) have an investigation. If null, includes all lessons and shows their investigation status.

View Source utils/lessonsFactory.js, line 13

  • A formatted string containing the unit and lesson information.
Promise.<string>

# getLinksByInvestigationId(investigationId) → {Promise.<Array.<IUrl>>}

List all links for an investigation, sorted by creation date.

Parameters:
Name Type Description
investigationId Types.ObjectId

Investigation ID

View Source services/url.service.js, line 111

Array of URL documents (plain objects from lean())

Promise.<Array.<IUrl>>

# getLogger() → {Logger}

Get the logger from the async local storage context

View Source utils/asyncLocalStorage.js, line 8

Logger instance with request ID, or base logger if no context

Logger

# getRandomMetadata() → {Promise.<(IMetadataDocument|null)>}

Retrieves a random metadata entry for investigation generation.

View Source utils/lessonsFactory.js, line 82

  • A random metadata document or null if none found.
Promise.<(IMetadataDocument|null)>

# getRedisStatus() → {object}

Snapshot of the Redis client status.

View Source database/redis.client.js, line 126

High-level connection flags.

object

# getRequestId() → {string|undefined}

Get the request ID from the async local storage context

View Source utils/asyncLocalStorage.js, line 19

Request ID string or undefined if not in context

string | undefined

# getSocketServer() → {SocketIOServer|null}

Get the currently registered Socket.IO server instance, if any.

View Source utils/socket-events.js, line 17

Socket.IO server instance or null.

SocketIOServer | null

# getUnitNames() → {Promise.<string>}

Retrieves all unique units with their names and descriptions, grouped by grade. Formats the output similar to the detect_unit_from_message prompt format.

View Source utils/lessonsFactory.js, line 43

  • A formatted string containing all units grouped by grade.
Promise.<string>

# handleWebSocketConnection(ws, request)

Handle new WebSocket connections

Parameters:
Name Type Description
ws WebSocket

WebSocket instance

request IncomingMessage

HTTP request

View Source socket/websocket-handlers.js, line 11

# hasArrayValue(value) → {boolean}

Type-safe version of hasValue for arrays

Parameters:
Name Type Description
value Array.<unknown> | undefined | null

The value to check

View Source utils/hasValue.js, line 31

  • true if the value is not null and is an array
boolean

# hasNumberValue(value) → {boolean}

Type-safe version of hasValue for numbers

Parameters:
Name Type Description
value number | undefined | null

The value to check

View Source utils/hasValue.js, line 22

  • true if the value is not null
boolean

# hasStringValue(value) → {boolean}

Type-safe version of hasValue for strings

Parameters:
Name Type Description
value string | undefined | null

The value to check

View Source utils/hasValue.js, line 13

  • true if the value is not null, undefined, or empty string
boolean

# initializeDatabases() → {Promise.<void>}

Initialize database connections.

View Source database/index.js, line 10

Propagates connection errors.

unknown

Resolves when MongoDB and Redis are ready.

Promise.<void>

# initializeVault() → {Promise.<void>}

Initializes the Vault service and loads secrets from Vault.

View Source vault/index.js, line 9

  • Promise that resolves when the Vault service is initialized and secrets are loaded.
Promise.<void>

# lockInvestigation(investigationId, userId) → {Promise.<IInvestigation>}

Lock an investigation for editing by a specific user.

Parameters:
Name Type Description
investigationId string

The investigation ID to lock.

userId string

The user ID who is locking the investigation.

View Source services/investigation/locks.js, line 39

The updated investigation.

Promise.<IInvestigation>

# mapHistoryEntries(history, limit) → {Array.<IFieldHistoryEntryResponse>|undefined}

Maps history entries to response format

Parameters:
Name Type Description
history Array.<IHistoryEntry.<T>> | undefined

Array of history entries to map

limit number

Maximum number of history entries to return

View Source types/investigation/dto.utils.js, line 15

Mapped history entries or undefined if no history

Array.<IFieldHistoryEntryResponse> | undefined

# mapVector3History(vector, limit) → {IVector3HistoryResponse|undefined}

Maps Vector3 history (x, y, z) to response format

Parameters:
Name Type Description
vector IVector3Editable | undefined

Vector3 object with x, y, z editable fields

limit number

Maximum number of history entries per axis

View Source types/investigation/dto.utils.js, line 78

Object with x, y, z history arrays or undefined if no vector

IVector3HistoryResponse | undefined

# notFoundHandler(req, res) → {void}

Not Found Handler Middleware

Parameters:
Name Type Description
req Request

The request object

res Response

The response object

View Source middlewares/errorHandler.js, line 39

void

# optionalAuth(options) → {function}

Create optional authentication middleware

Parameters:
Name Type Description
options IAuthMiddlewareOptions

Configuration options for the middleware

View Source middlewares/auth.js, line 211

Express middleware function that optionally authenticates

function

# parseQueryStringArray(val) → {Array.<T>|undefined}

Parses a query parameter value into an array of specified type Handles both comma-separated strings and array inputs

Parameters:
Name Type Description
val unknown

The query parameter value to parse

View Source utils/query.utils.js, line 24

Parsed array or undefined if value is falsy

Array.<T> | undefined
Examples
// Comma-separated string
parseQueryStringArray<string>("foo,bar,baz") // ["foo", "bar", "baz"]
// Array input
parseQueryStringArray<string>(["foo", "bar"]) // ["foo", "bar"]
// Single value
parseQueryStringArray<string>("foo") // ["foo"]
// Empty/undefined
parseQueryStringArray<string>(undefined) // undefined

# prepareSnapshotForRestore(snapshot) → {Record.<string, unknown>}

Removes document metadata from a snapshot payload before restore.

Parameters:
Name Type Description
snapshot Record.<string, unknown>

Snapshot data as stored in versions.

View Source services/investigation/versioning-helpers.js, line 265

Snapshot payload without Mongo/Mongoose metadata fields.

Record.<string, unknown>

# randomSuffix() → {string}

Generate a short random subLink suffix (URL-safe).

View Source services/url.service.js, line 25

Lowercase URL-safe string (up to 8 chars)

string

# redoInvestigation(investigationId) → {Promise.<IInvestigation>}

Redo investigation - increment currentVersionIndex and return investigation at that version

Parameters:
Name Type Description
investigationId string

The ID of the investigation.

View Source services/investigation/versions.js, line 151

If the investigation is not found or if the index is out of bounds.

Error
  • The investigation at the new index.
Promise.<IInvestigation>

# regenerateOtherFields(aiProcessor, investigationId, fieldName, updatedBy, historyopt) → {Promise.<IInvestigation>}

Regenerates other fields in an investigation based on a specific field. This operation uses a 3-step process: text fields → objects → steps.

Parameters:
Name Type Attributes Description
aiProcessor AIProcessor

AI processor instance.

investigationId string

The ID of the investigation to update.

fieldName string

The name of the field to base regeneration on (e.g., "title", "curriculum", "objectives").

updatedBy Types.ObjectId | null

The user making the change (optional).

history string <optional>

Chat history in YAML format (optional, defaults to "-").

View Source services/investigation/ai-regenerate.js, line 320

If the investigation is not found or the field is invalid.

Error
  • The updated investigation.
Promise.<IInvestigation>

# regenerateOtherFieldsObjects(aiProcessor, fieldName, fieldValue, investigation, investigationMetadata, historyopt, contradictionInfoopt) → {Promise.<(IAssistantInvestigationFormat|null)>}

Regenerates objects based on regenerated text fields. This is Step 2 of the 3-step regeneration process.

Parameters:
Name Type Attributes Description
aiProcessor AIProcessor

AI processor instance.

fieldName string

The name of the field to base regeneration on.

fieldValue string

The value of the field to base regeneration on.

investigation string

The regenerated investigation from Step 1 (YAML format).

investigationMetadata string

The metadata/guide in YAML format.

history string <optional>

Chat history in YAML format (optional, defaults to "-").

contradictionInfo object <optional>

Optional contradiction information.

contradictionReason string | null <optional>

Reason for contradiction.

targetFieldName string | null <optional>

Target field name for contradiction.

isContradicting boolean <optional>

Whether the field is contradicting.

View Source services/investigation/ai-regenerate.js, line 129

If the prompt is not found or regeneration fails.

Error
  • The regenerated objects only.
Promise.<(IAssistantInvestigationFormat|null)>

# regenerateOtherFieldsSteps(aiProcessor, fieldName, fieldValue, investigation, investigationMetadata, historyopt, contradictionInfoopt) → {Promise.<(IAssistantInvestigationFormat|null)>}

Regenerates steps based on regenerated text fields and objects. This is Step 3 of the 3-step regeneration process.

Parameters:
Name Type Attributes Description
aiProcessor AIProcessor

AI processor instance.

fieldName string

The name of the field to base regeneration on.

fieldValue string

The value of the field to base regeneration on.

investigation string

The regenerated investigation from Step 1 + Step 2 (YAML format).

investigationMetadata string

The metadata/guide in YAML format.

history string <optional>

Chat history in YAML format (optional, defaults to "-").

contradictionInfo object <optional>

Optional contradiction information.

contradictionReason string | null <optional>

Reason for contradiction.

targetFieldName string | null <optional>

Target field name for contradiction.

isContradicting boolean <optional>

Whether the field is contradicting.

View Source services/investigation/ai-regenerate.js, line 227

If the prompt is not found or regeneration fails.

Error
  • The regenerated steps only.
Promise.<(IAssistantInvestigationFormat|null)>

# regenerateOtherFieldsWithoutStepsAndObjects(aiProcessor, fieldName, fieldValue, investigation, investigationMetadata, historyopt, contradictionInfoopt) → {Promise.<(IAssistantInvestigationFormat|null)>}

Regenerates text fields (without steps and objects) based on a specific field value. This is Step 1 of the 3-step regeneration process.

Parameters:
Name Type Attributes Description
aiProcessor AIProcessor

AI processor instance.

fieldName string

The name of the field to base regeneration on.

fieldValue string

The value of the field to base regeneration on.

investigation string

The current investigation in YAML format.

investigationMetadata string

The metadata/guide in YAML format.

history string <optional>

Chat history in YAML format (optional, defaults to "-").

contradictionInfo object <optional>

Optional contradiction information.

contradictionReason string | null <optional>

Reason for contradiction.

targetFieldName string | null <optional>

Target field name for contradiction.

isContradicting boolean <optional>

Whether the field is contradicting.

View Source services/investigation/ai-regenerate.js, line 27

If the prompt is not found or regeneration fails.

Error
  • The regenerated text fields only.
Promise.<(IAssistantInvestigationFormat|null)>

# registerInvestigationCollaborationHandlers(io, socket, context)

Register real-time collaboration (presence + action tracking) handlers for a specific investigation on a given socket connection.

Parameters:
Name Type Description
io SocketIOServer

Socket.IO server instance.

socket Socket

Connected client socket.

context ICollaborationContext

Connection and user metadata.

View Source socket/investigation-collaboration.js, line 13

# removeAiGeneratedValues(obj)

Recursively sets all aiGeneratedValue fields to null.

This method is schema-agnostic and works regardless of changes to the investigation structure.

Parameters:
Name Type Description
obj Record.<string, unknown>

The object whose aiGeneratedValue fields should be cleared.

View Source services/investigation/versioning-helpers.js, line 9

# removeInvestigationObjectCoordinates(investigation) → {IInvestigationWithoutObjectsCoordinatesDto}

Removes the current investigation objects' coordinates

Parameters:
Name Type Description
investigation IInvestigation

The investigation in the model format.

View Source helpers/investigation.js, line 31

The investigation converted to a simple ICreateInvestigationDto format.

IInvestigationWithoutObjectsCoordinatesDto

# requestIdMiddleware(req, res, next)

Middleware to add request ID tracking to each request

Parameters:
Name Type Description
req Request

Express request object

res Response

Express response object

next NextFunction

Express next function

View Source middlewares/requestId.js, line 10

# requireAdmin(options) → {function}

Create middleware that requires admin role

Parameters:
Name Type Description
options Omit.<IAuthMiddlewareOptions, "requiredRoles">

Configuration options (excluding requiredRoles)

View Source middlewares/auth.js, line 190

Express middleware function that only allows admin users

function

# resolveAndIncrementVisit(key, subLink) → {Promise.<IResolveLinkResult>}

Resolve a link by (key, subLink): increment visit count and return investigation id.

Parameters:
Name Type Description
key string

Link key (e.g. "physical-tool")

subLink string

Slug identifying the link

View Source services/url.service.js, line 122

404 if no URL document exists for this key and subLink

ApiError

Resolve result with investigationId, linkId, and counters

Promise.<IResolveLinkResult>

# restoreInvestigationFromSnapshot(investigation, snapshot) → {IInvestigation}

Restores an investigation from a snapshot

Parameters:
Name Type Description
investigation IInvestigation

The investigation document to restore

snapshot IInvestigationSnapshot

The snapshot data to apply

View Source services/investigation/versioning-helpers.js, line 42

  • The investigation with snapshot data applied
IInvestigation

# saveFieldHistory(investigation, updateFields, updatedBy) → {Record.<string, {historyEntry: *, fieldPath: string}>}

Computes history updates for an investigation update payload.

Parameters:
Name Type Description
investigation IInvestigation

Current investigation document (used as the source of "old" values).

updateFields MongoUpdateFields

Flat update payload (typically produced by the builder) to compare against current values.

updatedBy Types.ObjectId | null

User id who made the change (null when not available).

View Source services/investigation/versioning-helpers.js, line 121

History entries keyed by base field path.

Record.<string, {historyEntry: *, fieldPath: string}>

# async seedInvestigation() → {Promise.<void>}

Main seed function

View Source scripts/seed-investigation.js, line 563

A promise that resolves when the seed script is completed

Promise.<void>

# setSocketServer(io)

Attach a Socket.IO server instance so that other modules (e.g. controllers) can emit real-time events without tight coupling to the HTTP bootstrap code.

This should be called once during application startup from the place where the Socket.IO server is created.

Parameters:
Name Type Description
io SocketIOServer

Socket.IO server instance.

View Source utils/socket-events.js, line 10

# setupConnectionEventListeners()

Register listeners for Mongo connection lifecycle events.

View Source database/mongo.connection.js, line 74

# setupPhysicsHandlers(client, optionsopt)

Setup physics handlers for a WebSocket client

Parameters:
Name Type Attributes Description
client WebSocketClient

WebSocket client

options IPhysicsHandlerOptions <optional>

Optional overrides (e.g. physics host for dev-stage)

View Source socket/handlers/physics.js, line 10

# setupRedisEventListeners(client)

Internal helper that wires Redis connection lifecycle logging.

Parameters:
Name Type Description
client Redis

Connected Redis instance.

View Source database/redis.client.js, line 35

# slugify(text) → {string}

Slugify a string for use as subLink: lowercase, alphanumeric + . _ -

Parameters:
Name Type Description
text string

Raw string (e.g. investigation title)

View Source services/url.service.js, line 13

Slug suitable for subLink (max SUBLINK_MAX_LENGTH chars)

string

# stripMarkdown(text) → {string}

Strips markdown formatting from text while preserving HTML/XML tags. Used to clean AI assistant responses before displaying to users.

Parameters:
Name Type Description
text string

The text containing markdown formatting

View Source utils/markdown.utils.js, line 7

The text with markdown formatting removed

string

# toInvestigationResponseDto(investigation) → {IInvestigationResponseDto}

Convert Investigation database model to Response DTO

Parameters:
Name Type Description
investigation IInvestigation

The investigation document from the database

View Source types/investigation/dto.js, line 8

  • The formatted response DTO
IInvestigationResponseDto

# toUrlResponseDto(doc) → {IUrlResponseDto}

Map a URL document (or lean plain object) to the response DTO shape.

Parameters:
Name Type Description
doc IUrl

URL document or lean result

View Source services/url.service.js, line 144

DTO with string ids and flattened counters

IUrlResponseDto

# toggleInvestigationDevelopment(investigationId) → {Promise.<IInvestigation>}

Sends/return investigation to/from InDevelopment.

Parameters:
Name Type Description
investigationId string

The ID of the investigation.

View Source services/investigation/locks.js, line 12

If the investigation is not found.

Error
  • The modified investigation.
Promise.<IInvestigation>

# trimEditableField(field)

Helper function to trim string fields in an editable field object

Parameters:
Name Type Description
field Record.<string, unknown> | null | undefined

Editable field object

View Source models/investigation/schema-definition.js, line 455

# trimIfString(value) → {unknown}

Helper function to trim a string value if it exists

Parameters:
Name Type Description
value unknown

Value to trim

View Source models/investigation/schema-definition.js, line 445

Trimmed value or original value if not a string

unknown

# trimUpdateObject(obj)

Helper function to recursively trim string values in an update object Handles $set operations and nested editable field structures

Parameters:
Name Type Description
obj Record.<string, unknown>

Object to process

View Source models/investigation/schema-definition.js, line 524

# undoInvestigation(investigationId) → {Promise.<IInvestigation>}

Undo investigation - decrement currentVersionIndex and return investigation at that version

Parameters:
Name Type Description
investigationId string

The ID of the investigation.

View Source services/investigation/versions.js, line 99

If the investigation is not found or if the index is out of bounds.

Error
  • The investigation at the new index.
Promise.<IInvestigation>

# unlockInvestigation(investigationId, userId) → {Promise.<IInvestigation>}

Unlock an investigation. Only the user who locked it can unlock it.

Parameters:
Name Type Description
investigationId string

The investigation ID to unlock.

userId string

The user ID attempting to unlock (must be the lock owner).

View Source services/investigation/locks.js, line 64

The updated investigation.

Promise.<IInvestigation>

# updateInvestigation(investigationId, updateData, obj) → {Promise.<IUpdateInvestigationResponse>}

Updates an investigation using the new API format.

Parameters:
Name Type Description
investigationId string

The ID of the investigation to update.

updateData IUpdateInvestigationDto

The update data in the new format, including string/number fields and step updates.

obj object

Optional object used to determine if the update data should be built from scratch.

needsBuildUpdate boolean

Whether the update data should be built from scratch.

updatedBy Types.ObjectId | null

The user making the change (optional).

isAiGenerated boolean

Whether this update is AI-generated (default: false).

skipVersioning boolean

Whether to skip versioning (default: false).

View Source services/investigation/crud.js, line 107

If the investigation is not found or is locked.

Error
  • The result of the update operation.
Promise.<IUpdateInvestigationResponse>

# updateInvestigationByVersion(oldInvestigation, investigation, userId, isUserChangeExist) → {Promise.<IInvestigation>}

Updates investigation by adding new version.

Parameters:
Name Type Description
oldInvestigation IInvestigation

The latest investigation version.

investigation IInvestigation

The entire investigation model.

userId ObjectId | null

The ID of the user.

isUserChangeExist boolean

Whether the change was made by the user (true) or AI (false). Defaults to false.

View Source services/investigation/versions.js, line 204

  • If an error occurs during the update process.
Error
  • An investigation updated with new version.
Promise.<IInvestigation>

# validateRequest(schema) → {function}

Middleware factory for request validation

Parameters:
Name Type Description
schema object

The schema to validate the request

body ZodSchema.<unknown>

The schema to validate the request body

query ZodSchema.<unknown>

The schema to validate the request query

params ZodSchema.<Record.<string, string>>

The schema to validate the request parameters

View Source middlewares/validateRequest.js, line 16

Express middleware function

function