Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,6 @@ COPY --from=builder /app/dist ./dist

EXPOSE 4000

ENV NODE_ENV=production

CMD ["node", "dist/server.js"]
3,301 changes: 2,064 additions & 1,237 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@
"start": "node dist/server.js"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.948.0",
"@aws-sdk/s3-request-presigner": "^3.948.0",
"@aws-sdk/client-s3": "^3.1004.0",
"@aws-sdk/s3-request-presigner": "^3.1004.0",
"@types/cookie-parser": "^1.4.10",
"@types/multer": "^2.0.0",
"bcrypt": "^6.0.0",
Expand All @@ -24,6 +24,7 @@
"multer": "^2.0.2",
"nodemailer": "^7.0.11",
"pino": "^10.1.0",
"sharp": "^0.34.5",
"ua-parser-js": "^2.0.6",
"undici": "^7.16.0",
"zod": "^4.1.13"
Expand Down
42 changes: 14 additions & 28 deletions src/config/corsConfig.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,20 @@
import { ALLOWED_ORIGINS } from 'constants/globalConts.js';
import { ALLOWED_ORIGINS } from '@constants/globalConts.js';
import type { CorsOptions } from 'cors';

/**
* Returns the appropriate CORS configuration based on the current environment.
* @returns CorsOptions object for the Express 'cors' middleware.
*/
const getCorsConfig = (): CorsOptions => {
// Check if the environment is explicitly set to production
const isProduction = process.env.NODE_ENV === 'production';

// Determine the allowed origin
// In production, strictly use the production URL.
// In any other environment (development, staging, test), use the development URL.
const allowedOrigin = ALLOWED_ORIGINS;
const isProduction = process.env.NODE_ENV === 'production';

return {
// Set the dynamic origin
origin: allowedOrigin,

// Define allowed interactions
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'X-CSRF-Token'],


// Allow cookies or authorization headers to be sent
credentials: true,

// Caching for preflight requests
maxAge: 86400 // Cache preflight response for 24 hours
};
const allowedOrigin = ALLOWED_ORIGINS.filter((origin): origin is string => origin !== undefined);

return {
origin: allowedOrigin,

methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'X-CSRF-Token'],
credentials: true,

maxAge: 86400,
};
};

export default getCorsConfig;
export default getCorsConfig;
28 changes: 28 additions & 0 deletions src/constants/audioConsts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Audio generation configuration
export const DEFAULT_VOICE_STABILITY = 0.5;
export const DEFAULT_VOICE_SIMILARITY_BOOST = 0.75;
export const DEFAULT_VOICE_STYLE = 0;
export const DEFAULT_USE_SPEAKER_BOOST = true;

// Supported TTS providers
export const TTS_PROVIDERS = ['elevenlabs', 'openai', 'azure', 'google'] as const;
export type TTSProvider = (typeof TTS_PROVIDERS)[number];

// Default provider
export const DEFAULT_TTS_PROVIDER: TTSProvider = 'elevenlabs';

// Audio quality settings
export const AUDIO_OUTPUT_FORMAT = 'mp3_44100_128' as const;
export const AUDIO_SAMPLE_RATE = 44100;
export const AUDIO_BIT_RATE = 128;

// Rate limiting
export const MAX_AUDIO_GENERATIONS_PER_DAY = 100;
export const MAX_AUDIO_GENERATIONS_PER_HOUR = 20;

// Cache TTL (in seconds)
export const AUDIO_CACHE_TTL = 86400; // 24 hours

// Version constants
export const AUDIO_VERSION_START = 1;
export const MAX_AUDIO_VERSIONS_PER_NARRATION = 100;
6 changes: 1 addition & 5 deletions src/constants/globalConts.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
export const ALLOWED_ORIGINS = process.env.ALLOWED_ORIGINS
? process.env.ALLOWED_ORIGINS.split(',')
: [
process.env.DEV_CLIENT_URL || 'http://localhost:5173',
process.env.PROD_CLIENT_URL || 'https://your-production-app.com',
];

