Skip to content

Updated Complete Code for first prodution frontend Connection - #20

Merged
azeemstack merged 1 commit into
mainfrom
API-LogicBuilding
Apr 14, 2026
Merged

azeemstack merged 1 commit into
mainfrom
API-LogicBuilding

Conversation

@azeemstack

@azeemstack azeemstack commented Apr 14, 2026 •

Copy link
Copy Markdown
Owner

Used Antigravity for fast error resolving and Folder Structure Cleaning

Summary by CodeRabbit

Release Notes

  • New Features

    • Added audio asset generation and management capabilities with status tracking
    • Introduced scene image asset generation
    • Enabled batch scene creation from JSON files
    • Added project and story context profile management
    • Implemented cloud-based file storage for images and videos
  • Improvements

    • Standardized API response formatting across all endpoints
    • Enhanced file upload handling with in-memory processing
    • Added comprehensive status tracking for generated content
  • Chores

    • Reorganized project constants and type definitions
    • Updated AWS SDK dependencies

…I for fast error resolving and Folder Structure Cleaning
Copilot AI review requested due to automatic review settings April 14, 2026 22:27
@coderabbitai

coderabbitai Bot commented Apr 14, 2026 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 21499885-2143-482f-9c09-bb4fa5e2541a

📥 Commits

Reviewing files that changed from the base of the PR and between c99cb3b and 5bcdb78.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (93)
  • Dockerfile
  • package.json
  • src/config/corsConfig.ts
  • src/constants/audioConsts.ts
  • src/constants/globalConts.ts
  • src/constants/narrationConsts.ts
  • src/db/connect.ts
  • src/libs/ai/clients/openAI.ts
  • src/libs/ai/policies/resolveModel.ts
  • src/libs/ai/prompts/batchScenesPrompt.ts
  • src/libs/ai/prompts/generateStoryRegenerationPrompt.ts
  • src/libs/ai/prompts/narrationPrompt.ts
  • src/libs/ai/prompts/singleScenePrompt.ts
  • src/libs/aws/s3.ts
  • src/middleware/404/notFoundHandler.ts
  • src/middleware/error/appError.ts
  • src/middleware/error/globalErrorHandler.ts
  • src/middleware/error/index.ts
  • src/middleware/multer/filenameLogic/multerAudio.ts
  • src/middleware/multer/filenameLogic/multerImage.ts
  • src/middleware/multer/filenameLogic/multerJSON.ts
  • src/middleware/multer/filenameLogic/multerVideo.ts
  • src/middleware/multer/scenesJSONUpload.ts
  • src/middleware/request/paginationAndSorting.ts
  • src/middleware/security/requireCsrf.ts
  • src/models/AudioAsset.ts
  • src/models/ContextProfile.ts
  • src/models/Narration.ts
  • src/models/Scene.ts
  • src/models/SceneAssets.ts
  • src/models/Story.ts
  • src/models/User.ts
  • src/modules/audio/audio.constants.ts
  • src/modules/audio/audio.controller.ts
  • src/modules/audio/audio.routes.ts
  • src/modules/audio/audio.service.ts
  • src/modules/auth/auth.controller.ts
  • src/modules/auth/auth.service.ts
  • src/modules/contextProfile/contextProfile.controller.ts
  • src/modules/contextProfile/contextProfile.service.ts
  • src/modules/narration/narration.controller.ts
  • src/modules/narration/narration.routes.ts
  • src/modules/narration/narration.service.ts
  • src/modules/project/project.controller.ts
  • src/modules/project/project.routes.ts
  • src/modules/project/project.service.ts
  • src/modules/project/rules/projectStatus.ts
  • src/modules/project/utils/transitionProjectById.ts
  • src/modules/sceneAssets/sceneAssets.controller.ts
  • src/modules/sceneAssets/sceneAssets.private.routes.ts
  • src/modules/sceneAssets/sceneAssets.service.ts
  • src/modules/scenes/scenes.controller.ts
  • src/modules/scenes/scenes.private.routes.ts
  • src/modules/scenes/scenes.service.ts
  • src/modules/story/story.controller.ts
  • src/modules/story/story.private.routes.ts
  • src/modules/story/story.service.ts
  • src/modules/user/user.controller.ts
  • src/modules/user/user.service.ts
  • src/routes/api.ts
  • src/routes/index.ts
  • src/server.ts
  • src/shared/index.ts
  • src/shared/response.ts
  • src/types/Audio.ts
  • src/types/Auth.ts
  • src/types/ContextProfile.ts
  • src/types/Error.ts
  • src/types/Project.ts
  • src/types/Scene.ts
  • src/types/SceneAsset.ts
  • src/types/Story.ts
  • src/types/express.d.ts
  • src/types/index.ts
  • src/utils/file.ts
  • src/utils/getVideoDuration.ts
  • src/utils/logger.ts
  • src/utils/paginationResponse.ts
  • src/utils/sanitizeProjectResponse.ts
  • src/utils/sanitizers/index.ts
  • src/utils/sanitizers/sanitizeAudioAssetResponse.ts
  • src/utils/sanitizers/sanitizeContextProfileResponse.ts
  • src/utils/sanitizers/sanitizeNarrationResponse.ts
  • src/utils/sanitizers/sanitizeProjectResponse.ts
  • src/utils/sanitizers/sanitizeSceneAssetResponse.ts
  • src/utils/sanitizers/sanitizeScenesResponse.ts
  • src/utils/sanitizers/sanitizeStoryResponse.ts
  • src/utils/sanitizers/sanitizeUserResponse.ts
  • src/validation/narration.schema.ts
  • src/validation/project.schema.ts
  • src/validation/scenes.schema.ts
  • src/validation/user.schema.ts
  • tsconfig.json

