Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Docker Build (#397)

Omar McAdam1c6277ba2297
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 000000000..f3006cb25
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,3 @@
+target/
+node_modules/
+crates/
diff --git a/.npmrc b/.npmrc
index 1560b99cc..bb7b7ccd8 100644
--- a/.npmrc
+++ b/.npmrc
@@ -1 +1,2 @@
-auto-install-peers = true
\ No newline at end of file
+auto-install-peers = true
+inject-workspace-packages=true
\ No newline at end of file
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 000000000..c04b6071c
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,41 @@
+# syntax=docker.io/docker/dockerfile:1
+
+FROM node:20-alpine AS base
+RUN corepack enable
+
+FROM base AS builder
+WORKDIR /app
+COPY . .
+
+RUN corepack enable pnpm
+RUN --mount=type=cache,id=pnpm,target=/root/.local/share/pnpm/store pnpm i --frozen-lockfile
+
+ARG DOCKER_BUILD=true
+ENV NEXT_PUBLIC_WEB_URL=http://localhost:3000
+ENV NEXT_PUBLIC_CAP_AWS_BUCKET=capso
+ENV NEXT_PUBLIC_CAP_AWS_REGION=us-east-1
+
+RUN pnpm run build:web
+
+
+# 3. Production image, copy all the files and run next
+FROM base AS runner
+WORKDIR /app
+
+RUN addgroup -g 1001 -S nodejs
+RUN adduser -S nextjs -u 1001
+
+
+# Automatically leverage output traces to reduce image size
+# https://nextjs.org/docs/advanced-features/output-file-tracing
+COPY --from=builder --chown=nextjs:nodejs /app/apps/web/.next/standalone ./
+COPY --from=builder --chown=nextjs:nodejs /app/apps/web/.next/static ./apps/web/.next/static
+COPY --from=builder --chown=nextjs:nodejs /app/apps/web/public ./apps/web/public
+COPY --from=builder --chown=nextjs:nodejs /app/packages/database/migrations ./apps/web/migrations
+
+
+USER nextjs
+
+EXPOSE 3000
+
+CMD HOSTNAME="0.0.0.0" node apps/web/server.js
diff --git a/apps/web/actions/screenshots/get-screenshot.ts b/apps/web/actions/screenshots/get-screenshot.ts
index f9836b0d6..ee8ddd976 100644
--- a/apps/web/actions/screenshots/get-screenshot.ts
+++ b/apps/web/actions/screenshots/get-screenshot.ts
@@ -10,14 +10,14 @@ import { getCurrentUser } from "@cap/database/auth/session";
import { createS3Client, getS3Bucket } from "@/utils/s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { S3_BUCKET_URL } from "@cap/utils";
-import { clientEnv } from "@cap/env";
+import { buildEnv, serverEnv } from "@cap/env";
export async function getScreenshot(userId: string, screenshotId: string) {
if (!userId || !screenshotId) {
throw new Error("userId or screenshotId not supplied");
}
- const query = await db
+ const query = await db()
.select({ video: videos, bucket: s3Buckets })
.from(videos)
.leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
@@ -65,7 +65,7 @@ export async function getScreenshot(userId: string, screenshotId: string) {
let screenshotUrl: string;
- if (video.awsBucket !== clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET) {
+ if (video.awsBucket !== serverEnv().CAP_AWS_BUCKET) {
screenshotUrl = await getSignedUrl(
s3Client,
new GetObjectCommand({
@@ -82,4 +82,4 @@ export async function getScreenshot(userId: string, screenshotId: string) {
} catch (error) {
throw new Error(`Error generating screenshot URL: ${error}`);
}
-}
\ No newline at end of file
+}
diff --git a/apps/web/actions/videos/delete.ts b/apps/web/actions/videos/delete.ts
index 7c77904fe..2ee8d27f1 100644
--- a/apps/web/actions/videos/delete.ts
+++ b/apps/web/actions/videos/delete.ts
@@ -4,10 +4,7 @@ import { getCurrentUser } from "@cap/database/auth/session";
import { s3Buckets, videos } from "@cap/database/schema";
import { db } from "@cap/database";
import { and, eq } from "drizzle-orm";
-import {
- DeleteObjectsCommand,
- ListObjectsV2Command,
-} from "@aws-sdk/client-s3";
+import { DeleteObjectsCommand, ListObjectsV2Command } from "@aws-sdk/client-s3";
import { createS3Client, getS3Bucket } from "@/utils/s3";
export async function deleteVideo(videoId: string) {
@@ -22,7 +19,7 @@ export async function deleteVideo(videoId: string) {
};
}
- const query = await db
+ const query = await db()
.select({ video: videos, bucket: s3Buckets })
.from(videos)
.leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
@@ -43,7 +40,7 @@ export async function deleteVideo(videoId: string) {
};
}
- await db
+ await db()
.delete(videos)
.where(and(eq(videos.id, videoId), eq(videos.ownerId, userId)));
@@ -82,4 +79,4 @@ export async function deleteVideo(videoId: string) {
message: "Failed to delete video",
};
}
-}
\ No newline at end of file
+}
diff --git a/apps/web/actions/videos/edit-date.ts b/apps/web/actions/videos/edit-date.ts
index 6e3b50caf..4a6d508b4 100644
--- a/apps/web/actions/videos/edit-date.ts
+++ b/apps/web/actions/videos/edit-date.ts
@@ -1,4 +1,4 @@
-'use server';
+"use server";
import { getCurrentUser } from "@cap/database/auth/session";
import { videos } from "@cap/database/schema";
@@ -9,13 +9,13 @@ import { revalidatePath } from "next/cache";
export async function editDate(videoId: string, date: string) {
const user = await getCurrentUser();
-
+
if (!user || !date || !videoId) {
throw new Error("Missing required data for updating video date");
}
const userId = user.id;
- const query = await db.select().from(videos).where(eq(videos.id, videoId));
+ const query = await db().select().from(videos).where(eq(videos.id, videoId));
if (query.length === 0) {
throw new Error("Video not found");
@@ -33,20 +33,20 @@ export async function editDate(videoId: string, date: string) {
try {
const newDate = new Date(date);
const currentDate = new Date();
-
+
// Prevent future dates
if (newDate > currentDate) {
throw new Error("Cannot set a date in the future");
}
-
+
// Store the custom date in the metadata field
- const currentMetadata = video.metadata as VideoMetadata || {};
+ const currentMetadata = (video.metadata as VideoMetadata) || {};
const updatedMetadata: VideoMetadata = {
...currentMetadata,
customCreatedAt: newDate.toISOString(),
};
-
- await db
+
+ await db()
.update(videos)
.set({
metadata: updatedMetadata,
@@ -54,9 +54,9 @@ export async function editDate(videoId: string, date: string) {
.where(eq(videos.id, videoId));
// Revalidate paths to update the UI
- revalidatePath('/dashboard/caps');
- revalidatePath('/dashboard/shared-caps');
-
+ revalidatePath("/dashboard/caps");
+ revalidatePath("/dashboard/shared-caps");
+
return { success: true };
} catch (error) {
console.error("Error updating video date:", error);
@@ -65,4 +65,4 @@ export async function editDate(videoId: string, date: string) {
}
throw new Error("Failed to update video date");
}
-}
\ No newline at end of file
+}
diff --git a/apps/web/actions/videos/edit-title.ts b/apps/web/actions/videos/edit-title.ts
index 2190cb007..727a7db77 100644
--- a/apps/web/actions/videos/edit-title.ts
+++ b/apps/web/actions/videos/edit-title.ts
@@ -1,4 +1,4 @@
-'use server';
+"use server";
import { getCurrentUser } from "@cap/database/auth/session";
import { videos } from "@cap/database/schema";
@@ -8,13 +8,13 @@ import { revalidatePath } from "next/cache";
export async function editTitle(videoId: string, title: string) {
const user = await getCurrentUser();
-
+
if (!user || !title || !videoId) {
throw new Error("Missing required data for updating video title");
}
const userId = user.id;
- const query = await db.select().from(videos).where(eq(videos.id, videoId));
+ const query = await db().select().from(videos).where(eq(videos.id, videoId));
if (query.length === 0) {
throw new Error("Video not found");
@@ -30,15 +30,15 @@ export async function editTitle(videoId: string, title: string) {
}
try {
- await db
+ await db()
.update(videos)
.set({ name: title })
.where(eq(videos.id, videoId));
- revalidatePath('/dashboard/caps');
- revalidatePath('/dashboard/shared-caps');
+ revalidatePath("/dashboard/caps");
+ revalidatePath("/dashboard/shared-caps");
revalidatePath(`/s/${videoId}`);
-
+
return { success: true };
} catch (error) {
console.error("Error updating video title:", error);
@@ -47,4 +47,4 @@ export async function editTitle(videoId: string, title: string) {
}
throw new Error("Failed to update video title");
}
-}
\ No newline at end of file
+}
diff --git a/apps/web/actions/videos/get-analytics.ts b/apps/web/actions/videos/get-analytics.ts
index 4b699497d..4f2b76a5c 100644
--- a/apps/web/actions/videos/get-analytics.ts
+++ b/apps/web/actions/videos/get-analytics.ts
@@ -1,4 +1,4 @@
-'use server';
+"use server";
import { dub } from "@/utils/dub";
import { ClicksCount } from "dub/models/components";
@@ -9,7 +9,7 @@ export async function getVideoAnalytics(videoId: string) {
}
try {
- const response = await dub.analytics.retrieve({
+ const response = await dub().analytics.retrieve({
domain: "cap.link",
key: videoId,
});
@@ -28,4 +28,4 @@ export async function getVideoAnalytics(videoId: string) {
console.error("Error fetching video analytics:", error);
return { count: 0 };
}
-}
\ No newline at end of file
+}
diff --git a/apps/web/actions/videos/get-og-image.tsx b/apps/web/actions/videos/get-og-image.tsx
index 5f6a339d1..cfae27374 100644
--- a/apps/web/actions/videos/get-og-image.tsx
+++ b/apps/web/actions/videos/get-og-image.tsx
@@ -2,7 +2,7 @@ import { ImageResponse } from "next/og";
import { GetObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { createS3Client, getS3Bucket } from "@/utils/s3";
-import { clientEnv, serverEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
import { db } from "@cap/database";
import { s3Buckets, videos } from "@cap/database/schema";
import { eq } from "drizzle-orm";
@@ -160,7 +160,7 @@ export async function generateVideoOgImage(videoId: string) {
}
async function getData(videoId: string) {
- const query = await db
+ const query = await db()
.select({
video: videos,
bucket: s3Buckets,
@@ -174,10 +174,10 @@ async function getData(videoId: string) {
if (!result) return;
const defaultBucket = {
- name: clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET,
- region: clientEnv.NEXT_PUBLIC_CAP_AWS_REGION,
- accessKeyId: serverEnv.CAP_AWS_ACCESS_KEY,
- secretAccessKey: serverEnv.CAP_AWS_SECRET_KEY,
+ name: serverEnv().CAP_AWS_BUCKET,
+ region: serverEnv().CAP_AWS_REGION,
+ accessKeyId: serverEnv().CAP_AWS_ACCESS_KEY,
+ secretAccessKey: serverEnv().CAP_AWS_SECRET_KEY,
};
return {
diff --git a/apps/web/actions/videos/transcribe.ts b/apps/web/actions/videos/transcribe.ts
index 5e6b57302..de7145197 100644
--- a/apps/web/actions/videos/transcribe.ts
+++ b/apps/web/actions/videos/transcribe.ts
@@ -1,9 +1,4 @@
-"use server";
-
-import {
- GetObjectCommand,
- PutObjectCommand,
-} from "@aws-sdk/client-s3";
+import { GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { createClient } from "@deepgram/sdk";
import { db } from "@cap/database";
@@ -21,7 +16,7 @@ export async function transcribeVideo(
videoId: string,
userId: string
): Promise<TranscribeResult> {
- if (!serverEnv.DEEPGRAM_API_KEY) {
+ if (!serverEnv().DEEPGRAM_API_KEY) {
return {
success: false,
message: "Missing necessary environment variables",
@@ -35,7 +30,7 @@ export async function transcribeVideo(
};
}
- const query = await db
+ const query = await db()
.select({
video: videos,
bucket: s3Buckets,
@@ -79,7 +74,7 @@ export async function transcribeVideo(
};
}
- await db
+ await db()
.update(videos)
.set({ transcriptionStatus: "PROCESSING" })
.where(eq(videos.id, videoId));
@@ -112,7 +107,7 @@ export async function transcribeVideo(
await s3Client.send(uploadCommand);
- await db
+ await db()
.update(videos)
.set({ transcriptionStatus: "COMPLETE" })
.where(eq(videos.id, videoId));
@@ -122,7 +117,7 @@ export async function transcribeVideo(
message: "VTT file generated and uploaded successfully",
};
} catch (error) {
- await db
+ await db()
.update(videos)
.set({ transcriptionStatus: "ERROR" })
.where(eq(videos.id, videoId));
@@ -179,7 +174,7 @@ function formatTimestamp(seconds: number): string {
}
async function transcribeAudio(videoUrl: string): Promise<string> {
- const deepgram = createClient(serverEnv.DEEPGRAM_API_KEY as string);
+ const deepgram = createClient(serverEnv().DEEPGRAM_API_KEY as string);
const { result, error } = await deepgram.listen.prerecorded.transcribeUrl(
{
@@ -201,4 +196,4 @@ async function transcribeAudio(videoUrl: string): Promise<string> {
const captions = formatToWebVTT(result);
return captions;
-}
\ No newline at end of file
+}
diff --git a/apps/web/actions/workspace/check-domain.ts b/apps/web/actions/workspace/check-domain.ts
index 8fdb64b13..b8acc4ca8 100644
--- a/apps/web/actions/workspace/check-domain.ts
+++ b/apps/web/actions/workspace/check-domain.ts
@@ -1,4 +1,4 @@
-'use server';
+"use server";
import { getCurrentUser } from "@cap/database/auth/session";
import { spaces } from "@cap/database/schema";
@@ -13,7 +13,10 @@ export async function checkWorkspaceDomain(spaceId: string) {
throw new Error("Unauthorized");
}
- const [space] = await db.select().from(spaces).where(eq(spaces.id, spaceId));
+ const [space] = await db()
+ .select()
+ .from(spaces)
+ .where(eq(spaces.id, spaceId));
if (!space || space.ownerId !== user.id) {
throw new Error("Only the owner can check domain status");
@@ -27,14 +30,14 @@ export async function checkWorkspaceDomain(spaceId: string) {
const status = await checkDomainStatus(space.customDomain);
if (status.verified && !space.domainVerified) {
- await db
+ await db()
.update(spaces)
.set({
domainVerified: new Date(),
})
.where(eq(spaces.id, spaceId));
} else if (!status.verified && space.domainVerified) {
- await db
+ await db()
.update(spaces)
.set({
domainVerified: null,
@@ -49,4 +52,4 @@ export async function checkWorkspaceDomain(spaceId: string) {
}
throw new Error("Failed to check domain status");
}
-}
\ No newline at end of file
+}
diff --git a/apps/web/actions/workspace/get-space.ts b/apps/web/actions/workspace/get-space.ts
index 8ea9b235e..32f5b2fb0 100644
--- a/apps/web/actions/workspace/get-space.ts
+++ b/apps/web/actions/workspace/get-space.ts
@@ -9,7 +9,7 @@ export async function getSpace(spaceId: string) {
throw new Error("Space ID is required");
}
- const [space] = await db
+ const [space] = await db()
.select({
workosOrganizationId: spaces.workosOrganizationId,
workosConnectionId: spaces.workosConnectionId,
@@ -27,4 +27,4 @@ export async function getSpace(spaceId: string) {
connectionId: space.workosConnectionId,
name: space.name,
};
-}
\ No newline at end of file
+}
diff --git a/apps/web/actions/workspace/manage-billing.ts b/apps/web/actions/workspace/manage-billing.ts
index 6f91cb77d..c93a8f238 100644
--- a/apps/web/actions/workspace/manage-billing.ts
+++ b/apps/web/actions/workspace/manage-billing.ts
@@ -1,11 +1,11 @@
-'use server';
+"use server";
import { stripe } from "@cap/utils";
import { getCurrentUser } from "@cap/database/auth/session";
import { eq } from "drizzle-orm";
import { db } from "@cap/database";
import { users } from "@cap/database/schema";
-import { clientEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
export async function manageBilling() {
const user = await getCurrentUser();
@@ -16,14 +16,14 @@ export async function manageBilling() {
}
if (!user.stripeCustomerId) {
- const customer = await stripe.customers.create({
+ const customer = await stripe().customers.create({
email: user.email,
metadata: {
userId: user.id,
},
});
- await db
+ await db()
.update(users)
.set({
stripeCustomerId: customer.id,
@@ -33,10 +33,10 @@ export async function manageBilling() {
customerId = customer.id;
}
- const { url } = await stripe.billingPortal.sessions.create({
+ const { url } = await stripe().billingPortal.sessions.create({
customer: customerId as string,
- return_url: `${clientEnv.NEXT_PUBLIC_WEB_URL}/dashboard/settings/workspace`,
+ return_url: `${serverEnv().WEB_URL}/dashboard/settings/workspace`,
});
-
+
return url;
-}
\ No newline at end of file
+}
diff --git a/apps/web/actions/workspace/remove-domain.ts b/apps/web/actions/workspace/remove-domain.ts
index ec8196905..a7de90654 100644
--- a/apps/web/actions/workspace/remove-domain.ts
+++ b/apps/web/actions/workspace/remove-domain.ts
@@ -1,4 +1,4 @@
-'use server';
+"use server";
import { getCurrentUser } from "@cap/database/auth/session";
import { spaces } from "@cap/database/schema";
@@ -13,7 +13,10 @@ export async function removeWorkspaceDomain(spaceId: string) {
throw new Error("Unauthorized");
}
- const [space] = await db.select().from(spaces).where(eq(spaces.id, spaceId));
+ const [space] = await db()
+ .select()
+ .from(spaces)
+ .where(eq(spaces.id, spaceId));
if (!space || space.ownerId !== user.id) {
throw new Error("Only the owner can remove the custom domain");
@@ -36,7 +39,7 @@ export async function removeWorkspaceDomain(spaceId: string) {
);
}
- await db
+ await db()
.update(spaces)
.set({
customDomain: null,
@@ -44,8 +47,8 @@ export async function removeWorkspaceDomain(spaceId: string) {
})
.where(eq(spaces.id, spaceId));
- revalidatePath('/dashboard/settings/workspace');
-
+ revalidatePath("/dashboard/settings/workspace");
+
return { success: true };
} catch (error) {
if (error instanceof Error) {
@@ -53,4 +56,4 @@ export async function removeWorkspaceDomain(spaceId: string) {
}
throw new Error("Failed to remove domain");
}
-}
\ No newline at end of file
+}
diff --git a/apps/web/actions/workspace/remove-invite.ts b/apps/web/actions/workspace/remove-invite.ts
index 58d0e2f95..6e04c2ab5 100644
--- a/apps/web/actions/workspace/remove-invite.ts
+++ b/apps/web/actions/workspace/remove-invite.ts
@@ -1,4 +1,4 @@
-'use server';
+"use server";
import { getCurrentUser } from "@cap/database/auth/session";
import { spaces, spaceInvites } from "@cap/database/schema";
@@ -6,17 +6,14 @@ import { db } from "@cap/database";
import { eq, and } from "drizzle-orm";
import { revalidatePath } from "next/cache";
-export async function removeWorkspaceInvite(
- inviteId: string,
- spaceId: string
-) {
+export async function removeWorkspaceInvite(inviteId: string, spaceId: string) {
const user = await getCurrentUser();
if (!user) {
throw new Error("Unauthorized");
}
- const space = await db
+ const space = await db()
.select()
.from(spaces)
.where(eq(spaces.id, spaceId))
@@ -30,7 +27,7 @@ export async function removeWorkspaceInvite(
throw new Error("Only the owner can remove workspace invites");
}
- const result = await db
+ const result = await db()
.delete(spaceInvites)
.where(
and(eq(spaceInvites.id, inviteId), eq(spaceInvites.spaceId, spaceId))
@@ -40,7 +37,7 @@ export async function removeWorkspaceInvite(
throw new Error("Invite not found");
}
- revalidatePath('/dashboard/settings/workspace');
-
+ revalidatePath("/dashboard/settings/workspace");
+
return { success: true };
-}
\ No newline at end of file
+}
diff --git a/apps/web/actions/workspace/send-invites.ts b/apps/web/actions/workspace/send-invites.ts
index 5ce774527..d8fc1ec3e 100644
--- a/apps/web/actions/workspace/send-invites.ts
+++ b/apps/web/actions/workspace/send-invites.ts
@@ -1,4 +1,4 @@
-'use server';
+"use server";
import { getCurrentUser } from "@cap/database/auth/session";
import { spaces, spaceInvites } from "@cap/database/schema";
@@ -7,7 +7,7 @@ import { eq } from "drizzle-orm";
import { nanoId } from "@cap/database/helpers";
import { sendEmail } from "@cap/database/emails/config";
import { WorkspaceInvite } from "@cap/database/emails/workspace-invite";
-import { clientEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
import { revalidatePath } from "next/cache";
export async function sendWorkspaceInvites(
@@ -20,7 +20,7 @@ export async function sendWorkspaceInvites(
throw new Error("Unauthorized");
}
- const space = await db.select().from(spaces).where(eq(spaces.id, spaceId));
+ const space = await db().select().from(spaces).where(eq(spaces.id, spaceId));
if (!space || space.length === 0) {
throw new Error("Workspace not found");
@@ -37,7 +37,7 @@ export async function sendWorkspaceInvites(
for (const email of validEmails) {
const inviteId = nanoId();
- await db.insert(spaceInvites).values({
+ await db().insert(spaceInvites).values({
id: inviteId,
spaceId: spaceId,
invitedEmail: email.trim(),
@@ -46,7 +46,7 @@ export async function sendWorkspaceInvites(
});
// Send invitation email
- const inviteUrl = `${clientEnv.NEXT_PUBLIC_WEB_URL}/invite/${inviteId}`;
+ const inviteUrl = `${serverEnv().WEB_URL}/invite/${inviteId}`;
await sendEmail({
email: email.trim(),
subject: `Invitation to join ${space[0].name} on Cap`,
@@ -58,7 +58,7 @@ export async function sendWorkspaceInvites(
});
}
- revalidatePath('/dashboard/settings/workspace');
-
+ revalidatePath("/dashboard/settings/workspace");
+
return { success: true };
-}
\ No newline at end of file
+}
diff --git a/apps/web/actions/workspace/update-details.ts b/apps/web/actions/workspace/update-details.ts
index 20632818b..513cab465 100644
--- a/apps/web/actions/workspace/update-details.ts
+++ b/apps/web/actions/workspace/update-details.ts
@@ -1,4 +1,4 @@
-'use server';
+"use server";
import { getCurrentUser } from "@cap/database/auth/session";
import { spaces } from "@cap/database/schema";
@@ -17,7 +17,7 @@ export async function updateWorkspaceDetails(
throw new Error("Unauthorized");
}
- const space = await db.select().from(spaces).where(eq(spaces.id, spaceId));
+ const space = await db().select().from(spaces).where(eq(spaces.id, spaceId));
if (!space || space.length === 0) {
throw new Error("Workspace not found");
@@ -27,7 +27,7 @@ export async function updateWorkspaceDetails(
throw new Error("Only the owner can update workspace details");
}
- await db
+ await db()
.update(spaces)
.set({
name: workspaceName,
@@ -35,7 +35,7 @@ export async function updateWorkspaceDetails(
})
.where(eq(spaces.id, spaceId));
- revalidatePath('/dashboard/settings/workspace');
-
+ revalidatePath("/dashboard/settings/workspace");
+
return { success: true };
-}
\ No newline at end of file
+}
diff --git a/apps/web/actions/workspace/update-domain.ts b/apps/web/actions/workspace/update-domain.ts
index c648deadc..664c865ec 100644
--- a/apps/web/actions/workspace/update-domain.ts
+++ b/apps/web/actions/workspace/update-domain.ts
@@ -1,4 +1,4 @@
-'use server';
+"use server";
import { getCurrentUser } from "@cap/database/auth/session";
import { spaces } from "@cap/database/schema";
@@ -14,7 +14,10 @@ export async function updateDomain(domain: string, spaceId: string) {
throw new Error("Unauthorized");
}
- const [space] = await db.select().from(spaces).where(eq(spaces.id, spaceId));
+ const [space] = await db()
+ .select()
+ .from(spaces)
+ .where(eq(spaces.id, spaceId));
if (!space || space.ownerId !== user.id) {
throw new Error("Only the owner can update the custom domain");
@@ -27,7 +30,7 @@ export async function updateDomain(domain: string, spaceId: string) {
throw new Error(addDomainResponse.error.message);
}
- await db
+ await db()
.update(spaces)
.set({
customDomain: domain,
@@ -38,7 +41,7 @@ export async function updateDomain(domain: string, spaceId: string) {
const status = await checkDomainStatus(domain);
if (status.verified) {
- await db
+ await db()
.update(spaces)
.set({
domainVerified: new Date(),
@@ -46,8 +49,8 @@ export async function updateDomain(domain: string, spaceId: string) {
.where(eq(spaces.id, spaceId));
}
- revalidatePath('/dashboard/settings/workspace');
-
+ revalidatePath("/dashboard/settings/workspace");
+
return status;
} catch (error) {
if (error instanceof Error) {
@@ -55,4 +58,4 @@ export async function updateDomain(domain: string, spaceId: string) {
}
throw new Error("Failed to update domain");
}
-}
\ No newline at end of file
+}
diff --git a/apps/web/app/AuthProvider.tsx b/apps/web/app/AuthProvider.tsx
index bb80a6258..f22904e22 100644
--- a/apps/web/app/AuthProvider.tsx
+++ b/apps/web/app/AuthProvider.tsx
@@ -1,7 +1,8 @@
"use client";
import { SessionProvider } from "next-auth/react";
+import { PropsWithChildren } from "react";
-export function AuthProvider({ children }: { children: React.ReactNode }) {
+export function AuthProvider({ children }: PropsWithChildren) {
return <SessionProvider>{children}</SessionProvider>;
}
diff --git a/apps/web/app/[slug]/layout.tsx b/apps/web/app/[slug]/layout.tsx
index a14e64fcd..5ff842ef0 100644
--- a/apps/web/app/[slug]/layout.tsx
+++ b/apps/web/app/[slug]/layout.tsx
@@ -1,16 +1,16 @@
export const metadata = {
- title: 'Next.js',
- description: 'Generated by Next.js',
-}
+ title: "Next.js",
+ description: "Generated by Next.js",
+};
export default function RootLayout({
children,
}: {
- children: React.ReactNode
+ children: React.ReactNode;
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
- )
+ );
}
diff --git a/apps/web/app/api/auth/[...nextauth]/route.ts b/apps/web/app/api/auth/[...nextauth]/route.ts
index 565ccb6cb..07032156a 100644
--- a/apps/web/app/api/auth/[...nextauth]/route.ts
+++ b/apps/web/app/api/auth/[...nextauth]/route.ts
@@ -1,6 +1,8 @@
import NextAuth from "next-auth";
import { authOptions } from "@cap/database/auth/auth-options";
-const handler = NextAuth(authOptions);
+export const dynamic = "force-dynamic";
+
+const handler = NextAuth(authOptions());
export { handler as GET, handler as POST };
diff --git a/apps/web/app/api/caps/share/route.ts b/apps/web/app/api/caps/share/route.ts
index e596bbf66..b53c33bec 100644
--- a/apps/web/app/api/caps/share/route.ts
+++ b/apps/web/app/api/caps/share/route.ts
@@ -15,13 +15,13 @@ export async function POST(request: NextRequest) {
try {
// Check if the user owns the cap
- const [cap] = await db.select().from(videos).where(eq(videos.id, capId));
+ const [cap] = await db().select().from(videos).where(eq(videos.id, capId));
if (!cap || cap.ownerId !== user.id) {
return NextResponse.json({ error: "Unauthorized" }, { status: 403 });
}
// Get current shared spaces
- const currentSharedSpaces = await db
+ const currentSharedSpaces = await db()
.select()
.from(sharedVideos)
.where(eq(sharedVideos.videoId, capId));
@@ -29,7 +29,7 @@ export async function POST(request: NextRequest) {
// Remove spaces that are no longer shared
for (const sharedSpace of currentSharedSpaces) {
if (!spaceIds.includes(sharedSpace.spaceId)) {
- await db
+ await db()
.delete(sharedVideos)
.where(
and(
@@ -46,7 +46,7 @@ export async function POST(request: NextRequest) {
(share) => share.spaceId === spaceId
);
if (!existingShare) {
- await db.insert(sharedVideos).values({
+ await db().insert(sharedVideos).values({
id: nanoId(),
videoId: capId,
spaceId: spaceId,
diff --git a/apps/web/app/api/changelog/status/route.ts b/apps/web/app/api/changelog/status/route.ts
index 339683bf8..d5a84f4ee 100644
--- a/apps/web/app/api/changelog/status/route.ts
+++ b/apps/web/app/api/changelog/status/route.ts
@@ -1,7 +1,6 @@
import { NextResponse } from "next/server";
import { getChangelogPosts } from "../../../../utils/changelog";
-export const dynamic = "force-dynamic";
export const revalidate = 0;
export async function GET(request: Request) {
diff --git a/apps/web/app/api/desktop/app.ts b/apps/web/app/api/desktop/app.ts
index 4ab2f67b2..cf06101c3 100644
--- a/apps/web/app/api/desktop/app.ts
+++ b/apps/web/app/api/desktop/app.ts
@@ -1,4 +1,4 @@
-import { clientEnv, serverEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
import { Hono } from "hono";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";
@@ -19,7 +19,7 @@ app.post(
try {
// Send feedback to Discord channel
- const discordWebhookUrl = serverEnv.DISCORD_FEEDBACK_WEBHOOK_URL;
+ const discordWebhookUrl = serverEnv().DISCORD_FEEDBACK_WEBHOOK_URL;
if (!discordWebhookUrl)
throw new Error("Discord webhook URL is not configured");
@@ -60,7 +60,7 @@ app.get("/plan", async (c) => {
if (!isSubscribed && !user.stripeSubscriptionId && user.stripeCustomerId) {
try {
- const subscriptions = await stripe.subscriptions.list({
+ const subscriptions = await stripe().subscriptions.list({
customer: user.stripeCustomerId,
});
const activeSubscription = subscriptions.data.find(
@@ -68,7 +68,7 @@ app.get("/plan", async (c) => {
);
if (activeSubscription) {
isSubscribed = true;
- await db
+ await db()
.update(users)
.set({
stripeSubscriptionStatus: activeSubscription.status,
@@ -82,9 +82,10 @@ app.get("/plan", async (c) => {
}
let intercomHash = "";
- if (serverEnv.INTERCOM_SECRET) {
+ const intercomSecret = serverEnv().INTERCOM_SECRET;
+ if (intercomSecret) {
intercomHash = crypto
- .createHmac("sha256", serverEnv.INTERCOM_SECRET)
+ .createHmac("sha256", intercomSecret)
.update(user?.id ?? "")
.digest("hex");
}
@@ -114,12 +115,12 @@ app.post(
if (user.stripeCustomerId === null) {
console.log("[POST] Creating new Stripe customer");
- const customer = await stripe.customers.create({
+ const customer = await stripe().customers.create({
email: user.email,
metadata: { userId: user.id },
});
- await db
+ await db()
.update(users)
.set({ stripeCustomerId: customer.id })
.where(eq(users.id, user.id));
@@ -129,12 +130,12 @@ app.post(
}
console.log("[POST] Creating checkout session");
- const checkoutSession = await stripe.checkout.sessions.create({
+ const checkoutSession = await stripe().checkout.sessions.create({
customer: customerId as string,
line_items: [{ price: priceId, quantity: 1 }],
mode: "subscription",
- success_url: `${clientEnv.NEXT_PUBLIC_WEB_URL}/dashboard/caps?upgrade=true`,
- cancel_url: `${clientEnv.NEXT_PUBLIC_WEB_URL}/pricing`,
+ success_url: `${serverEnv().WEB_URL}/dashboard/caps?upgrade=true`,
+ cancel_url: `${serverEnv().WEB_URL}/pricing`,
allow_promotion_codes: true,
});
diff --git a/apps/web/app/api/desktop/s3/config/app.ts b/apps/web/app/api/desktop/s3/config/app.ts
index 4d00abc94..67af6a2cc 100644
--- a/apps/web/app/api/desktop/s3/config/app.ts
+++ b/apps/web/app/api/desktop/s3/config/app.ts
@@ -42,20 +42,20 @@ app.post(
};
// Check if user already has a bucket config
- const [existingBucket] = await db
+ const [existingBucket] = await db()
.select()
.from(s3Buckets)
.where(eq(s3Buckets.ownerId, user.id));
if (existingBucket) {
// Update existing config
- await db
+ await db()
.update(s3Buckets)
.set(encryptedConfig)
.where(eq(s3Buckets.id, existingBucket.id));
} else {
// Insert new config
- await db.insert(s3Buckets).values(encryptedConfig);
+ await db().insert(s3Buckets).values(encryptedConfig);
}
return c.json({ success: true });
@@ -77,7 +77,7 @@ app.delete("/delete", async (c) => {
try {
// Delete the S3 configuration for the user
- await db.delete(s3Buckets).where(eq(s3Buckets.ownerId, user.id));
+ await db().delete(s3Buckets).where(eq(s3Buckets.ownerId, user.id));
return c.json({ success: true });
} catch (error) {
@@ -96,7 +96,7 @@ app.get("/get", async (c) => {
const user = c.get("user");
try {
- const [bucket] = await db
+ const [bucket] = await db()
.select()
.from(s3Buckets)
.where(eq(s3Buckets.ownerId, user.id));
diff --git a/apps/web/app/api/desktop/session/app.ts b/apps/web/app/api/desktop/session/app.ts
index e733e97f2..800cada4a 100644
--- a/apps/web/app/api/desktop/session/app.ts
+++ b/apps/web/app/api/desktop/session/app.ts
@@ -1,6 +1,6 @@
import { authOptions } from "@cap/database/auth/auth-options";
import { getCurrentUser } from "@cap/database/auth/session";
-import { clientEnv, serverEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import { getCookie } from "hono/cookie";
@@ -24,12 +24,14 @@ app.get(
async (c) => {
const { port, platform } = c.req.valid("query");
- const secret = serverEnv.NEXTAUTH_SECRET;
+ const secret = serverEnv().NEXTAUTH_SECRET;
const url = new URL(c.req.url);
- const loginRedirectUrl = `${clientEnv.NEXT_PUBLIC_WEB_URL}/login?next=${clientEnv.NEXT_PUBLIC_WEB_URL}${url.pathname}${url.search}`;
+ const loginRedirectUrl = `${serverEnv().WEB_URL}/login?next=${
+ serverEnv().WEB_URL
+ }${url.pathname}${url.search}`;
- const session = await getServerSession(authOptions);
+ const session = await getServerSession(authOptions());
if (!session) return c.redirect(loginRedirectUrl);
const token = getCookie(c, "next-auth.session-token");
diff --git a/apps/web/app/api/desktop/video/app.ts b/apps/web/app/api/desktop/video/app.ts
index 4b2aa4ecd..70748525f 100644
--- a/apps/web/app/api/desktop/video/app.ts
+++ b/apps/web/app/api/desktop/video/app.ts
@@ -5,7 +5,7 @@ import { sendEmail } from "@cap/database/emails/config";
import { FirstShareableLink } from "@cap/database/emails/first-shareable-link";
import { nanoId } from "@cap/database/helpers";
import { s3Buckets, videos } from "@cap/database/schema";
-import { clientEnv, NODE_ENV } from "@cap/env";
+import { buildEnv, NODE_ENV, serverEnv } from "@cap/env";
import { zValidator } from "@hono/zod-validator";
import { count, eq } from "drizzle-orm";
import { Hono } from "hono";
@@ -39,7 +39,7 @@ app.get(
if (!isUpgraded && duration && duration > 300)
return c.json({ error: "upgrade_required" }, { status: 403 });
- const [bucket] = await db
+ const [bucket] = await db()
.select()
.from(s3Buckets)
.where(eq(s3Buckets.ownerId, user.id));
@@ -53,7 +53,7 @@ app.get(
})} ${date.getFullYear()}`;
if (videoId !== undefined) {
- const [video] = await db
+ const [video] = await db()
.select()
.from(videos)
.where(eq(videos.id, videoId));
@@ -88,18 +88,18 @@ app.get(
bucket: bucket?.id,
};
- await db.insert(videos).values(videoData);
+ await db().insert(videos).values(videoData);
- if (clientEnv.NEXT_PUBLIC_IS_CAP && NODE_ENV === "production")
- await dub.links.create({
- url: `${clientEnv.NEXT_PUBLIC_WEB_URL}/s/${idToUse}`,
+ if (buildEnv.NEXT_PUBLIC_IS_CAP && NODE_ENV === "production")
+ await dub().links.create({
+ url: `${serverEnv().WEB_URL}/s/${idToUse}`,
domain: "cap.link",
key: idToUse,
});
// Check if this is the user's first video and send the first shareable link email
try {
- const videoCount = await db
+ const videoCount = await db()
.select({ count: count() })
.from(videos)
.where(eq(videos.ownerId, user.id));
@@ -114,9 +114,9 @@ app.get(
"[SendFirstShareableLinkEmail] Sending first shareable link email with 5-minute delay"
);
- const videoUrl = clientEnv.NEXT_PUBLIC_IS_CAP
+ const videoUrl = buildEnv.NEXT_PUBLIC_IS_CAP
? `https://cap.link/${idToUse}`
- : `${clientEnv.NEXT_PUBLIC_WEB_URL}/s/${idToUse}`;
+ : `${serverEnv().WEB_URL}/s/${idToUse}`;
// Send email with 5-minute delay using Resend's scheduling feature
await sendEmail({
diff --git a/apps/web/app/api/email/new-comment/route.ts b/apps/web/app/api/email/new-comment/route.ts
index 0e12f8e73..134e8ddfb 100644
--- a/apps/web/app/api/email/new-comment/route.ts
+++ b/apps/web/app/api/email/new-comment/route.ts
@@ -5,7 +5,7 @@ import { db } from "@cap/database";
import { eq, and, gt, ne } from "drizzle-orm";
import { sendEmail } from "@cap/database/emails/config";
import { NewComment } from "@cap/database/emails/new-comment";
-import { clientEnv } from "@cap/env";
+import { buildEnv, serverEnv } from "@cap/env";
// Cache to store the last email sent time for each user
const lastEmailSentCache = new Map<string, Date>();
@@ -25,7 +25,7 @@ export async function POST(request: NextRequest) {
try {
console.log(`Fetching comment details for commentId: ${commentId}`);
// Get the comment details
- const commentDetails = await db
+ const commentDetails = await db()
.select({
id: comments.id,
content: comments.content,
@@ -68,7 +68,7 @@ export async function POST(request: NextRequest) {
console.log(`Fetching video details for videoId: ${comment.videoId}`);
// Get the video details
- const videoDetails = await db
+ const videoDetails = await db()
.select({
id: videos.id,
name: videos.name,
@@ -97,7 +97,7 @@ export async function POST(request: NextRequest) {
console.log(`Fetching owner details for userId: ${video.ownerId}`);
// Get the video owner's email
- const ownerDetails = await db
+ const ownerDetails = await db()
.select({
id: users.id,
email: users.email,
@@ -128,7 +128,7 @@ export async function POST(request: NextRequest) {
let commenterName = "Anonymous";
if (comment.authorId) {
console.log(`Fetching commenter details for userId: ${comment.authorId}`);
- const commenterDetails = await db
+ const commenterDetails = await db()
.select({
id: users.id,
name: users.name,
@@ -178,7 +178,7 @@ export async function POST(request: NextRequest) {
console.log(
`Checking for recent comments since ${fifteenMinutesAgo.toISOString()}`
);
- const recentComments = await db
+ const recentComments = await db()
.select({
id: comments.id,
})
@@ -205,9 +205,9 @@ export async function POST(request: NextRequest) {
}
// Generate the video URL
- const videoUrl = clientEnv.NEXT_PUBLIC_IS_CAP
+ const videoUrl = buildEnv.NEXT_PUBLIC_IS_CAP
? `https://cap.link/${video.id}`
- : `${clientEnv.NEXT_PUBLIC_WEB_URL}/s/${video.id}`;
+ : `${serverEnv().WEB_URL}/s/${video.id}`;
console.log(`Generated video URL: ${videoUrl}`);
// Send the email
diff --git a/apps/web/app/api/invite/accept/route.ts b/apps/web/app/api/invite/accept/route.ts
index 404f32dce..d3e2e7170 100644
--- a/apps/web/app/api/invite/accept/route.ts
+++ b/apps/web/app/api/invite/accept/route.ts
@@ -15,7 +15,7 @@ export async function POST(request: NextRequest) {
try {
// Find the invite
- const [invite] = await db
+ const [invite] = await db()
.select()
.from(spaceInvites)
.where(eq(spaceInvites.id, inviteId));
@@ -30,7 +30,7 @@ export async function POST(request: NextRequest) {
}
// Get the space owner's subscription ID
- const [spaceOwner] = await db
+ const [spaceOwner] = await db()
.select({
stripeSubscriptionId: users.stripeSubscriptionId,
})
@@ -45,7 +45,7 @@ export async function POST(request: NextRequest) {
}
// Create a new space member
- await db.insert(spaceMembers).values({
+ await db().insert(spaceMembers).values({
id: nanoId(),
spaceId: invite.spaceId,
userId: user.id,
@@ -53,7 +53,7 @@ export async function POST(request: NextRequest) {
});
// Update the user's thirdPartyStripeSubscriptionId
- await db
+ await db()
.update(users)
.set({
thirdPartyStripeSubscriptionId: spaceOwner.stripeSubscriptionId,
@@ -61,7 +61,7 @@ export async function POST(request: NextRequest) {
.where(eq(users.id, user.id));
// Delete the invite
- await db.delete(spaceInvites).where(eq(spaceInvites.id, inviteId));
+ await db().delete(spaceInvites).where(eq(spaceInvites.id, inviteId));
return NextResponse.json({ success: true });
} catch (error) {
diff --git a/apps/web/app/api/invite/decline/route.ts b/apps/web/app/api/invite/decline/route.ts
index b0b995b64..26c5caa22 100644
--- a/apps/web/app/api/invite/decline/route.ts
+++ b/apps/web/app/api/invite/decline/route.ts
@@ -8,7 +8,7 @@ export async function POST(request: NextRequest) {
try {
// Delete the invite
- await db.delete(spaceInvites).where(eq(spaceInvites.id, inviteId));
+ await db().delete(spaceInvites).where(eq(spaceInvites.id, inviteId));
return NextResponse.json({ success: true });
} catch (error) {
diff --git a/apps/web/app/api/playlist/route.ts b/apps/web/app/api/playlist/route.ts
index 6ed96cb94..09b75e7a7 100644
--- a/apps/web/app/api/playlist/route.ts
+++ b/apps/web/app/api/playlist/route.ts
@@ -16,7 +16,7 @@ import {
import { getHeaders, CACHE_CONTROL_HEADERS } from "@/utils/helpers";
import { createS3Client, getS3Bucket } from "@/utils/s3";
import { S3_BUCKET_URL } from "@cap/utils";
-import { clientEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
export const revalidate = 3599;
@@ -48,7 +48,7 @@ export async function GET(request: NextRequest) {
);
}
- const query = await db
+ const query = await db()
.select({ video: videos, bucket: s3Buckets })
.from(videos)
.leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
@@ -83,7 +83,7 @@ export async function GET(request: NextRequest) {
const Bucket = await getS3Bucket(bucket);
const [s3Client] = await createS3Client(bucket);
- if (!bucket || video.awsBucket === clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET) {
+ if (!bucket || video.awsBucket === serverEnv().CAP_AWS_BUCKET) {
if (video.source.type === "desktopMP4") {
return new Response(null, {
status: 302,
@@ -283,9 +283,13 @@ export async function GET(request: NextRequest) {
const generatedPlaylist = await generateMasterPlaylist(
videoMetadata?.Metadata?.resolution ?? "",
videoMetadata?.Metadata?.bandwidth ?? "",
- `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/playlist?userId=${userId}&videoId=${videoId}&videoType=video`,
+ `${
+ serverEnv().WEB_URL
+ }/api/playlist?userId=${userId}&videoId=${videoId}&videoType=video`,
audioMetadata
- ? `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/playlist?userId=${userId}&videoId=${videoId}&videoType=audio`
+ ? `${
+ serverEnv().WEB_URL
+ }/api/playlist?userId=${userId}&videoId=${videoId}&videoType=audio`
: null,
video.xStreamInfo ?? ""
);
diff --git a/apps/web/app/api/revalidate/route.ts b/apps/web/app/api/revalidate/route.ts
index 2f24caad8..d6afc0645 100644
--- a/apps/web/app/api/revalidate/route.ts
+++ b/apps/web/app/api/revalidate/route.ts
@@ -21,7 +21,7 @@ export async function POST(request: NextRequest) {
});
}
- const [video] = await db
+ const [video] = await db()
.select()
.from(videos)
.where(eq(videos.id, videoId));
diff --git a/apps/web/app/api/screenshot/route.ts b/apps/web/app/api/screenshot/route.ts
new file mode 100644
index 000000000..f2badabea
--- /dev/null
+++ b/apps/web/app/api/screenshot/route.ts
@@ -0,0 +1,130 @@
+import { type NextRequest } from "next/server";
+import { db } from "@cap/database";
+import { s3Buckets, videos } from "@cap/database/schema";
+import { eq } from "drizzle-orm";
+import {
+ S3Client,
+ ListObjectsV2Command,
+ GetObjectCommand,
+} from "@aws-sdk/client-s3";
+import { getCurrentUser } from "@cap/database/auth/session";
+import { getHeaders } from "@/utils/helpers";
+import { createS3Client, getS3Bucket } from "@/utils/s3";
+import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
+import { S3_BUCKET_URL } from "@cap/utils";
+import { serverEnv } from "@cap/env";
+
+export const revalidate = 0;
+
+export async function OPTIONS(request: NextRequest) {
+ const origin = request.headers.get("origin") as string;
+
+ return new Response(null, {
+ status: 200,
+ headers: getHeaders(origin),
+ });
+}
+
+export async function GET(request: NextRequest) {
+ const searchParams = request.nextUrl.searchParams;
+ const userId = searchParams.get("userId") || "";
+ const videoId = searchParams.get("screenshotId") || "";
+ const origin = request.headers.get("origin") as string;
+
+ if (!userId || !videoId) {
+ return new Response(
+ JSON.stringify({
+ error: true,
+ message: "userId or videoId not supplied",
+ }),
+ { status: 401, headers: getHeaders(origin) }
+ );
+ }
+
+ const query = await db()
+ .select({ video: videos, bucket: s3Buckets })
+ .from(videos)
+ .leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
+ .where(eq(videos.id, videoId));
+
+ if (query.length === 0) {
+ return new Response(
+ JSON.stringify({ error: true, message: "Video does not exist" }),
+ { status: 401, headers: getHeaders(origin) }
+ );
+ }
+
+ const result = query[0];
+ if (!result?.video) {
+ return new Response(
+ JSON.stringify({ error: true, message: "Video not found" }),
+ { status: 401, headers: getHeaders(origin) }
+ );
+ }
+
+ const { video, bucket } = result;
+
+ if (video.public === false) {
+ const user = await getCurrentUser();
+
+ if (!user || user.id !== video.ownerId) {
+ return new Response(
+ JSON.stringify({ error: true, message: "Video is not public" }),
+ { status: 401, headers: getHeaders(origin) }
+ );
+ }
+ }
+
+ const Bucket = await getS3Bucket(bucket);
+ const screenshotPrefix = `${userId}/${videoId}/`;
+
+ try {
+ const [s3Client] = await createS3Client(bucket);
+
+ const objectsCommand = new ListObjectsV2Command({
+ Bucket,
+ Prefix: screenshotPrefix,
+ });
+
+ const objects = await s3Client.send(objectsCommand);
+
+ const screenshot = objects.Contents?.find((object) =>
+ object.Key?.endsWith(".png")
+ );
+
+ if (!screenshot) {
+ return new Response(
+ JSON.stringify({ error: true, message: "Screenshot not found" }),
+ { status: 404, headers: getHeaders(origin) }
+ );
+ }
+
+ let screenshotUrl: string;
+
+ if (video.awsBucket !== serverEnv().CAP_AWS_BUCKET) {
+ screenshotUrl = await getSignedUrl(
+ s3Client,
+ new GetObjectCommand({
+ Bucket,
+ Key: screenshot.Key,
+ }),
+ { expiresIn: 3600 }
+ );
+ } else {
+ screenshotUrl = `${S3_BUCKET_URL}/${screenshot.Key}`;
+ }
+
+ return new Response(JSON.stringify({ url: screenshotUrl }), {
+ status: 200,
+ headers: getHeaders(origin),
+ });
+ } catch (error) {
+ return new Response(
+ JSON.stringify({
+ error: error,
+ message: "Error generating screenshot URL",
+ }),
+ { status: 500, headers: getHeaders(origin) }
+ );
+ }
+}
diff --git a/apps/web/app/api/selfhosted/migrations/route.ts b/apps/web/app/api/selfhosted/migrations/route.ts
new file mode 100644
index 000000000..db28d63f0
--- /dev/null
+++ b/apps/web/app/api/selfhosted/migrations/route.ts
@@ -0,0 +1,50 @@
+import { NextResponse } from "next/server";
+import { db } from "@cap/database";
+import { migrate } from "drizzle-orm/mysql2/migrator";
+import path from "path";
+import { serverEnv } from "@cap/env";
+
+const migrations = {
+ run: false,
+};
+
+export async function POST() {
+ if (migrations.run) {
+ console.log(" ✅ DB migrations triggered but already run, skipping");
+ return NextResponse.json({
+ message: "✅ DB migrations already run, skipping",
+ });
+ }
+
+ const isDockerBuild = serverEnv().DOCKER_BUILD === "true";
+ if (isDockerBuild) {
+ try {
+ console.log("🔍 DB migrations triggered");
+ console.log("💿 Running DB migrations...");
+
+ await migrate(db() as any, {
+ migrationsFolder: path.join(process.cwd(), "/migrations"),
+ });
+ migrations.run = true;
+ console.log("💿 Migrations run successfully!");
+ return NextResponse.json({
+ message: "✅ DB migrations run successfully!",
+ });
+ } catch (error) {
+ console.error("🚨 MIGRATION_FAILED", { error });
+ return NextResponse.json(
+ {
+ message: "🚨 DB migrations failed",
+ error: error instanceof Error ? error.message : String(error),
+ },
+ { status: 500 }
+ );
+ }
+ }
+
+ migrations.run = true;
+
+ return NextResponse.json({
+ message: "DB migrations dont need to run in this environment",
+ });
+}
diff --git a/apps/web/app/api/settings/billing/manage/route.ts b/apps/web/app/api/settings/billing/manage/route.ts
index fdee85d6c..9c47b94c9 100644
--- a/apps/web/app/api/settings/billing/manage/route.ts
+++ b/apps/web/app/api/settings/billing/manage/route.ts
@@ -4,7 +4,7 @@ import { NextRequest, NextResponse } from "next/server";
import { eq } from "drizzle-orm";
import { db } from "@cap/database";
import { users } from "@cap/database/schema";
-import { clientEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
export async function POST(request: NextRequest) {
const user = await getCurrentUser();
@@ -17,14 +17,14 @@ export async function POST(request: NextRequest) {
}
if (!user.stripeCustomerId) {
- const customer = await stripe.customers.create({
+ const customer = await stripe().customers.create({
email: user.email,
metadata: {
userId: user.id,
},
});
- await db
+ await db()
.update(users)
.set({
stripeCustomerId: customer.id,
@@ -34,9 +34,9 @@ export async function POST(request: NextRequest) {
customerId = customer.id;
}
- const { url } = await stripe.billingPortal.sessions.create({
+ const { url } = await stripe().billingPortal.sessions.create({
customer: customerId as string,
- return_url: `${clientEnv.NEXT_PUBLIC_WEB_URL}/dashboard/settings/workspace`,
+ return_url: `${serverEnv().WEB_URL}/dashboard/settings/workspace`,
});
return NextResponse.json(url);
}
diff --git a/apps/web/app/api/settings/billing/quota/route.ts b/apps/web/app/api/settings/billing/quota/route.ts
deleted file mode 100644
index e69de29bb..000000000
diff --git a/apps/web/app/api/settings/billing/subscribe/route.ts b/apps/web/app/api/settings/billing/subscribe/route.ts
index ef98c6faa..9f617aac5 100644
--- a/apps/web/app/api/settings/billing/subscribe/route.ts
+++ b/apps/web/app/api/settings/billing/subscribe/route.ts
@@ -4,7 +4,7 @@ import { NextRequest } from "next/server";
import { eq } from "drizzle-orm";
import { db } from "@cap/database";
import { users } from "@cap/database/schema";
-import { clientEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
import posthog from "posthog-js";
export async function POST(request: NextRequest) {
@@ -47,7 +47,7 @@ export async function POST(request: NextRequest) {
if (!user.stripeCustomerId) {
console.log("Creating new Stripe customer for user:", user.id);
- const customer = await stripe.customers.create({
+ const customer = await stripe().customers.create({
email: user.email,
metadata: {
userId: user.id,
@@ -56,7 +56,7 @@ export async function POST(request: NextRequest) {
console.log("Created Stripe customer:", customer.id);
- await db
+ await db()
.update(users)
.set({
stripeCustomerId: customer.id,
@@ -68,12 +68,12 @@ export async function POST(request: NextRequest) {
}
console.log("Creating checkout session for customer:", customerId);
- const checkoutSession = await stripe.checkout.sessions.create({
+ const checkoutSession = await stripe().checkout.sessions.create({
customer: customerId as string,
line_items: [{ price: priceId, quantity: quantity }],
mode: "subscription",
- success_url: `${clientEnv.NEXT_PUBLIC_WEB_URL}/dashboard/caps?upgrade=true`,
- cancel_url: `${clientEnv.NEXT_PUBLIC_WEB_URL}/pricing`,
+ success_url: `${serverEnv().WEB_URL}/dashboard/caps?upgrade=true`,
+ cancel_url: `${serverEnv().WEB_URL}/pricing`,
allow_promotion_codes: true,
});
diff --git a/apps/web/app/api/settings/billing/usage/route.ts b/apps/web/app/api/settings/billing/usage/route.ts
index 2a0bb87e8..0452694e2 100644
--- a/apps/web/app/api/settings/billing/usage/route.ts
+++ b/apps/web/app/api/settings/billing/usage/route.ts
@@ -5,14 +5,16 @@ import { count, eq } from "drizzle-orm";
import { db } from "@cap/database";
import { videos } from "@cap/database/schema";
-export async function GET(request: NextRequest) {
+export const dynamic = "force-dynamic";
+
+export async function GET() {
const user = await getCurrentUser();
if (!user) {
return Response.json({ auth: false }, { status: 401 });
}
- const numberOfVideos = await db
+ const numberOfVideos = await db()
.select({ count: count() })
.from(videos)
.where(eq(videos.ownerId, user.id));
diff --git a/apps/web/app/api/settings/onboarding/route.ts b/apps/web/app/api/settings/onboarding/route.ts
index 434908db3..4e1e37453 100644
--- a/apps/web/app/api/settings/onboarding/route.ts
+++ b/apps/web/app/api/settings/onboarding/route.ts
@@ -15,7 +15,7 @@ export async function POST(request: NextRequest) {
return Response.json({ error: true }, { status: 401 });
}
- await db
+ await db()
.update(users)
.set({
name: firstName,
@@ -28,7 +28,7 @@ export async function POST(request: NextRequest) {
fullName += ` ${lastName}`;
}
- const [space] = await db
+ const [space] = await db()
.select()
.from(spaces)
.where(or(eq(spaces.ownerId, user.id), eq(spaceMembers.userId, user.id)))
@@ -37,20 +37,22 @@ export async function POST(request: NextRequest) {
if (!space) {
const spaceId = nanoId();
- await db.insert(spaces).values({
- id: spaceId,
- ownerId: user.id,
- name: `${fullName}'s Space`,
- });
+ await db()
+ .insert(spaces)
+ .values({
+ id: spaceId,
+ ownerId: user.id,
+ name: `${fullName}'s Space`,
+ });
- await db.insert(spaceMembers).values({
+ await db().insert(spaceMembers).values({
id: nanoId(),
userId: user.id,
role: "owner",
spaceId,
});
- await db
+ await db()
.update(users)
.set({ activeSpaceId: spaceId })
.where(eq(users.id, user.id));
diff --git a/apps/web/app/api/settings/user/name/route.ts b/apps/web/app/api/settings/user/name/route.ts
index 70de72548..3f2c51d5b 100644
--- a/apps/web/app/api/settings/user/name/route.ts
+++ b/apps/web/app/api/settings/user/name/route.ts
@@ -14,7 +14,7 @@ export async function POST(request: NextRequest) {
return Response.json({ error: true }, { status: 401 });
}
- await db
+ await db()
.update(users)
.set({
name: firstName,
diff --git a/apps/web/app/api/thumbnail/route.ts b/apps/web/app/api/thumbnail/route.ts
index 4972769b2..6bc4af261 100644
--- a/apps/web/app/api/thumbnail/route.ts
+++ b/apps/web/app/api/thumbnail/route.ts
@@ -7,7 +7,7 @@ import { s3Buckets, videos } from "@cap/database/schema";
import { createS3Client, getS3Bucket } from "@/utils/s3";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
import { S3_BUCKET_URL } from "@cap/utils";
-import { clientEnv } from "@cap/env";
+import { buildEnv, serverEnv } from "@cap/env";
export const revalidate = 0;
@@ -30,7 +30,7 @@ export async function GET(request: NextRequest) {
);
}
- const query = await db
+ const query = await db()
.select({
video: videos,
bucket: s3Buckets,
@@ -65,10 +65,7 @@ export async function GET(request: NextRequest) {
let thumbnailUrl: string;
- if (
- !result.bucket ||
- video.awsBucket === clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET
- ) {
+ if (!result.bucket || video.awsBucket === serverEnv().CAP_AWS_BUCKET) {
thumbnailUrl = `${S3_BUCKET_URL}/${prefix}screenshot/screen-capture.jpg`;
return new Response(JSON.stringify({ screen: thumbnailUrl }), {
status: 200,
@@ -77,7 +74,7 @@ export async function GET(request: NextRequest) {
}
const Bucket = await getS3Bucket(result.bucket);
- const s3Client = await createS3Client(result.bucket);
+ const [s3Client] = await createS3Client(result.bucket);
try {
const listCommand = new ListObjectsV2Command({
diff --git a/apps/web/app/api/upload/multipart/[...route]/route.ts b/apps/web/app/api/upload/multipart/[...route]/route.ts
index a968557db..719f48280 100644
--- a/apps/web/app/api/upload/multipart/[...route]/route.ts
+++ b/apps/web/app/api/upload/multipart/[...route]/route.ts
@@ -13,7 +13,7 @@ import { eq } from "drizzle-orm";
import { zValidator } from "@hono/zod-validator";
import { z } from "zod";
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
-import { clientEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
import { handle } from "hono/vercel";
import { withAuth, corsMiddleware } from "@/app/api/utils";
@@ -265,7 +265,7 @@ app.post(
const videoId = fileKey.split("/")[1];
if (videoId) {
try {
- await fetch(`${clientEnv.NEXT_PUBLIC_WEB_URL}/api/revalidate`, {
+ await fetch(`${serverEnv().WEB_URL}/api/revalidate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@ -322,7 +322,7 @@ app.post(
);
async function getUserBucketWithClient(userId: string) {
- const [bucket] = await db
+ const [bucket] = await db()
.select()
.from(s3Buckets)
.where(eq(s3Buckets.ownerId, userId));
diff --git a/apps/web/app/api/upload/mux/create/route.ts b/apps/web/app/api/upload/mux/create/route.ts
index ffa5289d3..191b2f2fc 100644
--- a/apps/web/app/api/upload/mux/create/route.ts
+++ b/apps/web/app/api/upload/mux/create/route.ts
@@ -8,10 +8,10 @@ import {
CreateJobCommand,
} from "@aws-sdk/client-mediaconvert";
import { createS3Client, getS3Bucket } from "@/utils/s3";
-import { serverEnv, clientEnv } from "@cap/env";
+import { serverEnv, buildEnv } from "@cap/env";
const allowedOrigins = [
- clientEnv.NEXT_PUBLIC_WEB_URL,
+ buildEnv.NEXT_PUBLIC_WEB_URL,
"http://localhost:3001",
"tauri://localhost",
"http://tauri.localhost",
@@ -66,7 +66,7 @@ export async function GET(request: NextRequest) {
);
}
- const query = await db
+ const query = await db()
.select({
video: videos,
bucket: s3Buckets,
@@ -148,7 +148,7 @@ export async function GET(request: NextRequest) {
);
if (videoSegmentKeys.length > 149) {
- await db
+ await db()
.update(videos)
.set({ skipProcessing: true })
.where(eq(videos.id, videoId));
@@ -174,17 +174,17 @@ export async function GET(request: NextRequest) {
);
const mediaConvertClient = new MediaConvertClient({
- region: clientEnv.NEXT_PUBLIC_CAP_AWS_REGION || "",
+ region: serverEnv().CAP_AWS_REGION || "",
credentials: {
- accessKeyId: serverEnv.CAP_AWS_ACCESS_KEY || "",
- secretAccessKey: serverEnv.CAP_AWS_SECRET_KEY || "",
+ accessKeyId: serverEnv().CAP_AWS_ACCESS_KEY || "",
+ secretAccessKey: serverEnv().CAP_AWS_SECRET_KEY || "",
},
});
const outputKey = `${userId}/${videoId}/output/`;
const createJobCommand = new CreateJobCommand({
- Role: serverEnv.CAP_AWS_MEDIACONVERT_ROLE_ARN || "",
+ Role: serverEnv().CAP_AWS_MEDIACONVERT_ROLE_ARN || "",
Settings: {
Inputs: videoSegmentKeys.map((videoSegmentKey, index) => {
const audioSegmentKey = audioSegmentKeys[index];
@@ -267,7 +267,7 @@ export async function GET(request: NextRequest) {
const createJobResponse = await mediaConvertClient.send(createJobCommand);
const jobId = createJobResponse.Job?.Id;
- await db.update(videos).set({ jobId }).where(eq(videos.id, videoId));
+ await db().update(videos).set({ jobId }).where(eq(videos.id, videoId));
return new Response(JSON.stringify({ jobId: jobId }), {
status: 200,
diff --git a/apps/web/app/api/upload/mux/status/route.ts b/apps/web/app/api/upload/mux/status/route.ts
index be1b30216..b0a89146f 100644
--- a/apps/web/app/api/upload/mux/status/route.ts
+++ b/apps/web/app/api/upload/mux/status/route.ts
@@ -6,10 +6,10 @@ import {
MediaConvertClient,
GetJobCommand,
} from "@aws-sdk/client-mediaconvert";
-import { serverEnv, clientEnv } from "@cap/env";
+import { serverEnv, buildEnv } from "@cap/env";
const allowedOrigins = [
- clientEnv.NEXT_PUBLIC_WEB_URL,
+ buildEnv.NEXT_PUBLIC_WEB_URL,
"http://localhost:3001",
"tauri://localhost",
"http://tauri.localhost",
@@ -64,7 +64,7 @@ export async function GET(request: NextRequest) {
);
}
- const query = await db.select().from(videos).where(eq(videos.id, videoId));
+ const query = await db().select().from(videos).where(eq(videos.id, videoId));
if (query.length === 0) {
return new Response(
@@ -118,10 +118,10 @@ export async function GET(request: NextRequest) {
}
const mediaConvertClient = new MediaConvertClient({
- region: clientEnv.NEXT_PUBLIC_CAP_AWS_REGION || "",
+ region: serverEnv().CAP_AWS_REGION || "",
credentials: {
- accessKeyId: serverEnv.CAP_AWS_ACCESS_KEY || "",
- secretAccessKey: serverEnv.CAP_AWS_SECRET_KEY || "",
+ accessKeyId: serverEnv().CAP_AWS_ACCESS_KEY || "",
+ secretAccessKey: serverEnv().CAP_AWS_SECRET_KEY || "",
},
});
@@ -133,7 +133,7 @@ export async function GET(request: NextRequest) {
const jobResponse = await mediaConvertClient.send(getJobCommand);
const jobStatus = jobResponse.Job?.Status;
- await db.update(videos).set({ jobStatus }).where(eq(videos.id, videoId));
+ await db().update(videos).set({ jobStatus }).where(eq(videos.id, videoId));
return new Response(JSON.stringify({ jobStatus: jobStatus }), {
status: 200,
diff --git a/apps/web/app/api/upload/new/route.ts b/apps/web/app/api/upload/new/route.ts
index 0d36064c7..f9889290b 100644
--- a/apps/web/app/api/upload/new/route.ts
+++ b/apps/web/app/api/upload/new/route.ts
@@ -1,7 +1,7 @@
import { type NextRequest } from "next/server";
import { getCurrentUser } from "@cap/database/auth/session";
import { uploadToS3 } from "@/utils/video/upload/helpers";
-import { clientEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
export async function POST(request: NextRequest) {
const user = await getCurrentUser();
@@ -14,8 +14,8 @@ export async function POST(request: NextRequest) {
const videoCodec = formData.get("videoCodec");
const audioCodec = formData.get("audioCodec");
- const awsRegion = clientEnv.NEXT_PUBLIC_CAP_AWS_REGION;
- const awsBucket = clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET;
+ const awsRegion = serverEnv().CAP_AWS_REGION;
+ const awsBucket = serverEnv().CAP_AWS_BUCKET;
if (!user || !awsRegion || !awsBucket || !filename || !blobData) {
console.error("Missing required data in /api/upload/new/route.ts");
diff --git a/apps/web/app/api/upload/signed/route.ts b/apps/web/app/api/upload/signed/route.ts
index 3bbf512c8..0e20d5aa1 100644
--- a/apps/web/app/api/upload/signed/route.ts
+++ b/apps/web/app/api/upload/signed/route.ts
@@ -13,7 +13,7 @@ import { s3Buckets } from "@cap/database/schema";
import { eq } from "drizzle-orm";
import { cookies } from "next/headers";
import type { NextRequest } from "next/server";
-import { clientEnv, serverEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
export async function POST(request: NextRequest) {
try {
@@ -48,7 +48,7 @@ export async function POST(request: NextRequest) {
}
try {
- const [bucket] = await db
+ const [bucket] = await db()
.select()
.from(s3Buckets)
.where(eq(s3Buckets.ownerId, user.id));
@@ -65,17 +65,17 @@ export async function POST(request: NextRequest) {
if (
!bucket ||
!s3Config ||
- bucket.bucketName !== clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET
+ bucket.bucketName !== serverEnv().CAP_AWS_BUCKET
) {
- const distributionId = serverEnv.CAP_CLOUDFRONT_DISTRIBUTION_ID;
+ const distributionId = serverEnv().CAP_CLOUDFRONT_DISTRIBUTION_ID;
if (distributionId) {
console.log("Creating CloudFront invalidation for", fileKey);
const cloudfront = new CloudFrontClient({
- region: clientEnv.NEXT_PUBLIC_CAP_AWS_REGION || "us-east-1",
+ region: serverEnv().CAP_AWS_REGION || "us-east-1",
credentials: {
- accessKeyId: serverEnv.CAP_AWS_ACCESS_KEY || "",
- secretAccessKey: serverEnv.CAP_AWS_SECRET_KEY || "",
+ accessKeyId: serverEnv().CAP_AWS_ACCESS_KEY || "",
+ secretAccessKey: serverEnv().CAP_AWS_SECRET_KEY || "",
},
});
@@ -146,13 +146,11 @@ export async function POST(request: NextRequest) {
// When not using aws s3, we need to transform the url to the local endpoint
if (
- clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET_URL &&
- !clientEnv.NEXT_PUBLIC_CAP_AWS_ENDPOINT?.endsWith(
- "s3-accelerate.amazonaws.com"
- )
+ serverEnv().CAP_AWS_BUCKET_URL &&
+ !serverEnv().CAP_AWS_ENDPOINT?.endsWith("s3-accelerate.amazonaws.com")
) {
- const endpoint = clientEnv.NEXT_PUBLIC_CAP_AWS_ENDPOINT;
- const bucket = clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET;
+ const endpoint = serverEnv().CAP_AWS_ENDPOINT;
+ const bucket = serverEnv().CAP_AWS_BUCKET;
const newUrl = `${endpoint}/${bucket}/`;
presignedPostData.url = newUrl;
}
@@ -163,7 +161,7 @@ export async function POST(request: NextRequest) {
const videoId = fileKey.split("/")[1]; // Assuming fileKey format is userId/videoId/...
if (videoId) {
try {
- await fetch(`${clientEnv.NEXT_PUBLIC_WEB_URL}/api/revalidate`, {
+ await fetch(`${serverEnv().WEB_URL}/api/revalidate`, {
method: "POST",
headers: {
"Content-Type": "application/json",
diff --git a/apps/web/app/api/utils.ts b/apps/web/app/api/utils.ts
index dc62e11a6..81446247e 100644
--- a/apps/web/app/api/utils.ts
+++ b/apps/web/app/api/utils.ts
@@ -1,7 +1,7 @@
import { getCurrentUser } from "@cap/database/auth/session";
import { cookies } from "next/headers";
import { createMiddleware } from "hono/factory";
-import { clientEnv } from "@cap/env";
+import { buildEnv, serverEnv } from "@cap/env";
import { cors } from "hono/cors";
import { getServerSession, Session } from "next-auth";
import { authOptions } from "@cap/database/auth/auth-options";
@@ -20,7 +20,7 @@ async function getAuth(c: Context) {
});
}
- const session = await getServerSession(authOptions);
+ const session = await getServerSession(authOptions());
if (!session) return;
const user = await getCurrentUser(session);
if (!user) return;
@@ -60,7 +60,7 @@ export const withAuth = createMiddleware<{
});
const allowedOrigins = [
- clientEnv.NEXT_PUBLIC_WEB_URL,
+ buildEnv.NEXT_PUBLIC_WEB_URL,
"http://localhost:3001",
"http://localhost:3000",
"tauri://localhost",
diff --git a/apps/web/app/api/video/comment/delete/route.ts b/apps/web/app/api/video/comment/delete/route.ts
index 22ca9ca58..7b361146d 100644
--- a/apps/web/app/api/video/comment/delete/route.ts
+++ b/apps/web/app/api/video/comment/delete/route.ts
@@ -20,7 +20,7 @@ export async function DELETE(request: NextRequest) {
try {
// First, verify that the comment belongs to the user
- const query = await db
+ const query = await db()
.select()
.from(comments)
.where(and(eq(comments.id, commentId), eq(comments.authorId, user.id)));
@@ -36,7 +36,7 @@ export async function DELETE(request: NextRequest) {
}
// Delete the comment and all its replies
- await db
+ await db()
.delete(comments)
.where(
or(eq(comments.id, commentId), eq(comments.parentCommentId, commentId))
diff --git a/apps/web/app/api/video/comment/route.ts b/apps/web/app/api/video/comment/route.ts
index 3e5cc81ee..ab4268c46 100644
--- a/apps/web/app/api/video/comment/route.ts
+++ b/apps/web/app/api/video/comment/route.ts
@@ -5,7 +5,7 @@ import { comments } from "@cap/database/schema";
import { db } from "@cap/database";
import { rateLimitMiddleware } from "@/utils/helpers";
import { headers } from "next/headers";
-import { clientEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
async function handlePost(request: NextRequest) {
const user = await getCurrentUser();
@@ -44,7 +44,7 @@ async function handlePost(request: NextRequest) {
updatedAt: new Date(),
};
- await db.insert(comments).values(newComment);
+ await db().insert(comments).values(newComment);
// Trigger email notification for new comment
if (type === "text" && userId !== "anonymous") {
@@ -52,7 +52,7 @@ async function handlePost(request: NextRequest) {
// Don't await this to avoid blocking the response
const absoluteUrl = new URL(
"/api/email/new-comment",
- clientEnv.NEXT_PUBLIC_WEB_URL
+ serverEnv().WEB_URL
).toString();
fetch(absoluteUrl, {
method: "POST",
diff --git a/apps/web/app/api/video/delete/route.ts b/apps/web/app/api/video/delete/route.ts
index 7f82a8d12..49e84ee62 100644
--- a/apps/web/app/api/video/delete/route.ts
+++ b/apps/web/app/api/video/delete/route.ts
@@ -24,7 +24,7 @@ export async function DELETE(request: NextRequest) {
return Response.json({ error: true }, { status: 401 });
}
- const query = await db
+ const query = await db()
.select({ video: videos, bucket: s3Buckets })
.from(videos)
.leftJoin(s3Buckets, eq(videos.bucket, s3Buckets.id))
@@ -51,7 +51,7 @@ export async function DELETE(request: NextRequest) {
);
}
- await db
+ await db()
.delete(videos)
.where(and(eq(videos.id, videoId), eq(videos.ownerId, userId)));
diff --git a/apps/web/app/api/video/domain-info/route.ts b/apps/web/app/api/video/domain-info/route.ts
index 56c7c2147..c45f49a86 100644
--- a/apps/web/app/api/video/domain-info/route.ts
+++ b/apps/web/app/api/video/domain-info/route.ts
@@ -13,7 +13,7 @@ export async function GET(request: NextRequest) {
try {
// First, get the video to find the owner or shared space
- const video = await db
+ const video = await db()
.select({
id: videos.id,
ownerId: videos.ownerId,
@@ -32,7 +32,7 @@ export async function GET(request: NextRequest) {
}
// Check if the video is shared with a space
- const sharedVideo = await db
+ const sharedVideo = await db()
.select({
spaceId: sharedVideos.spaceId,
})
@@ -47,7 +47,7 @@ export async function GET(request: NextRequest) {
// If we have a space ID, get the space's custom domain
if (spaceId) {
- const space = await db
+ const space = await db()
.select({
customDomain: spaces.customDomain,
domainVerified: spaces.domainVerified,
@@ -65,7 +65,7 @@ export async function GET(request: NextRequest) {
}
// If no shared space or no custom domain, check the owner's space
- const ownerSpaces = await db
+ const ownerSpaces = await db()
.select({
customDomain: spaces.customDomain,
domainVerified: spaces.domainVerified,
diff --git a/apps/web/app/api/video/metadata/route.ts b/apps/web/app/api/video/metadata/route.ts
index 79e9eac7f..22c095469 100644
--- a/apps/web/app/api/video/metadata/route.ts
+++ b/apps/web/app/api/video/metadata/route.ts
@@ -15,7 +15,7 @@ export async function PUT(request: NextRequest) {
return Response.json({ error: true }, { status: 401 });
}
- const query = await db.select().from(videos).where(eq(videos.id, videoId));
+ const query = await db().select().from(videos).where(eq(videos.id, videoId));
if (query.length === 0) {
return Response.json({ error: true }, { status: 401 });
@@ -30,7 +30,7 @@ export async function PUT(request: NextRequest) {
return Response.json({ error: true }, { status: 401 });
}
- await db
+ await db()
.update(videos)
.set({
metadata: metadata,
diff --git a/apps/web/app/api/video/playlistUrl/route.ts b/apps/web/app/api/video/playlistUrl/route.ts
index f6ce15aa6..0095a9ccb 100644
--- a/apps/web/app/api/video/playlistUrl/route.ts
+++ b/apps/web/app/api/video/playlistUrl/route.ts
@@ -5,7 +5,7 @@ import { eq } from "drizzle-orm";
import { getHeaders } from "@/utils/helpers";
import { CACHE_CONTROL_HEADERS } from "@/utils/helpers";
import { S3_BUCKET_URL } from "@cap/utils";
-import { clientEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
export const revalidate = 0;
@@ -37,7 +37,7 @@ export async function GET(request: NextRequest) {
);
}
- const query = await db.select().from(videos).where(eq(videos.id, videoId));
+ const query = await db().select().from(videos).where(eq(videos.id, videoId));
if (query.length === 0) {
return new Response(
@@ -76,8 +76,12 @@ export async function GET(request: NextRequest) {
return new Response(
JSON.stringify({
- playlistOne: `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/playlist?userId=${video.ownerId}&videoId=${video.id}&videoType=video`,
- playlistTwo: `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/playlist?userId=${video.ownerId}&videoId=${video.id}&videoType=audio`,
+ playlistOne: `${serverEnv().WEB_URL}/api/playlist?userId=${
+ video.ownerId
+ }&videoId=${video.id}&videoType=video`,
+ playlistTwo: `${serverEnv().WEB_URL}/api/playlist?userId=${
+ video.ownerId
+ }&videoId=${video.id}&videoType=audio`,
}),
{
status: 200,
diff --git a/apps/web/app/api/video/transcribe/status/route.ts b/apps/web/app/api/video/transcribe/status/route.ts
index 8cb2877a6..bdcb93c99 100644
--- a/apps/web/app/api/video/transcribe/status/route.ts
+++ b/apps/web/app/api/video/transcribe/status/route.ts
@@ -5,6 +5,8 @@ import { count, eq } from "drizzle-orm";
import { db } from "@cap/database";
import { videos } from "@cap/database/schema";
+export const dynamic = "force-dynamic";
+
export async function GET(request: NextRequest) {
const user = await getCurrentUser();
const url = new URL(request.url);
@@ -21,7 +23,7 @@ export async function GET(request: NextRequest) {
);
}
- const video = await db.select().from(videos).where(eq(videos.id, videoId));
+ const video = await db().select().from(videos).where(eq(videos.id, videoId));
if (video.length === 0 || !video[0]) {
return Response.json(
diff --git a/apps/web/app/api/waitlist/route.ts b/apps/web/app/api/waitlist/route.ts
index 679b8ec15..164fa60ab 100644
--- a/apps/web/app/api/waitlist/route.ts
+++ b/apps/web/app/api/waitlist/route.ts
@@ -14,7 +14,7 @@ export async function POST(request: Request) {
method: "POST",
headers: {
"Content-Type": "application/json",
- Authorization: `Bearer ${serverEnv.NEXT_LOOPS_KEY}`,
+ Authorization: `Bearer ${serverEnv().NEXT_LOOPS_KEY}`,
},
body: JSON.stringify({
email,
diff --git a/apps/web/app/api/webhooks/stripe/route.ts b/apps/web/app/api/webhooks/stripe/route.ts
index cb998f08f..350b12ad3 100644
--- a/apps/web/app/api/webhooks/stripe/route.ts
+++ b/apps/web/app/api/webhooks/stripe/route.ts
@@ -4,7 +4,7 @@ import { users } from "@cap/database/schema";
import { eq } from "drizzle-orm";
import { NextResponse } from "next/server";
import Stripe from "stripe";
-import { serverEnv } from "@cap/env";
+import { buildEnv, serverEnv } from "@cap/env";
import { PostHog } from "posthog-node";
const relevantEvents = new Set([
@@ -29,7 +29,7 @@ async function findUserWithRetry(
// Try finding by userId first if available
if (userId) {
console.log(`Attempting to find user by ID: ${userId}`);
- const userById = await db
+ const userById = await db()
.select()
.from(users)
.where(eq(users.id, userId))
@@ -46,7 +46,7 @@ async function findUserWithRetry(
// If not found by ID or no ID provided, try email
if (email) {
console.log(`Attempting to find user by email: ${email}`);
- const userByEmail = await db
+ const userByEmail = await db()
.select()
.from(users)
.where(eq(users.email, email))
@@ -89,7 +89,7 @@ export const POST = async (req: Request) => {
console.log("Webhook received");
const buf = await req.text();
const sig = req.headers.get("Stripe-Signature") as string;
- const webhookSecret = serverEnv.STRIPE_WEBHOOK_SECRET;
+ const webhookSecret = serverEnv().STRIPE_WEBHOOK_SECRET;
let event: Stripe.Event;
try {
@@ -99,7 +99,7 @@ export const POST = async (req: Request) => {
status: 400,
});
}
- event = stripe.webhooks.constructEvent(buf, sig, webhookSecret);
+ event = stripe().webhooks.constructEvent(buf, sig, webhookSecret);
console.log(`✅ Event received: ${event.type}`);
} catch (err: any) {
console.log(`❌ Error message: ${err.message}`);
@@ -117,7 +117,7 @@ export const POST = async (req: Request) => {
subscriptionId: session.subscription,
});
- const customer = await stripe.customers.retrieve(
+ const customer = await stripe().customers.retrieve(
session.customer as string
);
console.log("Retrieved customer:", {
@@ -162,7 +162,7 @@ export const POST = async (req: Request) => {
name: dbUser.name,
});
- const subscription = await stripe.subscriptions.retrieve(
+ const subscription = await stripe().subscriptions.retrieve(
session.subscription as string
);
console.log("Retrieved subscription:", {
@@ -182,7 +182,7 @@ export const POST = async (req: Request) => {
inviteQuota,
});
- await db
+ await db()
.update(users)
.set({
stripeSubscriptionId: session.subscription as string,
@@ -198,8 +198,8 @@ export const POST = async (req: Request) => {
try {
// Initialize server-side PostHog
const serverPostHog = new PostHog(
- process.env.NEXT_PUBLIC_POSTHOG_KEY || "",
- { host: process.env.NEXT_PUBLIC_POSTHOG_HOST || "" }
+ buildEnv.NEXT_PUBLIC_POSTHOG_KEY || "",
+ { host: buildEnv.NEXT_PUBLIC_POSTHOG_HOST || "" }
);
// Track subscription completed event
@@ -235,7 +235,7 @@ export const POST = async (req: Request) => {
customerId: subscription.customer,
});
- const customer = await stripe.customers.retrieve(
+ const customer = await stripe().customers.retrieve(
subscription.customer as string
);
console.log("Retrieved customer:", {
@@ -281,7 +281,7 @@ export const POST = async (req: Request) => {
});
// Get all active subscriptions for this customer
- const subscriptions = await stripe.subscriptions.list({
+ const subscriptions = await stripe().subscriptions.list({
customer: customer.id,
status: "active",
});
@@ -308,7 +308,7 @@ export const POST = async (req: Request) => {
inviteQuota,
});
- await db
+ await db()
.update(users)
.set({
stripeSubscriptionId: subscription.id,
@@ -326,7 +326,7 @@ export const POST = async (req: Request) => {
if (event.type === "customer.subscription.deleted") {
const subscription = event.data.object as Stripe.Subscription;
- const customer = await stripe.customers.retrieve(
+ const customer = await stripe().customers.retrieve(
subscription.customer as string
);
let foundUserId;
@@ -336,7 +336,7 @@ export const POST = async (req: Request) => {
if (!foundUserId) {
console.log("No user found in metadata, checking customer email");
if ("email" in customer && customer.email) {
- const userByEmail = await db
+ const userByEmail = await db()
.select()
.from(users)
.where(eq(users.email, customer.email))
@@ -346,7 +346,7 @@ export const POST = async (req: Request) => {
foundUserId = userByEmail[0].id;
console.log(`User found by email: ${foundUserId}`);
// Update customer metadata with userId
- await stripe.customers.update(customer.id, {
+ await stripe().customers.update(customer.id, {
metadata: { userId: foundUserId },
});
} else {
@@ -363,7 +363,7 @@ export const POST = async (req: Request) => {
}
}
- const userResult = await db
+ const userResult = await db()
.select()
.from(users)
.where(eq(users.id, foundUserId));
@@ -373,7 +373,7 @@ export const POST = async (req: Request) => {
return new Response("No user found", { status: 400 });
}
- await db
+ await db()
.update(users)
.set({
stripeSubscriptionId: subscription.id,
diff --git a/apps/web/app/blog/[slug]/page.tsx b/apps/web/app/blog/[slug]/page.tsx
index 687442c6a..e4f16d765 100644
--- a/apps/web/app/blog/[slug]/page.tsx
+++ b/apps/web/app/blog/[slug]/page.tsx
@@ -1,7 +1,7 @@
import { ReadyToGetStarted } from "@/components/ReadyToGetStarted";
import { getBlogPosts } from "@/utils/blog";
import { calculateReadingTime } from "@/utils/readTime";
-import { clientEnv } from "@cap/env";
+import { buildEnv } from "@cap/env";
import { format, parseISO } from "date-fns";
import type { Metadata } from "next";
import { MDXRemote } from "next-mdx-remote/rsc";
@@ -34,7 +34,7 @@ export async function generateMetadata({
description: string;
image: string;
};
- let ogImage = `${clientEnv.NEXT_PUBLIC_WEB_URL}${image}`;
+ let ogImage = `${buildEnv.NEXT_PUBLIC_WEB_URL}${image}`;
return {
title,
@@ -44,7 +44,7 @@ export async function generateMetadata({
description,
type: "article",
publishedTime,
- url: `${clientEnv.NEXT_PUBLIC_WEB_URL}/blog/${post.slug}`,
+ url: `${buildEnv.NEXT_PUBLIC_WEB_URL}/blog/${post.slug}`,
images: [
{
url: ogImage,
@@ -103,7 +103,10 @@ export default async function PostPage({ params }: PostProps) {
</header>
<hr className="my-6" />
<MDXRemote source={post.content} />
- <Share post={post} />
+ <Share
+ post={post}
+ url={`${buildEnv.NEXT_PUBLIC_WEB_URL}/blog/${post.slug}`}
+ />
</div>
</article>
<div className="mb-4 wrapper">
diff --git a/apps/web/app/blog/_components/Share.tsx b/apps/web/app/blog/_components/Share.tsx
index 44062f8c7..7ee20567e 100644
--- a/apps/web/app/blog/_components/Share.tsx
+++ b/apps/web/app/blog/_components/Share.tsx
@@ -1,8 +1,7 @@
"use client";
-import { clientEnv } from "@cap/env";
-import { useState } from "react";
import toast from "react-hot-toast";
+import { useState } from "react";
interface ShareProps {
post: {
@@ -11,10 +10,10 @@ interface ShareProps {
title: string;
};
};
+ url: string;
}
-export function Share({ post }: ShareProps) {
- const shareUrl = `${clientEnv.NEXT_PUBLIC_WEB_URL}/blog/${post.slug}`;
+export function Share({ post, url }: ShareProps) {
const [copied, setCopied] = useState(false);
return (
@@ -25,7 +24,7 @@ export function Share({ post }: ShareProps) {
<a
href={`https://twitter.com/intent/tweet?text=${encodeURIComponent(
post.metadata.title
- )}&url=${encodeURIComponent(shareUrl)}`}
+ )}&url=${encodeURIComponent(url)}`}
target="_blank"
rel="noopener noreferrer"
className="text-lg text-gray-600 hover:text-blue-500 hover:underline"
@@ -34,7 +33,7 @@ export function Share({ post }: ShareProps) {
</a>
<a
href={`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(
- shareUrl
+ url
)}`}
target="_blank"
rel="noopener noreferrer"
@@ -44,7 +43,7 @@ export function Share({ post }: ShareProps) {
</a>
<button
onClick={() => {
- navigator.clipboard.writeText(shareUrl);
+ navigator.clipboard.writeText(url);
toast.success("Link copied to clipboard");
setCopied(true);
setTimeout(() => setCopied(false), 2000);
diff --git a/apps/web/app/blog/_components/UpdatePage.tsx b/apps/web/app/blog/_components/UpdatePage.tsx
deleted file mode 100644
index edd40dcab..000000000
--- a/apps/web/app/blog/_components/UpdatePage.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-"use client";
-
-import { getBlogPosts } from "@/utils/blog";
-import { format, parseISO } from "date-fns";
-import { MDXRemote } from "next-mdx-remote/rsc";
-import Image from "next/image";
-
-export const UpdatePage = ({ postSlug }: { postSlug: string }) => {
- const post = getBlogPosts().find((post) => post.slug === postSlug);
-
- if (!post) {
- return null;
- }
-
- return (
- <article className="py-32 mx-auto prose">
- {post.metadata.image && (
- <div className="relative mb-12 h-[345px] w-full">
- <Image
- className="object-cover m-0 w-full rounded-lg"
- src={post.metadata.image}
- alt={post.metadata.title}
- fill
- priority
- sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
- />
- </div>
- )}
-
- <header>
- <h1 className="mb-2">{post.metadata.title}</h1>
- <p className="space-x-1 text-xs text-gray-12">
- <span>
- {format(parseISO(post.metadata.publishedAt), "MMMM dd, yyyy")}
- </span>
- </p>
- </header>
- <hr className="my-6" />
- <MDXRemote source={post.content} />
- </article>
- );
-};
diff --git a/apps/web/app/dashboard/_components/AdminNavbar/AdminNavItems.tsx b/apps/web/app/dashboard/_components/AdminNavbar/AdminNavItems.tsx
index 0bee53d92..0cbdb9259 100644
--- a/apps/web/app/dashboard/_components/AdminNavbar/AdminNavItems.tsx
+++ b/apps/web/app/dashboard/_components/AdminNavbar/AdminNavItems.tsx
@@ -40,6 +40,7 @@ import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import clsx from "clsx";
import { motion } from "framer-motion";
import { updateActiveSpace } from "./server";
+import { buildEnv } from "@cap/env";
export const AdminNavItems = ({ collapsed }: { collapsed?: boolean }) => {
const pathname = usePathname();
@@ -71,12 +72,12 @@ export const AdminNavItems = ({ collapsed }: { collapsed?: boolean }) => {
icon: faBuilding,
subNav: [],
},
- ...(user.email.endsWith("@cap.so")
+ ...(buildEnv.NEXT_PUBLIC_IS_CAP && user.email.endsWith("@cap.so")
? [
{
- name: "Admin",
+ name: "Admin Dev",
href: "/dashboard/admin",
- icon: faBuilding, // Using Building icon as a fallback
+ icon: faBuilding,
subNav: [],
},
]
diff --git a/apps/web/app/dashboard/_components/AdminNavbar/server.ts b/apps/web/app/dashboard/_components/AdminNavbar/server.ts
index 0d0e14eab..44617ba32 100644
--- a/apps/web/app/dashboard/_components/AdminNavbar/server.ts
+++ b/apps/web/app/dashboard/_components/AdminNavbar/server.ts
@@ -10,7 +10,7 @@ export async function updateActiveSpace(spaceId: string) {
const user = await getCurrentUser();
if (!user) throw new Error("Unauthorized");
- const [space] = await db
+ const [space] = await db()
.select({ space: spaces })
.from(spaces)
.innerJoin(
@@ -21,7 +21,7 @@ export async function updateActiveSpace(spaceId: string) {
if (!space) throw new Error("Space not found");
- await db
+ await db()
.update(users)
.set({ activeSpaceId: space.space.id })
.where(eq(users.id, user.id));
diff --git a/apps/web/app/dashboard/_components/DashboardInner.tsx b/apps/web/app/dashboard/_components/DashboardInner.tsx
index cd18887b6..6cd0c11af 100644
--- a/apps/web/app/dashboard/_components/DashboardInner.tsx
+++ b/apps/web/app/dashboard/_components/DashboardInner.tsx
@@ -8,9 +8,8 @@ import {
PopoverContent,
PopoverTrigger,
} from "@cap/ui";
-import { MoreVertical } from "lucide-react";
+import { MoreVertical, Sparkles } from "lucide-react";
import { useState } from "react";
-
import {
useSharedContext,
useTheme,
@@ -18,12 +17,12 @@ import {
import { Avatar } from "@/app/s/[videoId]/_components/tabs/Activity";
import { UpgradeModal } from "@/components/UpgradeModal";
import {
- faCrown,
faGear,
faHome,
faMessage,
faMoon,
faSignOut,
+ faCrown,
faSun,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
diff --git a/apps/web/app/dashboard/admin/actions.ts b/apps/web/app/dashboard/admin/actions.ts
index 677d4da51..faf128f1c 100644
--- a/apps/web/app/dashboard/admin/actions.ts
+++ b/apps/web/app/dashboard/admin/actions.ts
@@ -9,7 +9,7 @@ export async function lookupUserById(data: FormData) {
const currentUser = await getCurrentUser();
if (!currentUser?.email.endsWith("@cap.so")) return;
- const [user] = await db
+ const [user] = await db()
.select()
.from(users)
.where(eq(users.id, data.get("id") as string));
diff --git a/apps/web/app/dashboard/caps/Caps.tsx b/apps/web/app/dashboard/caps/Caps.tsx
index 262986fe3..306ff223a 100644
--- a/apps/web/app/dashboard/caps/Caps.tsx
+++ b/apps/web/app/dashboard/caps/Caps.tsx
@@ -1,11 +1,7 @@
"use client";
-import { deleteVideo } from "@/actions/videos/delete";
import { useSharedContext } from "@/app/dashboard/_components/DynamicSharedLayout";
-import { apiClient } from "@/utils/web-api";
+import { useApiClient } from "@/utils/web-api";
import { VideoMetadata } from "@cap/database/types";
-import { Button } from "@cap/ui";
-import { faTrash } from "@fortawesome/free-solid-svg-icons";
-import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { AnimatePresence, motion } from "framer-motion";
import { useRouter, useSearchParams } from "next/navigation";
import { useEffect, useRef, useState } from "react";
@@ -13,6 +9,10 @@ import toast from "react-hot-toast";
import { CapCard } from "./components/CapCard";
import { CapPagination } from "./components/CapPagination";
import { EmptyCapState } from "./components/EmptyCapState";
+import { Button } from "@cap/ui";
+import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
+import { faTrash } from "@fortawesome/free-solid-svg-icons";
+import { deleteVideo } from "@/actions/videos/delete";
type VideoData = {
id: string;
@@ -49,6 +49,8 @@ export const Caps = ({
const anyCapSelected = selectedCaps.length > 0;
+ const apiClient = useApiClient();
+
useEffect(() => {
const fetchAnalytics = async () => {
const analyticsData: Record<string, number> = {};
diff --git a/apps/web/app/dashboard/caps/components/CapCard.tsx b/apps/web/app/dashboard/caps/components/CapCard.tsx
index 3abd579cf..73381b49f 100644
--- a/apps/web/app/dashboard/caps/components/CapCard.tsx
+++ b/apps/web/app/dashboard/caps/components/CapCard.tsx
@@ -5,24 +5,25 @@ import { CapCardAnalytics } from "@/app/dashboard/caps/components/CapCardAnalyti
import { SharingDialog } from "@/app/dashboard/caps/components/SharingDialog";
import { Tooltip } from "@/components/Tooltip";
import { VideoThumbnail } from "@/components/VideoThumbnail";
+import { usePublicEnv } from "@/utils/public-env";
import { VideoMetadata } from "@cap/database/types";
-import { clientEnv, NODE_ENV } from "@cap/env";
+import { buildEnv, NODE_ENV } from "@cap/env";
import { Button } from "@cap/ui";
import {
- faCheck,
faChevronDown,
faLink,
faTrash,
+ faCheck,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import clsx from "clsx";
import moment from "moment";
import Link from "next/link";
import { useRouter } from "next/navigation";
-import { useState } from "react";
+import { useState, PropsWithChildren } from "react";
import { toast } from "react-hot-toast";
-export interface CapCardProps {
+interface Props extends PropsWithChildren {
cap: {
id: string;
ownerId: string;
@@ -34,7 +35,6 @@ export interface CapCardProps {
ownerName: string | null;
metadata?: VideoMetadata;
};
- children?: React.ReactNode;
analytics: number;
onDelete?: (videoId: string) => Promise<void>;
userId?: string;
@@ -45,7 +45,7 @@ export interface CapCardProps {
anyCapSelected?: boolean;
}
-export const CapCard: React.FC<CapCardProps> = ({
+export const CapCard = ({
cap,
analytics,
children,
@@ -56,7 +56,7 @@ export const CapCard: React.FC<CapCardProps> = ({
isSelected = false,
onSelectToggle,
anyCapSelected = false,
-}) => {
+}: Props) => {
const effectiveDate = cap.metadata?.customCreatedAt
? new Date(cap.metadata.customCreatedAt)
: cap.createdAt;
@@ -235,11 +235,14 @@ export const CapCard: React.FC<CapCardProps> = ({
}
};
- const capUrl = activeSpace?.space.customDomain
- ? `https://${activeSpace.space.customDomain}/s/${cap.id}`
- : clientEnv.NEXT_PUBLIC_IS_CAP && NODE_ENV === "production"
- ? `https://cap.link/${cap.id}`
- : `${clientEnv.NEXT_PUBLIC_WEB_URL}/s/${cap.id}`;
+ const { webUrl } = usePublicEnv();
+
+ const capUrl =
+ activeSpace?.space.customDomain && activeSpace.space.domainVerified
+ ? `https://${activeSpace.space.customDomain}/s/${cap.id}`
+ : buildEnv.NEXT_PUBLIC_IS_CAP && NODE_ENV === "production"
+ ? `https://cap.link/${cap.id}`
+ : `${webUrl}/s/${cap.id}`;
return (
<>
diff --git a/apps/web/app/dashboard/caps/components/CapCardActions.tsx b/apps/web/app/dashboard/caps/components/CapCardActions.tsx
index 2cdb4a17c..e68ea6851 100644
--- a/apps/web/app/dashboard/caps/components/CapCardActions.tsx
+++ b/apps/web/app/dashboard/caps/components/CapCardActions.tsx
@@ -1,27 +1,21 @@
-import { clientEnv, NODE_ENV } from "@cap/env";
+import { serverEnv, NODE_ENV } from "@cap/env";
import { LinkIcon, Trash } from "lucide-react";
import { toast } from "react-hot-toast";
import { Tooltip } from "react-tooltip";
import { useSharedContext } from "../../_components/DynamicSharedLayout";
interface CapCardActionsProps {
capId: string;
+ url: string;
onDelete: (videoId: string) => Promise<void>;
}
-export const CapCardActions: React.FC<CapCardActionsProps> = ({
+export const CapCardActions = ({
capId,
+ url,
onDelete,
-}) => {
- const { activeSpace } = useSharedContext();
+}: CapCardActionsProps) => {
const copyLink = () => {
- const link =
- activeSpace?.space.customDomain && activeSpace.space.domainVerified
- ? `https://${activeSpace.space.customDomain}/s/${capId}`
- : clientEnv.NEXT_PUBLIC_IS_CAP && NODE_ENV === "production"
- ? `https://cap.link/${capId}`
- : `${clientEnv.NEXT_PUBLIC_WEB_URL}/s/${capId}`;
-
- navigator.clipboard.writeText(link);
+ navigator.clipboard.writeText(url);
toast.success("Link copied to clipboard!");
};
diff --git a/apps/web/app/dashboard/caps/components/CapPagination.tsx b/apps/web/app/dashboard/caps/components/CapPagination.tsx
index 2426c54af..33e08cb32 100644
--- a/apps/web/app/dashboard/caps/components/CapPagination.tsx
+++ b/apps/web/app/dashboard/caps/components/CapPagination.tsx
@@ -1,4 +1,4 @@
-import { clientEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
import {
Pagination,
PaginationContent,
@@ -24,16 +24,14 @@ export const CapPagination: React.FC<CapPaginationProps> = ({
{currentPage > 1 && (
<PaginationItem>
<PaginationPrevious
- href={`${clientEnv.NEXT_PUBLIC_WEB_URL}/dashboard/caps?page=${
- currentPage - 1
- }`}
+ href={`/dashboard/caps?page=${currentPage - 1}`}
/>
</PaginationItem>
)}
<PaginationItem>
<PaginationLink
className="min-w-[54px]"
- href={`${clientEnv.NEXT_PUBLIC_WEB_URL}/dashboard/caps?page=1`}
+ href={`/dashboard/caps?page=1`}
isActive={currentPage === 1}
>
1
@@ -42,7 +40,7 @@ export const CapPagination: React.FC<CapPaginationProps> = ({
{currentPage !== 1 && (
<PaginationItem>
<PaginationLink
- href={`${clientEnv.NEXT_PUBLIC_WEB_URL}/dashboard/caps?page=${currentPage}`}
+ href={`/dashboard/caps?page=${currentPage}`}
isActive={true}
>
{currentPage}
@@ -52,9 +50,7 @@ export const CapPagination: React.FC<CapPaginationProps> = ({
{totalPages > currentPage + 1 && (
<PaginationItem>
<PaginationLink
- href={`${clientEnv.NEXT_PUBLIC_WEB_URL}/dashboard/caps?page=${
- currentPage + 1
- }`}
+ href={`/dashboard/caps?page=${currentPage + 1}`}
isActive={false}
>
{currentPage + 1}
@@ -64,7 +60,7 @@ export const CapPagination: React.FC<CapPaginationProps> = ({
{currentPage > 2 && <PaginationEllipsis />}
<PaginationItem>
<PaginationNext
- href={`${clientEnv.NEXT_PUBLIC_WEB_URL}/dashboard/caps?page=${
+ href={`/dashboard/caps?page=${
currentPage === totalPages ? currentPage : currentPage + 1
}`}
/>
diff --git a/apps/web/app/dashboard/caps/page.tsx b/apps/web/app/dashboard/caps/page.tsx
index 0cdb4054a..25428a30e 100644
--- a/apps/web/app/dashboard/caps/page.tsx
+++ b/apps/web/app/dashboard/caps/page.tsx
@@ -39,14 +39,14 @@ export default async function CapsPage({
const limit = Number(searchParams.limit) || 15;
const offset = (page - 1) * limit;
- const totalCountResult = await db
+ const totalCountResult = await db()
.select({ count: count() })
.from(videos)
.where(eq(videos.ownerId, userId));
const totalCount = totalCountResult[0]?.count || 0;
- const videoData = await db
+ const videoData = await db()
.select({
id: videos.id,
ownerId: videos.ownerId,
@@ -69,7 +69,7 @@ export default async function CapsPage({
ownerName: users.name,
effectiveDate: sql<string>`
COALESCE(
- JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.customCreatedAt')),
+ JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.customCreatedAt')),
${videos.createdAt}
)
`,
@@ -90,14 +90,14 @@ export default async function CapsPage({
)
.orderBy(
desc(sql`COALESCE(
- JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.customCreatedAt')),
+ JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.customCreatedAt')),
${videos.createdAt}
)`)
)
.limit(limit)
.offset(offset);
- const userSpaces = await db
+ const userSpaces = await db()
.select({
id: spaces.id,
name: spaces.name,
diff --git a/apps/web/app/dashboard/layout.tsx b/apps/web/app/dashboard/layout.tsx
index 30132a7bc..e9c769fa5 100644
--- a/apps/web/app/dashboard/layout.tsx
+++ b/apps/web/app/dashboard/layout.tsx
@@ -22,6 +22,8 @@ export type Space = {
totalInvites: number;
};
+export const dynamic = "force-dynamic";
+
export default async function DashboardLayout({
children,
}: {
@@ -37,7 +39,7 @@ export default async function DashboardLayout({
redirect("/onboarding");
}
- const spacesWithMembers = await db
+ const spacesWithMembers = await db()
.select({
space: spaces,
member: spaceMembers,
@@ -58,7 +60,7 @@ export default async function DashboardLayout({
let spaceInvitesData: (typeof spaceInvites.$inferSelect)[] = [];
if (spaceIds.length > 0) {
- spaceInvitesData = await db
+ spaceInvitesData = await db()
.select()
.from(spaceInvites)
.where(inArray(spaceInvites.spaceId, spaceIds));
@@ -74,7 +76,7 @@ export default async function DashboardLayout({
return acc;
}, [])
.map(async (space) => {
- const allMembers = await db
+ const allMembers = await db()
.select({
member: spaceMembers,
user: {
@@ -88,7 +90,7 @@ export default async function DashboardLayout({
.leftJoin(users, eq(spaceMembers.userId, users.id))
.where(eq(spaceMembers.spaceId, space.id));
- const owner = await db
+ const owner = await db()
.select({
inviteQuota: users.inviteQuota,
})
@@ -96,7 +98,7 @@ export default async function DashboardLayout({
.where(eq(users.id, space.ownerId))
.then((result) => result[0]);
- const totalInvitesResult = await db
+ const totalInvitesResult = await db()
.select({
value: sql<number>`
${count(spaceMembers.id)} + ${count(spaceInvites.id)}
diff --git a/apps/web/app/dashboard/page.tsx b/apps/web/app/dashboard/page.tsx
index a10e569e7..39ee39b67 100644
--- a/apps/web/app/dashboard/page.tsx
+++ b/apps/web/app/dashboard/page.tsx
@@ -1,5 +1,3 @@
-"use server";
-
import { redirect } from "next/navigation";
export default async function DashboardWebsitePage() {
diff --git a/apps/web/app/dashboard/settings/account/Settings.tsx b/apps/web/app/dashboard/settings/account/Settings.tsx
index fa2a57284..f30a199a2 100644
--- a/apps/web/app/dashboard/settings/account/Settings.tsx
+++ b/apps/web/app/dashboard/settings/account/Settings.tsx
@@ -8,7 +8,7 @@ import toast from "react-hot-toast";
export const Settings = ({
user,
}: {
- user: typeof users.$inferSelect | null;
+ user?: typeof users.$inferSelect | null;
}) => {
const firstName = user ? user?.name : "";
const lastName = user ? user?.lastName : "";
diff --git a/apps/web/app/dashboard/settings/workspace/components/CustomDomain.tsx b/apps/web/app/dashboard/settings/workspace/components/CustomDomain.tsx
index db3d561bd..e04fdb265 100644
--- a/apps/web/app/dashboard/settings/workspace/components/CustomDomain.tsx
+++ b/apps/web/app/dashboard/settings/workspace/components/CustomDomain.tsx
@@ -1,4 +1,3 @@
-export const dynamic = "force-dynamic";
export const revalidate = 0;
export const fetchCache = "force-no-store";
diff --git a/apps/web/app/dashboard/shared-caps/page.tsx b/apps/web/app/dashboard/shared-caps/page.tsx
index 3b3c07bf7..7556f59eb 100644
--- a/apps/web/app/dashboard/shared-caps/page.tsx
+++ b/apps/web/app/dashboard/shared-caps/page.tsx
@@ -31,7 +31,7 @@ export default async function SharedCapsPage({
let activeSpaceId = user?.activeSpaceId;
if (!activeSpaceId) {
// Get the first available space if activeSpaceId doesn't exist
- const firstSpace = await db
+ const firstSpace = await db()
.select({ id: spaces.id })
.from(spaces)
.innerJoin(spaceMembers, eq(spaces.id, spaceMembers.spaceId))
@@ -49,14 +49,14 @@ export default async function SharedCapsPage({
const offset = (page - 1) * limit;
- const totalCountResult = await db
+ const totalCountResult = await db()
.select({ count: count() })
.from(sharedVideos)
.where(eq(sharedVideos.spaceId, activeSpaceId));
const totalCount = totalCountResult[0]?.count || 0;
- const sharedVideoData = await db
+ const sharedVideoData = await db()
.select({
id: videos.id,
ownerId: videos.ownerId,
@@ -68,7 +68,7 @@ export default async function SharedCapsPage({
ownerName: users.name,
effectiveDate: sql<string>`
COALESCE(
- JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.customCreatedAt')),
+ JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.customCreatedAt')),
${videos.createdAt}
)
`,
@@ -88,7 +88,7 @@ export default async function SharedCapsPage({
)
.orderBy(
desc(sql`COALESCE(
- JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.customCreatedAt')),
+ JSON_UNQUOTE(JSON_EXTRACT(${videos.metadata}, '$.customCreatedAt')),
${videos.createdAt}
)`)
)
@@ -115,7 +115,7 @@ export default async function SharedCapsPage({
console.log(processedSharedVideoData);
// Debug: Check if there are any shared videos for this space
- const debugSharedVideos = await db
+ const debugSharedVideos = await db()
.select({
id: sharedVideos.id,
videoId: sharedVideos.videoId,
@@ -129,7 +129,7 @@ export default async function SharedCapsPage({
// Debug: Check if the videos exist
if (debugSharedVideos.length > 0) {
- const debugVideos = await db
+ const debugVideos = await db()
.select({
id: videos.id,
name: videos.name,
@@ -142,11 +142,5 @@ export default async function SharedCapsPage({
console.log(debugVideos);
}
- return (
- <SharedCaps
- data={processedSharedVideoData}
- count={totalCount}
- activeSpaceId={activeSpaceId}
- />
- );
+ return <SharedCaps data={processedSharedVideoData} count={totalCount} />;
}
diff --git a/apps/web/app/docs/[...slug]/page.tsx b/apps/web/app/docs/[...slug]/page.tsx
index 6ac56d1f7..f26dfa386 100644
--- a/apps/web/app/docs/[...slug]/page.tsx
+++ b/apps/web/app/docs/[...slug]/page.tsx
@@ -1,6 +1,6 @@
import type { DocMetadata } from "@/utils/blog";
import { getDocs } from "@/utils/blog";
-import { clientEnv } from "@cap/env";
+import { buildEnv } from "@cap/env";
import type { Metadata } from "next";
import { MDXRemote } from "next-mdx-remote/rsc";
import Image from "next/image";
@@ -49,9 +49,7 @@ export async function generateMetadata(
if (!doc) return;
const { title, summary, image } = doc.metadata;
- const ogImage = image
- ? `${clientEnv.NEXT_PUBLIC_WEB_URL}${image}`
- : undefined;
+ const ogImage = image ? `${buildEnv.NEXT_PUBLIC_WEB_URL}${image}` : undefined;
const description = summary || title;
return {
@@ -61,7 +59,7 @@ export async function generateMetadata(
title,
description,
type: "article",
- url: `${clientEnv.NEXT_PUBLIC_WEB_URL}/docs/${fullSlug}`,
+ url: `${buildEnv.NEXT_PUBLIC_WEB_URL}/docs/${fullSlug}`,
...(ogImage && {
images: [{ url: ogImage }],
}),
diff --git a/apps/web/app/docs/[slug]/page.tsx b/apps/web/app/docs/[slug]/page.tsx
index b23dde7e6..5c03b9b29 100644
--- a/apps/web/app/docs/[slug]/page.tsx
+++ b/apps/web/app/docs/[slug]/page.tsx
@@ -1,5 +1,5 @@
import { getDocs } from "@/utils/blog";
-import { clientEnv } from "@cap/env";
+import { buildEnv } from "@cap/env";
import type { Metadata } from "next";
import { MDXRemote } from "next-mdx-remote/rsc";
import Image from "next/image";
@@ -20,7 +20,7 @@ export async function generateMetadata({
}
let { title, summary: description, image } = doc.metadata;
- let ogImage = image ? `${clientEnv.NEXT_PUBLIC_WEB_URL}${image}` : undefined;
+ let ogImage = image ? `${buildEnv.NEXT_PUBLIC_WEB_URL}${image}` : undefined;
return {
title,
@@ -29,7 +29,7 @@ export async function generateMetadata({
title,
description,
type: "article",
- url: `${clientEnv.NEXT_PUBLIC_WEB_URL}/docs/${doc.slug}`,
+ url: `${buildEnv.NEXT_PUBLIC_WEB_URL}/docs/${doc.slug}`,
...(ogImage && {
images: [
{
diff --git a/apps/web/app/invite/[inviteId]/page.tsx b/apps/web/app/invite/[inviteId]/page.tsx
index 728991b5e..8ec1afa51 100644
--- a/apps/web/app/invite/[inviteId]/page.tsx
+++ b/apps/web/app/invite/[inviteId]/page.tsx
@@ -1,4 +1,3 @@
-"use server";
import { db } from "@cap/database";
import { eq } from "drizzle-orm";
import { spaceInvites, spaces, users } from "@cap/database/schema";
@@ -26,7 +25,7 @@ export async function generateMetadata({ params }: Props): Promise<Metadata> {
}
async function getInviteDetails(inviteId: string) {
- const query = await db
+ const query = await db()
.select({
invite: spaceInvites,
spaceName: spaces.name,
diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx
index e881dacec..4b0d46f91 100644
--- a/apps/web/app/layout.tsx
+++ b/apps/web/app/layout.tsx
@@ -3,14 +3,18 @@ import { BentoScript } from "@/components/BentoScript";
import { Footer } from "@/components/Footer";
import { Navbar } from "@/components/Navbar";
import { getCurrentUser } from "@cap/database/auth/session";
-import { serverEnv } from "@cap/env";
+import { buildEnv, serverEnv } from "@cap/env";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
-import crypto from "crypto";
import type { Metadata } from "next";
-import { cookies, headers } from "next/headers";
import { Toaster } from "react-hot-toast";
import { AuthProvider } from "./AuthProvider";
import { PostHogProvider, Providers } from "./providers";
+import { PublicEnvContext } from "@/utils/public-env";
+import { S3_BUCKET_URL } from "@cap/utils";
+import { PropsWithChildren } from "react";
+import crypto from "crypto";
+//@ts-expect-error
+import { script } from "./themeScript";
export const metadata: Metadata = {
title: "Cap — Beautiful screen recordings, owned by you.",
@@ -26,29 +30,17 @@ export const metadata: Metadata = {
},
};
-export default async function RootLayout({
- children,
-}: {
- children: React.ReactNode;
-}) {
+export default async function RootLayout({ children }: PropsWithChildren) {
const user = await getCurrentUser();
+ const intercomSecret = serverEnv().INTERCOM_SECRET;
let intercomHash = "";
- if (serverEnv.INTERCOM_SECRET) {
+ if (intercomSecret) {
intercomHash = crypto
- .createHmac("sha256", serverEnv.INTERCOM_SECRET)
+ .createHmac("sha256", intercomSecret)
.update(user?.id ?? "")
.digest("hex");
}
- const path = headers().get("x-current-path");
- const isPathDashboard =
- path?.startsWith("/dashboard") ||
- path?.startsWith("/login") ||
- path?.startsWith("/onboarding");
-
- const cookieStore = await cookies();
- const theme = cookieStore.get("theme")?.value === "dark" ? "dark" : "light";
-
return (
<html lang="en">
<head>
@@ -75,24 +67,35 @@ export default async function RootLayout({
<meta name="msapplication-TileColor" content="#da532c" />
<meta name="theme-color" content="#ffffff" />
</head>
- <body className={isPathDashboard ? theme : "light"}>
+ <body suppressHydrationWarning>
+ <script
+ dangerouslySetInnerHTML={{ __html: `(${script.toString()})()` }}
+ />
<TooltipPrimitive.Provider>
<PostHogProvider>
<AuthProvider>
- <Providers
- userId={user?.id}
- intercomHash={intercomHash}
- name={`${user?.name ?? ""} ${user?.lastName ?? ""}`}
- email={user?.email ?? ""}
+ <PublicEnvContext
+ value={{
+ webUrl: buildEnv.NEXT_PUBLIC_WEB_URL,
+ awsBucket: buildEnv.NEXT_PUBLIC_CAP_AWS_BUCKET,
+ s3BucketUrl: S3_BUCKET_URL,
+ }}
>
- <Toaster />
- <main className="overflow-x-hidden w-full">
- <Navbar auth={user ? true : false} />
- {children}
- <Footer />
- </main>
- <BentoScript user={user} />
- </Providers>
+ <Providers
+ userId={user?.id}
+ intercomHash={intercomHash}
+ name={`${user?.name ?? ""} ${user?.lastName ?? ""}`}
+ email={user?.email ?? ""}
+ >
+ <Toaster />
+ <main className="overflow-x-hidden w-full">
+ <Navbar auth={user ? true : false} />
+ {children}
+ <Footer />
+ </main>
+ <BentoScript user={user} />
+ </Providers>
+ </PublicEnvContext>
</AuthProvider>
</PostHogProvider>
</TooltipPrimitive.Provider>
diff --git a/apps/web/app/login/page.tsx b/apps/web/app/login/page.tsx
index b77e9f99d..8065d9022 100644
--- a/apps/web/app/login/page.tsx
+++ b/apps/web/app/login/page.tsx
@@ -2,6 +2,8 @@ import { getCurrentUser } from "@cap/database/auth/session";
import { redirect } from "next/navigation";
import { LoginForm } from "./form";
+export const dynamic = "force-dynamic";
+
export default async function LoginPage() {
const session = await getCurrentUser();
if (session) {
diff --git a/apps/web/app/onboarding/page.tsx b/apps/web/app/onboarding/page.tsx
index b8fd43830..22e8c324f 100644
--- a/apps/web/app/onboarding/page.tsx
+++ b/apps/web/app/onboarding/page.tsx
@@ -3,6 +3,8 @@ import { LogoBadge } from "@cap/ui";
import { redirect } from "next/navigation";
import { Onboarding } from "./Onboarding";
+export const dynamic = "force-dynamic";
+
export default async function OnboardingPage() {
const user = await getCurrentUser();
diff --git a/apps/web/app/pricing/page.tsx b/apps/web/app/pricing/page.tsx
index 8654ee4f6..23fb6756e 100644
--- a/apps/web/app/pricing/page.tsx
+++ b/apps/web/app/pricing/page.tsx
@@ -1,10 +1,15 @@
import { PricingPage } from "@/components/pages/PricingPage";
import { Metadata } from "next";
+import { Suspense } from "react";
export const metadata: Metadata = {
title: "Early Adopter Pricing — Cap",
};
export default function App() {
- return <PricingPage />;
+ return (
+ <Suspense>
+ <PricingPage />
+ </Suspense>
+ );
}
diff --git a/apps/web/app/providers.tsx b/apps/web/app/providers.tsx
index 16ab0783a..0aee21035 100644
--- a/apps/web/app/providers.tsx
+++ b/apps/web/app/providers.tsx
@@ -1,18 +1,18 @@
"use client";
-import { useEffect } from "react";
+import { PropsWithChildren, useEffect } from "react";
import { identifyUser, initAnonymousUser, trackEvent } from "./utils/analytics";
import posthog from "posthog-js";
import { PostHogProvider as PHProvider } from "posthog-js/react";
-import { clientEnv } from "@cap/env";
+import { buildEnv } from "@cap/env";
import PostHogPageView from "./PosthogPageView";
import Intercom from "@intercom/messenger-js-sdk";
import { usePathname } from "next/navigation";
-export function PostHogProvider({ children }: { children: React.ReactNode }) {
+export function PostHogProvider({ children }: PropsWithChildren) {
useEffect(() => {
- const key = clientEnv.NEXT_PUBLIC_POSTHOG_KEY;
- const host = clientEnv.NEXT_PUBLIC_POSTHOG_HOST;
+ const key = buildEnv.NEXT_PUBLIC_POSTHOG_KEY;
+ const host = buildEnv.NEXT_PUBLIC_POSTHOG_HOST;
if (key && host) {
try {
diff --git a/apps/web/app/robots.ts b/apps/web/app/robots.ts
index bdbbeab43..c0d4e8698 100644
--- a/apps/web/app/robots.ts
+++ b/apps/web/app/robots.ts
@@ -1,7 +1,6 @@
import { seoPages } from "@/lib/seo-pages";
import { MetadataRoute } from "next";
-export const dynamic = "force-dynamic";
export const revalidate = 0;
export default function robots(): MetadataRoute.Robots {
diff --git a/apps/web/app/s/[videoId]/Share.tsx b/apps/web/app/s/[videoId]/Share.tsx
index a29112e86..7af1de57f 100644
--- a/apps/web/app/s/[videoId]/Share.tsx
+++ b/apps/web/app/s/[videoId]/Share.tsx
@@ -3,7 +3,6 @@
import { getVideoAnalytics } from "@/actions/videos/get-analytics";
import { userSelectProps } from "@cap/database/auth/session";
import { comments as commentsSchema, videos } from "@cap/database/schema";
-import { clientEnv } from "@cap/env";
import { Logo } from "@cap/ui";
import { useEffect, useRef, useState } from "react";
import { ShareHeader } from "./_components/ShareHeader";
@@ -137,7 +136,7 @@ export const Share: React.FC<ShareProps> = ({
<div className="py-4 mt-auto">
<a
target="_blank"
- href={`${clientEnv.NEXT_PUBLIC_WEB_URL}?ref=video_${data.id}`}
+ href={`/?ref=video_${data.id}`}
className="flex justify-center items-center px-4 py-2 mx-auto space-x-2 bg-gray-1 rounded-full new-card-style w-fit"
>
<span className="text-sm">Recorded with</span>
diff --git a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx b/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
index 42d74fe6e..c950604ca 100644
--- a/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareHeader.tsx
@@ -1,17 +1,18 @@
-import { editTitle } from "@/actions/videos/edit-title";
-import { UpgradeModal } from "@/components/UpgradeModal";
-import { userSelectProps } from "@cap/database/auth/session";
-import { videos } from "@cap/database/schema";
-import { clientEnv, NODE_ENV } from "@cap/env";
import { Button } from "@cap/ui";
-import { isUserOnProPlan } from "@cap/utils";
-import { Copy, Globe2 } from "lucide-react";
+import { videos } from "@cap/database/schema";
+import moment from "moment";
+import { userSelectProps } from "@cap/database/auth/session";
import { faChevronDown } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
-import moment from "moment";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { toast } from "react-hot-toast";
+import { Copy, Globe2 } from "lucide-react";
+import { buildEnv, NODE_ENV } from "@cap/env";
+import { editTitle } from "@/actions/videos/edit-title";
+import { usePublicEnv } from "@/utils/public-env";
+import { isUserOnProPlan } from "@cap/utils";
+import { UpgradeModal } from "@/components/UpgradeModal";
import { SharingDialog } from "@/app/dashboard/caps/components/SharingDialog";
import clsx from "clsx";
@@ -40,6 +41,8 @@ export const ShareHeader = ({
const isOwner = user !== null && user.id.toString() === data.ownerId;
+ const { webUrl } = usePublicEnv();
+
const handleBlur = async () => {
setIsEditing(false);
@@ -65,17 +68,17 @@ export const ShareHeader = ({
const getVideoLink = () => {
return customDomain && domainVerified
? `https://${customDomain}/s/${data.id}`
- : clientEnv.NEXT_PUBLIC_IS_CAP && NODE_ENV === "production"
+ : buildEnv.NEXT_PUBLIC_IS_CAP && NODE_ENV === "production"
? `https://cap.link/${data.id}`
- : `${clientEnv.NEXT_PUBLIC_WEB_URL}/s/${data.id}`;
+ : `${webUrl}/s/${data.id}`;
};
const getDisplayLink = () => {
return customDomain && domainVerified
? `${customDomain}/s/${data.id}`
- : clientEnv.NEXT_PUBLIC_IS_CAP && NODE_ENV === "production"
+ : buildEnv.NEXT_PUBLIC_IS_CAP && NODE_ENV === "production"
? `cap.link/${data.id}`
- : `${clientEnv.NEXT_PUBLIC_WEB_URL}/s/${data.id}`;
+ : `${webUrl}/s/${data.id}`;
};
const isUserPro = user
@@ -196,7 +199,7 @@ export const ShareHeader = ({
<div className="hidden md:flex">
<Button
onClick={() => {
- push(`${clientEnv.NEXT_PUBLIC_WEB_URL}/dashboard`);
+ push("/dashboard");
}}
>
<span className="hidden text-sm text-white lg:block">
diff --git a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
index 1db4a7dba..c6b0e73a8 100644
--- a/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
+++ b/apps/web/app/s/[videoId]/_components/ShareVideo.tsx
@@ -1,10 +1,9 @@
-import { UpgradeModal } from "@/components/UpgradeModal";
-import { apiClient } from "@/utils/web-api";
+import { useApiClient } from "@/utils/web-api";
import { userSelectProps } from "@cap/database/auth/session";
import { comments as commentsSchema, videos } from "@cap/database/schema";
-import { clientEnv, NODE_ENV } from "@cap/env";
+import { NODE_ENV } from "@cap/env";
import { Logo, LogoSpinner } from "@cap/ui";
-import { isUserOnProPlan, S3_BUCKET_URL } from "@cap/utils";
+import { isUserOnProPlan } from "@cap/utils";
import clsx from "clsx";
import { AnimatePresence, motion } from "framer-motion";
import {
@@ -27,6 +26,8 @@ import { Tooltip } from "react-tooltip";
import { fromVtt, Subtitle } from "subtitles-parser-vtt";
import { MP4VideoPlayer } from "./MP4VideoPlayer";
import { VideoPlayer } from "./VideoPlayer";
+import { usePublicEnv } from "@/utils/public-env";
+import { UpgradeModal } from "@/components/UpgradeModal";
declare global {
interface Window {
@@ -129,7 +130,7 @@ export const ShareVideo = forwardRef<
// Pre-fetch the first thumbnail to check if it exists
if (data.source.type === "desktopMP4") {
- const thumbUrl = `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&thumbnailTime=0`;
+ const thumbUrl = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&thumbnailTime=0`;
// Check if the thumbnail exists
fetch(thumbUrl, { method: "HEAD" })
@@ -503,7 +504,7 @@ export const ShareVideo = forwardRef<
const scrubVideo = document.createElement("video");
// Use the same MP4 source construction as the main video
- const mp4Source = `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=mp4`;
+ const mp4Source = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=mp4`;
scrubVideo.src = mp4Source;
scrubVideo.crossOrigin = "anonymous";
@@ -951,19 +952,20 @@ export const ShareVideo = forwardRef<
return hoursValue * 3600 + minutesValue * 60 + secondsValue;
};
+ const publicEnv = usePublicEnv();
+
+ const apiClient = useApiClient();
+
useEffect(() => {
const fetchSubtitles = async () => {
let transcriptionUrl;
- if (
- data.bucket &&
- data.awsBucket !== clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET
- ) {
+ if (data.bucket && data.awsBucket !== publicEnv.awsBucket) {
// For custom S3 buckets, fetch through the API
transcriptionUrl = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&fileType=transcription`;
} else {
// For default Cap storage
- transcriptionUrl = `${S3_BUCKET_URL}/${data.ownerId}/${data.id}/transcription.vtt`;
+ transcriptionUrl = `${publicEnv.s3BucketUrl}/${data.ownerId}/${data.id}/transcription.vtt`;
}
try {
@@ -1093,18 +1095,18 @@ export const ShareVideo = forwardRef<
let videoSrc: string;
if (data.source.type === "desktopMP4") {
- videoSrc = `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=mp4`;
+ videoSrc = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=mp4`;
} else if (
// v.cap.so is only available in prod
NODE_ENV === "development" ||
((data.skipProcessing === true || data.jobStatus !== "COMPLETE") &&
data.source.type === "MediaConvert")
) {
- videoSrc = `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=master`;
+ videoSrc = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&videoType=master`;
} else if (data.source.type === "MediaConvert") {
- videoSrc = `${S3_BUCKET_URL}/${data.ownerId}/${data.id}/output/video_recording_000.m3u8`;
+ videoSrc = `${publicEnv.s3BucketUrl}/${data.ownerId}/${data.id}/output/video_recording_000.m3u8`;
} else {
- videoSrc = `${S3_BUCKET_URL}/${data.ownerId}/${data.id}/combined-source/stream.m3u8`;
+ videoSrc = `${publicEnv.s3BucketUrl}/${data.ownerId}/${data.id}/combined-source/stream.m3u8`;
}
return (
diff --git a/apps/web/app/s/[videoId]/_components/Toolbar.tsx b/apps/web/app/s/[videoId]/_components/Toolbar.tsx
index 093a9363b..cabb78208 100644
--- a/apps/web/app/s/[videoId]/_components/Toolbar.tsx
+++ b/apps/web/app/s/[videoId]/_components/Toolbar.tsx
@@ -1,7 +1,6 @@
"use client";
import { userSelectProps } from "@cap/database/auth/session";
import { videos } from "@cap/database/schema";
-import { clientEnv } from "@cap/env";
import { Button } from "@cap/ui";
import { useRouter } from "next/navigation";
import { useEffect, useRef, useState } from "react";
@@ -82,22 +81,19 @@ export const Toolbar = ({
const timestamp = getTimestamp();
console.log("Current timestamp:", timestamp);
- const response = await fetch(
- `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/video/comment`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- type: "emoji",
- content: emoji,
- videoId: data.id,
- parentCommentId: null,
- timestamp: timestamp,
- }),
- }
- );
+ const response = await fetch("/api/video/comment", {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ type: "emoji",
+ content: emoji,
+ videoId: data.id,
+ parentCommentId: null,
+ timestamp: timestamp,
+ }),
+ });
if (response.status === 429) {
toast.error("Too many requests - please try again later.");
diff --git a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
index 53f05a640..503dd6df5 100644
--- a/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
+++ b/apps/web/app/s/[videoId]/_components/tabs/Transcript.tsx
@@ -1,10 +1,9 @@
"use client";
import { videos } from "@cap/database/schema";
-import { clientEnv } from "@cap/env";
-import { S3_BUCKET_URL } from "@cap/utils";
+import { useState, useEffect } from "react";
import { MessageSquare } from "lucide-react";
-import { useEffect, useState } from "react";
+import { usePublicEnv } from "@/utils/public-env";
interface TranscriptProps {
data: typeof videos.$inferSelect;
@@ -116,17 +115,18 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
useState(false);
const [hasTimedOut, setHasTimedOut] = useState(false);
+ const publicEnv = usePublicEnv();
+
useEffect(() => {
const fetchTranscript = async () => {
let transcriptionUrl;
- if (
- data.bucket &&
- data.awsBucket !== clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET
- ) {
+ if (data.bucket && data.awsBucket !== publicEnv.awsBucket) {
+ // For custom S3 buckets, fetch through the API
transcriptionUrl = `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&fileType=transcription`;
} else {
- transcriptionUrl = `${S3_BUCKET_URL}/${data.ownerId}/${data.id}/transcription.vtt`;
+ // For default Cap storage
+ transcriptionUrl = `${publicEnv.s3BucketUrl}/${data.ownerId}/${data.id}/transcription.vtt`;
}
try {
@@ -191,9 +191,9 @@ export const Transcript: React.FC<TranscriptProps> = ({ data, onSeek }) => {
setIsLoading(true);
const fetchTranscript = async () => {
const transcriptionUrl =
- data.bucket && data.awsBucket !== clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET
+ data.bucket && data.awsBucket !== publicEnv.awsBucket
? `/api/playlist?userId=${data.ownerId}&videoId=${data.id}&fileType=transcription`
- : `${S3_BUCKET_URL}/${data.ownerId}/${data.id}/transcription.vtt`;
+ : `${publicEnv.s3BucketUrl}/${data.ownerId}/${data.id}/transcription.vtt`;
try {
const response = await fetch(transcriptionUrl);
diff --git a/apps/web/app/s/[videoId]/page.tsx b/apps/web/app/s/[videoId]/page.tsx
index 52c36dcb3..b54417155 100644
--- a/apps/web/app/s/[videoId]/page.tsx
+++ b/apps/web/app/s/[videoId]/page.tsx
@@ -13,7 +13,7 @@ import { getCurrentUser, userSelectProps } from "@cap/database/auth/session";
import type { Metadata, ResolvingMetadata } from "next";
import { notFound } from "next/navigation";
import { ImageViewer } from "./_components/ImageViewer";
-import { clientEnv } from "@cap/env";
+import { buildEnv, serverEnv } from "@cap/env";
import { getVideoAnalytics } from "@/actions/videos/get-analytics";
import { transcribeVideo } from "@/actions/videos/transcribe";
import { getScreenshot } from "@/actions/screenshots/get-screenshot";
@@ -52,7 +52,7 @@ export async function generateMetadata(
"[generateMetadata] Fetching video metadata for videoId:",
videoId
);
- const query = await db.select().from(videos).where(eq(videos.id, videoId));
+ const query = await db().select().from(videos).where(eq(videos.id, videoId));
if (query.length === 0) {
console.log("[generateMetadata] No video found for videoId:", videoId);
@@ -74,7 +74,7 @@ export async function generateMetadata(
{
url: new URL(
`/api/video/og?videoId=${videoId}`,
- clientEnv.NEXT_PUBLIC_WEB_URL
+ buildEnv.NEXT_PUBLIC_WEB_URL
).toString(),
width: 1200,
height: 630,
@@ -92,7 +92,7 @@ export async function generateMetadata(
{
url: new URL(
`/api/video/og?videoId=${videoId}`,
- clientEnv.NEXT_PUBLIC_WEB_URL
+ buildEnv.NEXT_PUBLIC_WEB_URL
).toString(),
width: 1200,
height: 630,
@@ -111,7 +111,7 @@ export default async function ShareVideoPage(props: Props) {
const userId = user?.id as string | undefined;
console.log("[ShareVideoPage] Current user:", userId);
- const videoWithSpace = await db
+ const videoWithSpace = await db()
.select({
id: videos.id,
name: videos.name,
@@ -149,7 +149,7 @@ export default async function ShareVideoPage(props: Props) {
}
if (video.sharedSpace?.spaceId) {
- const space = await db
+ const space = await db()
.select()
.from(spaces)
.where(eq(spaces.id, video.sharedSpace.spaceId))
@@ -191,7 +191,7 @@ export default async function ShareVideoPage(props: Props) {
}
console.log("[ShareVideoPage] Fetching comments for video:", videoId);
- const commentsQuery: CommentWithAuthor[] = await db
+ const commentsQuery: CommentWithAuthor[] = await db()
.select({
id: comments.id,
content: comments.content,
@@ -242,7 +242,7 @@ export default async function ShareVideoPage(props: Props) {
let domainVerified = false;
if (video.sharedSpace?.spaceId) {
- const spaceData = await db
+ const spaceData = await db()
.select({
customDomain: spaces.customDomain,
domainVerified: spaces.domainVerified,
@@ -260,7 +260,7 @@ export default async function ShareVideoPage(props: Props) {
}
if (!customDomain && video.ownerId) {
- const ownerSpaces = await db
+ const ownerSpaces = await db()
.select({
customDomain: spaces.customDomain,
domainVerified: spaces.domainVerified,
@@ -281,7 +281,7 @@ export default async function ShareVideoPage(props: Props) {
}
}
- const sharedSpacesData = await db
+ const sharedSpacesData = await db()
.select({
id: spaces.id,
name: spaces.name,
@@ -292,7 +292,7 @@ export default async function ShareVideoPage(props: Props) {
let userSpaces: { id: string; name: string }[] = [];
if (userId) {
- const ownedSpaces = await db
+ const ownedSpaces = await db()
.select({
id: spaces.id,
name: spaces.name,
@@ -300,7 +300,7 @@ export default async function ShareVideoPage(props: Props) {
.from(spaces)
.where(eq(spaces.ownerId, userId));
- const memberSpaces = await db
+ const memberSpaces = await db()
.select({
id: spaces.id,
name: spaces.name,
@@ -319,7 +319,7 @@ export default async function ShareVideoPage(props: Props) {
}
const membersList = video.sharedSpace?.spaceId
- ? await db
+ ? await db()
.select({
userId: spaceMembers.userId,
})
diff --git a/apps/web/app/themeScript.js b/apps/web/app/themeScript.js
new file mode 100644
index 000000000..247e8aff5
--- /dev/null
+++ b/apps/web/app/themeScript.js
@@ -0,0 +1,15 @@
+export function script() {
+ const cookie = (() => {
+ if (!document.cookie) return undefined;
+ const match = document.cookie.match(/\W?theme=(?<theme>\w+)/);
+ return match?.groups?.theme;
+ })();
+
+ const pathname = window.location.pathname;
+ const isDashboardPath =
+ pathname.startsWith("/dashboard") ||
+ pathname.startsWith("/login") ||
+ pathname.startsWith("/onboarding");
+
+ if (isDashboardPath) document.body.classList.add(cookie ?? "light");
+}
diff --git a/apps/web/app/tools/layout.tsx b/apps/web/app/tools/layout.tsx
index 90b8c3d67..bb8f26805 100644
--- a/apps/web/app/tools/layout.tsx
+++ b/apps/web/app/tools/layout.tsx
@@ -1,7 +1,13 @@
+import { Suspense } from "react";
+
export default function ToolsLayout({
children,
}: {
children: React.ReactNode;
}) {
- return <section>{children}</section>;
+ return (
+ <Suspense>
+ <section>{children}</section>
+ </Suspense>
+ );
}
diff --git a/apps/web/components/BentoScript.tsx b/apps/web/components/BentoScript.tsx
index a044c641e..2b550d84c 100644
--- a/apps/web/components/BentoScript.tsx
+++ b/apps/web/components/BentoScript.tsx
@@ -3,7 +3,7 @@
import { useEffect } from "react";
import Script from "next/script";
import { users } from "@cap/database/schema";
-import { usePathname, useSearchParams } from "next/navigation";
+import { usePathname } from "next/navigation";
declare global {
interface Window {
@@ -17,7 +17,6 @@ export function BentoScript({
user?: typeof users.$inferSelect | null;
}) {
const pathname = usePathname();
- const searchParams = useSearchParams();
useEffect(() => {
if (window.bento !== undefined) {
@@ -26,7 +25,7 @@ export function BentoScript({
}
window.bento.view();
}
- }, [pathname, searchParams]);
+ }, [pathname]);
return (
<Script
diff --git a/apps/web/components/forms/server.ts b/apps/web/components/forms/server.ts
index 9672d58b4..c430eb848 100644
--- a/apps/web/components/forms/server.ts
+++ b/apps/web/components/forms/server.ts
@@ -12,20 +12,20 @@ export async function createSpace(args: { name: string }) {
if (!user) throw new Error("Unauthorized");
const spaceId = nanoId();
- await db.insert(spaces).values({
+ await db().insert(spaces).values({
id: spaceId,
ownerId: user.id,
name: args.name,
});
- await db.insert(spaceMembers).values({
+ await db().insert(spaceMembers).values({
id: nanoId(),
userId: user.id,
role: "owner",
spaceId,
});
- await db
+ await db()
.update(users)
.set({ activeSpaceId: spaceId })
.where(eq(users.id, user.id));
diff --git a/apps/web/components/tools/types.ts b/apps/web/components/tools/types.ts
index f33ff33ed..a834b9143 100644
--- a/apps/web/components/tools/types.ts
+++ b/apps/web/components/tools/types.ts
@@ -6,22 +6,22 @@ export interface ToolPageContent {
category: string;
author: string;
tags: string[];
-
+
cta: {
title: string;
description: string;
buttonText: string;
};
-
+
featuresTitle: string;
featuresDescription: string;
features: Array<{
title: string;
description: string;
}>;
-
+
faqs?: Array<{
question: string;
answer: string;
}>;
-}
\ No newline at end of file
+}
diff --git a/apps/web/instrumentation.ts b/apps/web/instrumentation.ts
new file mode 100644
index 000000000..5dc20ffdb
--- /dev/null
+++ b/apps/web/instrumentation.ts
@@ -0,0 +1,96 @@
+// This file is used to run database migrations in the docker builds or other self hosting environments.
+// It is not suitable (a.k.a DEADLY) for serverless environments where the server will be restarted on each request.
+
+import { serverEnv } from "@cap/env";
+import { createS3Client } from "./utils/s3";
+import {
+ BucketAlreadyOwnedByYou,
+ CreateBucketCommand,
+ PutBucketPolicyCommand,
+} from "@aws-sdk/client-s3";
+
+export async function register() {
+ if (process.env.NEXT_RUNTIME === "nodejs") {
+ console.log("Waiting 5 seconds to run migrations");
+
+ // Function to trigger migrations with retry logic
+ const triggerMigrations = async (retryCount = 0, maxRetries = 3) => {
+ try {
+ const response = await fetch(
+ `${serverEnv().WEB_URL}/api/selfhosted/migrations`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }
+ );
+
+ // This will throw an error if the response status is not ok
+ response.ok ||
+ (await Promise.reject(new Error(`HTTP error ${response.status}`)));
+
+ const responseData = await response.json();
+ console.log(
+ "✅ Migrations triggered successfully:",
+ responseData.message
+ );
+ } catch (error) {
+ console.error(
+ `🚨 Error triggering migrations (attempt ${retryCount + 1}):`,
+ error
+ );
+ if (retryCount < maxRetries - 1) {
+ console.log(
+ `🔄 Retrying in 5 seconds... (${retryCount + 1}/${maxRetries})`
+ );
+ setTimeout(() => triggerMigrations(retryCount + 1, maxRetries), 5000);
+ } else {
+ console.error(`🚨 All ${maxRetries} migration attempts failed.`);
+ process.exit(1); // Exit with error code if all attempts fail
+ }
+ }
+ };
+
+ // Add a timeout to trigger migrations after 5 seconds on server start
+ setTimeout(() => triggerMigrations(), 5000);
+
+ setTimeout(() => createS3Bucket(), 5000);
+ }
+ return;
+}
+
+async function createS3Bucket() {
+ const [s3Client] = await createS3Client();
+
+ await s3Client
+ .send(new CreateBucketCommand({ Bucket: serverEnv().CAP_AWS_BUCKET }))
+ .then(() => {
+ console.log("Created S3 bucket");
+ return s3Client.send(
+ new PutBucketPolicyCommand({
+ Bucket: serverEnv().CAP_AWS_BUCKET,
+ Policy: JSON.stringify({
+ Version: "2012-10-17",
+ Statement: [
+ {
+ Effect: "Allow",
+ Principal: "*",
+ Action: ["s3:GetObject"],
+ Resource: [`arn:aws:s3:::${serverEnv().CAP_AWS_BUCKET}/*`],
+ },
+ ],
+ }),
+ })
+ );
+ })
+ .then(() => {
+ console.log("Configured S3 buckeet");
+ })
+ .catch((e) => {
+ if (e instanceof BucketAlreadyOwnedByYou) {
+ console.log("Found existing S3 bucket");
+ return;
+ }
+ });
+}
diff --git a/apps/web/middleware.ts b/apps/web/middleware.ts
index 25572a9c6..e71af0711 100644
--- a/apps/web/middleware.ts
+++ b/apps/web/middleware.ts
@@ -1,17 +1,23 @@
import { db } from "@cap/database";
import { spaces } from "@cap/database/schema";
-import { serverEnv } from "@cap/env";
import { eq } from "drizzle-orm";
-import type { NextRequest } from "next/server";
-import { NextResponse } from "next/server";
+import { buildEnv, serverEnv } from "@cap/env";
+import { notFound } from "next/navigation";
+import { NextRequest, NextResponse } from "next/server";
-const mainDomains = [
- "cap.so",
- "cap.link",
- "localhost",
- serverEnv.VERCEL_URL,
- serverEnv.VERCEL_BRANCH_URL,
- serverEnv.VERCEL_PROJECT_PRODUCTION_URL,
+const addHttps = (s?: string) => {
+ if (!s) return s;
+ return `https://${s}`;
+};
+
+const mainOrigins = [
+ "https://cap.so",
+ "https://cap.link",
+ "http://localhost",
+ serverEnv().WEB_URL,
+ addHttps(serverEnv().VERCEL_URL),
+ addHttps(serverEnv().VERCEL_BRANCH_URL),
+ addHttps(serverEnv().VERCEL_PROJECT_PRODUCTION_URL),
].filter(Boolean) as string[];
export async function middleware(request: NextRequest) {
@@ -19,67 +25,32 @@ export async function middleware(request: NextRequest) {
const hostname = url.hostname;
const path = url.pathname;
-
- if (!hostname) return NextResponse.next();
-
- // we use this to set the theme to light mode outside of the dashboard
- if (path) {
- const response = NextResponse.next();
- response.headers.set("x-current-path", path);
- return response;
- }
-
- if (mainDomains.some((d) => hostname.includes(d))) {
+ if (
+ buildEnv.NEXT_PUBLIC_IS_CAP !== "true" ||
+ mainOrigins.some((d) => url.origin === d)
+ ) {
// We just let the request go through for main domains, page-level logic will handle redirects
return NextResponse.next();
}
- // We're on a custom domain at this point
- // Only allow /s/ routes for custom domains
- if (!path.startsWith("/s/")) {
- const url = new URL(request.url);
- url.hostname = "cap.so";
- return NextResponse.redirect(url);
- }
-
- // Check if we have a cached verification
- const verifiedDomain = request.cookies.get("verified_domain");
- if (verifiedDomain?.value === hostname) {
- // Domain is verified from cache, handle CORS for API routes
- if (path.startsWith("/api/")) {
- if (request.method === "OPTIONS") {
- const response = new NextResponse(null, { status: 204 });
- response.headers.set("Access-Control-Allow-Origin", "*");
- response.headers.set(
- "Access-Control-Allow-Methods",
- "GET, POST, PUT, DELETE, OPTIONS"
- );
- response.headers.set(
- "Access-Control-Allow-Headers",
- "Content-Type, Authorization"
- );
- response.headers.set("Access-Control-Max-Age", "86400");
- return response;
- }
+ const webUrl = new URL(serverEnv().WEB_URL).hostname;
- const response = NextResponse.next();
- response.headers.set("Access-Control-Allow-Origin", "*");
- response.headers.set(
- "Access-Control-Allow-Methods",
- "GET, POST, PUT, DELETE, OPTIONS"
- );
- response.headers.set(
- "Access-Control-Allow-Headers",
- "Content-Type, Authorization"
- );
- return response;
+ try {
+ // We're on a custom domain at this point
+ // Only allow /s/ routes for custom domains
+ if (!path.startsWith("/s/")) {
+ const url = new URL(request.url);
+ url.hostname = webUrl;
+ console.log({ url });
+ return NextResponse.redirect(url);
}
- return NextResponse.next();
- }
- try {
+ // Check if we have a cached verification
+ const verifiedDomain = request.cookies.get("verified_domain");
+ if (verifiedDomain?.value === hostname) return NextResponse.next();
+
// Query the space with this custom domain
- const [space] = await db
+ const [space] = await db()
.select()
.from(spaces)
.where(eq(spaces.customDomain, hostname));
@@ -87,54 +58,10 @@ export async function middleware(request: NextRequest) {
if (!space || !space.domainVerified) {
// If no verified custom domain found, redirect to main domain
const url = new URL(request.url);
- url.hostname = "cap.so";
+ url.hostname = webUrl;
return NextResponse.redirect(url);
}
- // Domain is verified at this point, handle CORS for API routes
- if (path.startsWith("/api/")) {
- if (request.method === "OPTIONS") {
- const response = new NextResponse(null, { status: 204 });
- response.headers.set("Access-Control-Allow-Origin", "*");
- response.headers.set(
- "Access-Control-Allow-Methods",
- "GET, POST, PUT, DELETE, OPTIONS"
- );
- response.headers.set(
- "Access-Control-Allow-Headers",
- "Content-Type, Authorization"
- );
- response.headers.set("Access-Control-Max-Age", "86400");
- // Set verification cookie
- response.cookies.set("verified_domain", hostname, {
- httpOnly: true,
- secure: process.env.NODE_ENV === "production",
- sameSite: "strict",
- maxAge: 3600, // Cache for 1 hour
- });
- return response;
- }
-
- const response = NextResponse.next();
- response.headers.set("Access-Control-Allow-Origin", "*");
- response.headers.set(
- "Access-Control-Allow-Methods",
- "GET, POST, PUT, DELETE, OPTIONS"
- );
- response.headers.set(
- "Access-Control-Allow-Headers",
- "Content-Type, Authorization"
- );
- // Set verification cookie
- response.cookies.set("verified_domain", hostname, {
- httpOnly: true,
- secure: process.env.NODE_ENV === "production",
- sameSite: "strict",
- maxAge: 3600, // Cache for 1 hour
- });
- return response;
- }
-
// Set verification cookie for non-API routes too
const response = NextResponse.next();
response.cookies.set("verified_domain", hostname, {
@@ -146,7 +73,7 @@ export async function middleware(request: NextRequest) {
return response;
} catch (error) {
console.error("Error in middleware:", error);
- return NextResponse.next();
+ return notFound();
}
}
diff --git a/apps/web/next.config.mjs b/apps/web/next.config.mjs
index 5c7a0035a..d1dd18f7c 100644
--- a/apps/web/next.config.mjs
+++ b/apps/web/next.config.mjs
@@ -21,6 +21,7 @@ const nextConfig = {
ignoreBuildErrors: true,
},
experimental: {
+ instrumentationHook: process.env.DOCKER_BUILD === "true",
optimizePackageImports: ["@cap/ui", "@cap/utils", "@cap/web-api-contract"],
serverComponentsExternalPackages: [
"@react-email/components",
@@ -61,15 +62,15 @@ const nextConfig = {
destination: "https://l.cap.so/api/commercial/:path*",
},
{
- source: '/s/:videoId',
- destination: '/s/:videoId',
+ source: "/s/:videoId",
+ destination: "/s/:videoId",
has: [
{
- type: 'host',
- value: '(?!cap\.so|cap\.link).*',
+ type: "host",
+ value: "(?!cap.so|cap.link).*",
},
],
- }
+ },
];
},
async redirects() {
@@ -100,6 +101,8 @@ const nextConfig = {
env: {
appVersion: version,
},
+ // If the DOCKER_BUILD environment variable is set to true, we are output nextjs to standalone ready for docker deployment
+ output: process.env.DOCKER_BUILD === "true" ? "standalone" : undefined,
};
export default nextConfig;
diff --git a/apps/web/package.json b/apps/web/package.json
index 24b483cd4..d620ad24d 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -5,6 +5,8 @@
"scripts": {
"dev": "dotenv -e ../../.env -- next dev",
"build": "next build",
+ "build:web": "next build",
+ "build:web:docker": "cd ../.. && docker build -t cap-web-docker . --no-cache --progress=plain",
"start": "next start",
"lint": "next lint",
"compress-images": "bash tools/compress-images.sh"
@@ -108,4 +110,4 @@
"engines": {
"node": "20"
}
-}
+}
\ No newline at end of file
diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json
index 9db93bcf8..95571bbc7 100644
--- a/apps/web/tsconfig.json
+++ b/apps/web/tsconfig.json
@@ -2,7 +2,11 @@
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
- "lib": ["DOM", "DOM.Iterable", "ESNext"],
+ "lib": [
+ "DOM",
+ "DOM.Iterable",
+ "ESNext"
+ ],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
@@ -24,15 +28,33 @@
],
"baseUrl": ".",
"paths": {
- "@/app/*": ["app/*"],
- "@/components/*": ["components/*"],
- "@/pages/*": ["components/pages/*"],
- "@/utils/*": ["utils/*"],
- "@/lib/*": ["lib/*"],
- "@/actions/*": ["actions/*"]
+ "@/app/*": [
+ "app/*"
+ ],
+ "@/components/*": [
+ "components/*"
+ ],
+ "@/pages/*": [
+ "components/pages/*"
+ ],
+ "@/utils/*": [
+ "utils/*"
+ ],
+ "@/lib/*": [
+ "lib/*"
+ ],
+ "@/actions/*": [
+ "actions/*"
+ ]
}
},
-
- "include": ["next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"],
- "exclude": ["node_modules"]
+ "include": [
+ "next-env.d.ts",
+ "**/*.ts",
+ "**/*.tsx",
+ ".next/types/**/*.ts"
+ ],
+ "exclude": [
+ "node_modules"
+ ]
}
diff --git a/apps/web/utils/cors.ts b/apps/web/utils/cors.ts
index 699de9881..c9885b6f5 100644
--- a/apps/web/utils/cors.ts
+++ b/apps/web/utils/cors.ts
@@ -1,7 +1,7 @@
-import { clientEnv } from "@cap/env";
+import { buildEnv } from "@cap/env";
export const allowedOrigins = [
- clientEnv.NEXT_PUBLIC_WEB_URL,
+ buildEnv.NEXT_PUBLIC_WEB_URL,
"http://localhost:3001",
"http://localhost:3000",
"tauri://localhost",
diff --git a/apps/web/utils/dub.ts b/apps/web/utils/dub.ts
index 82517d99a..fdefc646a 100644
--- a/apps/web/utils/dub.ts
+++ b/apps/web/utils/dub.ts
@@ -1,6 +1,7 @@
import { Dub } from "dub";
import { serverEnv } from "@cap/env";
-export const dub = new Dub({
- token: serverEnv.DUB_API_KEY,
-});
+export const dub = () =>
+ new Dub({
+ token: serverEnv().DUB_API_KEY,
+ });
diff --git a/apps/web/utils/helpers.ts b/apps/web/utils/helpers.ts
index cfd361c19..47f81dd4d 100644
--- a/apps/web/utils/helpers.ts
+++ b/apps/web/utils/helpers.ts
@@ -2,7 +2,7 @@ import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
import { type NextRequest } from "next/server";
import { ReadonlyHeaders } from "next/dist/server/web/spec-extension/adapters/headers";
-import { clientEnv } from "@cap/env";
+import { buildEnv, serverEnv } from "@cap/env";
export function classNames(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
@@ -10,7 +10,7 @@ export function classNames(...inputs: ClassValue[]) {
// Base allowed origins
export const allowedOrigins = [
- clientEnv.NEXT_PUBLIC_WEB_URL,
+ buildEnv.NEXT_PUBLIC_WEB_URL,
"https://cap.link",
"cap.link",
];
diff --git a/apps/web/utils/public-env.tsx b/apps/web/utils/public-env.tsx
new file mode 100644
index 000000000..e7534146e
--- /dev/null
+++ b/apps/web/utils/public-env.tsx
@@ -0,0 +1,25 @@
+"use client";
+
+import { createContext, PropsWithChildren, useContext } from "react";
+type PublicEnvContext = {
+ webUrl: string;
+ awsBucket: string;
+ s3BucketUrl: string;
+};
+
+const Context = createContext<PublicEnvContext | null>(null);
+
+export function PublicEnvContext(
+ props: { value: PublicEnvContext } & PropsWithChildren
+) {
+ return (
+ <Context.Provider value={props.value}>{props.children}</Context.Provider>
+ );
+}
+
+export function usePublicEnv() {
+ const ctx = useContext(Context);
+ if (!ctx)
+ throw new Error("usePublicEnv must be used within a PublicEnvContext");
+ return ctx;
+}
diff --git a/apps/web/utils/s3.ts b/apps/web/utils/s3.ts
index bd3980307..e7c0cf971 100644
--- a/apps/web/utils/s3.ts
+++ b/apps/web/utils/s3.ts
@@ -2,7 +2,7 @@ import { S3Client } from "@aws-sdk/client-s3";
import type { s3Buckets } from "@cap/database/schema";
import type { InferSelectModel } from "drizzle-orm";
import { decrypt } from "@cap/database/crypto";
-import { clientEnv, serverEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
type S3Config = {
endpoint?: string | null;
@@ -27,23 +27,22 @@ async function tryDecrypt(
export async function getS3Config(config?: S3Config) {
if (!config) {
return {
- endpoint: clientEnv.NEXT_PUBLIC_CAP_AWS_ENDPOINT,
- region: clientEnv.NEXT_PUBLIC_CAP_AWS_REGION,
+ endpoint: serverEnv().CAP_AWS_ENDPOINT,
+ region: serverEnv().CAP_AWS_REGION,
credentials: {
- accessKeyId: serverEnv.CAP_AWS_ACCESS_KEY ?? "",
- secretAccessKey: serverEnv.CAP_AWS_SECRET_KEY ?? "",
+ accessKeyId: serverEnv().CAP_AWS_ACCESS_KEY ?? "",
+ secretAccessKey: serverEnv().CAP_AWS_SECRET_KEY ?? "",
},
- forcePathStyle:
- clientEnv.NEXT_PUBLIC_CAP_AWS_ENDPOINT?.includes("localhost"),
+ forcePathStyle: serverEnv().S3_PATH_STYLE,
};
}
const endpoint = config.endpoint
? await tryDecrypt(config.endpoint)
- : clientEnv.NEXT_PUBLIC_CAP_AWS_ENDPOINT;
+ : serverEnv().CAP_AWS_ENDPOINT;
const region =
- (await tryDecrypt(config.region)) ?? clientEnv.NEXT_PUBLIC_CAP_AWS_REGION;
+ (await tryDecrypt(config.region)) ?? serverEnv().CAP_AWS_REGION;
const finalRegion = endpoint?.includes("localhost") ? "us-east-1" : region;
@@ -56,11 +55,11 @@ export async function getS3Config(config?: S3Config) {
credentials: {
accessKeyId:
(await tryDecrypt(config.accessKeyId)) ??
- serverEnv.CAP_AWS_ACCESS_KEY ??
+ serverEnv().CAP_AWS_ACCESS_KEY ??
"",
secretAccessKey:
(await tryDecrypt(config.secretAccessKey)) ??
- serverEnv.CAP_AWS_SECRET_KEY ??
+ serverEnv().CAP_AWS_SECRET_KEY ??
"",
},
forcePathStyle: config.forcePathStyle ?? true,
@@ -76,13 +75,11 @@ export async function getS3Bucket(
bucket?: InferSelectModel<typeof s3Buckets> | null
) {
if (!bucket?.bucketName) {
- return clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET || "";
+ return serverEnv().CAP_AWS_BUCKET || "";
}
return (
- ((await tryDecrypt(bucket.bucketName)) ??
- clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET) ||
- ""
+ ((await tryDecrypt(bucket.bucketName)) ?? serverEnv().CAP_AWS_BUCKET) || ""
);
}
diff --git a/apps/web/utils/video/ffmpeg/helpers.ts b/apps/web/utils/video/ffmpeg/helpers.ts
index d1b4763ea..214a343d6 100644
--- a/apps/web/utils/video/ffmpeg/helpers.ts
+++ b/apps/web/utils/video/ffmpeg/helpers.ts
@@ -1,140 +1,4 @@
import { S3_BUCKET_URL } from "@cap/utils";
-import { FFmpeg } from "@ffmpeg/ffmpeg";
-import { clientEnv } from "@cap/env";
-
-export const playlistToMp4 = async (
- userId: string,
- videoId: string,
- videoName: string
-) => {
- const ffmpeg = new FFmpeg();
- await ffmpeg.load();
-
- if (!ffmpeg) {
- throw new Error("FFmpeg not loaded");
- }
-
- const videoFetch = await fetch(
- `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/video/playlistUrl?userId=${userId}&videoId=${videoId}`
- );
-
- if (videoFetch.status !== 200) {
- throw new Error("Could not fetch video");
- }
-
- const video = await videoFetch.json();
-
- if (!video.playlistOne) {
- throw new Error("Video does not have a valid video playlist");
- }
-
- // Fetch the video playlist data
- const videoResponse = await fetch(video.playlistOne);
- const videoData = await videoResponse.text();
- const videoUrls = videoData
- .split("\n")
- .filter((line) => line && !line.startsWith("#"));
-
- // Download video files and write to FFmpeg FS
- for (const [index, url] of videoUrls.entries()) {
- const fullUrl = url.startsWith("https")
- ? url
- : `${S3_BUCKET_URL}/${userId}/${videoId}/output/${url}`;
- const segmentResponse = await fetch(fullUrl);
- const segmentData = new Uint8Array(await segmentResponse.arrayBuffer());
- await ffmpeg.writeFile(`video${index}.ts`, segmentData);
- }
-
- // Concatenate all video files using FFmpeg
- const videoConcatList = videoUrls
- .map((_, index) => `file 'video${index}.ts'`)
- .join("\n");
- await ffmpeg.writeFile("videolist.txt", videoConcatList);
-
- if (video.playlistTwo) {
- // Fetch the audio playlist data if available
- const audioResponse = await fetch(video.playlistTwo);
- const audioData = await audioResponse.text();
- const audioUrls = audioData
- .split("\n")
- .filter((line) => line && !line.startsWith("#"));
-
- // Download audio files and write to FFmpeg FS
- for (const [index, url] of audioUrls.entries()) {
- const fullUrl = url.startsWith("https")
- ? url
- : `${S3_BUCKET_URL}/tzv973qb6ghnznf/z3ha0dv61q5hrdw/output/${url}`;
- const segmentResponse = await fetch(fullUrl);
- const segmentData = new Uint8Array(await segmentResponse.arrayBuffer());
- await ffmpeg.writeFile(`audio${index}.ts`, segmentData);
- }
-
- // Concatenate all audio files using FFmpeg
- const audioConcatList = audioUrls
- .map((_, index) => `file 'audio${index}.ts'`)
- .join("\n");
- await ffmpeg.writeFile("audiolist.txt", audioConcatList);
-
- // Merge video and audio into final MP4
- await ffmpeg.exec([
- "-f",
- "concat",
- "-safe",
- "0",
- "-i",
- "videolist.txt",
- "-c",
- "copy",
- "temp_video.mp4",
- ]);
- await ffmpeg.exec([
- "-f",
- "concat",
- "-safe",
- "0",
- "-i",
- "audiolist.txt",
- "-c",
- "copy",
- "temp_audio.mp4",
- ]);
- await ffmpeg.exec([
- "-i",
- "temp_video.mp4",
- "-i",
- "temp_audio.mp4",
- "-c:v",
- "copy",
- "-c:a",
- "aac",
- "-async",
- "1", // Adjusts audio to match the number of video frames
- "-vsync",
- "1", // Ensures frames are handled correctly
- "-copyts", // Copy timestamps
- videoName + ".mp4",
- ]);
- } else {
- // Only video available, process as single MP4
- await ffmpeg.exec([
- "-f",
- "concat",
- "-safe",
- "0",
- "-i",
- "videolist.txt",
- "-c",
- "copy",
- videoName + ".mp4",
- ]);
- }
-
- // Read the result and create a Blob
- const mp4Data = await ffmpeg.readFile(videoName + ".mp4");
- const mp4Blob = new Blob([mp4Data], { type: "video/mp4" });
-
- return mp4Blob;
-};
export function generateM3U8Playlist(
urls: {
diff --git a/apps/web/utils/video/upload/helpers.ts b/apps/web/utils/video/upload/helpers.ts
index c6dfad8ad..9b2a82015 100644
--- a/apps/web/utils/video/upload/helpers.ts
+++ b/apps/web/utils/video/upload/helpers.ts
@@ -1,4 +1,4 @@
-import { clientEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
export async function uploadToS3({
filename,
@@ -21,25 +21,22 @@ export async function uploadToS3({
awsBucket: string;
awsRegion: string;
}) {
- const response = await fetch(
- `${clientEnv.NEXT_PUBLIC_WEB_URL}/api/upload/signed`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- userId: userId,
- fileKey: filename,
- duration: duration,
- resolution: resolution,
- videoCodec: videoCodec,
- audioCodec: audioCodec,
- awsBucket: awsBucket,
- awsRegion: awsRegion,
- }),
- }
- );
+ const response = await fetch(`${serverEnv().WEB_URL}/api/upload/signed`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ userId: userId,
+ fileKey: filename,
+ duration: duration,
+ resolution: resolution,
+ videoCodec: videoCodec,
+ audioCodec: audioCodec,
+ awsBucket: awsBucket,
+ awsRegion: awsRegion,
+ }),
+ });
const { presignedPostData } = await response.json();
diff --git a/apps/web/utils/web-api.ts b/apps/web/utils/web-api.ts
index dbeb1a2f2..d3650b1c9 100644
--- a/apps/web/utils/web-api.ts
+++ b/apps/web/utils/web-api.ts
@@ -1,10 +1,16 @@
import { initClient } from "@ts-rest/core";
import { contract } from "@cap/web-api-contract";
-import { clientEnv } from "@cap/env";
+import { useContext, useState } from "react";
-export const apiClient = initClient(contract, {
- baseUrl:
- typeof window !== "undefined"
- ? `${clientEnv.NEXT_PUBLIC_WEB_URL}/api`
- : "/api",
-});
+import { usePublicEnv } from "./public-env";
+
+export function useApiClient() {
+ const { webUrl } = usePublicEnv();
+ const [client] = useState(() =>
+ initClient(contract, {
+ baseUrl: typeof window !== "undefined" ? `${webUrl}/api` : "/api",
+ })
+ );
+
+ return client;
+}
diff --git a/docker-compose.template.yml b/docker-compose.template.yml
new file mode 100644
index 000000000..1f057badc
--- /dev/null
+++ b/docker-compose.template.yml
@@ -0,0 +1,70 @@
+name: cap-so-docker-template
+
+# THIS IS A TEMPLATE FOR DOCKER COMPOSE FILES
+# IT IS NOT MEANT FOR PRODUCTION DEPLOYMENT WITHOUT MODIFICATIONS TO ENVIRONMENT VARIABLES
+# IT IS MEANT FOR LOCAL EVALUATION AND DEVELOPMENT PURPOSES ONLY
+
+services:
+ cap-web:
+ container_name: cap-web
+ image: cap-web-docker:latest
+ restart: unless-stopped
+ environment:
+ DATABASE_URL: 'mysql://root:@ps-mysql:3306/planetscale?ssl={"rejectUnauthorized":false}'
+ DATABASE_MIGRATION_URL: 'mysql://root:@ps-mysql:3306/planetscale?ssl={"rejectUnauthorized":false}'
+ WEB_URL: http://localhost:3000
+ NEXTAUTH_URL: http://localhost:3000
+ DOCKER_BUILD: true
+ # CHANGE THESE TO YOUR OWN VALUES
+ DATABASE_ENCRYPTION_KEY: c7a1e98e1e5e4cec5a3fbf5eaf502d262fb99807ae2be8ee70537409e29cb6f9
+ NEXTAUTH_SECRET: c7a1e98e1e5e4cec5a3fbf5eaf502d262fb99807ae2be8ee70537409e29cb6f9
+ # CHANGE THESE TO MATCH YOUR MINIO or S3 STORAGE SETUP
+ CAP_AWS_ACCESS_KEY: capS3root
+ CAP_AWS_SECRET_KEY: capS3root
+ CAP_AWS_BUCKET: capso
+ CAP_AWS_REGION: us-east-1
+ CAP_AWS_ENDPOINT: http://minio:3902
+ ports:
+ - 3000:3000
+
+ ps-mysql:
+ container_name: cap-primary-db
+ image: mysql:8.0
+ restart: unless-stopped
+ environment:
+ # CHANGE THESE TO YOUR OWN VALUES - BE SURE TO SET A PASSWORD FOR THE ROOT USER
+ MYSQL_DATABASE: planetscale
+ MYSQL_ROOT_HOST: "%"
+ MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
+ command:
+ [
+ "--max_connections=1000",
+ "--default-authentication-plugin=mysql_native_password",
+ ]
+ ports:
+ - "3306:3306"
+ volumes:
+ - ps-mysql:/var/lib/mysql
+
+ # Local S3 Strorage
+ minio:
+ container_name: cap-minio-storage
+ image: "bitnami/minio:latest"
+ restart: unless-stopped
+ ports:
+ - "3902:3902"
+ - "3903:3903"
+ environment:
+ - MINIO_API_PORT_NUMBER=3902
+ - MINIO_CONSOLE_PORT_NUMBER=3903
+ # CHANGE THESE TO YOUR OWN VALUES
+ - MINIO_ROOT_USER=capS3root
+ - MINIO_ROOT_PASSWORD=capS3root
+ volumes:
+ - minio-data:/bitnami/minio/data
+ - minio-certs:/certs
+volumes:
+ ps-mysql:
+ # REMOVE THESE IF YOU ARE NOT USING MINIO VIA THIS DOCKER COMPOSE FILE
+ minio-data:
+ minio-certs:
diff --git a/package.json b/package.json
index 5dc9f6ecb..540d4b88e 100644
--- a/package.json
+++ b/package.json
@@ -2,6 +2,8 @@
"type": "module",
"scripts": {
"build": "dotenv -e .env -- turbo run build",
+ "build:web": "turbo run build:web",
+ "build:web:docker": "pnpm run --filter=@cap/web build:web:docker",
"cap-setup": "dotenv -e .env -- node scripts/setup.js",
"db:generate": "dotenv -e .env -- pnpm --dir packages/database db:generate",
"db:push": "dotenv -e .env -- pnpm --dir packages/database db:push",
diff --git a/packages/database/.gitignore b/packages/database/.gitignore
index 7598f9f53..e69de29bb 100644
--- a/packages/database/.gitignore
+++ b/packages/database/.gitignore
@@ -1 +0,0 @@
-/migrations
\ No newline at end of file
diff --git a/packages/database/auth/auth-options.ts b/packages/database/auth/auth-options.ts
index ed9134ef0..e9dd5daef 100644
--- a/packages/database/auth/auth-options.ts
+++ b/packages/database/auth/auth-options.ts
@@ -10,140 +10,159 @@ import { LoginLink } from "../emails/login-link";
import { nanoId } from "../helpers";
import WorkOSProvider from "next-auth/providers/workos";
import { NODE_ENV, serverEnv } from "@cap/env";
+import type { Adapter } from "next-auth/adapters";
+import type { Provider } from "next-auth/providers/index";
export const config = {
maxDuration: 120,
};
-const secret = serverEnv.NEXTAUTH_SECRET;
+export const authOptions = (): NextAuthOptions => {
+ let _adapter: Adapter | undefined;
+ let _providers: Provider[] | undefined;
-export const authOptions: NextAuthOptions = {
- adapter: DrizzleAdapter(db),
- debug: true,
- session: {
- strategy: "jwt",
- },
- secret: secret as string,
- pages: {
- signIn: "/login",
- },
- providers: [
- GoogleProvider({
- clientId: serverEnv.GOOGLE_CLIENT_ID!,
- clientSecret: serverEnv.GOOGLE_CLIENT_SECRET!,
- authorization: {
- params: {
- scope: [
- "https://www.googleapis.com/auth/userinfo.email",
- "https://www.googleapis.com/auth/userinfo.profile",
- ].join(" "),
- prompt: "select_account",
+ return {
+ get adapter() {
+ if (_adapter) return _adapter;
+ _adapter = DrizzleAdapter(db());
+ return _adapter;
+ },
+ debug: true,
+ session: {
+ strategy: "jwt",
+ },
+ get secret() {
+ return serverEnv().NEXTAUTH_SECRET;
+ },
+ pages: {
+ signIn: "/login",
+ },
+ get providers() {
+ if (_providers) return _providers;
+ _providers = [
+ GoogleProvider({
+ clientId: serverEnv().GOOGLE_CLIENT_ID!,
+ clientSecret: serverEnv().GOOGLE_CLIENT_SECRET!,
+ authorization: {
+ params: {
+ scope: [
+ "https://www.googleapis.com/auth/userinfo.email",
+ "https://www.googleapis.com/auth/userinfo.profile",
+ ].join(" "),
+ prompt: "select_account",
+ },
+ },
+ }),
+ WorkOSProvider({
+ clientId: serverEnv().WORKOS_CLIENT_ID as string,
+ clientSecret: serverEnv().WORKOS_API_KEY as string,
+ profile(profile) {
+ return {
+ id: profile.id,
+ name: profile.first_name
+ ? `${profile.first_name} ${profile.last_name || ""}`
+ : profile.email?.split("@")[0] || profile.id,
+ email: profile.email,
+ image: profile.profile_picture_url,
+ };
+ },
+ }),
+ EmailProvider({
+ sendVerificationRequest({ identifier, url }) {
+ if (
+ NODE_ENV === "development" ||
+ !serverEnv().RESEND_API_KEY ||
+ serverEnv().RESEND_API_KEY === ""
+ ) {
+ console.log(`Login link: ${url}`);
+ } else {
+ sendEmail({
+ email: identifier,
+ subject: `Your Cap Login Link`,
+ react: LoginLink({ url, email: identifier }),
+ });
+ }
+ },
+ }),
+ ];
+
+ return _providers;
+ },
+ cookies: {
+ sessionToken: {
+ name: `next-auth.session-token`,
+ options: {
+ httpOnly: true,
+ sameSite: "none",
+ path: "/",
+ secure: true,
},
},
- }),
- WorkOSProvider({
- clientId: serverEnv.WORKOS_CLIENT_ID as string,
- clientSecret: serverEnv.WORKOS_API_KEY as string,
- profile(profile) {
- return {
- id: profile.id,
- name: profile.first_name
- ? `${profile.first_name} ${profile.last_name || ""}`
- : profile.email?.split("@")[0] || profile.id,
- email: profile.email,
- image: profile.profile_picture_url,
- };
- },
- }),
- EmailProvider({
- sendVerificationRequest({ identifier, url }) {
- console.log({ NODE_ENV });
- if (NODE_ENV === "development") {
- console.log(`Login link: ${url}`);
- } else {
- sendEmail({
- email: identifier,
- subject: `Your Cap Login Link`,
- react: LoginLink({ url, email: identifier }),
- });
- }
- },
- }),
- ],
- cookies: {
- sessionToken: {
- name: `next-auth.session-token`,
- options: {
- httpOnly: true,
- sameSite: "none",
- path: "/",
- secure: true,
- },
},
- },
- events: {
- async signIn({ user, account, isNewUser }) {
- if (isNewUser) {
- // Create initial space for the user
- const spaceId = nanoId();
+ events: {
+ async signIn({ user, account, isNewUser }) {
+ if (isNewUser) {
+ // Create initial space for the user
+ const spaceId = nanoId();
- // Create space
- await db.insert(spaces).values({
- id: spaceId,
- name: "My Space",
- ownerId: user.id,
- });
+ // Create space
+ await db().insert(spaces).values({
+ id: spaceId,
+ name: "My Space",
+ ownerId: user.id,
+ });
- // Add user as member of the space
- await db.insert(spaceMembers).values({
- id: nanoId(),
- userId: user.id,
- spaceId: spaceId,
- role: "owner",
- });
+ // Add user as member of the space
+ await db().insert(spaceMembers).values({
+ id: nanoId(),
+ userId: user.id,
+ spaceId: spaceId,
+ role: "owner",
+ });
- // Update user's activeSpaceId
- await db
- .update(users)
- .set({ activeSpaceId: spaceId })
- .where(eq(users.id, user.id));
- }
+ // Update user's activeSpaceId
+ await db()
+ .update(users)
+ .set({ activeSpaceId: spaceId })
+ .where(eq(users.id, user.id));
+ }
+ },
},
- },
- callbacks: {
- async session({ token, session }) {
- if (!session.user) return session;
+ callbacks: {
+ async session({ token, session }) {
+ if (!session.user) return session;
- if (token) {
- session.user.id = token.id;
- session.user.name = token.name;
- session.user.email = token.email;
- session.user.image = token.picture;
- }
+ if (token) {
+ session.user.id = token.id;
+ session.user.name = token.name;
+ session.user.email = token.email;
+ session.user.image = token.picture;
+ }
- return session;
- },
- async jwt({ token, user }) {
- const [dbUser] = await db
- .select()
- .from(users)
- .where(eq(users.email, token.email || ""))
- .limit(1);
+ return session;
+ },
+ async jwt({ token, user }) {
+ const [dbUser] = await db()
+ .select()
+ .from(users)
+ .where(eq(users.email, token.email || ""))
+ .limit(1);
- if (!dbUser) {
- if (user) {
- token.id = user?.id;
+ if (!dbUser) {
+ if (user) {
+ token.id = user?.id;
+ }
+ return token;
}
- return token;
- }
- return {
- id: dbUser.id,
- name: dbUser.name,
- lastName: dbUser.lastName,
- email: dbUser.email,
- picture: dbUser.image,
- };
+ return {
+ id: dbUser.id,
+ name: dbUser.name,
+ lastName: dbUser.lastName,
+ email: dbUser.email,
+ picture: dbUser.image,
+ };
+ },
},
- },
+ };
};
diff --git a/packages/database/auth/drizzle-adapter.ts b/packages/database/auth/drizzle-adapter.ts
index 3538997e1..f347358aa 100644
--- a/packages/database/auth/drizzle-adapter.ts
+++ b/packages/database/auth/drizzle-adapter.ts
@@ -25,8 +25,8 @@ export function DrizzleAdapter(db: PlanetScaleDatabase): Adapter {
const row = rows[0];
if (!row) throw new Error("User not found");
- if (STRIPE_AVAILABLE) {
- const customer = await stripe.customers.create({
+ if (STRIPE_AVAILABLE()) {
+ const customer = await stripe().customers.create({
email: userData.email,
metadata: {
userId: nanoId(),
diff --git a/packages/database/auth/session.ts b/packages/database/auth/session.ts
index 51f278c84..2684e8c84 100644
--- a/packages/database/auth/session.ts
+++ b/packages/database/auth/session.ts
@@ -5,19 +5,19 @@ import { db } from "../";
import { users } from "../schema";
export const getSession = async () => {
- const session = await getServerSession(authOptions);
+ const session = await getServerSession(authOptions());
return session;
};
export const getCurrentUser = async (session?: Session) => {
- const _session = session ?? (await getServerSession(authOptions));
+ const _session = session ?? (await getServerSession(authOptions()));
if (!_session) {
return null;
}
- const [currentUser] = await db
+ const [currentUser] = await db()
.select()
.from(users)
.where(eq(users.id, _session?.user.id));
diff --git a/packages/database/crypto.ts b/packages/database/crypto.ts
index 6aa74cb5d..96ab6cbcd 100644
--- a/packages/database/crypto.ts
+++ b/packages/database/crypto.ts
@@ -6,28 +6,36 @@ const SALT_LENGTH = 16;
const KEY_LENGTH = 32;
const ITERATIONS = 100000;
-const ENCRYPTION_KEY = serverEnv.DATABASE_ENCRYPTION_KEY as string;
-
-// Verify the encryption key is valid hex and correct length
-try {
- const keyBuffer = Buffer.from(ENCRYPTION_KEY, "hex");
- if (keyBuffer.length !== KEY_LENGTH) {
- throw new Error(
- `Encryption key must be ${KEY_LENGTH} bytes (${
- KEY_LENGTH * 2
- } hex characters)`
- );
- }
-} catch (error: unknown) {
- if (error instanceof Error) {
- throw new Error(`Invalid encryption key format: ${error.message}`);
+const ENCRYPTION_KEY = () => {
+ const key = serverEnv().DATABASE_ENCRYPTION_KEY;
+ if (!key) return;
+
+ // Verify the encryption key is valid hex and correct length
+ try {
+ const keyBuffer = Buffer.from(key, "hex");
+ if (keyBuffer.length !== KEY_LENGTH) {
+ throw new Error(
+ `Encryption key must be ${KEY_LENGTH} bytes (${
+ KEY_LENGTH * 2
+ } hex characters)`
+ );
+ }
+ } catch (error: unknown) {
+ if (error instanceof Error) {
+ throw new Error(`Invalid encryption key format: ${error.message}`);
+ }
+ throw new Error("Invalid encryption key format");
}
- throw new Error("Invalid encryption key format");
-}
+
+ return key;
+};
async function deriveKey(salt: Uint8Array): Promise<CryptoKey> {
+ const key = ENCRYPTION_KEY();
+ if (!key) throw new Error("Encryption key is not available");
+
// Convert hex string to ArrayBuffer for Web Crypto API
- const keyBuffer = Buffer.from(ENCRYPTION_KEY, "hex");
+ const keyBuffer = Buffer.from(key, "hex");
const keyMaterial = await crypto.subtle.importKey(
"raw",
@@ -73,9 +81,9 @@ export async function encrypt(text: string): Promise<string> {
// Combine salt, IV, and encrypted content
const result = Buffer.concat([
- Buffer.from(salt),
- Buffer.from(iv),
- Buffer.from(encrypted),
+ Buffer.from(salt as any) as any,
+ Buffer.from(iv as any) as any,
+ Buffer.from(encrypted as any) as any,
]);
return result.toString("base64");
@@ -101,7 +109,7 @@ export async function decrypt(encryptedText: string): Promise<string> {
const content = encrypted.subarray(SALT_LENGTH + IV_LENGTH);
// Derive the same key using the extracted salt
- const key = await deriveKey(salt);
+ const key = await deriveKey(salt as Uint8Array);
const decrypted = await crypto.subtle.decrypt(
{
diff --git a/packages/database/drizzle.config.ts b/packages/database/drizzle.config.ts
index dfc8589fb..4195dc069 100644
--- a/packages/database/drizzle.config.ts
+++ b/packages/database/drizzle.config.ts
@@ -1,7 +1,7 @@
import { serverEnv } from "@cap/env";
import type { Config } from "drizzle-kit";
-const URL = serverEnv.DATABASE_MIGRATION_URL ?? serverEnv.DATABASE_URL;
+const URL = serverEnv().DATABASE_MIGRATION_URL ?? serverEnv().DATABASE_URL;
if (!URL)
throw new Error("DATABASE_URL or DATABASE_MIGRATION_URL must be set!");
diff --git a/packages/database/emails/config.ts b/packages/database/emails/config.ts
index bd29ee15c..eacdea0b9 100644
--- a/packages/database/emails/config.ts
+++ b/packages/database/emails/config.ts
@@ -1,10 +1,9 @@
-import { clientEnv, serverEnv } from "@cap/env";
+import { buildEnv, serverEnv } from "@cap/env";
import { JSXElementConstructor, ReactElement } from "react";
import { Resend } from "resend";
-export const resend = serverEnv.RESEND_API_KEY
- ? new Resend(serverEnv.RESEND_API_KEY)
- : null;
+export const resend = () =>
+ serverEnv().RESEND_API_KEY ? new Resend(serverEnv().RESEND_API_KEY) : null;
// Augment the CreateEmailOptions type to include scheduledAt
type EmailOptions = {
@@ -30,16 +29,19 @@ export const sendEmail = async ({
test?: boolean;
scheduledAt?: string;
}) => {
- if (!resend) {
+ const r = resend();
+ if (!r) {
return Promise.resolve();
}
- return resend.emails.send({
+ return r.emails.send({
from: marketing
? "Richie from Cap <[email protected]>"
- : clientEnv.NEXT_PUBLIC_IS_CAP
+ : buildEnv.NEXT_PUBLIC_IS_CAP
? "Cap Auth <[email protected]>"
- : `auth@${clientEnv.NEXT_PUBLIC_WEB_URL}`,
+ : `auth@${
+ serverEnv().RESEND_FROM_DOMAIN ?? buildEnv.NEXT_PUBLIC_WEB_URL
+ }`,
to: test ? "[email protected]" : email,
subject,
react,
diff --git a/packages/database/index.ts b/packages/database/index.ts
index f633f34f9..5866114ae 100644
--- a/packages/database/index.ts
+++ b/packages/database/index.ts
@@ -1,22 +1,33 @@
import { drizzle } from "drizzle-orm/planetscale-serverless";
import { Client, Config } from "@planetscale/database";
-import { NODE_ENV, serverEnv } from "@cap/env";
+import { serverEnv } from "@cap/env";
-const URL = serverEnv.DATABASE_URL;
+function createDrizzle() {
+ const URL = serverEnv().DATABASE_URL;
-let fetchHandler: Promise<Config["fetch"]> | undefined = undefined;
+ let fetchHandler: Promise<Config["fetch"]> | undefined = undefined;
-if (NODE_ENV === "development" && URL.startsWith("mysql://")) {
- fetchHandler = import("@mattrax/mysql-planetscale").then((m) =>
- m.createFetchHandler(URL)
- );
+ if (URL.startsWith("mysql://")) {
+ fetchHandler = import("@mattrax/mysql-planetscale").then((m) =>
+ m.createFetchHandler(URL)
+ );
+ }
+
+ const connection = new Client({
+ url: URL,
+ fetch: async (input, init) => {
+ return await ((await fetchHandler) || fetch)(input, init);
+ },
+ });
+
+ return drizzle(connection);
}
-export const connection = new Client({
- url: URL,
- fetch: async (input, init) => {
- return await ((await fetchHandler) || fetch)(input, init);
- },
-});
+let _cached: ReturnType<typeof createDrizzle> | undefined = undefined;
-export const db = drizzle(connection);
+export const db = () => {
+ if (!_cached) {
+ _cached = createDrizzle();
+ }
+ return _cached;
+};
diff --git a/packages/database/migrations/0000_brown_sunfire.sql b/packages/database/migrations/0000_brown_sunfire.sql
new file mode 100644
index 000000000..fdba906d5
--- /dev/null
+++ b/packages/database/migrations/0000_brown_sunfire.sql
@@ -0,0 +1,191 @@
+CREATE TABLE `accounts` (
+ `id` varchar(15) NOT NULL,
+ `userId` varchar(15) NOT NULL,
+ `type` varchar(255) NOT NULL,
+ `provider` varchar(255) NOT NULL,
+ `providerAccountId` varchar(255) NOT NULL,
+ `access_token` text,
+ `expires_in` int,
+ `id_token` text,
+ `refresh_token` text,
+ `refresh_token_expires_in` int,
+ `scope` varchar(255),
+ `token_type` varchar(255),
+ `createdAt` timestamp NOT NULL DEFAULT (now()),
+ `updatedAt` timestamp NOT NULL DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
+ `tempColumn` text,
+ CONSTRAINT `accounts_id` PRIMARY KEY(`id`),
+ CONSTRAINT `accounts_id_unique` UNIQUE(`id`)
+);
+--> statement-breakpoint
+CREATE TABLE `comments` (
+ `id` varchar(15) NOT NULL,
+ `type` varchar(6) NOT NULL,
+ `content` text NOT NULL,
+ `timestamp` float,
+ `authorId` varchar(15) NOT NULL,
+ `videoId` varchar(15) NOT NULL,
+ `createdAt` timestamp NOT NULL DEFAULT (now()),
+ `updatedAt` timestamp NOT NULL DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
+ `parentCommentId` varchar(15),
+ CONSTRAINT `comments_id` PRIMARY KEY(`id`),
+ CONSTRAINT `comments_id_unique` UNIQUE(`id`)
+);
+--> statement-breakpoint
+CREATE TABLE `s3_buckets` (
+ `id` varchar(15) NOT NULL,
+ `ownerId` varchar(15) NOT NULL,
+ `region` text NOT NULL,
+ `endpoint` text,
+ `bucketName` text NOT NULL,
+ `accessKeyId` text NOT NULL,
+ `secretAccessKey` text NOT NULL,
+ `provider` text NOT NULL DEFAULT ('aws'),
+ CONSTRAINT `s3_buckets_id` PRIMARY KEY(`id`),
+ CONSTRAINT `s3_buckets_id_unique` UNIQUE(`id`)
+);
+--> statement-breakpoint
+CREATE TABLE `sessions` (
+ `id` varchar(15) NOT NULL,
+ `sessionToken` varchar(255) NOT NULL,
+ `userId` varchar(15) NOT NULL,
+ `expires` datetime NOT NULL,
+ `created_at` timestamp NOT NULL DEFAULT (now()),
+ `updated_at` timestamp NOT NULL DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
+ CONSTRAINT `sessions_id` PRIMARY KEY(`id`),
+ CONSTRAINT `sessions_id_unique` UNIQUE(`id`),
+ CONSTRAINT `sessions_sessionToken_unique` UNIQUE(`sessionToken`),
+ CONSTRAINT `session_token_idx` UNIQUE(`sessionToken`)
+);
+--> statement-breakpoint
+CREATE TABLE `shared_videos` (
+ `id` varchar(15) NOT NULL,
+ `videoId` varchar(15) NOT NULL,
+ `spaceId` varchar(15) NOT NULL,
+ `sharedByUserId` varchar(15) NOT NULL,
+ `sharedAt` timestamp NOT NULL DEFAULT (now()),
+ CONSTRAINT `shared_videos_id` PRIMARY KEY(`id`),
+ CONSTRAINT `shared_videos_id_unique` UNIQUE(`id`)
+);
+--> statement-breakpoint
+CREATE TABLE `space_invites` (
+ `id` varchar(15) NOT NULL,
+ `spaceId` varchar(15) NOT NULL,
+ `invitedEmail` varchar(255) NOT NULL,
+ `invitedByUserId` varchar(15) NOT NULL,
+ `role` varchar(255) NOT NULL,
+ `status` varchar(255) NOT NULL DEFAULT 'pending',
+ `createdAt` timestamp NOT NULL DEFAULT (now()),
+ `updatedAt` timestamp NOT NULL DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
+ `expiresAt` timestamp,
+ CONSTRAINT `space_invites_id` PRIMARY KEY(`id`),
+ CONSTRAINT `space_invites_id_unique` UNIQUE(`id`)
+);
+--> statement-breakpoint
+CREATE TABLE `space_members` (
+ `id` varchar(15) NOT NULL,
+ `userId` varchar(15) NOT NULL,
+ `spaceId` varchar(15) NOT NULL,
+ `role` varchar(255) NOT NULL,
+ `createdAt` timestamp NOT NULL DEFAULT (now()),
+ `updatedAt` timestamp NOT NULL DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
+ CONSTRAINT `space_members_id` PRIMARY KEY(`id`),
+ CONSTRAINT `space_members_id_unique` UNIQUE(`id`)
+);
+--> statement-breakpoint
+CREATE TABLE `spaces` (
+ `id` varchar(15) NOT NULL,
+ `name` varchar(255) NOT NULL,
+ `ownerId` varchar(15) NOT NULL,
+ `metadata` json,
+ `allowedEmailDomain` varchar(255),
+ `customDomain` varchar(255),
+ `domainVerified` timestamp,
+ `createdAt` timestamp NOT NULL DEFAULT (now()),
+ `updatedAt` timestamp NOT NULL DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
+ `workosOrganizationId` varchar(255),
+ `workosConnectionId` varchar(255),
+ CONSTRAINT `spaces_id` PRIMARY KEY(`id`),
+ CONSTRAINT `spaces_id_unique` UNIQUE(`id`)
+);
+--> statement-breakpoint
+CREATE TABLE `users` (
+ `id` varchar(15) NOT NULL,
+ `name` varchar(255),
+ `lastName` varchar(255),
+ `email` varchar(255) NOT NULL,
+ `emailVerified` timestamp,
+ `image` varchar(255),
+ `stripeCustomerId` varchar(255),
+ `stripeSubscriptionId` varchar(255),
+ `thirdPartyStripeSubscriptionId` varchar(255),
+ `stripeSubscriptionStatus` varchar(255),
+ `stripeSubscriptionPriceId` varchar(255),
+ `activeSpaceId` varchar(15),
+ `created_at` timestamp NOT NULL DEFAULT (now()),
+ `updated_at` timestamp NOT NULL DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
+ `onboarding_completed_at` timestamp,
+ `customBucket` varchar(15),
+ `inviteQuota` int NOT NULL DEFAULT 1,
+ CONSTRAINT `users_id` PRIMARY KEY(`id`),
+ CONSTRAINT `users_id_unique` UNIQUE(`id`),
+ CONSTRAINT `users_email_unique` UNIQUE(`email`),
+ CONSTRAINT `email_idx` UNIQUE(`email`)
+);
+--> statement-breakpoint
+CREATE TABLE `verification_tokens` (
+ `identifier` varchar(255) NOT NULL,
+ `token` varchar(255) NOT NULL,
+ `expires` datetime NOT NULL,
+ `created_at` timestamp NOT NULL DEFAULT (now()),
+ `updated_at` timestamp NOT NULL DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
+ CONSTRAINT `verification_tokens_identifier` PRIMARY KEY(`identifier`),
+ CONSTRAINT `verification_tokens_token_unique` UNIQUE(`token`)
+);
+--> statement-breakpoint
+CREATE TABLE `videos` (
+ `id` varchar(15) NOT NULL,
+ `ownerId` varchar(15) NOT NULL,
+ `name` varchar(255) NOT NULL DEFAULT 'My Video',
+ `awsRegion` varchar(255),
+ `awsBucket` varchar(255),
+ `bucket` varchar(15),
+ `metadata` json,
+ `public` boolean NOT NULL DEFAULT true,
+ `videoStartTime` varchar(255),
+ `audioStartTime` varchar(255),
+ `xStreamInfo` text,
+ `jobId` varchar(255),
+ `jobStatus` varchar(255),
+ `isScreenshot` boolean NOT NULL DEFAULT false,
+ `skipProcessing` boolean NOT NULL DEFAULT false,
+ `transcriptionStatus` varchar(255),
+ `createdAt` timestamp NOT NULL DEFAULT (now()),
+ `updatedAt` timestamp NOT NULL DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
+ `source` json NOT NULL DEFAULT ('{"type":"MediaConvert"}'),
+ CONSTRAINT `videos_id` PRIMARY KEY(`id`),
+ CONSTRAINT `videos_id_unique` UNIQUE(`id`)
+);
+--> statement-breakpoint
+CREATE INDEX `user_id_idx` ON `accounts` (`userId`);--> statement-breakpoint
+CREATE INDEX `provider_account_id_idx` ON `accounts` (`providerAccountId`);--> statement-breakpoint
+CREATE INDEX `video_id_idx` ON `comments` (`videoId`);--> statement-breakpoint
+CREATE INDEX `author_id_idx` ON `comments` (`authorId`);--> statement-breakpoint
+CREATE INDEX `parent_comment_id_idx` ON `comments` (`parentCommentId`);--> statement-breakpoint
+CREATE INDEX `user_id_idx` ON `sessions` (`userId`);--> statement-breakpoint
+CREATE INDEX `video_id_idx` ON `shared_videos` (`videoId`);--> statement-breakpoint
+CREATE INDEX `space_id_idx` ON `shared_videos` (`spaceId`);--> statement-breakpoint
+CREATE INDEX `shared_by_user_id_idx` ON `shared_videos` (`sharedByUserId`);--> statement-breakpoint
+CREATE INDEX `video_id_space_id_idx` ON `shared_videos` (`videoId`,`spaceId`);--> statement-breakpoint
+CREATE INDEX `space_id_idx` ON `space_invites` (`spaceId`);--> statement-breakpoint
+CREATE INDEX `invited_email_idx` ON `space_invites` (`invitedEmail`);--> statement-breakpoint
+CREATE INDEX `invited_by_user_id_idx` ON `space_invites` (`invitedByUserId`);--> statement-breakpoint
+CREATE INDEX `status_idx` ON `space_invites` (`status`);--> statement-breakpoint
+CREATE INDEX `user_id_idx` ON `space_members` (`userId`);--> statement-breakpoint
+CREATE INDEX `space_id_idx` ON `space_members` (`spaceId`);--> statement-breakpoint
+CREATE INDEX `user_id_space_id_idx` ON `space_members` (`userId`,`spaceId`);--> statement-breakpoint
+CREATE INDEX `owner_id_idx` ON `spaces` (`ownerId`);--> statement-breakpoint
+CREATE INDEX `custom_domain_idx` ON `spaces` (`customDomain`);--> statement-breakpoint
+CREATE INDEX `id_idx` ON `videos` (`id`);--> statement-breakpoint
+CREATE INDEX `owner_id_idx` ON `videos` (`ownerId`);--> statement-breakpoint
+CREATE INDEX `is_public_idx` ON `videos` (`public`);
\ No newline at end of file
diff --git a/packages/database/migrations/meta/0000_snapshot.json b/packages/database/migrations/meta/0000_snapshot.json
new file mode 100644
index 000000000..fed508679
--- /dev/null
+++ b/packages/database/migrations/meta/0000_snapshot.json
@@ -0,0 +1,1264 @@
+{
+ "version": "5",
+ "dialect": "mysql",
+ "id": "3d91bc9d-85c3-45eb-b6b6-e1db45b8151d",
+ "prevId": "00000000-0000-0000-0000-000000000000",
+ "tables": {
+ "accounts": {
+ "name": "accounts",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "providerAccountId": {
+ "name": "providerAccountId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "access_token": {
+ "name": "access_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "expires_in": {
+ "name": "expires_in",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "id_token": {
+ "name": "id_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token": {
+ "name": "refresh_token",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "refresh_token_expires_in": {
+ "name": "refresh_token_expires_in",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "scope": {
+ "name": "scope",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "token_type": {
+ "name": "token_type",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "tempColumn": {
+ "name": "tempColumn",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "user_id_idx": {
+ "name": "user_id_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "provider_account_id_idx": {
+ "name": "provider_account_id_idx",
+ "columns": [
+ "providerAccountId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "accounts_id": {
+ "name": "accounts_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {
+ "accounts_id_unique": {
+ "name": "accounts_id_unique",
+ "columns": [
+ "id"
+ ]
+ }
+ }
+ },
+ "comments": {
+ "name": "comments",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(6)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "timestamp": {
+ "name": "timestamp",
+ "type": "float",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "authorId": {
+ "name": "authorId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "parentCommentId": {
+ "name": "parentCommentId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "video_id_idx": {
+ "name": "video_id_idx",
+ "columns": [
+ "videoId"
+ ],
+ "isUnique": false
+ },
+ "author_id_idx": {
+ "name": "author_id_idx",
+ "columns": [
+ "authorId"
+ ],
+ "isUnique": false
+ },
+ "parent_comment_id_idx": {
+ "name": "parent_comment_id_idx",
+ "columns": [
+ "parentCommentId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "comments_id": {
+ "name": "comments_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {
+ "comments_id_unique": {
+ "name": "comments_id_unique",
+ "columns": [
+ "id"
+ ]
+ }
+ }
+ },
+ "s3_buckets": {
+ "name": "s3_buckets",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "region": {
+ "name": "region",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "endpoint": {
+ "name": "endpoint",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "bucketName": {
+ "name": "bucketName",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "accessKeyId": {
+ "name": "accessKeyId",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "secretAccessKey": {
+ "name": "secretAccessKey",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "provider": {
+ "name": "provider",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "('aws')"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "s3_buckets_id": {
+ "name": "s3_buckets_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {
+ "s3_buckets_id_unique": {
+ "name": "s3_buckets_id_unique",
+ "columns": [
+ "id"
+ ]
+ }
+ }
+ },
+ "sessions": {
+ "name": "sessions",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sessionToken": {
+ "name": "sessionToken",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "session_token_idx": {
+ "name": "session_token_idx",
+ "columns": [
+ "sessionToken"
+ ],
+ "isUnique": true
+ },
+ "user_id_idx": {
+ "name": "user_id_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "sessions_id": {
+ "name": "sessions_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {
+ "sessions_id_unique": {
+ "name": "sessions_id_unique",
+ "columns": [
+ "id"
+ ]
+ },
+ "sessions_sessionToken_unique": {
+ "name": "sessions_sessionToken_unique",
+ "columns": [
+ "sessionToken"
+ ]
+ }
+ }
+ },
+ "shared_videos": {
+ "name": "shared_videos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "videoId": {
+ "name": "videoId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sharedByUserId": {
+ "name": "sharedByUserId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "sharedAt": {
+ "name": "sharedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "video_id_idx": {
+ "name": "video_id_idx",
+ "columns": [
+ "videoId"
+ ],
+ "isUnique": false
+ },
+ "space_id_idx": {
+ "name": "space_id_idx",
+ "columns": [
+ "spaceId"
+ ],
+ "isUnique": false
+ },
+ "shared_by_user_id_idx": {
+ "name": "shared_by_user_id_idx",
+ "columns": [
+ "sharedByUserId"
+ ],
+ "isUnique": false
+ },
+ "video_id_space_id_idx": {
+ "name": "video_id_space_id_idx",
+ "columns": [
+ "videoId",
+ "spaceId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "shared_videos_id": {
+ "name": "shared_videos_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {
+ "shared_videos_id_unique": {
+ "name": "shared_videos_id_unique",
+ "columns": [
+ "id"
+ ]
+ }
+ }
+ },
+ "space_invites": {
+ "name": "space_invites",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "invitedEmail": {
+ "name": "invitedEmail",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "invitedByUserId": {
+ "name": "invitedByUserId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "status": {
+ "name": "status",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'pending'"
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "expiresAt": {
+ "name": "expiresAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "space_id_idx": {
+ "name": "space_id_idx",
+ "columns": [
+ "spaceId"
+ ],
+ "isUnique": false
+ },
+ "invited_email_idx": {
+ "name": "invited_email_idx",
+ "columns": [
+ "invitedEmail"
+ ],
+ "isUnique": false
+ },
+ "invited_by_user_id_idx": {
+ "name": "invited_by_user_id_idx",
+ "columns": [
+ "invitedByUserId"
+ ],
+ "isUnique": false
+ },
+ "status_idx": {
+ "name": "status_idx",
+ "columns": [
+ "status"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "space_invites_id": {
+ "name": "space_invites_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {
+ "space_invites_id_unique": {
+ "name": "space_invites_id_unique",
+ "columns": [
+ "id"
+ ]
+ }
+ }
+ },
+ "space_members": {
+ "name": "space_members",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "userId": {
+ "name": "userId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "spaceId": {
+ "name": "spaceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {
+ "user_id_idx": {
+ "name": "user_id_idx",
+ "columns": [
+ "userId"
+ ],
+ "isUnique": false
+ },
+ "space_id_idx": {
+ "name": "space_id_idx",
+ "columns": [
+ "spaceId"
+ ],
+ "isUnique": false
+ },
+ "user_id_space_id_idx": {
+ "name": "user_id_space_id_idx",
+ "columns": [
+ "userId",
+ "spaceId"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "space_members_id": {
+ "name": "space_members_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {
+ "space_members_id_unique": {
+ "name": "space_members_id_unique",
+ "columns": [
+ "id"
+ ]
+ }
+ }
+ },
+ "spaces": {
+ "name": "spaces",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "allowedEmailDomain": {
+ "name": "allowedEmailDomain",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "customDomain": {
+ "name": "customDomain",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "domainVerified": {
+ "name": "domainVerified",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "workosOrganizationId": {
+ "name": "workosOrganizationId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "workosConnectionId": {
+ "name": "workosConnectionId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ }
+ },
+ "indexes": {
+ "owner_id_idx": {
+ "name": "owner_id_idx",
+ "columns": [
+ "ownerId"
+ ],
+ "isUnique": false
+ },
+ "custom_domain_idx": {
+ "name": "custom_domain_idx",
+ "columns": [
+ "customDomain"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "spaces_id": {
+ "name": "spaces_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {
+ "spaces_id_unique": {
+ "name": "spaces_id_unique",
+ "columns": [
+ "id"
+ ]
+ }
+ }
+ },
+ "users": {
+ "name": "users",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "lastName": {
+ "name": "lastName",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "email": {
+ "name": "email",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "emailVerified": {
+ "name": "emailVerified",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "image": {
+ "name": "image",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeCustomerId": {
+ "name": "stripeCustomerId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeSubscriptionId": {
+ "name": "stripeSubscriptionId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "thirdPartyStripeSubscriptionId": {
+ "name": "thirdPartyStripeSubscriptionId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeSubscriptionStatus": {
+ "name": "stripeSubscriptionStatus",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "stripeSubscriptionPriceId": {
+ "name": "stripeSubscriptionPriceId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "activeSpaceId": {
+ "name": "activeSpaceId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "onboarding_completed_at": {
+ "name": "onboarding_completed_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "customBucket": {
+ "name": "customBucket",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "inviteQuota": {
+ "name": "inviteQuota",
+ "type": "int",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": 1
+ }
+ },
+ "indexes": {
+ "email_idx": {
+ "name": "email_idx",
+ "columns": [
+ "email"
+ ],
+ "isUnique": true
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "users_id": {
+ "name": "users_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {
+ "users_id_unique": {
+ "name": "users_id_unique",
+ "columns": [
+ "id"
+ ]
+ },
+ "users_email_unique": {
+ "name": "users_email_unique",
+ "columns": [
+ "email"
+ ]
+ }
+ }
+ },
+ "verification_tokens": {
+ "name": "verification_tokens",
+ "columns": {
+ "identifier": {
+ "name": "identifier",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "token": {
+ "name": "token",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "expires": {
+ "name": "expires",
+ "type": "datetime",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "verification_tokens_identifier": {
+ "name": "verification_tokens_identifier",
+ "columns": [
+ "identifier"
+ ]
+ }
+ },
+ "uniqueConstraints": {
+ "verification_tokens_token_unique": {
+ "name": "verification_tokens_token_unique",
+ "columns": [
+ "token"
+ ]
+ }
+ }
+ },
+ "videos": {
+ "name": "videos",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "ownerId": {
+ "name": "ownerId",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false
+ },
+ "name": {
+ "name": "name",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "'My Video'"
+ },
+ "awsRegion": {
+ "name": "awsRegion",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "awsBucket": {
+ "name": "awsBucket",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "bucket": {
+ "name": "bucket",
+ "type": "varchar(15)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "public": {
+ "name": "public",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": true
+ },
+ "videoStartTime": {
+ "name": "videoStartTime",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "audioStartTime": {
+ "name": "audioStartTime",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "xStreamInfo": {
+ "name": "xStreamInfo",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "jobId": {
+ "name": "jobId",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "jobStatus": {
+ "name": "jobStatus",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "isScreenshot": {
+ "name": "isScreenshot",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "skipProcessing": {
+ "name": "skipProcessing",
+ "type": "boolean",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": false
+ },
+ "transcriptionStatus": {
+ "name": "transcriptionStatus",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false,
+ "autoincrement": false
+ },
+ "createdAt": {
+ "name": "createdAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "(now())"
+ },
+ "updatedAt": {
+ "name": "updatedAt",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "onUpdate": true,
+ "default": "(now())"
+ },
+ "source": {
+ "name": "source",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": true,
+ "autoincrement": false,
+ "default": "('{\"type\":\"MediaConvert\"}')"
+ }
+ },
+ "indexes": {
+ "id_idx": {
+ "name": "id_idx",
+ "columns": [
+ "id"
+ ],
+ "isUnique": false
+ },
+ "owner_id_idx": {
+ "name": "owner_id_idx",
+ "columns": [
+ "ownerId"
+ ],
+ "isUnique": false
+ },
+ "is_public_idx": {
+ "name": "is_public_idx",
+ "columns": [
+ "public"
+ ],
+ "isUnique": false
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {
+ "videos_id": {
+ "name": "videos_id",
+ "columns": [
+ "id"
+ ]
+ }
+ },
+ "uniqueConstraints": {
+ "videos_id_unique": {
+ "name": "videos_id_unique",
+ "columns": [
+ "id"
+ ]
+ }
+ }
+ }
+ },
+ "schemas": {},
+ "_meta": {
+ "schemas": {},
+ "tables": {},
+ "columns": {}
+ }
+}
\ No newline at end of file
diff --git a/packages/database/migrations/meta/_journal.json b/packages/database/migrations/meta/_journal.json
new file mode 100644
index 000000000..89f7557ac
--- /dev/null
+++ b/packages/database/migrations/meta/_journal.json
@@ -0,0 +1,13 @@
+{
+ "version": "5",
+ "dialect": "mysql",
+ "entries": [
+ {
+ "idx": 0,
+ "version": "5",
+ "when": 1743020179593,
+ "tag": "0000_brown_sunfire",
+ "breakpoints": true
+ }
+ ]
+}
\ No newline at end of file
diff --git a/packages/env/client.ts b/packages/env/build.ts
similarity index 50%
rename from packages/env/client.ts
rename to packages/env/build.ts
index 1d52b6a7b..158ebedd1 100644
--- a/packages/env/client.ts
+++ b/packages/env/build.ts
@@ -3,25 +3,31 @@ import { z } from "zod";
export const NODE_ENV = process.env.NODE_ENV as string;
-export const clientEnv = createEnv({
+// Environment variables that are needed in the build process, and may be incorrect on the client.
+// Some are only provided by `NEXT_PUBLIC`, but others can be provdied at runtime
+export const buildEnv = createEnv({
client: {
+ NEXT_PUBLIC_IS_CAP: z.string().optional(),
+ NEXT_PUBLIC_POSTHOG_KEY: z.string().optional(),
+ NEXT_PUBLIC_POSTHOG_HOST: z.string().optional(),
NEXT_PUBLIC_WEB_URL: z.string(),
NEXT_PUBLIC_CAP_AWS_BUCKET: z.string(),
NEXT_PUBLIC_CAP_AWS_REGION: z.string(),
NEXT_PUBLIC_CAP_AWS_ENDPOINT: z.string().optional(),
NEXT_PUBLIC_CAP_AWS_BUCKET_URL: z.string().optional(),
- NEXT_PUBLIC_IS_CAP: z.string().optional(),
- NEXT_PUBLIC_POSTHOG_KEY: z.string().optional(),
- NEXT_PUBLIC_POSTHOG_HOST: z.string().optional(),
},
runtimeEnv: {
- NEXT_PUBLIC_WEB_URL: process.env.NEXT_PUBLIC_WEB_URL,
- NEXT_PUBLIC_CAP_AWS_BUCKET: process.env.NEXT_PUBLIC_CAP_AWS_BUCKET,
- NEXT_PUBLIC_CAP_AWS_REGION: process.env.NEXT_PUBLIC_CAP_AWS_REGION,
- NEXT_PUBLIC_CAP_AWS_ENDPOINT: process.env.NEXT_PUBLIC_CAP_AWS_ENDPOINT,
- NEXT_PUBLIC_CAP_AWS_BUCKET_URL: process.env.NEXT_PUBLIC_CAP_AWS_BUCKET_URL,
NEXT_PUBLIC_IS_CAP: process.env.NEXT_PUBLIC_IS_CAP,
NEXT_PUBLIC_POSTHOG_KEY: process.env.NEXT_PUBLIC_POSTHOG_KEY,
NEXT_PUBLIC_POSTHOG_HOST: process.env.NEXT_PUBLIC_POSTHOG_HOST,
+ NEXT_PUBLIC_WEB_URL: process.env.WEB_URL ?? process.env.NEXT_PUBLIC_WEB_URL,
+ NEXT_PUBLIC_CAP_AWS_BUCKET:
+ process.env.CAP_AWS_BUCKET ?? process.env.NEXT_PUBLIC_CAP_AWS_BUCKET,
+ NEXT_PUBLIC_CAP_AWS_REGION:
+ process.env.CAP_AWS_REGION ?? process.env.NEXT_PUBLIC_CAP_AWS_REGION,
+ NEXT_PUBLIC_CAP_AWS_ENDPOINT:
+ process.env.CAP_AWS_ENDPOINT ?? process.env.NEXT_PUBLIC_CAP_AWS_ENDPOINT,
+ NEXT_PUBLIC_CAP_AWS_BUCKET_URL:
+ process.env.CAP_AWS_URL ?? process.env.NEXT_PUBLIC_CAP_AWS_BUCKET_URL,
},
});
diff --git a/packages/env/index.ts b/packages/env/index.ts
index 40db60cf6..51282f4fb 100644
--- a/packages/env/index.ts
+++ b/packages/env/index.ts
@@ -1,2 +1,2 @@
-export { clientEnv, NODE_ENV } from "./client";
+export { buildEnv, NODE_ENV } from "./build";
export { serverEnv } from "./server";
diff --git a/packages/env/server.ts b/packages/env/server.ts
index a4ea8fd40..a0a42a0ea 100644
--- a/packages/env/server.ts
+++ b/packages/env/server.ts
@@ -1,37 +1,65 @@
import { createEnv } from "@t3-oss/env-nextjs";
import { z } from "zod";
-export const serverEnv = createEnv({
- server: {
- NODE_ENV: z.string(),
- DATABASE_URL: z.string(),
- DATABASE_MIGRATION_URL: z.string().optional(),
- DATABASE_ENCRYPTION_KEY: z.string().optional(),
- CAP_AWS_ACCESS_KEY: z.string().default("capS3root"),
- CAP_AWS_SECRET_KEY: z.string().default("capS3root"),
- CAP_AWS_MEDIACONVERT_ROLE_ARN: z.string().optional(),
- CAP_CLOUDFRONT_DISTRIBUTION_ID: z.string().optional(),
- NEXTAUTH_SECRET: z.string(),
- NEXTAUTH_URL: z.string(),
- GOOGLE_CLIENT_ID: z.string().optional(),
- GOOGLE_CLIENT_SECRET: z.string().optional(),
- WORKOS_CLIENT_ID: z.string().optional(),
- WORKOS_API_KEY: z.string().optional(),
- DUB_API_KEY: z.string().optional(),
- RESEND_API_KEY: z.string().optional(),
- DEEPGRAM_API_KEY: z.string().optional(),
- NEXT_LOOPS_KEY: z.string().optional(),
- STRIPE_SECRET_KEY_TEST: z.string().optional(),
- STRIPE_SECRET_KEY_LIVE: z.string().optional(),
- STRIPE_WEBHOOK_SECRET: z.string().optional(),
- DISCORD_FEEDBACK_WEBHOOK_URL: z.string().optional(),
- INTERCOM_SECRET: z.string().optional(),
- VERCEL_TEAM_ID: z.string().optional(),
- VERCEL_PROJECT_ID: z.string().optional(),
- VERCEL_AUTH_TOKEN: z.string().optional(),
- VERCEL_URL: z.string().optional(),
- VERCEL_BRANCH_URL: z.string().optional(),
- VERCEL_PROJECT_PRODUCTION_URL: z.string().optional(),
- },
- experimental__runtimeEnv: process.env,
-});
+const boolString = (_default = false) =>
+ z
+ .string()
+ .optional()
+ .default(_default ? "true" : "false")
+ .transform((v) => v === "true")
+ .pipe(z.boolean());
+
+function createServerEnv() {
+ return createEnv({
+ server: {
+ NODE_ENV: z.string(),
+ DATABASE_URL: z.string(),
+ WEB_URL: z.string(),
+ DATABASE_MIGRATION_URL: z.string().optional(),
+ DATABASE_ENCRYPTION_KEY: z.string().optional(),
+ S3_PATH_STYLE: boolString(true),
+ CAP_AWS_BUCKET: z.string(),
+ CAP_AWS_REGION: z.string(),
+ CAP_AWS_BUCKET_URL: z.string().optional(),
+ CAP_AWS_ACCESS_KEY: z.string(),
+ CAP_AWS_SECRET_KEY: z.string(),
+ CAP_AWS_ENDPOINT: z.string().optional(),
+ CAP_AWS_MEDIACONVERT_ROLE_ARN: z.string().optional(),
+ CAP_CLOUDFRONT_DISTRIBUTION_ID: z.string().optional(),
+ NEXTAUTH_SECRET: z.string(),
+ NEXTAUTH_URL: z.string(),
+ GOOGLE_CLIENT_ID: z.string().optional(),
+ GOOGLE_CLIENT_SECRET: z.string().optional(),
+ WORKOS_CLIENT_ID: z.string().optional(),
+ WORKOS_API_KEY: z.string().optional(),
+ DUB_API_KEY: z.string().optional(),
+ RESEND_API_KEY: z.string().optional(),
+ RESEND_FROM_DOMAIN: z.string().optional(),
+ DEEPGRAM_API_KEY: z.string().optional(),
+ NEXT_LOOPS_KEY: z.string().optional(),
+ STRIPE_SECRET_KEY_TEST: z.string().optional(),
+ STRIPE_SECRET_KEY_LIVE: z.string().optional(),
+ STRIPE_WEBHOOK_SECRET: z.string().optional(),
+ DISCORD_FEEDBACK_WEBHOOK_URL: z.string().optional(),
+ INTERCOM_SECRET: z.string().optional(),
+ VERCEL_TEAM_ID: z.string().optional(),
+ VERCEL_PROJECT_ID: z.string().optional(),
+ VERCEL_AUTH_TOKEN: z.string().optional(),
+ VERCEL_URL: z.string().optional(),
+ VERCEL_BRANCH_URL: z.string().optional(),
+ VERCEL_PROJECT_PRODUCTION_URL: z.string().optional(),
+ DOCKER_BUILD: z.string().optional(),
+ },
+ experimental__runtimeEnv: {
+ ...process.env,
+ },
+ });
+}
+
+let _cached: ReturnType<typeof createServerEnv> | undefined;
+export const serverEnv = () => {
+ if (_cached) return _cached;
+ _cached = createServerEnv();
+ console.log({ S3_PATH_STYLE: _cached.S3_PATH_STYLE });
+ return _cached;
+};
diff --git a/packages/ui-solid/package.json b/packages/ui-solid/package.json
index 14496be2f..1162d10b9 100644
--- a/packages/ui-solid/package.json
+++ b/packages/ui-solid/package.json
@@ -4,7 +4,7 @@
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
- ".": "./src/index.ts",
+ ".": "./src/index.tsx",
"./tailwind": "./tailwind.config.js",
"./main.css": "./src/main.css",
"./vite": "./vite.js",
diff --git a/packages/ui-solid/src/index.ts b/packages/ui-solid/src/index.tsx
similarity index 100%
rename from packages/ui-solid/src/index.ts
rename to packages/ui-solid/src/index.tsx
diff --git a/packages/ui/package.json b/packages/ui/package.json
index a4da3dd6e..b00947e2f 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -11,8 +11,7 @@
},
"scripts": {
"lint": "eslint src --cache",
- "typecheck": "tsc -b",
- "build": "tsc"
+ "typecheck": "tsc -b"
},
"devDependencies": {
"@tauri-apps/cli": "^1.5.11",
diff --git a/packages/utils/package.json b/packages/utils/package.json
index 6a74f4cb3..0cfb30fae 100644
--- a/packages/utils/package.json
+++ b/packages/utils/package.json
@@ -8,8 +8,7 @@
},
"scripts": {
"lint": "eslint src --cache",
- "typecheck": "tsc -b",
- "build": "tsc"
+ "typecheck": "tsc -b"
},
"devDependencies": {
"react": "^18.2.0",
diff --git a/packages/utils/src/constants/s3.ts b/packages/utils/src/constants/s3.ts
index bca3a93e6..ba1b7546b 100644
--- a/packages/utils/src/constants/s3.ts
+++ b/packages/utils/src/constants/s3.ts
@@ -1,10 +1,10 @@
-import { clientEnv } from "@cap/env";
+import { buildEnv } from "@cap/env";
export const S3_BUCKET_URL = (() => {
- const fixedUrl = clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET_URL;
- const endpoint = clientEnv.NEXT_PUBLIC_CAP_AWS_ENDPOINT;
- const bucket = clientEnv.NEXT_PUBLIC_CAP_AWS_BUCKET;
- const region = clientEnv.NEXT_PUBLIC_CAP_AWS_REGION;
+ const fixedUrl = buildEnv.NEXT_PUBLIC_CAP_AWS_BUCKET_URL;
+ const endpoint = buildEnv.NEXT_PUBLIC_CAP_AWS_ENDPOINT;
+ const bucket = buildEnv.NEXT_PUBLIC_CAP_AWS_BUCKET;
+ const region = buildEnv.NEXT_PUBLIC_CAP_AWS_REGION;
if (fixedUrl) return fixedUrl;
if (endpoint) return `${endpoint}/${bucket}`;
diff --git a/packages/utils/src/lib/stripe/stripe.ts b/packages/utils/src/lib/stripe/stripe.ts
index 24e9f68ea..53795c710 100644
--- a/packages/utils/src/lib/stripe/stripe.ts
+++ b/packages/utils/src/lib/stripe/stripe.ts
@@ -1,13 +1,16 @@
import { serverEnv } from "@cap/env";
import Stripe from "stripe";
-const key =
- serverEnv.STRIPE_SECRET_KEY_TEST ?? serverEnv.STRIPE_SECRET_KEY_LIVE ?? "";
-export const STRIPE_AVAILABLE = key !== "";
-export const stripe = new Stripe(key, {
- apiVersion: "2023-10-16",
- appInfo: {
- name: "Cap",
- version: "0.1.0",
- },
-});
+const key = () =>
+ serverEnv().STRIPE_SECRET_KEY_TEST ??
+ serverEnv().STRIPE_SECRET_KEY_LIVE ??
+ "";
+export const STRIPE_AVAILABLE = () => key() !== "";
+export const stripe = () =>
+ new Stripe(key(), {
+ apiVersion: "2023-10-16",
+ appInfo: {
+ name: "Cap",
+ version: "0.1.0",
+ },
+ });
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index bb24c91e8..6b58e8576 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -3,6 +3,7 @@ lockfileVersion: '9.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
+ injectWorkspacePackages: true
patchedDependencies:
'@kobalte/[email protected]':
@@ -36,16 +37,16 @@ importers:
version: 2.1.4
'@cap/database':
specifier: workspace:*
- version: link:../../packages/database
'@cap/ui':
specifier: workspace:*
- version: link:../../packages/ui
'@cap/ui-solid':
specifier: workspace:*
- version: link:../../packages/ui-solid
+ version: file:packages/ui-solid(@fontsource/[email protected])
'@cap/utils':
specifier: workspace:*
- version: link:../../packages/utils
+ version: file:packages/utils([email protected])([email protected]([email protected]))
'@cap/web-api-contract':
specifier: workspace:*
version: link:../../packages/web-api-contract
@@ -272,7 +273,7 @@ importers:
dependencies:
'@cap/ui-solid':
specifier: workspace:*
- version: link:../../packages/ui-solid
+ version: file:packages/ui-solid(@fontsource/[email protected])
postcss-pseudo-companion-classes:
specifier: ^0.1.1
version: 0.1.1([email protected])
@@ -424,13 +425,13 @@ importers:
version: link:../../packages/env
'@cap/ui':
specifier: workspace:*
- version: link:../../packages/ui
'@cap/utils':
specifier: workspace:*
version: link:../../packages/utils
'@cap/web-api-contract':
specifier: workspace:*
- version: link:../../packages/web-api-contract
+ version: file:packages/web-api-contract(@types/[email protected])
'@deepgram/sdk':
specifier: ^3.3.4
version: 3.7.0([email protected])
@@ -769,10 +770,10 @@ importers:
version: 5.0.7
next:
specifier: 14.2.9
next-auth:
specifier: ^4.24.5
react-email:
specifier: ^1.10.1
version: 1.10.1([email protected])
@@ -782,7 +783,7 @@ importers:
devDependencies:
'@cap/ui':
specifier: workspace:*
- version: link:../ui
'@cap/utils':
specifier: workspace:*
version: link:../utils
@@ -841,7 +842,7 @@ importers:
dependencies:
'@cap/utils':
specifier: workspace:*
- version: link:../utils
+ version: file:packages/utils([email protected])([email protected]([email protected]))
'@kobalte/tailwindcss':
specifier: ^0.9.0
@@ -1517,6 +1518,29 @@ packages:
resolution: {integrity: sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==}
+ '@cap/database@file:packages/database':
+ resolution: {directory: packages/database, type: directory}
+ engines: {node: '20'}
+
+ '@cap/env@file:packages/env':
+ resolution: {directory: packages/env, type: directory}
+
+ '@cap/ui-solid@file:packages/ui-solid':
+ resolution: {directory: packages/ui-solid, type: directory}
+ peerDependencies:
+ '@fontsource/geist-sans': ^5.0.3
+
+ '@cap/ui@file:packages/ui':
+ resolution: {directory: packages/ui, type: directory}
+ engines: {node: '20'}
+
+ '@cap/utils@file:packages/utils':
+ resolution: {directory: packages/utils, type: directory}
+ engines: {node: '20'}
+
+ '@cap/web-api-contract@file:packages/web-api-contract':
+ resolution: {directory: packages/web-api-contract, type: directory}
+
'@chromatic-com/[email protected]':
resolution: {integrity: sha512-vYQ+TcfktEE3GHnLZXHCzXF/sN9dw+KivH8a5cmPyd9YtQs7fZtHrEgsIjWpYycXiweKMo1Lm1RZsjxk8DH3rA==}
engines: {node: '>=16.0.0', yarn: '>=1.22.18'}
@@ -5887,10 +5911,10 @@ packages:
react-dom:
optional: true
- '@storybook/[email protected]':
- resolution: {integrity: sha512-FBrVGft5u26aB47AU5k4CgHqwAFp075KFAyRSj3eeqb8kJjHDuGeFKL02fr7dprqAYsko0BkksTWbYm/+c0ysg==}
+ '@storybook/[email protected]':
+ resolution: {integrity: sha512-eOv2hlqVdwtyMgMxTaZliEkWEKt+BoxTUZOHmw0mcY7aa6iKhegMLRMEMddr2Dqn+QuAEOCi+O3af6eQwrSm5g==}
peerDependencies:
- storybook: ^9.0.0-beta.5
+ storybook: ^9.0.0-beta.6
vite: ^5.0.0 || ^6.0.0
'@storybook/[email protected]':
@@ -5901,10 +5925,10 @@ packages:
peerDependencies:
storybook: ^8.3.3
- '@storybook/[email protected]':
- resolution: {integrity: sha512-JoParjJNyRlzzJyoacPJSpeoZMT1JRNZfzsiLK8OH3ko1cnQrx0I38q2/w7rUOiqxEyp40DEwAmjv0srRHOJBA==}
+ '@storybook/[email protected]':
+ resolution: {integrity: sha512-dS6hgrs6z+e2He+s1mzxo669tLTkiFsDft5/suRaoM8kEKSW4Q7FSbizPC9xAhF7YJDzgBRAhMXe92ldDngmyg==}
peerDependencies:
- storybook: ^9.0.0-beta.5
+ storybook: ^9.0.0-beta.6
'@storybook/[email protected]':
resolution: {integrity: sha512-dHYFQH3mA+EtnCkHXzicbLgsvzYjcDJ1JWsogbItZogkPHgSJM/Wr71uMkcvw8v9mmCyP4NpXJuu6bPoVsOnzg==}
@@ -14755,6 +14779,147 @@ snapshots:
'@bcoe/[email protected]': {}
+ dependencies:
+ '@cap/env': file:packages/env([email protected])([email protected]([email protected]))
+ '@mattrax/mysql-planetscale': 0.0.3
+ '@paralleldrive/cuid2': 2.2.2
+ '@planetscale/database': 1.19.0
+ '@react-email/components': 0.0.13(@types/[email protected])([email protected])
+ '@react-email/render': 0.0.11
+ drizzle-orm: 0.30.9(@cloudflare/[email protected])(@opentelemetry/[email protected])(@planetscale/[email protected])(@types/[email protected])([email protected])([email protected])
+ nanoid: 5.0.7
+ react-email: 1.10.1([email protected])
+ transitivePeerDependencies:
+ - '@auth/core'
+ - '@aws-sdk/client-rds-data'
+ - '@babel/core'
+ - '@cloudflare/workers-types'
+ - '@electric-sql/pglite'
+ - '@libsql/client'
+ - '@neondatabase/serverless'
+ - '@op-engineering/op-sqlite'
+ - '@opentelemetry/api'
+ - '@playwright/test'
+ - '@types/better-sqlite3'
+ - '@types/pg'
+ - '@types/react'
+ - '@types/sql.js'
+ - '@vercel/postgres'
+ - '@xata.io/client'
+ - babel-plugin-macros
+ - better-sqlite3
+ - bun-types
+ - encoding
+ - expo-sqlite
+ - knex
+ - kysely
+ - mysql2
+ - nodemailer
+ - pg
+ - postgres
+ - react
+ - react-dom
+ - sass
+ - sql.js
+ - sqlite3
+ - typescript
+ - valibot
+
+ '@cap/env@file:packages/env([email protected])([email protected]([email protected]))':
+ dependencies:
+ zod: 3.24.2
+ transitivePeerDependencies:
+ - typescript
+ - valibot
+
+ '@cap/ui-solid@file:packages/ui-solid(@fontsource/[email protected])':
+ dependencies:
+ '@fontsource/geist-sans': 5.1.0
+ '@kobalte/core': 0.13.7(patch_hash=daf56e70aa12211e66d61eca48f0538cc1963c967982714f3abc09110083cf0d)([email protected])
+ solid-js: 1.9.3
+ transitivePeerDependencies:
+ - ts-node
+
+ dependencies:
+ '@cap/utils': file:packages/utils([email protected])([email protected]([email protected]))
+ '@radix-ui/react-dropdown-menu': 2.1.1(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-navigation-menu': 1.2.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-slot': 1.1.0(@types/[email protected])([email protected])
+ '@tailwindcss/typography': 0.5.15([email protected]([email protected](@types/[email protected])([email protected])))
+ class-variance-authority: 0.7.0
+ lucide-react: 0.294.0([email protected])
+ react-hook-form: 7.53.0([email protected])
+ react-loading-skeleton: 3.5.0([email protected])
+ transitivePeerDependencies:
+ - '@types/react'
+ - '@types/react-dom'
+ - aws-crt
+ - react
+ - react-dom
+ - tailwindcss
+ - typescript
+ - valibot
+
+ dependencies:
+ '@cap/utils': file:packages/utils([email protected])([email protected]([email protected]))
+ '@radix-ui/react-dropdown-menu': 2.1.1(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-navigation-menu': 1.2.0(@types/[email protected](@types/[email protected]))(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-slot': 1.1.0(@types/[email protected])([email protected])
+ '@tailwindcss/typography': 0.5.15([email protected]([email protected](@types/[email protected])([email protected])))
+ class-variance-authority: 0.7.0
+ lucide-react: 0.294.0([email protected])
+ react-hook-form: 7.53.0([email protected])
+ react-loading-skeleton: 3.5.0([email protected])
+ transitivePeerDependencies:
+ - '@types/react'
+ - '@types/react-dom'
+ - aws-crt
+ - react
+ - react-dom
+ - tailwindcss
+ - typescript
+ - valibot
+
+ '@cap/utils@file:packages/utils([email protected])([email protected]([email protected]))':
+ dependencies:
+ '@aws-sdk/client-s3': 3.658.1
+ '@cap/env': file:packages/env([email protected])([email protected]([email protected]))
+ clsx: 2.1.1
+ stripe: 14.25.0
+ tailwind-merge: 2.5.2
+ transitivePeerDependencies:
+ - aws-crt
+ - typescript
+ - valibot
+
+ '@cap/web-api-contract@file:packages/web-api-contract(@types/[email protected])':
+ dependencies:
+ '@ts-rest/core': 3.52.1(@types/[email protected])([email protected])
+ zod: 3.24.2
+ transitivePeerDependencies:
+ - '@types/node'
+
dependencies:
chromatic: 11.10.4
@@ -17314,6 +17479,15 @@ snapshots:
'@radix-ui/[email protected]': {}
+ dependencies:
+ '@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
@@ -17332,6 +17506,18 @@ snapshots:
'@types/react': 18.3.9
'@types/react-dom': 18.3.0
+ dependencies:
+ '@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-slot': 1.1.0(@types/[email protected])([email protected])
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
'@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])
@@ -17407,6 +17593,28 @@ snapshots:
transitivePeerDependencies:
- '@types/react'
+ dependencies:
+ '@radix-ui/primitive': 1.1.0
+ '@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-dismissable-layer': 1.1.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-focus-guards': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-focus-scope': 1.1.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-id': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-slot': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-controllable-state': 1.1.0(@types/[email protected])([email protected])
+ aria-hidden: 1.2.4
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ react-remove-scroll: 2.5.7(@types/[email protected])([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
'@radix-ui/primitive': 1.1.0
@@ -17446,6 +17654,19 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
+ dependencies:
+ '@radix-ui/primitive': 1.1.0
+ '@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-use-callback-ref': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-escape-keydown': 1.1.0(@types/[email protected])([email protected])
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
'@radix-ui/primitive': 1.1.0
@@ -17472,6 +17693,21 @@ snapshots:
'@types/react': 18.3.9
'@types/react-dom': 18.3.0
+ dependencies:
+ '@radix-ui/primitive': 1.1.0
+ '@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-id': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-use-controllable-state': 1.1.0(@types/[email protected])([email protected])
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
'@radix-ui/primitive': 1.1.0
@@ -17507,6 +17743,17 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
+ dependencies:
+ '@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-use-callback-ref': 1.1.0(@types/[email protected])([email protected])
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
'@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])
@@ -17538,6 +17785,15 @@ snapshots:
optionalDependencies:
'@types/react': 18.3.9
+ dependencies:
+ '@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
@@ -17547,6 +17803,32 @@ snapshots:
'@types/react': 18.3.9
'@types/react-dom': 19.1.2(@types/[email protected])
+ dependencies:
+ '@radix-ui/primitive': 1.1.0
+ '@radix-ui/react-collection': 1.1.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-direction': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-dismissable-layer': 1.1.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-focus-guards': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-focus-scope': 1.1.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-id': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-roving-focus': 1.1.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-slot': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-callback-ref': 1.1.0(@types/[email protected])([email protected])
+ aria-hidden: 1.2.4
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ react-remove-scroll: 2.5.7(@types/[email protected])([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
'@radix-ui/primitive': 1.1.0
@@ -17573,6 +17855,28 @@ snapshots:
'@types/react': 18.3.9
'@types/react-dom': 19.1.2(@types/[email protected])
+ dependencies:
+ '@radix-ui/primitive': 1.1.0
+ '@radix-ui/react-collection': 1.1.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-direction': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-dismissable-layer': 1.1.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-id': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-use-callback-ref': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-controllable-state': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-layout-effect': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-previous': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-visually-hidden': 1.1.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
'@radix-ui/primitive': 1.1.0
@@ -17595,6 +17899,29 @@ snapshots:
'@types/react': 18.3.9
'@types/react-dom': 19.1.2(@types/[email protected])
+ dependencies:
+ '@radix-ui/primitive': 1.1.0
+ '@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-dismissable-layer': 1.1.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-focus-guards': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-focus-scope': 1.1.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-id': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-slot': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-controllable-state': 1.1.0(@types/[email protected])([email protected])
+ aria-hidden: 1.2.4
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ react-remove-scroll: 2.5.7(@types/[email protected])([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
'@radix-ui/primitive': 1.1.0
@@ -17618,6 +17945,24 @@ snapshots:
'@types/react': 18.3.9
'@types/react-dom': 19.1.2(@types/[email protected])
+ dependencies:
+ '@floating-ui/react-dom': 2.1.2([email protected]([email protected]))([email protected])
+ '@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-use-callback-ref': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-layout-effect': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-rect': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-size': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/rect': 1.1.0
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
'@floating-ui/react-dom': 2.1.2([email protected]([email protected]))([email protected])
@@ -17661,6 +18006,16 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
+ dependencies:
+ '@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-use-layout-effect': 1.1.0(@types/[email protected])([email protected])
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
@@ -17689,6 +18044,16 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
+ dependencies:
+ '@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-layout-effect': 1.1.0(@types/[email protected])([email protected])
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
'@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])
@@ -17716,6 +18081,15 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
+ dependencies:
+ '@radix-ui/react-slot': 1.1.0(@types/[email protected])([email protected])
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
'@radix-ui/react-slot': 1.1.0(@types/[email protected])([email protected])
@@ -17734,6 +18108,23 @@ snapshots:
'@types/react': 18.3.9
'@types/react-dom': 18.3.0
+ dependencies:
+ '@radix-ui/primitive': 1.1.0
+ '@radix-ui/react-collection': 1.1.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-direction': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-id': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-use-callback-ref': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-controllable-state': 1.1.0(@types/[email protected])([email protected])
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
'@radix-ui/primitive': 1.1.0
@@ -17779,6 +18170,21 @@ snapshots:
optionalDependencies:
'@types/react': 18.3.9
+ dependencies:
+ '@radix-ui/primitive': 1.1.0
+ '@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-context': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ '@radix-ui/react-use-controllable-state': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-previous': 1.1.0(@types/[email protected])([email protected])
+ '@radix-ui/react-use-size': 1.1.0(@types/[email protected])([email protected])
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
'@radix-ui/primitive': 1.1.0
@@ -17922,6 +18328,15 @@ snapshots:
optionalDependencies:
'@types/react': 18.3.9
+ dependencies:
+ '@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ optionalDependencies:
+ '@types/react': 18.3.9
+ '@types/react-dom': 18.3.0
+
dependencies:
@@ -18951,9 +19366,9 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
dependencies:
- '@storybook/csf-plugin': 9.0.0-beta.5([email protected])
+ '@storybook/csf-plugin': 9.0.0-beta.6([email protected])
browser-assert: 1.2.1
storybook: 8.3.3
ts-dedent: 2.2.0
@@ -18984,7 +19399,7 @@ snapshots:
storybook: 8.3.3
unplugin: 1.16.1
dependencies:
storybook: 8.3.3
unplugin: 1.16.1
@@ -21977,7 +22392,7 @@ snapshots:
'@typescript-eslint/parser': 5.62.0([email protected])([email protected])
eslint: 8.57.1
eslint-import-resolver-node: 0.3.9
+ eslint-import-resolver-typescript: 3.6.3(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])
eslint-plugin-jsx-a11y: 6.10.0([email protected])
eslint-plugin-react: 7.37.0([email protected])
@@ -22006,25 +22421,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- dependencies:
- '@nolyfill/is-core-module': 1.0.39
- debug: 4.3.7([email protected])
- enhanced-resolve: 5.17.1
- eslint: 8.57.1
- fast-glob: 3.3.2
- get-tsconfig: 4.8.1
- is-bun-module: 1.2.1
- is-glob: 4.0.3
- optionalDependencies:
- transitivePeerDependencies:
- - '@typescript-eslint/parser'
- - eslint-import-resolver-node
- - eslint-import-resolver-webpack
- - supports-color
-
dependencies:
'@nolyfill/is-core-module': 1.0.39
@@ -22070,7 +22466,7 @@ snapshots:
'@typescript-eslint/parser': 5.62.0([email protected])([email protected])
eslint: 8.57.1
eslint-import-resolver-node: 0.3.9
+ eslint-import-resolver-typescript: 3.6.3(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected])
transitivePeerDependencies:
- supports-color
@@ -25415,13 +25811,13 @@ snapshots:
optionalDependencies:
nodemailer: 6.9.15
dependencies:
'@babel/runtime': 7.25.6
'@panva/hkdf': 1.2.1
cookie: 0.5.0
jose: 4.15.9
oauth: 0.9.15
openid-client: 5.7.0
preact: 10.24.1
@@ -25470,7 +25866,7 @@ snapshots:
postcss: 8.4.31
react: 18.3.1
react-dom: 18.3.1([email protected])
- styled-jsx: 5.1.1([email protected])
+ styled-jsx: 5.1.1(@babel/[email protected])([email protected])
optionalDependencies:
'@next/swc-darwin-arm64': 14.2.3
'@next/swc-darwin-x64': 14.2.3
@@ -25486,7 +25882,7 @@ snapshots:
- '@babel/core'
- babel-plugin-macros
dependencies:
'@next/env': 14.2.9
'@swc/helpers': 0.5.5
@@ -25496,7 +25892,7 @@ snapshots:
postcss: 8.4.31
react: 18.3.1
react-dom: 18.3.1([email protected])
- styled-jsx: 5.1.1([email protected])
+ styled-jsx: 5.1.1(@babel/[email protected])([email protected])
optionalDependencies:
'@next/swc-darwin-arm64': 14.2.9
'@next/swc-darwin-x64': 14.2.9
@@ -27399,7 +27795,7 @@ snapshots:
dependencies:
transitivePeerDependencies:
- storybook
- vite
@@ -27561,10 +27957,12 @@ snapshots:
dependencies:
inline-style-parser: 0.2.4
dependencies:
client-only: 0.0.1
react: 18.3.1
+ optionalDependencies:
+ '@babel/core': 7.26.10
diff --git a/scripts/env-cli.js b/scripts/env-cli.js
index 8748f2ebd..9dda89777 100644
--- a/scripts/env-cli.js
+++ b/scripts/env-cli.js
@@ -52,8 +52,8 @@ async function main() {
if (hasWeb) {
envs.VITE_SERVER_URL = "http://localhost:3000";
- envs.NEXT_PUBLIC_WEB_URL = "http://localhost:3000";
- envs.NEXTAUTH_URL = envs.NEXT_PUBLIC_WEB_URL;
+ envs.WEB_URL = "http://localhost:3000";
+ envs.NEXTAUTH_URL = envs.WEB_URL;
if (!allEnvs.NEXTAUTH_SECRET) {
allEnvs.NEXTAUTH_SECRET = crypto.randomBytes(32).toString("base64");
@@ -117,26 +117,25 @@ async function main() {
placeholder: allEnvs.CAP_AWS_SECRET_KEY,
defaultValue: allEnvs.CAP_AWS_SECRET_KEY,
}),
- NEXT_PUBLIC_CAP_AWS_BUCKET: () =>
+ CAP_AWS_BUCKET: () =>
text({
- message: "NEXT_PUBLIC_CAP_AWS_BUCKET",
- defaultValue: allEnvs.NEXT_PUBLIC_CAP_AWS_BUCKET,
- placeholder: allEnvs.NEXT_PUBLIC_CAP_AWS_BUCKET,
+ message: "CAP_AWS_BUCKET",
+ defaultValue: allEnvs.CAP_AWS_BUCKET,
+ placeholder: allEnvs.CAP_AWS_BUCKET,
}),
- NEXT_PUBLIC_CAP_AWS_REGION: () =>
+ CAP_AWS_REGION: () =>
text({
- message: "NEXT_PUBLIC_CAP_AWS_REGION",
+ message: "CAP_AWS_REGION",
defaultValue: allEnvs.NEXT_PUBLIC_CAP_AWS_REGION,
placeholder: allEnvs.NEXT_PUBLIC_CAP_AWS_REGION,
}),
- NEXT_PUBLIC_CAP_AWS_ENDPOINT: () =>
+ CAP_AWS_ENDPOINT: () =>
text({
- message: "NEXT_PUBLIC_CAP_AWS_ENDPOINT",
+ message: "CAP_AWS_ENDPOINT",
defaultValue: allEnvs.NEXT_PUBLIC_CAP_AWS_ENDPOINT,
placeholder: allEnvs.NEXT_PUBLIC_CAP_AWS_ENDPOINT,
}),
- NEXT_PUBLIC_CAP_AWS_BUCKET_URL: () =>
- text({ message: "NEXT_PUBLIC_CAP_AWS_BUCKET_URL" }),
+ CAP_AWS_BUCKET_URL: () => text({ message: "CAP_AWS_BUCKET_URL" }),
CAP_CLOUDFRONT_DISTRIBUTION_ID: () =>
text({ message: "CAP_CLOUDFRONT_DISTRIBUTION_ID" }),
},
@@ -150,12 +149,14 @@ async function main() {
envs.CAP_AWS_ACCESS_KEY = DOCKER_S3_ENVS.accessKey;
envs.CAP_AWS_SECRET_KEY = DOCKER_S3_ENVS.secretKey;
- envs.NEXT_PUBLIC_CAP_AWS_BUCKET = DOCKER_S3_ENVS.bucket;
- envs.NEXT_PUBLIC_CAP_AWS_REGION = DOCKER_S3_ENVS.region;
- envs.NEXT_PUBLIC_CAP_AWS_ENDPOINT = DOCKER_S3_ENVS.endpoint;
+ envs.CAP_AWS_BUCKET = DOCKER_S3_ENVS.bucket;
+ envs.CAP_AWS_REGION = DOCKER_S3_ENVS.region;
+ envs.CAP_AWS_ENDPOINT = DOCKER_S3_ENVS.endpoint;
}
- } else {
- envs.VITE_SERVER_URL = "https://cap.so";
+
+ envs.NEXT_PUBLIC_WEB_URL = envs.WEB_URL;
+ envs.NEXT_PUBLIC_CAP_AWS_BUCKET = envs.CAP_AWS_BUCKET;
+ envs.NEXT_PUBLIC_CAP_AWS_REGION = envs.CAP_AWS_REGION;
}
if (hasDesktop) {
@@ -163,6 +164,14 @@ async function main() {
const values = await group(
{
+ VITE_SERVER_URL: () => {
+ if (!hasWeb)
+ return text({
+ message: "VITE_SERVER_URL",
+ placeholder: "http://cap.so",
+ defaultValue: "http://cap.so",
+ });
+ },
VITE_VERCEL_AUTOMATION_BYPASS_SECRET: () => {
if (!hasWeb)
return text({
diff --git a/turbo.json b/turbo.json
index 2a0cef434..70fedba45 100644
--- a/turbo.json
+++ b/turbo.json
@@ -1,12 +1,57 @@
{
"$schema": "https://turbo.build/schema.json",
- "globalDependencies": [".env", ".env"],
- "globalEnv": ["*"],
+ "globalDependencies": [
+ ".env",
+ ".env"
+ ],
+ "globalEnv": [
+ "*"
+ ],
"tasks": {
"build": {
- "inputs": ["**/*.ts", "**/*.tsx", "!src-tauri/**", "!node_modules/**"],
- "dependsOn": ["^build"],
- "outputs": [".next/**", "!.next/cache/**"]
+ "inputs": [
+ "**/*.ts",
+ "**/*.tsx",
+ "!src-tauri/**",
+ "!node_modules/**"
+ ],
+ "dependsOn": [
+ "^build"
+ ],
+ "outputs": [
+ ".next/**",
+ "!.next/cache/**"
+ ]
+ },
+ "build:web:docker": {
+ "inputs": [
+ "**/*.ts",
+ "**/*.tsx",
+ "!src-tauri/**",
+ "!node_modules/**"
+ ],
+ "dependsOn": [
+ "^build"
+ ],
+ "outputs": [
+ ".next/**",
+ "!.next/cache/**"
+ ]
+ },
+ "build:web": {
+ "inputs": [
+ "**/*.ts",
+ "**/*.tsx",
+ "!src-tauri/**",
+ "!node_modules/**"
+ ],
+ "dependsOn": [
+ "^build"
+ ],
+ "outputs": [
+ ".next/**",
+ "!.next/cache/**"
+ ]
},
"lint": {
"cache": false
@@ -28,9 +73,12 @@
"cache": false
},
"dev": {
- "dependsOn": ["db:push", "db:generate"],
+ "dependsOn": [
+ "db:push",
+ "db:generate"
+ ],
"cache": false,
"persistent": true
}
}
-}
+}
\ No newline at end of file