: [process.env.DEV_CLIENT_URL, process.env.PROD_CLIENT_URL];
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// Narration timing constants
export const DEFAULT_WORDS_PER_SECOND = 2.5;
export const MAX_NARRATION_LENGTH = 20000;
export const NARRATION_VERSION_GAP = 1;
export const NARRATION_VERSION_GAP = 1;
21 changes: 9 additions & 12 deletions src/db/connect.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,24 @@
import mongoose from "mongoose";
import dotenv from "dotenv";
import mongoose from 'mongoose';
import dotenv from 'dotenv';

dotenv.config();

const password = encodeURIComponent(process.env.DB_PASSWORD ?? "");
const username = encodeURIComponent(process.env.DB_USERNAME ?? "");
const password = encodeURIComponent(process.env.DB_PASSWORD ?? '');
const username = encodeURIComponent(process.env.DB_USERNAME ?? '');

const CONNECTION_STRING = `${
process.env.NODE_ENV !== "production"
? "mongodb://localhost:27017/your_db_name?replicaSet=rs0"
process.env.NODE_ENV === 'development'
? 'mongodb://localhost:27017/your_db_name?replicaSet=rs0'
: `mongodb+srv://${username}:${password}@db0.huxhv46.mongodb.net/?appName=DB0`
}`;
const connectDB = async () => {
try {
await mongoose.connect(`${CONNECTION_STRING}`, {
dbName: "myapp",
dbName: 'myapp',
});
console.log("✅ MongoDB Connected");
console.log('✅ MongoDB Connected');
} catch (err) {
console.error(
"❌ MongoDB Error:",
err instanceof Error ? err.message : String(err)
);
console.error('❌ MongoDB Error:', err instanceof Error ? err.message : String(err));
process.exit(1);
}
};
Expand Down
2 changes: 1 addition & 1 deletion src/libs/ai/clients/openAI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export async function openRouterAI(prompt: string): Promise<any> {
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'google/gemma-3-27b-it:free',
model: 'google/gemma-4-31b-it:free',
temperature: 0.7,
messages: [
{
Expand Down
2 changes: 1 addition & 1 deletion src/libs/ai/policies/resolveModel.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { BadRequestError } from '@middleware/error/index.js';
import type { AIMode, Plan } from 'types/index.js';
import type { AIMode, Plan } from '@app-types/index.js';

type ModelConfig =
| {
Expand Down
6 changes: 4 additions & 2 deletions src/libs/ai/prompts/batchScenesPrompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@ import {
MULTI_SCENE_REGENERATION_PROMPT,
MULTI_SCENE_STRUCTURE_FORMAT,
} from '../constants/scenesPromptConts.js';
import { StoryContent } from 'types/index.js';
import { StoryContent } from '@app-types/index.js';

export type BatchSceneMode = 'generate' | 'regenerate';
import type { BatchSceneMode } from '@app-types/Scene.js';

export type { BatchSceneMode };

type BuildBatchScenePromptInput = {
mode: BatchSceneMode;
Expand Down
2 changes: 1 addition & 1 deletion src/libs/ai/prompts/generateStoryRegenerationPrompt.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Platform, StoryIntent } from '@constants/storyConsts.js';
import { ContextProfile } from '@models/ContextProfile.js';
import { GLOBAL_SAFETY_RULES } from 'libs/ai/constants/globalSafetyRules.js';
import { GLOBAL_SAFETY_RULES } from '@libs/ai/constants/globalSafetyRules.js';
import { STORY_GENERATION_FORMAT } from '../constants/storyPromptConts.js';
import { buildContextSection } from './utils/buildContextSection.js';
import { calculateWordLimits } from '../constants/calculateWordLimits.js';
Expand Down
2 changes: 1 addition & 1 deletion src/libs/ai/prompts/narrationPrompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { ContextProfile } from '@models/ContextProfile.js';
import { GLOBAL_SAFETY_RULES } from '../constants/globalSafetyRules.js';
import { FULL_STORY_NARRATION_STRUCTURE_FORMAT } from '../constants/narrationPromptConsts.js';
import { Platform, StoryIntent } from '@constants/storyConsts.js';
import { StoryContent } from 'types/index.js';
import { StoryContent } from '@app-types/index.js';

type BuildFullNarrationPromptInput = {
storyTitle: string;
Expand Down
6 changes: 4 additions & 2 deletions src/libs/ai/prompts/singleScenePrompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ import {
SCENE_STRUCTURE_FORMAT,
} from '../constants/scenesPromptConts.js';
import { BadRequestError } from '@middleware/error/index.js';
import { StoryContent } from 'types/index.js';
import { StoryContent } from '@app-types/index.js';

export type SingleSceneMode = 'generate' | 'variation' | 'regenerate';
import type { SingleSceneMode } from '@app-types/Scene.js';

export type { SingleSceneMode };

type BuildSingleScenePromptInput = {
mode: SingleSceneMode;
Expand Down
84 changes: 67 additions & 17 deletions src/libs/aws/s3.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,73 @@
import { GetObjectAclCommand, S3Client } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";

const s3Client = new S3Client({
region: "us-east-1",
endpoint: "http://localhost.localstack.cloud:4566",
forcePathStyle: true,
credentials: {
accessKeyId: "test",
secretAccessKey: "test",
},
import { S3Client, PutObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3';

import { getSignedUrl } from '@aws-sdk/s3-request-presigner';

const REGION = process.env.AWS_REGION!;
const BUCKET = process.env.S3_BUCKET!;
const CDN = process.env.CDN_URL!;

export const s3 = new S3Client({
region: REGION,
});

async function getObjectURL(key:any) {
const command = new GetObjectAclCommand({
Bucket: "sample-bucket",
export async function uploadFile({
buffer,
key,
contentType,
}: {
buffer: Buffer;
key: string;
contentType: string;
}) {
const command = new PutObjectCommand({
Bucket: BUCKET,
Key: key,
Body: buffer,
ContentType: contentType,
});

await s3.send(command);

return `${CDN}/${key}`;
}

export async function deleteFile(key: string) {
const command = new DeleteObjectCommand({
Bucket: BUCKET,
Key: key,
});
const url = await getSignedUrl(s3Client, command, { expiresIn: 3600 });
return url;

await s3.send(command);

return true;
}

console.log("Generated Signed URL:", await getObjectURL("AI Studio API.txt"));

export function getFileUrl(key: string) {
return `${CDN}/${key}`;
}

export async function createPresignedUploadUrl({
key,
contentType,
expiresIn = 300,
}: {
key: string;
contentType: string;
expiresIn?: number;
}) {
const command = new PutObjectCommand({
Bucket: BUCKET,
Key: key,
ContentType: contentType,
});

const url = await getSignedUrl(s3, command, {
expiresIn,
});

return {
uploadUrl: url,
fileUrl: `${CDN}/${key}`,
};
}
35 changes: 11 additions & 24 deletions src/middleware/404/notFoundHandler.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,13 @@
import type { Request, Response, NextFunction } from "express";

interface ErrorResponse {
error: string;
message: string;
}

const notFoundHandler = (
req: Request,
res: Response,
next: NextFunction
): void => {
res.status(404);

if (req.accepts("json")) {
res.json({
error: "Not Found",
message: `The resource at ${req.originalUrl} was not found on this server.`,
} as ErrorResponse);
return;
}

res.type("txt").send("404 Not Found");
import type { Request, Response, NextFunction } from 'express';

const notFoundHandler = (req: Request, res: Response, _next: NextFunction): void => {
res.status(404).json({
message: `The resource at ${req.originalUrl} was not found on this server.`,
data: {
code: 'not_found',
path: req.originalUrl,
},
});
};

export default notFoundHandler;
export default notFoundHandler;
Loading
Loading