📝 Walkthrough

Walkthrough

The pull request introduces a comprehensive refactoring and feature expansion that modernizes the codebase's HTTP response handling, file upload strategy, AWS S3 integration, and type system architecture. It adds new features for JSON scene uploads, project/story context profiles, and implements consistent response standardization across controllers while migrating Multer to in-memory storage and refactoring S3 interactions to use presigned URLs.

Changes

Cohort / File(s) Summary
Configuration & Environment
Dockerfile, src/db/connect.ts, src/utils/logger.ts
Added production NODE_ENV to Dockerfile runtime stage, changed database connection logic to use local MongoDB only in development mode (not just non-production), and updated logger production detection from strict equality to inequality check.
Core Constants
src/constants/audioConsts.ts, src/constants/narrationConsts.ts, src/constants/globalConts.ts
Added new audio constants module with TTS provider config, voice tuning, and rate limits. Updated narration constants documentation. Modified ALLOWED_ORIGINS to use raw environment variables without fallback defaults.
AWS S3 Integration & File Operations
src/libs/aws/s3.ts, src/utils/file.ts, src/modules/sceneAssets/sceneAssets.service.ts
Refactored S3 client from hardcoded config to environment-driven setup, replaced signed URL helpers with direct upload/delete/presigned URL APIs, introduced uploadFile, deleteFile, getFileUrl, createPresignedUploadUrl exports. Added removeTempFile utility for async file cleanup.
HTTP Response Standardization
src/shared/response.ts, src/shared/index.ts, src/routes/index.ts
Created new response helpers sendSuccess, sendPaginated with typed ApiResponse/PaginatedApiResponse envelopes and sanitizeResponseData recursive data transformer. Added Cache-Control header middleware and updated health endpoint response shape.
Multer File Upload Migration
src/middleware/multer/filenameLogic/*.ts, src/middleware/multer/scenesJSONUpload.ts
Replaced disk-based Multer storage across multerAudio.ts, multerImage.ts, multerJSON.ts with in-memory storage, removing filesystem directory creation. Increased video upload limit from 20MB to 50MB. Added new scenesJSONUpload middleware for JSON file validation and error handling.
Type System Reorganization
src/types/Auth.ts, src/types/Scene.ts, src/types/Project.ts, src/types/Error.ts, src/types/Audio.ts, src/types/ContextProfile.ts, src/types/SceneAsset.ts, src/types/Story.ts, src/types/index.ts, tsconfig.json
Added new sanitized response types (SanitizedAudioAsset, SanitizedScene, SanitizedProject*, SanitizedStory, SanitizedSceneAsset, SanitizedContextProfile), auth output types (SignOutput, RefreshTokenOutput), scene modes (SingleSceneMode, BatchSceneMode), and UserReturnType enum. Added @app-types/* and @shared/* path aliases.
Database Models with Status Fields
src/models/AudioAsset.ts, src/models/SceneAssets.ts, src/models/Scene.ts, src/models/Story.ts, src/models/Narration.ts, src/models/ContextProfile.ts, src/models/User.ts
Added status lifecycle field ('not-generated' | 'generating' | 'ready' | 'error') to AudioAsset, SceneAsset, Scene, and Story.content. Added source field to NarrationSegment. Updated ContextProfile with storyId reference and indexing. Removed usage tracking from User model; tightened User privacy preferences enumeration.
Response Sanitizer Utilities
src/utils/sanitizers/index.ts, src/utils/sanitizers/sanitize*.ts
Created comprehensive sanitizer module with 9+ sanitization helpers (sanitizeUserResponse, sanitizeProjectResponse, sanitizeScenesResponse, sanitizeNarrationsResponse, sanitizeContextProfileResponse, sanitizeStoryResponse, sanitizeAudioAssetResponse, sanitizeSceneAssetResponse) that normalize Mongoose documents to safe response shapes with string IDs and ISO timestamps.
Import Path Refactoring
src/config/corsConfig.ts, src/libs/ai/policies/resolveModel.ts, src/libs/ai/prompts/*.ts, src/modules/auth/auth.service.ts, src/modules/story/story.service.ts, src/types/express.d.ts, and multiple other modules
Updated imports from relative paths to use centralized @constants/*, @app-types/*, @libs/*, @shared/*, @utils/* path aliases throughout codebase.
Authentication Module
src/modules/auth/auth.controller.ts, src/modules/auth/auth.service.ts, src/middleware/error/index.ts
Introduced setAuthCookies helper for centralized cookie handling. Changed response payloads to use sendSuccess with new user projection shape (email, username, displayName, avatarUrl, accountStatus). Updated error messages and default message for UnauthenticatedError.
User Module
src/modules/user/user.controller.ts, src/modules/user/user.service.ts, src/validation/user.schema.ts
Refactored all controllers to use sendSuccess helper. Changed getProfile return type to Partial<User> with sanitization. Updated avatar handling to use S3 upload/delete. Added URL validation schema for profile links with HTTP(S) protocol enforcement.
Audio Module
src/modules/audio/audio.constants.ts, src/modules/audio/audio.controller.ts, src/modules/audio/audio.routes.ts, src/modules/audio/audio.service.ts
Moved audio constants to centralized @constants/audioConsts.ts and re-exported from module. Updated controllers to use sendSuccess/sendPaginated. Removed unused validation schema imports. Changed pagination type imports to use path aliases.
Narration Module
src/modules/narration/narration.controller.ts, src/modules/narration/narration.service.ts, src/modules/narration/narration.routes.ts, src/validation/narration.schema.ts
Standardized responses via sendSuccess and sendPaginated. Simplified getAllNarrationsForStory signature (removed pagination/sorting params) and return type. Updated all queries to populate activeAudioAssetId and return sanitized responses. Imported MAX_NARRATION_LENGTH from constants.
Scene Module
src/modules/scenes/scenes.controller.ts, src/modules/scenes/scenes.service.ts, src/modules/scenes/scenes.private.routes.ts, src/validation/scenes.schema.ts
Added uploadScenesJSONController and uploadScenesFileController for JSON scene imports. Implemented createScenesFromJSON and uploadScenesJSONFromFile services with transaction support. Added validation schemas for scene item and JSON upload inputs. Updated route handler to use scenesJSONUpload middleware.
SceneAssets Module
src/modules/sceneAssets/sceneAssets.controller.ts, src/modules/sceneAssets/sceneAssets.service.ts, src/modules/sceneAssets/sceneAssets.private.routes.ts
Implemented generateImageAsset with S3 upload, updated uploadVideoAsset and uploadImageAsset to use S3, changed duration check condition from > 0.25 to < 0.25. Standardized responses via sendSuccess/sendPaginated. Updated route handler for permanent bulk delete.
Project Module
src/modules/project/project.controller.ts, src/modules/project/project.service.ts, src/modules/project/project.routes.ts, src/modules/project/rules/projectStatus.ts, src/modules/project/utils/transitionProjectById.ts, src/validation/project.schema.ts
Added updateProjectContextProfileController and service function with transaction-wrapped context profile creation. Moved ProjectStatus types to @app-types/Project.ts. Standardized responses via sendSuccess/sendPaginated. Added updateProjectContextProfileSchema for validation.
ContextProfile Module
src/modules/contextProfile/contextProfile.controller.ts, src/modules/contextProfile/contextProfile.service.ts
Updated controllers to use sendSuccess. Changed service to use withTransaction wrapper for session management. Added sanitizeContextProfileResponse calls in all query returns.
Story Module
src/modules/story/story.controller.ts, src/modules/story/story.service.ts, src/modules/story/story.private.routes.ts
Added listStoryContextProfilesController and service function to fetch story-associated context profiles. Updated all existing controllers to use sendSuccess/sendPaginated. Updated context profile creation to include storyId reference.
Error Handling & Middleware
src/middleware/error/appError.ts, src/middleware/error/globalErrorHandler.ts, src/middleware/404/notFoundHandler.ts, src/middleware/security/requireCsrf.ts, src/config/corsConfig.ts
Changed AppError.serialize() output to envelope format { message, data: { code, ... } }. Updated 404 handler to always return JSON response. Modified 500 error response shape. Changed CSRF validation from direct header access to req.header() with fallback. Simplified CORS config by removing production branching and filtering undefined origins.
AI Model & Prompts
src/libs/ai/clients/openAI.ts, src/libs/ai/prompts/batchScenesPrompt.ts, src/libs/ai/prompts/singleScenePrompt.ts, src/libs/ai/prompts/narrationPrompt.ts, src/libs/ai/prompts/generateStoryRegenerationPrompt.ts
Updated OpenAI model from google/gemma-3-27b-it to google/gemma-4-31b-it. Moved BatchSceneMode and SingleSceneMode type definitions to @app-types/Scene.ts and re-exported. Updated import paths to use path aliases.
Package & Server Configuration
package.json, src/server.ts
Updated AWS SDK (@aws-sdk/client-s3, @aws-sdk/s3-request-presigner) from ^3.948.0 to ^3.1004.0. Added sharp dependency at ^0.34.5. Removed comment-only lines from server startup.
Utilities & Helpers
src/utils/getVideoDuration.ts, src/utils/paginationResponse.ts, src/utils/sanitizeProjectResponse.ts (removed), src/routes/api.ts
Updated type imports to use @app-types/* and type-only imports. Removed old sanitizeProjectResponse.ts utility (replaced by new sanitizers). Added /audio route mounting to API router with auth/CSRF middleware for auth endpoints.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Controller as SceneController
    participant Service as SceneService
    participant Multer as scenesJSONUpload
    participant DB as Database
    participant Response as sendSuccess

    Client->>Controller: POST /upload-json
    Controller->>Multer: validate JSON upload
    Multer->>Multer: extract file buffer
    Multer->>Controller: pass to next
    Controller->>Service: createScenesFromJSON(userId, storyId, scenes)
    Service->>Service: withTransaction(session)
    Service->>DB: deactivate existing scenes
    Service->>DB: insert new scenes with authorType='user'
    DB-->>Service: created scenes
    Service-->>Controller: scenes array
    Controller->>Response: sendSuccess(201, scenes)
    Response-->>Client: {message, data: scenes[], status: 201}
Loading
sequenceDiagram
    participant Client
    participant Controller as SceneAssetsController
    participant Service as SceneAssetsService
    participant S3 as uploadFile
    participant DB as Database
    participant Response as sendSuccess

    Client->>Controller: POST /generate-image
    Controller->>Service: generateImageAsset(userId, sceneId)
    Service->>DB: validate scene ownership
    Service->>S3: uploadFile(buffer, key, contentType)
    S3-->>Service: upload result with URL
    Service->>DB: create SceneAsset with status='ready'
    Service->>DB: update Scene.activeAssetId
    Service->>DB: update Scene.status
    DB-->>Service: asset object
    Service-->>Controller: asset
    Controller->>Response: sendSuccess(201, asset)
    Response-->>Client: {message, data: asset, status: 201}
Loading
sequenceDiagram
    participant Client
    participant Controller as ProjectController
    participant Service as ProjectService
    participant ContextSvc as ContextProfileService
    participant DB as Database
    participant Response as sendSuccess

    Client->>Controller: PATCH /:projectId/context-profile
    Controller->>Service: updateProjectContextProfile(userId, projectId, payload)
    Service->>Service: withTransaction(session)
    Service->>DB: load project (validate ownership)
    Service->>ContextSvc: create ContextProfile(scope='PROJECT', isDefault=true)
    ContextSvc->>DB: insert new context profile
    DB-->>ContextSvc: new context
    Service->>DB: demote old defaultContextProfileId (isDefault=false)
    Service->>DB: update project.defaultContextProfileId
    DB-->>Service: updated project
    Service-->>Controller: sanitized project
    Controller->>Response: sendSuccess(res, project)
    Response-->>Client: {message, data: project}
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 Whiskers twitching with glee,
Files organized, path aliases free,
S3 uploads now neat, responses so clean,
Status fields tracking each dream we have seen,
JSON scenes hopping in, types aligned just right,
This refactor shines brilliant—a coder's delight! 🌟

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch API-LogicBuilding

@azeemstack
azeemstack merged commit d34e364 into main Apr 14, 2026
3 of 4 checks passed

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR standardizes backend API responses for frontend consumption by introducing shared response helpers and explicit “sanitized” response shapes, while also expanding validation, adding JSON upload flows, and integrating S3-based media handling.

Changes:

  • Added shared API response envelope helpers (sendSuccess, sendPaginated) and updated many controllers to use them.
  • Introduced/expanded response “sanitizers” and centralized app type exports via @app-types/*.
  • Added new upload/creation flows (scene JSON upload, avatar/media S3 upload) and updated several schemas/models accordingly.

Reviewed changes

Copilot reviewed 90 out of 94 changed files in this pull request and generated 8 comments.

Show a summary per file
File Description
tsconfig.json Adds path aliases for @shared/* and @app-types/*.
src/validation/user.schema.ts Refactors link URL validation via a shared urlField.
src/validation/scenes.schema.ts Adds schemas/types for uploading scenes via JSON.
src/validation/project.schema.ts Adds schema/type for updating project context profile payload.
src/validation/narration.schema.ts Moves narration constant to shared constants module.
src/utils/sanitizers/sanitizeUserResponse.ts Expands sanitized user shapes and switches to id string.
src/utils/sanitizers/sanitizeStoryResponse.ts Adds story sanitizer returning id-based response.
src/utils/sanitizers/sanitizeScenesResponse.ts Adds scenes sanitizer with optional active asset expansion.
src/utils/sanitizers/sanitizeSceneAssetResponse.ts Adds scene asset sanitizer.
src/utils/sanitizers/sanitizeProjectResponse.ts Adds project sanitizer (list/detail variants).
src/utils/sanitizers/sanitizeNarrationResponse.ts Adds narration sanitizer with active audio asset.
src/utils/sanitizers/sanitizeContextProfileResponse.ts Adds context profile sanitizer.
src/utils/sanitizers/sanitizeAudioAssetResponse.ts Adds audio asset sanitizer.
src/utils/sanitizers/index.ts Adds barrel exports for sanitizer utilities.
src/utils/sanitizeProjectResponse.ts Removes legacy project sanitizer in favor of new sanitizers.
src/utils/paginationResponse.ts Updates Pagination import to @app-types.
src/utils/logger.ts Changes “production vs pretty logging” environment logic.
src/utils/getVideoDuration.ts Minor formatting change in exported function declaration.
src/utils/file.ts Adds temp file cleanup helper (removeTempFile).
src/types/index.ts Adds central type barrel + exports UserReturnType and Plan.
src/types/express.d.ts Fixes imports to .js paths and constants module.
src/types/Story.ts Adds sanitized story response interface.
src/types/SceneAsset.ts Adds sanitized scene asset response interface.
src/types/Scene.ts Adds sanitized scene response interface + scene mode types.
src/types/Project.ts Adds project status and sanitized project response interfaces.
src/types/Error.ts Re-exports ErrorCode type.
src/types/ContextProfile.ts Adds sanitized context profile response interface.
src/types/Auth.ts Adds auth response output types.
src/types/Audio.ts Adds sanitized audio asset response interface.
src/shared/response.ts Adds response envelope + generic object-id stripping sanitizer.
src/shared/index.ts Adds barrel exports for shared response utilities.
src/server.ts Minor startup flow cleanup.
src/routes/index.ts Adds Cache-Control: no-store and updates /health envelope.
src/routes/api.ts Adds audio router and reorders private route middleware usage.
src/modules/user/user.service.ts Uses new user sanitizer; adds S3 avatar upload/delete logic.
src/modules/user/user.controller.ts Migrates responses to sendSuccess and error throwing.
src/modules/story/story.service.ts Switches imports to aliases and adds story context list service.
src/modules/story/story.private.routes.ts Adds route to list story context profiles.
src/modules/story/story.controller.ts Migrates many handlers to shared response helpers.
src/modules/scenes/scenes.service.ts Returns sanitized scenes + adds JSON upload/create flows.
src/modules/scenes/scenes.private.routes.ts Adds routes/middleware for scenes JSON upload (body + file).
src/modules/scenes/scenes.controller.ts Adds controllers for scenes JSON upload + shared response envelope.
src/modules/sceneAssets/sceneAssets.service.ts Adds S3 upload + temp cleanup; updates generation/upload paths.
src/modules/sceneAssets/sceneAssets.private.routes.ts Fixes route handler reference for permanent bulk delete.
src/modules/sceneAssets/sceneAssets.controller.ts Migrates handlers to shared response helpers; adds image generation.
src/modules/project/utils/transitionProjectById.ts Updates sanitizer import path.
src/modules/project/rules/projectStatus.ts Moves project status types to @app-types.
src/modules/project/project.service.ts Adds project context update service + updated imports.
src/modules/project/project.routes.ts Adds route for updating project context profile.
src/modules/project/project.controller.ts Migrates to shared response helpers; adds context update controller.
src/modules/narration/narration.service.ts Adds narration sanitization; changes list API shape and population.
src/modules/narration/narration.routes.ts Adjusts middleware usage for deleted narrations endpoint.
src/modules/narration/narration.controller.ts Migrates to shared response envelope; refactors pagination usage.
src/modules/contextProfile/contextProfile.service.ts Adds sanitization + uses withTransaction.
src/modules/contextProfile/contextProfile.controller.ts Migrates to shared response helper.
src/modules/auth/auth.service.ts Uses aliased constants + returns safe SignOutput user shape.
src/modules/auth/auth.controller.ts Refactors cookie-setting and standardizes response envelopes.
src/modules/audio/audio.service.ts Updates Pagination import path.
src/modules/audio/audio.routes.ts Removes unused schema import and keeps routes aligned.
src/modules/audio/audio.controller.ts Migrates to shared response helpers.
src/modules/audio/audio.constants.ts Re-exports audio constants from global constants module.
src/models/User.ts Changes privacy prefs enum/fields and removes usage subdocument.
src/models/Story.ts Adds contentStatus into story content.
src/models/SceneAssets.ts Adds thumbnailUrl and status to scene assets.
src/models/Scene.ts Adds status to scenes.
src/models/Narration.ts Adds segment source and narration status.
src/models/ContextProfile.ts Adds storyId support and index.
src/models/AudioAsset.ts Adds status to audio assets.
src/middleware/security/requireCsrf.ts Updates constants import and adjusts origin extraction/validation.
src/middleware/request/paginationAndSorting.ts Updates Pagination import to @app-types.
src/middleware/multer/scenesJSONUpload.ts Adds dedicated multer wrapper for scenes JSON uploads.
src/middleware/multer/filenameLogic/multerVideo.ts Increases max video upload size limit.
src/middleware/multer/filenameLogic/multerJSON.ts Switches JSON uploads to memory storage + simplified filter.
src/middleware/multer/filenameLogic/multerImage.ts Switches image uploads to memory storage + simplified filter.
src/middleware/multer/filenameLogic/multerAudio.ts Switches audio uploads to memory storage + simplified filter.
src/middleware/error/index.ts Adjusts error constructors to new AppError signature.
src/middleware/error/globalErrorHandler.ts Removes stray console logging and standardizes 500 envelope.
src/middleware/error/appError.ts Standardizes serialized error envelope and hides prod details.
src/middleware/404/notFoundHandler.ts Standardizes 404 JSON response envelope.
src/libs/aws/s3.ts Replaces localstack demo code with real S3 upload/delete/presign helpers.
src/libs/ai/prompts/singleScenePrompt.ts Switches to @app-types and re-exports scene mode types.
src/libs/ai/prompts/narrationPrompt.ts Switches StoryContent import to @app-types.
src/libs/ai/prompts/generateStoryRegenerationPrompt.ts Fixes import path to @libs alias.
src/libs/ai/prompts/batchScenesPrompt.ts Switches to @app-types and re-exports scene mode types.
src/libs/ai/policies/resolveModel.ts Switches type imports to @app-types.
src/libs/ai/clients/openAI.ts Updates OpenRouter model identifier.
src/db/connect.ts Refactors env handling + connection string selection.
src/constants/narrationConsts.ts Adds header comment and formatting cleanup.
src/constants/globalConts.ts Simplifies allowed origins list to env-provided URLs.
src/constants/audioConsts.ts Adds new global audio constants module.
src/config/corsConfig.ts Updates constants import and filters undefined origins.
package.json Bumps AWS SDK packages and adds sharp.
Dockerfile Sets NODE_ENV=production in container.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/models/User.ts
Comment on lines 80 to 96
@@ -95,10 +92,6 @@ const privacyPrefsSchema = new Schema(
type: Boolean,
default: true,
},
allowDiscoverability: {
type: Boolean,
default: true,
},
},
{ _id: false }

Copilot AI Apr 14, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

privacyPrefsSchema no longer allows profileVisibility: 'unlisted' and no longer defines allowDiscoverability, but other parts of the code (e.g., the privacyPrefs default object and updatePrivacySettings logic) still reference allowDiscoverability, and validation still accepts 'unlisted'. This mismatch will cause updates/defaults to be dropped (or invalid values to be stored) depending on Mongoose update settings. Align the schema with the expected fields/enum values, or update the rest of the codebase and request validation accordingly.

Copilot uses AI. Check for mistakes.
import ffmpeg from 'fluent-ffmpeg';

export function getVideoDuration(filePath: string): Promise<number> {
export function getVideoDuration(filePath: string): Promise<number> {

Copilot AI Apr 14, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are extra spaces in the function declaration (export function getVideoDuration...). This is easy to miss in reviews and can cause noisy diffs / formatter churn; please normalize the whitespace.

Copilot uses AI. Check for mistakes.
const origin = req.headers.Origin;
if (origin && (origin === 'null' || !ALLOWED_ORIGINS.includes(origin as string))) {
const origin = req.header('Origin') || req.headers['origin'] || req.headers.origin;
if (!origin && (origin === 'null' || !ALLOWED_ORIGINS.includes(origin as string))) {

Copilot AI Apr 14, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CSRF origin validation logic is inverted: if (!origin && (origin === 'null' || !ALLOWED_ORIGINS.includes(origin as string))) will (a) reject requests without an Origin header, and (b) allow requests with a disallowed Origin header. This effectively disables the origin allowlist and can break non-browser clients. Change the condition to validate when an origin is present (and explicitly handle origin === 'null').

Suggested change
if (!origin && (origin === 'null' || !ALLOWED_ORIGINS.includes(origin as string))) {
if (origin && (origin === 'null' || !ALLOWED_ORIGINS.includes(origin as string))) {

Copilot uses AI. Check for mistakes.
Comment on lines +418 to 421
if (scene.duration !== undefined && Math.abs(duration - scene.duration) < 0.25) {
await removeTempFile(file.path);
throw new BadRequestError('Video duration does not match existing scene duration and cannot be uploaded');
}

Copilot AI Apr 14, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The video-duration mismatch check is reversed: it currently throws when the uploaded video duration is within 0.25s of the scene duration (< 0.25). This will reject valid uploads and allow mismatched ones. Flip the comparison so it rejects when the difference exceeds the tolerance.

Copilot uses AI. Check for mistakes.
Comment on lines 40 to 44
router.get(
'/story/:storyId/deleted',
validateParams(storyIdParamSchema),
paginationAndSortingMiddleware,
asyncHandler(getAllDeletedNarrationsController)
);

Copilot AI Apr 14, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This route no longer applies paginationAndSortingMiddleware, but getAllDeletedNarrationsController still reads req.pagination / req.sorting and calls paginationResponse(...). As-is, requests to /story/:storyId/deleted will likely crash or return incorrect pagination. Either re-add the middleware here, or update the controller/service to not require pagination for this endpoint.

Copilot uses AI. Check for mistakes.
Comment on lines 70 to +81
export async function getAllNarrationForSceneOrder(userId: string, storyId: string, sceneOrderIds: string[]) {
const sceneOrderHash = hashSceneOrder(sceneOrderIds.map((id) => new Types.ObjectId(id)));
const narration = await StoryNarrationModel.findOne({
userId,
storyId,
sceneOrderHash,
deletedAt: { $exists: false },
});
return narration;
}).populate('activeAudioAssetId');

const sanitizedResponse = sanitizeNarrationsResponse([narration as StoryNarration]);

return sanitizedResponse;

Copilot AI Apr 14, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getAllNarrationForSceneOrder can return null from findOne(...), but the code force-casts it to StoryNarration and passes it into sanitizeNarrationsResponse, which will throw at runtime. Handle the not-found case explicitly (e.g., return null or throw NotFoundError) before sanitizing. Also consider returning a single sanitized narration rather than an array, since the function name implies a single match.

Copilot uses AI. Check for mistakes.
Comment on lines +45 to 51
export const upload = multer({
storage: multer.memoryStorage(),
fileFilter,
limits: { fileSize: 10 * 1024 * 1024 }, // 10 MB limit
limits: {
fileSize: 10 * 1024 * 1024, // 10MB
},
});

Copilot AI Apr 14, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

multer.memoryStorage() does not set req.file.path (it only provides req.file.buffer). Downstream code (e.g., audio upload controller/service) currently passes req.file.path, which will be undefined and break uploads. Either switch back to disk storage or update the upload flow to consume req.file.buffer and/or stream directly to S3.

Copilot uses AI. Check for mistakes.
Comment on lines 172 to +181
export const uploadAudioAssetController = async (req: Request, res: Response) => {
const userId = req.user!.id;
const { narrationId } = req.params;

if (!req.file) {
return res.status(400).json({
message: 'No file uploaded',
});
throw new BadRequestError('No file uploaded');
}

const audioAsset = await uploadNarrationAudioAsset(userId, narrationId, req.file.path);

res.status(201).json({
message: 'Audio asset uploaded successfully',
data: audioAsset,
});
return sendSuccess(res, audioAsset, 'Audio asset uploaded successfully', 201);

Copilot AI Apr 14, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This controller passes req.file.path into uploadNarrationAudioAsset(...), but the multer audio upload now uses memoryStorage, so req.file.path will be undefined. Use req.file.buffer (or adjust multer storage back to disk) and update uploadNarrationAudioAsset to accept/process a Buffer or a persisted object-store URL.

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants