Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
feat: autonomous extraction of embedded videos & animated GIFs from PowerPoint slides
Marc Seitz97beaae9af09
diff --git a/app/api/views-dataroom/route.ts b/app/api/views-dataroom/route.tsindex 54ba16dc..f7b8b4c7 100644--- a/app/api/views-dataroom/route.ts+++ b/app/api/views-dataroom/route.ts@@ -19,6 +19,7 @@ import { PreviewSession, verifyPreviewSession } from "@/lib/auth/preview-auth";import { isEmbeddableUrl } from "@/lib/edge-config/embeddable-domains";import { sendOtpVerificationEmail } from "@/lib/emails/send-email-otp-verification";import { getFile } from "@/lib/files/get-file";+import { signPageLinks } from "@/lib/files/sign-page-links";import { newId } from "@/lib/id-helper";import {notifyDataroomAccess,@@ -1302,12 +1303,16 @@ export async function POST(request: NextRequest) {documentPages = await Promise.all(documentPages.map(async (page, index) => {const { storageType, ...otherPage } = page;+ const inWindow = index >= signStart && index < signEnd;return {...otherPage,- file:- index >= signStart && index < signEnd- ? await getFile({ data: page.file, type: storageType })- : null,+ file: inWindow+ ? await getFile({ data: page.file, type: storageType })+ : null,+ pageLinks: inWindow+ ? (await signPageLinks(otherPage.pageLinks)) ??+ otherPage.pageLinks+ : otherPage.pageLinks,};}),);diff --git a/app/api/views/pages/route.ts b/app/api/views/pages/route.tsindex 7cf31efd..acabbe78 100644--- a/app/api/views/pages/route.ts+++ b/app/api/views/pages/route.ts@@ -7,6 +7,7 @@ import { authOptions } from "@/lib/auth/auth-options";import { verifyDataroomSession } from "@/lib/auth/dataroom-auth";import { verifyPreviewSession } from "@/lib/auth/preview-auth";import { getFile } from "@/lib/files/get-file";+import { signPageLinks } from "@/lib/files/sign-page-links";import prisma from "@/lib/prisma";import { ratelimit } from "@/lib/redis";import { CustomUser } from "@/lib/types";@@ -249,15 +250,21 @@ async function fetchAndReturnPages(file: true,storageType: true,pageNumber: true,+ pageLinks: true,},});const pagesWithUrls = await Promise.all(documentPages.map(async (page) => {- const { storageType, ...otherPage } = page;+ const { storageType, pageLinks } = page;+ // Re-sign overlay URLs alongside the page-image URL — they share the+ // same TTL and the viewer needs both refreshed when it lazy-loads a+ // page outside the initial window.+ const signedLinks = await signPageLinks(pageLinks);return {- pageNumber: otherPage.pageNumber,+ pageNumber: page.pageNumber,file: await getFile({ data: page.file, type: storageType }),+ ...(signedLinks ? { pageLinks: signedLinks } : {}),};}),);diff --git a/app/api/views/route.ts b/app/api/views/route.tsindex 029cccb8..6d8bd091 100644--- a/app/api/views/route.ts+++ b/app/api/views/route.ts@@ -21,6 +21,7 @@ import { isEmbeddableUrl } from "@/lib/edge-config/embeddable-domains";import { sendOtpVerificationEmail } from "@/lib/emails/send-email-otp-verification";import { getFeatureFlags } from "@/lib/featureFlags";import { getFile } from "@/lib/files/get-file";+import { signPageLinks } from "@/lib/files/sign-page-links";import { newId } from "@/lib/id-helper";import { notifyDocumentView } from "@/lib/integrations/slack/events";import prisma from "@/lib/prisma";@@ -812,12 +813,18 @@ export async function POST(request: NextRequest) {documentPages = await Promise.all(documentPages.map(async (page, index) => {const { storageType, ...otherPage } = page;+ const inWindow = index >= signStart && index < signEnd;return {...otherPage,- file:- index >= signStart && index < signEnd- ? await getFile({ data: page.file, type: storageType })- : null,+ file: inWindow+ ? await getFile({ data: page.file, type: storageType })+ : null,+ // Always sign overlay URLs alongside whichever pages we sign+ // file URLs for; lazy-loaded pages re-sign via /api/views/pages.+ pageLinks: inWindow+ ? (await signPageLinks(otherPage.pageLinks)) ??+ otherPage.pageLinks+ : otherPage.pageLinks,};}),);diff --git a/components/view/viewer/horizontal-page-content.tsx b/components/view/viewer/horizontal-page-content.tsxindex 04cfed6d..9cce6f19 100644--- a/components/view/viewer/horizontal-page-content.tsx+++ b/components/view/viewer/horizontal-page-content.tsx@@ -2,35 +2,30 @@ import type { MouseEvent, MutableRefObject } from "react";import { getContainedImageRect } from "@/lib/hooks/use-fullscreen";import { WatermarkConfig } from "@/lib/types";+import { type PageLink } from "@/lib/types/page-link";import { getSafeLinkHref } from "@/lib/utils/sanitize-link-href";import { SVGWatermark } from "../watermark-svg";+import {+ partitionPageLinks,+ renderMediaOverlay,+ scaleCoordinates,+} from "./page-media";export type HorizontalViewerPage = {file: string | null;pageNumber: string;embeddedLinks: string[];- pageLinks: {- href: string;- coords: string;- isInternal?: boolean;- targetPage?: number;- }[];+ pageLinks: PageLink[];metadata: { width: number; height: number; scaleFactor: number };};type PageDimensions = Record<number, { width: number; height: number }>;-const scaleCoordinates = (coords: string, scaleFactor: number) => {- return coords- .split(",")- .map((coord) => parseFloat(coord) * scaleFactor)- .join(",");-};-export function HorizontalPageContent({page,index,+ isCurrentPage,imgHeight,imgMaxHeight,imgMaxWidth,@@ -46,6 +41,7 @@ export function HorizontalPageContent({}: {page: HorizontalViewerPage;index: number;+ isCurrentPage: boolean;imgHeight?: string;imgMaxHeight: string;imgMaxWidth?: string;@@ -111,7 +107,11 @@ export function HorizontalPageContent({{watermarkConfig && watermarkRect ? (<divclassName="pointer-events-none absolute"- style={{ left: watermarkRect.left, top: watermarkRect.top }}+ style={{+ left: watermarkRect.left,+ top: watermarkRect.top,+ zIndex: 20,+ }}><SVGWatermarkconfig={watermarkConfig}@@ -131,75 +131,81 @@ export function HorizontalPageContent({</div>) : null}- {page.pageLinks ? (- <map name={`page-map-${index + 1}`}>- {page.pageLinks- .filter((link) => !link.href.endsWith(".gif"))- .map((link, linkIndex) => {- const safeHref = getSafeLinkHref(link.href);- if (!safeHref) {- return null;- }- const isInternal = safeHref.startsWith("#");- return (- <area- key={linkIndex}- shape="rect"- coords={scaleCoordinates(- link.coords,- getScaleFactor({- naturalHeight: page.metadata.height,- scaleFactor: page.metadata.scaleFactor,- }),- )}- href={safeHref}- onClick={(event) => onLinkClick(safeHref, event)}- target={isInternal ? "_self" : "_blank"}- rel={isInternal ? undefined : "noopener noreferrer"}- />- );- })}- </map>- ) : null}+ {(() => {+ if (!page.pageLinks) return null;+ const { links, media } = partitionPageLinks(+ page.pageLinks as PageLink[],+ );+ const displayScale = getScaleFactor({+ naturalHeight: page.metadata.height,+ scaleFactor: page.metadata.scaleFactor,+ });- {page.pageLinks && imageDimensions[index]- ? page.pageLinks- .filter((link) => link.href.endsWith(".gif"))- .map((link, linkIndex) => {- const [x1, y1, x2, y2] = scaleCoordinates(- link.coords,- getScaleFactor({- naturalHeight: page.metadata.height,- scaleFactor: page.metadata.scaleFactor,- }),- )- .split(",")- .map(Number);+ // In fullscreen the <img> is given an explicit height plus+ // `object-contain`, so the visible image is letterboxed inside a larger+ // element box. Track the actual contained image rect (same math as the+ // watermark) so GIF/video overlays scale and sit on the image instead+ // of drifting into the letterbox bands and mis-scaling off the box.+ const mediaBox = imageDimensions[index];+ const mediaAspectRatio =+ page.metadata.height > 0+ ? page.metadata.width / page.metadata.height+ : 0;+ const mediaRect = mediaBox+ ? getContainedImageRect(+ mediaBox.width,+ mediaBox.height,+ mediaAspectRatio,+ )+ : null;+ const mediaScale =+ mediaRect && page.metadata.height > 0+ ? (page.metadata.scaleFactor * mediaRect.height) /+ page.metadata.height+ : displayScale;+ const mediaLeftOffset = mediaRect ? mediaRect.left : 0;+ const mediaTopOffset = mediaRect ? mediaRect.top : 0;- const overlayWidth = x2 - x1;- const overlayHeight = y2 - y1;- const containerWidth =- imageRefs.current[index]?.parentElement?.clientWidth || 0;- const imageWidth = imageDimensions[index].width;- const leftOffset = (containerWidth - imageWidth) / 2;+ return (+ <>+ {links.length > 0 ? (+ <map name={`page-map-${index + 1}`}>+ {links.map((link, linkIndex) => {+ const safeHref = getSafeLinkHref(link.href);+ if (!safeHref) {+ return null;+ }+ const isInternal = safeHref.startsWith("#");+ return (+ <area+ key={linkIndex}+ shape="rect"+ coords={scaleCoordinates(link.coords, displayScale)}+ href={safeHref}+ onClick={(event) => onLinkClick(safeHref, event)}+ target={isInternal ? "_self" : "_blank"}+ rel={isInternal ? undefined : "noopener noreferrer"}+ />+ );+ })}+ </map>+ ) : null}- return (- <img- key={`overlay-${index}-${linkIndex}`}- src={link.href}- alt={`Overlay ${index + 1}`}- style={{- position: "absolute",- top: y1,- left: x1 + leftOffset,- width: `${overlayWidth}px`,- height: `${overlayHeight}px`,- pointerEvents: "none",- }}- />- );- })- : null}+ {imageDimensions[index]+ ? media.map((link, linkIndex) =>+ renderMediaOverlay({+ key: `overlay-${index}-${linkIndex}`,+ link,+ displayScale: mediaScale,+ leftOffset: mediaLeftOffset,+ topOffset: mediaTopOffset,+ isCurrentPage,+ }),+ )+ : null}+ </>+ );+ })()}</div>);}diff --git a/components/view/viewer/media-video-overlay.tsx b/components/view/viewer/media-video-overlay.tsxnew file mode 100644index 00000000..6e9b2222--- /dev/null+++ b/components/view/viewer/media-video-overlay.tsx@@ -0,0 +1,201 @@+import React, { useCallback, useEffect, useRef, useState } from "react";++import { Pause, Play, Volume2, VolumeX } from "lucide-react";++import { cn } from "@/lib/utils";++function formatTime(seconds: number): string {+ if (!Number.isFinite(seconds) || seconds <= 0) return "0:00";+ const totalSeconds = Math.floor(seconds);+ const minutes = Math.floor(totalSeconds / 60);+ const secs = totalSeconds % 60;+ return `${minutes}:${secs.toString().padStart(2, "0")}`;+}++const HIDE_CONTROLS_DELAY_MS = 2500;++/**+ * Video overlay with fully custom controls. We render `controls={false}` so no+ * native control bar (and therefore no fullscreen button) appears — the only+ * reliable way to hide fullscreen on iOS Safari, which ignores `controlsList`.+ */+export function MediaVideoOverlay({+ src,+ poster,+ isCurrentPage,+ style,+}: {+ src: string;+ poster?: string;+ isCurrentPage: boolean;+ style: React.CSSProperties;+}) {+ const videoRef = useRef<HTMLVideoElement>(null);+ const hideTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);++ const [isPlaying, setIsPlaying] = useState(false);+ const [isMuted, setIsMuted] = useState(true);+ const [currentTime, setCurrentTime] = useState(0);+ const [duration, setDuration] = useState(0);+ const [controlsVisible, setControlsVisible] = useState(true);++ useEffect(() => {+ const video = videoRef.current;+ if (!video) return;+ if (isCurrentPage) {+ void video.play().catch(() => {});+ } else {+ video.pause();+ }+ }, [isCurrentPage]);++ useEffect(+ () => () => {+ if (hideTimeout.current) clearTimeout(hideTimeout.current);+ },+ [],+ );++ const revealControls = useCallback(() => {+ setControlsVisible(true);+ if (hideTimeout.current) clearTimeout(hideTimeout.current);+ hideTimeout.current = setTimeout(() => {+ const video = videoRef.current;+ if (video && !video.paused) setControlsVisible(false);+ }, HIDE_CONTROLS_DELAY_MS);+ }, []);++ const togglePlay = useCallback(() => {+ const video = videoRef.current;+ if (!video) return;+ if (video.paused) {+ void video.play().catch(() => {});+ } else {+ video.pause();+ }+ }, []);++ const toggleMute = useCallback(() => {+ const video = videoRef.current;+ if (!video) return;+ video.muted = !video.muted;+ setIsMuted(video.muted);+ }, []);++ const handleSeek = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {+ const video = videoRef.current;+ if (!video) return;+ const next = Number(event.target.value);+ video.currentTime = next;+ setCurrentTime(next);+ }, []);++ const progress = duration > 0 ? (currentTime / duration) * 100 : 0;+ const seekBackground = `linear-gradient(to right, white ${progress}%, rgba(255,255,255,0.35) ${progress}%)`;++ return (+ <div+ style={style}+ className="group/video overflow-hidden"+ onPointerMove={revealControls}+ onPointerLeave={() => {+ if (isPlaying) setControlsVisible(false);+ }}+ >+ <video+ ref={videoRef}+ src={src}+ poster={poster}+ muted+ playsInline+ controls={false}+ disablePictureInPicture+ controlsList="nodownload noremoteplayback nofullscreen"+ className="h-full w-full object-contain"+ onClick={() => {+ togglePlay();+ revealControls();+ }}+ onPlay={() => {+ setIsPlaying(true);+ revealControls();+ }}+ onPause={() => {+ setIsPlaying(false);+ setControlsVisible(true);+ }}+ onEnded={() => setControlsVisible(true)}+ onTimeUpdate={(e) => setCurrentTime(e.currentTarget.currentTime)}+ onLoadedMetadata={(e) => setDuration(e.currentTarget.duration)}+ onVolumeChange={(e) => setIsMuted(e.currentTarget.muted)}+ />++ {!isPlaying ? (+ <button+ type="button"+ aria-label="Play video"+ onClick={togglePlay}+ className="absolute inset-0 flex items-center justify-center"+ >+ <span className="flex h-12 w-12 items-center justify-center rounded-full bg-black/55 text-white backdrop-blur-sm transition-transform hover:scale-105">+ <Play className="ml-0.5 h-6 w-6 fill-current" />+ </span>+ </button>+ ) : null}++ <div+ className={cn(+ "absolute inset-x-0 bottom-0 flex items-center gap-2 bg-gradient-to-t from-black/70 to-transparent px-2.5 pb-2 pt-6 transition-opacity duration-200",+ controlsVisible ? "opacity-100" : "pointer-events-none opacity-0",+ )}+ >+ <button+ type="button"+ aria-label={isPlaying ? "Pause" : "Play"}+ onClick={togglePlay}+ className="shrink-0 text-white transition-opacity hover:opacity-80"+ >+ {isPlaying ? (+ <Pause className="h-4 w-4 fill-current" />+ ) : (+ <Play className="h-4 w-4 fill-current" />+ )}+ </button>++ <span className="shrink-0 select-none text-[11px] font-medium tabular-nums text-white">+ {formatTime(currentTime)}+ </span>++ <input+ type="range"+ aria-label="Seek"+ min={0}+ max={duration || 0}+ step="any"+ value={Math.min(currentTime, duration || 0)}+ onChange={handleSeek}+ onPointerDown={revealControls}+ style={{ background: seekBackground }}+ className="h-1 w-full cursor-pointer appearance-none rounded-full [&::-moz-range-thumb]:h-3 [&::-moz-range-thumb]:w-3 [&::-moz-range-thumb]:appearance-none [&::-moz-range-thumb]:rounded-full [&::-moz-range-thumb]:border-0 [&::-moz-range-thumb]:bg-white [&::-webkit-slider-thumb]:h-3 [&::-webkit-slider-thumb]:w-3 [&::-webkit-slider-thumb]:appearance-none [&::-webkit-slider-thumb]:rounded-full [&::-webkit-slider-thumb]:bg-white"+ />++ <span className="shrink-0 select-none text-[11px] font-medium tabular-nums text-white">+ {formatTime(duration)}+ </span>++ <button+ type="button"+ aria-label={isMuted ? "Unmute" : "Mute"}+ onClick={toggleMute}+ className="shrink-0 text-white transition-opacity hover:opacity-80"+ >+ {isMuted ? (+ <VolumeX className="h-4 w-4" />+ ) : (+ <Volume2 className="h-4 w-4" />+ )}+ </button>+ </div>+ </div>+ );+}diff --git a/components/view/viewer/page-media.tsx b/components/view/viewer/page-media.tsxnew file mode 100644index 00000000..a158d326--- /dev/null+++ b/components/view/viewer/page-media.tsx@@ -0,0 +1,113 @@+import React from "react";++import {+ resolvePageLinkKind,+ type MediaPageLink,+ type PageLink,+ type RegularPageLink,+} from "@/lib/types/page-link";++import { MediaVideoOverlay } from "./media-video-overlay";++export const scaleCoordinates = (coords: string, scaleFactor: number) => {+ return coords+ .split(",")+ .map((coord) => parseFloat(coord) * scaleFactor)+ .join(",");+};++/**+ * Splits a page's link entries into clickable hyperlinks and media overlays+ * (animated GIFs / embedded videos). Falls back to the legacy convention of+ * treating any href ending in `.gif` as an animated overlay.+ */+export function partitionPageLinks(pageLinks: PageLink[]): {+ links: RegularPageLink[];+ media: MediaPageLink[];+} {+ const links: RegularPageLink[] = [];+ const media: MediaPageLink[] = [];+ for (const link of pageLinks) {+ const kind = resolvePageLinkKind(link);+ if (kind === "link") {+ const href = "href" in link ? (link.href ?? "") : "";+ if (!href) continue;+ const regular = link as RegularPageLink;+ links.push({+ href,+ coords: regular.coords,+ ...(regular.isInternal ? { isInternal: regular.isInternal } : {}),+ ...(regular.targetPage ? { targetPage: regular.targetPage } : {}),+ });+ } else {+ // Promote legacy gif-by-href entries into the new shape.+ const media_link: MediaPageLink = {+ kind,+ coords: link.coords,+ ...("href" in link && link.href ? { href: link.href } : {}),+ ...("posterUrl" in link && link.posterUrl+ ? { posterUrl: link.posterUrl }+ : {}),+ ...("naturalWidth" in link && link.naturalWidth+ ? { naturalWidth: link.naturalWidth }+ : {}),+ ...("naturalHeight" in link && link.naturalHeight+ ? { naturalHeight: link.naturalHeight }+ : {}),+ };+ if (media_link.href) media.push(media_link);+ }+ }+ return { links, media };+}++export function renderMediaOverlay({+ key,+ link,+ displayScale,+ leftOffset,+ topOffset = 0,+ isCurrentPage,+}: {+ key: string;+ link: MediaPageLink;+ displayScale: number;+ leftOffset: number;+ topOffset?: number;+ isCurrentPage: boolean;+}) {+ if (!link.href) return null;+ const [x1, y1, x2, y2] = scaleCoordinates(link.coords, displayScale)+ .split(",")+ .map(Number);+ const overlayWidth = x2 - x1;+ const overlayHeight = y2 - y1;+ const style: React.CSSProperties = {+ position: "absolute",+ top: y1 + topOffset,+ left: x1 + leftOffset,+ width: `${overlayWidth}px`,+ height: `${overlayHeight}px`,+ };++ if (link.kind === "video") {+ return (+ <MediaVideoOverlay+ key={key}+ src={link.href}+ poster={link.posterUrl}+ isCurrentPage={isCurrentPage}+ style={{ ...style, background: "black" }}+ />+ );+ }++ return (+ <img+ key={key}+ src={link.href}+ alt="Animated overlay"+ style={{ ...style, pointerEvents: "none" }}+ />+ );+}diff --git a/components/view/viewer/pages-horizontal-viewer.tsx b/components/view/viewer/pages-horizontal-viewer.tsxindex fcbe6f19..9d6ff1a2 100644--- a/components/view/viewer/pages-horizontal-viewer.tsx+++ b/components/view/viewer/pages-horizontal-viewer.tsx@@ -708,6 +708,7 @@ export default function PagesHorizontalViewer({<HorizontalPageContentpage={page}index={index}+ isCurrentPage={pageNumber === index + 1}imgHeight={imgHeight}imgMaxHeight={imgMaxHeight}imgMaxWidth={imgMaxWidth}diff --git a/components/view/viewer/pages-vertical-viewer.tsx b/components/view/viewer/pages-vertical-viewer.tsxindex f0556737..eb75bba9 100644--- a/components/view/viewer/pages-vertical-viewer.tsx+++ b/components/view/viewer/pages-vertical-viewer.tsx@@ -18,6 +18,7 @@ import {import { useSafePageViewTracker } from "@/lib/tracking/safe-page-view-tracker";import { getTrackingOptions } from "@/lib/tracking/tracking-config";import { WatermarkConfig } from "@/lib/types";+import { type PageLink } from "@/lib/types/page-link";import { cn } from "@/lib/utils";import { getSafeLinkHref } from "@/lib/utils/sanitize-link-href";import { useMediaQuery } from "@/lib/utils/use-media-query";@@ -31,16 +32,14 @@ import { ViewerThemeColor } from "../viewer-theme-color";import { SVGWatermark } from "../watermark-svg";import { AwayPoster } from "./away-poster";import { FullscreenControls } from "./fullscreen-controls";+import {+ partitionPageLinks,+ renderMediaOverlay,+ scaleCoordinates,+} from "./page-media";import "@/styles/custom-viewer-styles.css";-const scaleCoordinates = (coords: string, scaleFactor: number) => {- return coords- .split(",")- .map((coord) => parseFloat(coord) * scaleFactor)- .join(",");-};-const calculateOptimalWidth = (containerWidth: number,metadata: { width: number; height: number } | null,@@ -88,12 +87,7 @@ export default function PagesVerticalViewer({file: string | null;pageNumber: string;embeddedLinks: string[];- pageLinks: {- href: string;- coords: string;- isInternal?: boolean;- targetPage?: number;- }[];+ pageLinks: PageLink[];metadata: { width: number; height: number; scaleFactor: number };}[];feedbackEnabled: boolean;@@ -995,7 +989,10 @@ export default function PagesVerticalViewer({/>{watermarkConfig && imageDimensions[index] ? (- <div className="absolute left-0 top-0">+ <div+ className="pointer-events-none absolute left-0 top-0"+ style={{ zIndex: 20 }}+ ><SVGWatermarkconfig={watermarkConfig}viewerData={{@@ -1012,82 +1009,75 @@ export default function PagesVerticalViewer({) : null}</div>- {page.pageLinks ? (- <map name={`page-map-${index + 1}`}>- {page.pageLinks- .filter((link) => !link.href.endsWith(".gif"))- .map((link, linkIndex) => {- const safeHref = getSafeLinkHref(link.href);- if (!safeHref) {- return null;- }- const isInternal = safeHref.startsWith("#");- return (- <area- key={linkIndex}- shape="rect"- coords={scaleCoordinates(- link.coords,- getScaleFactor({- naturalHeight: page.metadata.height,- scaleFactor: page.metadata.scaleFactor,- pageIndex: index,- }),- )}- href={safeHref}- onClick={(e) =>- handleLinkClick(safeHref, e)- }- target={isInternal ? "_self" : "_blank"}- rel={- isInternal- ? undefined- : "noopener noreferrer"+ {(() => {+ if (!page.pageLinks) return null;+ const { links, media } = partitionPageLinks(+ page.pageLinks as PageLink[],+ );+ const displayScale = getScaleFactor({+ naturalHeight: page.metadata.height,+ scaleFactor: page.metadata.scaleFactor,+ pageIndex: index,+ });+ // Vertical layout uses px-4/md:px-8 outer padding+ // instead of a center-aligned image, so the overlay+ // origin is shifted by the active padding.+ const leftOffset = isMobile ? 16 : 32;+ const isCurrentPage = pageNumber === index + 1;++ return (+ <>+ {links.length > 0 ? (+ <map name={`page-map-${index + 1}`}>+ {links.map((link, linkIndex) => {+ const safeHref = getSafeLinkHref(+ link.href,+ );+ if (!safeHref) {+ return null;}- />- );- })}- </map>- ) : null}-- {page.pageLinks && imageDimensions[index]- ? page.pageLinks- .filter((link) => link.href.endsWith(".gif"))- .map((link, linkIndex) => {- const [x1, y1, x2, y2] = scaleCoordinates(- link.coords,- getScaleFactor({- naturalHeight: page.metadata.height,- scaleFactor: page.metadata.scaleFactor,- pageIndex: index,- }),- )- .split(",")- .map(Number);-- const overlayWidth = x2 - x1;- const overlayHeight = y2 - y1;-- // Account for the padding on the outer container (px-4 md:px-8)- const padding = isMobile ? 16 : 32; // 1rem = 16px (px-4), 2rem = 32px (px-8)-- return (- <img- key={`overlay-${index}-${linkIndex}`}- src={link.href}- alt={`Overlay ${index + 1}`}- style={{- position: "absolute",- top: y1,- left: x1 + padding,- width: `${overlayWidth}px`,- height: `${overlayHeight}px`,- pointerEvents: "none",- }}- />- );- })- : null}+ const isInternal =+ safeHref.startsWith("#");+ return (+ <area+ key={linkIndex}+ shape="rect"+ coords={scaleCoordinates(+ link.coords,+ displayScale,+ )}+ href={safeHref}+ onClick={(e) =>+ handleLinkClick(safeHref, e)+ }+ target={+ isInternal ? "_self" : "_blank"+ }+ rel={+ isInternal+ ? undefined+ : "noopener noreferrer"+ }+ />+ );+ })}+ </map>+ ) : null}++ {imageDimensions[index]+ ? media.map((link, linkIndex) =>+ renderMediaOverlay({+ key: `overlay-${index}-${linkIndex}`,+ link,+ displayScale,+ leftOffset,+ isCurrentPage,+ }),+ )+ : null}+ </>+ );+ })()}</div>);})}diff --git a/lib/api/documents/process-document.ts b/lib/api/documents/process-document.tsindex 3bb974b5..95a9763b 100644--- a/lib/api/documents/process-document.ts+++ b/lib/api/documents/process-document.ts@@ -1,11 +1,13 @@+import { tasks } from "@trigger.dev/sdk";+import { validateExternalDocumentUrl } from "@/lib/api/documents/validate-external-url";import { DocumentData } from "@/lib/documents/create-document";import { copyFileToBucketServer } from "@/lib/files/copy-file-to-bucket-server";import prisma from "@/lib/prisma";-import {+import type {convertFilesToPdfTask,convertKeynoteToPdfTask,-} from "@/lib/trigger/convert-files";+} from "@/ee/features/conversions/lib/trigger/convert-files";import { processVideo } from "@/lib/trigger/optimize-video-files";import { convertPdfToImageRoute } from "@/lib/trigger/pdf-to-image-route";import { getExtension } from "@/lib/utils";@@ -139,7 +141,8 @@ export const processDocument = async ({(contentType === "application/vnd.apple.keynote" ||contentType === "application/x-iwork-keynote-sffkey")) {- await convertKeynoteToPdfTask.trigger(+ await tasks.trigger<typeof convertKeynoteToPdfTask>(+ "convert-keynote-to-pdf",{documentId: document.id,documentVersionId: document.versions[0].id,@@ -161,7 +164,8 @@ export const processDocument = async ({!isDownloadOnlyByExtension &&!isMarkdown) {- await convertFilesToPdfTask.trigger(+ await tasks.trigger<typeof convertFilesToPdfTask>(+ "convert-files-to-pdf",{documentId: document.id,documentVersionId: document.versions[0].id,diff --git a/lib/constants.ts b/lib/constants.tsindex 0e18fe31..e67372bd 100644--- a/lib/constants.ts+++ b/lib/constants.ts@@ -101,6 +101,7 @@ export const SUPPORTED_DOCUMENT_MIME_TYPES = ["image/png", // .png"image/jpeg", // .jpeg"image/jpg", // .jpg+ "image/gif", // .gif (also: animated overlays extracted from .pptx slides)"application/zip", // .zip"application/x-zip-compressed", // .zip"application/vnd.rar", // .rardiff --git a/lib/files/put-file-server.ts b/lib/files/put-file-server.tsindex 20440572..8b285fdf 100644--- a/lib/files/put-file-server.ts+++ b/lib/files/put-file-server.ts@@ -22,17 +22,19 @@ export const putFileServer = async ({teamId,docId,restricted = true,+ subfolder,}: {file: File;teamId: string;docId?: string;restricted?: boolean;+ subfolder?: string;}) => {const NEXT_PUBLIC_UPLOAD_TRANSPORT = process.env.NEXT_PUBLIC_UPLOAD_TRANSPORT;const { type, data } = await match(NEXT_PUBLIC_UPLOAD_TRANSPORT).with("s3", async () =>- putFileInS3Server({ file, teamId, docId, restricted }),+ putFileInS3Server({ file, teamId, docId, restricted, subfolder }),).with("vercel", async () => putFileInVercelServer(file)).otherwise(() => {@@ -65,11 +67,13 @@ const putFileInS3Server = async ({teamId,docId,restricted = true,+ subfolder,}: {file: File;teamId: string;docId?: string;restricted?: boolean;+ subfolder?: string;}) => {if (!docId) {docId = newId("doc");@@ -95,7 +99,8 @@ const putFileInS3Server = async ({const slugifiedName = safeSlugify(name) + ext;const originalFileName = `${name}${ext}`;- const key = `${teamId}/${docId}/${slugifiedName}`;+ const folderPrefix = subfolder ? `${safeSlugify(subfolder)}/` : "";+ const key = `${teamId}/${docId}/${folderPrefix}${slugifiedName}`;const params = {Bucket: config.bucket,diff --git a/lib/files/sign-page-links.ts b/lib/files/sign-page-links.tsnew file mode 100644index 00000000..3f2baa0f--- /dev/null+++ b/lib/files/sign-page-links.ts@@ -0,0 +1,74 @@+import {+ resolvePageLinkKind,+ type MediaPageLink,+ type PageLink,+ type StoredFileRef,+} from "@/lib/types/page-link";++import { getFile } from "./get-file";++/**+ * Signs the storage refs (`src` / `poster`) on `gif` / `video` overlay+ * entries inside a `DocumentPage.pageLinks` blob and returns a copy that+ * is safe to send to the client.+ *+ * - For each `MediaPageLink` that has `src`, mints an `href` signed URL.+ * - For each `MediaPageLink` that has `poster`, mints a `posterUrl`.+ * - The internal `src` / `poster` keys are stripped from the returned+ * payload so the client never sees raw S3 keys.+ * - Regular `link` entries (the default) are returned untouched.+ *+ * `pageLinks` is typed as `unknown` because Prisma stores it as `Json`;+ * we defensively coerce.+ */+export async function signPageLinks(+ pageLinks: unknown,+ /** Defaults to S3 lifetime; we use the same cap as the page-image URLs. */+ expiresIn?: number,+): Promise<PageLink[] | undefined> {+ if (!Array.isArray(pageLinks)) return undefined;++ const links = pageLinks as PageLink[];++ return Promise.all(+ links.map(async (link) => {+ const kind = resolvePageLinkKind(link);+ if (kind !== "gif" && kind !== "video") {+ // Regular link entry — pass through untouched.+ return link;+ }++ const media = link as MediaPageLink;+ const out: MediaPageLink = {+ kind: media.kind,+ coords: media.coords,+ ...(media.naturalWidth ? { naturalWidth: media.naturalWidth } : {}),+ ...(media.naturalHeight ? { naturalHeight: media.naturalHeight } : {}),+ };++ if (media.src) {+ out.href = await signRef(media.src, expiresIn);+ } else if (media.href) {+ // Legacy: external URL baked in directly.+ out.href = media.href;+ }++ if (media.poster) {+ out.posterUrl = await signRef(media.poster, expiresIn);+ }++ return out;+ }),+ );+}++async function signRef(+ ref: StoredFileRef,+ expiresIn?: number,+): Promise<string> {+ return getFile({+ type: ref.storageType,+ data: ref.data,+ ...(expiresIn ? { expiresIn } : {}),+ });+}diff --git a/lib/hooks/use-lazy-pages.ts b/lib/hooks/use-lazy-pages.tsindex 1c2e086f..12eb3f97 100644--- a/lib/hooks/use-lazy-pages.ts+++ b/lib/hooks/use-lazy-pages.ts@@ -1,20 +1,25 @@import { useCallback, useEffect, useRef, useState } from "react";+import type { PageLink } from "@/lib/types/page-link";+type PageData = {file: string | null;pageNumber: string;embeddedLinks: string[];- pageLinks: {- href: string;- coords: string;- isInternal?: boolean;- targetPage?: number;- }[];+ pageLinks: PageLink[];metadata: { width: number; height: number; scaleFactor: number };};type FetchPagesResponse = {- pages: { pageNumber: number; file: string }[];+ pages: {+ pageNumber: number;+ file: string;+ /**+ * Re-signed overlay URLs for `pageLinks` of the requested page.+ * Optional so older callers stay compatible.+ */+ pageLinks?: PageLink[];+ }[];};type UseLazyPagesOptions = {@@ -93,6 +98,9 @@ export function useLazyPages({updated[idx] = {...updated[idx],file: fetchedPage.file,+ ...(fetchedPage.pageLinks+ ? { pageLinks: fetchedPage.pageLinks }+ : {}),};}}diff --git a/lib/trigger/convert-files.ts b/lib/trigger/convert-files.tsdeleted file mode 100644index ab8e0b51..00000000--- a/lib/trigger/convert-files.ts+++ /dev/null@@ -1,687 +0,0 @@-import { python } from "@trigger.dev/python";-import { logger, retry, task } from "@trigger.dev/sdk";-import { writeFile, readFile, unlink } from "node:fs/promises";-import { tmpdir } from "node:os";-import { join } from "node:path";--import { getFile } from "@/lib/files/get-file";-import { putFileServer } from "@/lib/files/put-file-server";-import prisma from "@/lib/prisma";--import { updateStatus } from "../utils/generate-trigger-status";-import { getExtensionFromContentType } from "../utils/get-content-type";-import { convertPdfToImageRoute } from "./pdf-to-image-route";-import {- convertCadToPdfQueue,- convertFilesToPdfQueue,- convertKeynoteToPdfQueue,-} from "./queues";--export type ConvertPayload = {- documentId: string;- documentVersionId: string;- teamId: string;-};--export const convertFilesToPdfTask = task({- id: "convert-files-to-pdf",- retry: { maxAttempts: 3 },- queue: convertFilesToPdfQueue,- run: async (payload: ConvertPayload) => {- updateStatus({ progress: 0, text: "Initializing..." });-- const team = await prisma.team.findUnique({- where: {- id: payload.teamId,- },- });-- if (!team) {- logger.error("Team not found", { teamId: payload.teamId });- return;- }-- const document = await prisma.document.findUnique({- where: {- id: payload.documentId,- teamId: payload.teamId,- },- select: {- name: true,- versions: {- where: {- id: payload.documentVersionId,- },- select: {- file: true,- originalFile: true,- contentType: true,- storageType: true,- },- },- },- });-- if (- !document ||- !document.versions[0] ||- !document.versions[0].originalFile ||- !document.versions[0].contentType- ) {- updateStatus({ progress: 0, text: "Document not found" });-- logger.error("Document not found", {- documentId: payload.documentId,- documentVersionId: payload.documentVersionId,- teamId: payload.teamId,- });- return;- }-- updateStatus({ progress: 10, text: "Retrieving file..." });-- const fileUrl = await getFile({- data: document.versions[0].originalFile,- type: document.versions[0].storageType,- });-- const CONVERSION_TIMEOUT_MS = 3 * 60 * 1000; // 3 min client-side timeout-- updateStatus({ progress: 20, text: "Converting document…" });-- let conversionResponse: Response;- try {- const fd = new FormData();- fd.append("downloadFrom", JSON.stringify([{ url: fileUrl }]));- fd.append("quality", "75");-- conversionResponse = await fetch(- `${process.env.NEXT_PRIVATE_CONVERSION_BASE_URL}/forms/libreoffice/convert`,- {- method: "POST",- body: fd,- headers: {- Authorization: `Basic ${process.env.NEXT_PRIVATE_INTERNAL_AUTH_TOKEN}`,- },- signal: AbortSignal.timeout(CONVERSION_TIMEOUT_MS),- },- );- } catch (err) {- logger.warn("Gotenberg conversion failed, will attempt sanitization", {- error: String(err),- });- conversionResponse = new Response(null, {- status: 504,- statusText: "Conversion timed out or unreachable",- });- }-- let conversionBuffer!: Buffer;-- if (!conversionResponse.ok) {- const contentType = document.versions[0].contentType;- const isDocx =- contentType ===- "application/vnd.openxmlformats-officedocument.wordprocessingml.document";-- if (isDocx) {- const inputPath = join(tmpdir(), `input-${Date.now()}.docx`);- const outputPath = join(tmpdir(), `output-${Date.now()}.docx`);- try {- let docxResponse: Response;- try {- docxResponse = await fetch(fileUrl);- } catch (err) {- updateStatus({ progress: 0, text: "Failed to retrieve DOCX file" });- throw new Error(- `Failed to fetch DOCX from signed URL for sanitization: ${String(err)}`,- );- }-- if (!docxResponse.ok) {- updateStatus({ progress: 0, text: "Failed to retrieve DOCX file" });- throw new Error(- `Failed to fetch DOCX from signed URL for sanitization: HTTP ${docxResponse.status} ${docxResponse.statusText}`,- );- }-- const responseContentType = docxResponse.headers.get("content-type");- if (- responseContentType &&- !responseContentType.includes(- "application/vnd.openxmlformats-officedocument.wordprocessingml.document",- ) &&- !responseContentType.includes("application/octet-stream")- ) {- updateStatus({ progress: 0, text: "Invalid DOCX download response" });- throw new Error(- `Signed URL returned unexpected content-type for DOCX sanitization: ${responseContentType}`,- );- }-- const docxBuffer = Buffer.from(await docxResponse.arrayBuffer());- await writeFile(inputPath, docxBuffer);-- const attemptConversion = async (- sanitizedPath: string,- ): Promise<Response> => {- const buf = await readFile(sanitizedPath);- const fd = new FormData();- fd.append(- "files",- new Blob([new Uint8Array(buf)], { type: contentType }),- document.name,- );- fd.append("quality", "75");- return fetch(- `${process.env.NEXT_PRIVATE_CONVERSION_BASE_URL}/forms/libreoffice/convert`,- {- method: "POST",- body: fd,- headers: {- Authorization: `Basic ${process.env.NEXT_PRIVATE_INTERNAL_AUTH_TOKEN}`,- },- signal: AbortSignal.timeout(CONVERSION_TIMEOUT_MS),- },- );- };-- logger.warn("DOCX conversion failed, sanitizing document…", {- status: conversionResponse.status,- });-- updateStatus({ progress: 25, text: "Sanitizing document…" });-- const result = await python.runScript(- "./ee/features/conversions/python/docx-sanitizer.py",- ["-v", "--mode", "all", inputPath, outputPath],- );- logger.info("Sanitizer output", { stderr: result.stderr });-- let retryResponse: Response;- try {- retryResponse = await attemptConversion(outputPath);- } catch (err) {- updateStatus({ progress: 0, text: "Conversion timed out" });- throw new Error(- `Conversion timed out after sanitization — LibreOffice could not process this file within ${CONVERSION_TIMEOUT_MS / 1000}s`,- );- }-- if (!retryResponse.ok) {- updateStatus({ progress: 0, text: "Conversion failed" });- let message: string;- try {- const body = await retryResponse.json();- message = body.message ?? retryResponse.statusText;- } catch {- message = retryResponse.statusText || "Unknown error";- }- throw new Error(- `Conversion failed after sanitization: ${message} (${retryResponse.status})`,- );- }-- conversionBuffer = Buffer.from(await retryResponse.arrayBuffer());- } finally {- await Promise.allSettled([unlink(inputPath), unlink(outputPath)]);- }- } else {- updateStatus({ progress: 0, text: "Conversion failed" });- let message: string;- try {- const body = await conversionResponse.json();- message = body.message ?? conversionResponse.statusText;- } catch {- message = conversionResponse.statusText || "Unknown error";- }- throw new Error(- `Conversion failed: ${message} (${conversionResponse.status})`,- );- }- } else {- conversionBuffer = Buffer.from(await conversionResponse.arrayBuffer());- }-- console.log("conversionBuffer", conversionBuffer);-- // get docId from url with starts with "doc_" with regex- const match = document.versions[0].originalFile.match(/(doc_[^\/]+)\//);- const docId = match ? match[1] : undefined;-- updateStatus({ progress: 30, text: "Saving converted file..." });-- // Save the converted file to the database- const { type: storageType, data } = await putFileServer({- file: {- name: `${document.name}.pdf`,- type: "application/pdf",- buffer: conversionBuffer,- },- teamId: payload.teamId,- docId: docId,- });-- if (!data || !storageType) {- updateStatus({ progress: 0, text: "Failed to save converted file" });-- logger.error("Failed to save converted file to database", {- documentId: payload.documentId,- documentVersionId: payload.documentVersionId,- teamId: payload.teamId,- docId: docId,- });- return;- }-- console.log("data from conversion", data);- console.log("storageType from conversion", storageType);-- const { versionNumber } = await prisma.documentVersion.update({- where: { id: payload.documentVersionId },- data: {- file: data,- type: "pdf",- storageType: storageType,- },- select: {- versionNumber: true,- },- });-- updateStatus({ progress: 40, text: "Initiating document processing..." });-- await convertPdfToImageRoute.trigger(- {- documentId: payload.documentId,- documentVersionId: payload.documentVersionId,- teamId: payload.teamId,- versionNumber: versionNumber,- },- {- idempotencyKey: `${payload.teamId}-${payload.documentVersionId}`,- tags: [- `team_${payload.teamId}`,- `document_${payload.documentId}`,- `version:${payload.documentVersionId}`,- ],- },- );-- logger.info("Document converted", {- documentId: payload.documentId,- documentVersionId: payload.documentVersionId,- teamId: payload.teamId,- docId: docId,- });- return;- },-});--// convert cad file to pdf-export const convertCadToPdfTask = task({- id: "convert-cad-to-pdf",- retry: { maxAttempts: 3 },- queue: convertCadToPdfQueue,- run: async (payload: ConvertPayload) => {- const team = await prisma.team.findUnique({- where: {- id: payload.teamId,- },- });-- if (!team) {- logger.error("Team not found", { teamId: payload.teamId });- return;- }-- const document = await prisma.document.findUnique({- where: {- id: payload.documentId,- teamId: payload.teamId,- },- select: {- name: true,- versions: {- where: {- id: payload.documentVersionId,- },- select: {- file: true,- originalFile: true,- contentType: true,- storageType: true,- },- },- },- });-- if (- !document ||- !document.versions[0] ||- !document.versions[0].originalFile ||- !document.versions[0].contentType- ) {- logger.error("Document not found", {- documentId: payload.documentId,- documentVersionId: payload.documentVersionId,- teamId: payload.teamId,- });- return;- }-- const fileUrl = await getFile({- data: document.versions[0].originalFile,- type: document.versions[0].storageType,- });-- // create payload for cad to pdf conversion- const tasksPayload = {- tasks: {- "import-file-v1": {- operation: "import/url",- url: fileUrl,- filename: document.name,- },- "convert-file-v1": {- operation: "convert",- input: ["import-file-v1"],- input_format: getExtensionFromContentType(- document.versions[0].contentType,- ),- output_format: "pdf",- engine: "cadconverter",- all_layouts: true,- auto_zoom: false,- },- "export-file-v1": {- operation: "export/url",- input: ["convert-file-v1"],- inline: false,- archive_multiple_files: false,- },- },- redirect: true,- };-- // Make the conversion request- const conversionResponse = await retry.fetch(- `${process.env.NEXT_PRIVATE_CONVERT_API_URL}`,- {- method: "POST",- body: JSON.stringify(tasksPayload),- headers: {- Authorization: `Bearer ${process.env.NEXT_PRIVATE_CONVERT_API_KEY}`,- "Content-Type": "application/json",- },- retry: {- byStatus: {- "500-599": {- strategy: "backoff",- maxAttempts: 3,- factor: 2,- minTimeoutInMs: 1_000,- maxTimeoutInMs: 30_000,- randomize: false,- },- },- },- },- );-- if (!conversionResponse.ok) {- const body = await conversionResponse.json();- throw new Error(- `Conversion failed: ${body.message} ${conversionResponse.status}`,- );- }-- const conversionBuffer = Buffer.from(- await conversionResponse.arrayBuffer(),- );-- // get docId from url with starts with "doc_" with regex- const match = document.versions[0].originalFile.match(/(doc_[^\/]+)\//);- const docId = match ? match[1] : undefined;-- // Save the converted file to the database- const { type: storageType, data } = await putFileServer({- file: {- name: `${document.name}.pdf`,- type: "application/pdf",- buffer: conversionBuffer,- },- teamId: payload.teamId,- docId: docId,- });-- if (!data || !storageType) {- logger.error("Failed to save converted file to database", {- documentId: payload.documentId,- documentVersionId: payload.documentVersionId,- teamId: payload.teamId,- docId: docId,- });- return;- }-- console.log("data from conversion", data);- console.log("storageType from conversion", storageType);-- await prisma.documentVersion.update({- where: { id: payload.documentVersionId },- data: {- file: data,- type: "pdf",- storageType: storageType,- },- });-- await convertPdfToImageRoute.trigger(- {- documentId: payload.documentId,- documentVersionId: payload.documentVersionId,- teamId: payload.teamId,- },- {- idempotencyKey: `${payload.teamId}-${payload.documentVersionId}`,- tags: [- `team_${payload.teamId}`,- `document_${payload.documentId}`,- `version:${payload.documentVersionId}`,- ],- },- );-- logger.info("Document converted", {- documentId: payload.documentId,- documentVersionId: payload.documentVersionId,- teamId: payload.teamId,- docId: docId,- });- return;- },-});--// convert keynote file to pdf-export const convertKeynoteToPdfTask = task({- id: "convert-keynote-to-pdf",- retry: { maxAttempts: 3 },- queue: convertKeynoteToPdfQueue,- run: async (payload: ConvertPayload) => {- const team = await prisma.team.findUnique({- where: {- id: payload.teamId,- },- });-- if (!team) {- logger.error("Team not found", { teamId: payload.teamId });- return;- }-- const document = await prisma.document.findUnique({- where: {- id: payload.documentId,- teamId: payload.teamId,- },- select: {- name: true,- versions: {- where: {- id: payload.documentVersionId,- },- select: {- file: true,- originalFile: true,- contentType: true,- storageType: true,- },- },- },- });-- if (- !document ||- !document.versions[0] ||- !document.versions[0].originalFile ||- !document.versions[0].contentType- ) {- logger.error("Document not found", {- documentId: payload.documentId,- documentVersionId: payload.documentVersionId,- teamId: payload.teamId,- });- return;- }-- const fileUrl = await getFile({- data: document.versions[0].originalFile,- type: document.versions[0].storageType,- });-- // create payload for keynote to pdf conversion- const tasksPayload = {- tasks: {- "import-file-v1": {- operation: "import/url",- url: fileUrl,- filename: document.name,- },- "convert-file-v1": {- operation: "convert",- input: ["import-file-v1"],- input_format: getExtensionFromContentType(- document.versions[0].contentType,- ),- output_format: "pdf",- engine: "iwork",- },- "export-file-v1": {- operation: "export/url",- input: ["convert-file-v1"],- inline: false,- archive_multiple_files: false,- },- },- redirect: true,- };-- // Make the conversion request- const conversionResponse = await retry.fetch(- `${process.env.NEXT_PRIVATE_CONVERT_API_URL}`,- {- method: "POST",- body: JSON.stringify(tasksPayload),- headers: {- Authorization: `Bearer ${process.env.NEXT_PRIVATE_CONVERT_API_KEY}`,- "Content-Type": "application/json",- },- retry: {- byStatus: {- "500-599": {- strategy: "backoff",- maxAttempts: 3,- factor: 2,- minTimeoutInMs: 1_000,- maxTimeoutInMs: 30_000,- randomize: false,- },- },- },- },- );-- if (!conversionResponse.ok) {- const body = await conversionResponse.json();- throw new Error(- `Conversion failed: ${body.message} ${conversionResponse.status}`,- );- }-- const conversionBuffer = Buffer.from(- await conversionResponse.arrayBuffer(),- );-- // get docId from url with starts with "doc_" with regex- const match = document.versions[0].originalFile.match(/(doc_[^\/]+)\//);- const docId = match ? match[1] : undefined;-- // Save the converted file to the database- const { type: storageType, data } = await putFileServer({- file: {- name: `${document.name}.pdf`,- type: "application/pdf",- buffer: conversionBuffer,- },- teamId: payload.teamId,- docId: docId,- });-- if (!data || !storageType) {- logger.error("Failed to save converted file to database", {- documentId: payload.documentId,- documentVersionId: payload.documentVersionId,- teamId: payload.teamId,- docId: docId,- });- return;- }-- console.log("data from conversion", data);- console.log("storageType from conversion", storageType);-- await prisma.documentVersion.update({- where: { id: payload.documentVersionId },- data: {- file: data,- type: "pdf",- storageType: storageType,- },- });-- await convertPdfToImageRoute.trigger(- {- documentId: payload.documentId,- documentVersionId: payload.documentVersionId,- teamId: payload.teamId,- },- {- idempotencyKey: `${payload.teamId}-${payload.documentVersionId}`,- tags: [- `team_${payload.teamId}`,- `document_${payload.documentId}`,- `version:${payload.documentVersionId}`,- ],- },- );-- logger.info("Keynote document converted", {- documentId: payload.documentId,- documentVersionId: payload.documentVersionId,- teamId: payload.teamId,- docId: docId,- });- return;- },-});diff --git a/lib/types/document-preview.ts b/lib/types/document-preview.tsindex 986df9df..6ea78a63 100644--- a/lib/types/document-preview.ts+++ b/lib/types/document-preview.ts@@ -1,3 +1,5 @@+import type { PageLink } from "./page-link";+export interface DocumentPreviewData {documentId: string;documentName: string;@@ -10,12 +12,7 @@ export interface DocumentPreviewData {file: string | null;pageNumber: string;embeddedLinks: string[];- pageLinks: {- href: string;- coords: string;- isInternal?: boolean;- targetPage?: number;- }[];+ pageLinks: PageLink[];metadata: { width: number; height: number; scaleFactor: number };}[];file?: string;diff --git a/lib/types/page-link.ts b/lib/types/page-link.tsnew file mode 100644index 00000000..6aea8dab--- /dev/null+++ b/lib/types/page-link.ts@@ -0,0 +1,86 @@+import type { DocumentStorageType } from "@prisma/client";++/**+ * The kinds of entries a rendered page's `pageLinks` JSON can hold.+ *+ * - "link" — a regular hyperlink rectangle (clickable area). This is the+ * implicit default and is **not** stored on the entry — every+ * shape that lacks an explicit `kind` is treated as a link.+ * - "gif" — an animated GIF rendered as `<img>` on top of the static+ * page image.+ * - "video" — an embedded video rendered as `<video>` on top of the+ * static page image.+ *+ * Coordinates are always stored in **PDF user-space points** with the+ * top-left origin (matching what `mupdf`'s `link.getBounds()` returns and+ * what the existing `scaleCoordinates()` helper expects). The viewer+ * multiplies them by the per-page display scale-factor to get CSS pixels.+ *+ * For PowerPoint embeds, EMU coordinates from `<a:xfrm>` map to points via+ * `pt = emu / 12700` (1 inch = 914 400 EMU = 72 pt). LibreOffice preserves+ * slide dimensions in the generated PDF, so the same conversion lands the+ * overlay in the same place mupdf reports for hyperlinks on the same page.+ */+export type PageLinkKind = "link" | "gif" | "video";++/** Reference to a file living in our own storage (S3 / Vercel Blob). */+export interface StoredFileRef {+ storageType: DocumentStorageType;+ data: string;+}++/**+ * A regular hyperlink rectangle — the default `pageLinks` entry written+ * by `convert-page.ts`. There is no `kind` field on the wire; absence of+ * the discriminator means "link" so existing rows stay unchanged.+ */+export interface RegularPageLink {+ href: string;+ coords: string;+ isInternal?: boolean;+ targetPage?: number;+}++/**+ * A media overlay (gif or video) extracted from the source presentation.+ *+ * - `src` — internal storage reference (preferred). The server signs a+ * time-limited URL just before sending the page to the viewer.+ * - `poster`— optional internal storage reference for a still poster+ * frame (videos only).+ * - `href` — direct, public URL fallback (legacy convention where users+ * added a hyperlink in PowerPoint pointing to a hosted .gif).+ * - `posterUrl` — populated on the wire by the server after signing.+ * - `naturalWidth/Height` — pixels of the source media; used by the viewer+ * only for object-fit hints.+ */+export interface MediaPageLink {+ kind: "gif" | "video";+ coords: string;+ src?: StoredFileRef;+ poster?: StoredFileRef;+ href?: string;+ posterUrl?: string;+ naturalWidth?: number;+ naturalHeight?: number;+}++export type PageLink = RegularPageLink | MediaPageLink;++/**+ * Returns the resolved kind of a page-link entry. Falls back to `"link"`+ * when no discriminator is present (the standard case for hyperlink+ * rectangles) and to `"gif"` for the legacy convention of users adding+ * hyperlinks pointing at hosted `.gif` URLs.+ */+export function resolvePageLinkKind(link: PageLink): PageLinkKind {+ if ("kind" in link && link.kind) return link.kind;+ if (+ "href" in link &&+ typeof link.href === "string" &&+ link.href.endsWith(".gif")+ ) {+ return "gif";+ }+ return "link";+}diff --git a/package-lock.json b/package-lock.jsonindex b6c01006..479d4209 100644--- a/package-lock.json+++ b/package-lock.json@@ -69,9 +69,9 @@"@tiptap/react": "^3.22.5","@tiptap/starter-kit": "^3.22.5","@tremor/react": "^3.18.7",- "@trigger.dev/python": "4.5.5",- "@trigger.dev/react-hooks": "4.5.5",- "@trigger.dev/sdk": "4.5.5",+ "@trigger.dev/python": "4.5.6",+ "@trigger.dev/react-hooks": "4.5.6",+ "@trigger.dev/sdk": "4.5.6","@tus/s3-store": "^1.9.1","@tus/server": "^1.10.2","@tus/utils": "^0.5.1",@@ -99,12 +99,14 @@"eslint": "8.57.0","eslint-config-next": "^14.2.35","exceljs": "^4.4.0",+ "fast-xml-parser": "^5.8.0","fluent-ffmpeg": "^2.1.3","html2canvas": "^1.4.1","i18next": "^26.3.0","input-otp": "^1.4.2","js-cookie": "^3.0.7","jsonwebtoken": "^9.0.3",+ "jszip": "^3.10.1","lucide-react": "^1.16.0","mime-types": "^3.0.2","motion": "^12.40.0",@@ -167,7 +169,7 @@"devDependencies": {"@react-email/ui": "^6.3.2","@tailwindcss/forms": "^0.5.11",- "@trigger.dev/build": "4.5.5",+ "@trigger.dev/build": "4.5.6","@trivago/prettier-plugin-sort-imports": "^6.0.2","@types/bcryptjs": "^2.4.6","@types/cookie": "^0.6.0",@@ -2722,6 +2724,27 @@"node": ">=20.0.0"}},+ "node_modules/@aws-sdk/xml-builder/node_modules/fast-xml-parser": {+ "version": "5.7.2",+ "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.7.2.tgz",+ "integrity": "sha512-P7oW7tLbYnhOLQk/Gv7cZgzgMPP/XN03K02/Jy6Y/NHzyIAIpxuZIM/YqAkfiXFPxA2CTm7NtCijK9EDu09u2w==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "@nodable/entities": "^2.1.0",+ "fast-xml-builder": "^1.1.5",+ "path-expression-matcher": "^1.5.0",+ "strnum": "^2.2.3"+ },+ "bin": {+ "fxparser": "src/cli/cli.js"+ }+ },"node_modules/@aws/lambda-invoke-store": {"version": "0.2.4","license": "Apache-2.0",@@ -9232,13 +9255,13 @@}},"node_modules/@trigger.dev/build": {- "version": "4.5.5",- "resolved": "https://registry.npmjs.org/@trigger.dev/build/-/build-4.5.5.tgz",- "integrity": "sha512-OHEAUyStIxO77fC4o9p31pEg7PxNOZx5VVgIvlzy+YDdj26Qx1zY7A9OCCHT2LFquInZmMvIxvrmaVsx+lR0VA==",+ "version": "4.5.6",+ "resolved": "https://registry.npmjs.org/@trigger.dev/build/-/build-4.5.6.tgz",+ "integrity": "sha512-KV4AaOY43bN9cBhFgIhLXH6cBx+tpBlfi7VwJX79tVhDB4Ro9uvWlIO9/2av9TfSLKVLC2UEwYdpgyKUAXieIA==","license": "MIT","dependencies": {"@prisma/config": "^6.10.0",- "@trigger.dev/core": "4.5.5",+ "@trigger.dev/core": "4.5.6","mlly": "^1.7.1","pkg-types": "^1.1.3","resolve": "^1.22.8",@@ -9250,9 +9273,9 @@}},"node_modules/@trigger.dev/core": {- "version": "4.5.5",- "resolved": "https://registry.npmjs.org/@trigger.dev/core/-/core-4.5.5.tgz",- "integrity": "sha512-LKShPW6b049PRJ03ZOWuWXQ7d6gIS+LTrni6W3V87AXJEkp9+qwsboe2oelmQk8uHVk8QYk6CLItENkrofhvag==",+ "version": "4.5.6",+ "resolved": "https://registry.npmjs.org/@trigger.dev/core/-/core-4.5.6.tgz",+ "integrity": "sha512-G4moEUr3UeQ44AcbEoW8picaWBO+akw89u4fNDfIqXlR3LVCVgrDx2BGdCeopMSKuNVKfdCtmfZf8LphK8gIvg==","license": "MIT","dependencies": {"@bugsnag/cuid": "^3.1.1",@@ -9490,29 +9513,29 @@}},"node_modules/@trigger.dev/python": {- "version": "4.5.5",- "resolved": "https://registry.npmjs.org/@trigger.dev/python/-/python-4.5.5.tgz",- "integrity": "sha512-iMK26IPOi9n99Z7bdFk/67H1uhQG69cRi1LBjbTzeaMIq9uxvj0Zt0SNBh2TO3/d1pg0ogQgm5qSJrYwfnb/7w==",+ "version": "4.5.6",+ "resolved": "https://registry.npmjs.org/@trigger.dev/python/-/python-4.5.6.tgz",+ "integrity": "sha512-qnvQh55wLsAJLeROmkmLxngte13JqEreygVZlTjBNQ2j1DOAs6TkDhHNfpw1MSM+Lazvql+9X1NpkjBFkvtcfw==","license": "MIT","dependencies": {- "@trigger.dev/core": "4.5.5",+ "@trigger.dev/core": "4.5.6","tinyexec": "^0.3.2"},"engines": {"node": ">=18.20.0"},"peerDependencies": {- "@trigger.dev/build": "^4.5.5",- "@trigger.dev/sdk": "^4.5.5"+ "@trigger.dev/build": "^4.5.6",+ "@trigger.dev/sdk": "^4.5.6"}},"node_modules/@trigger.dev/react-hooks": {- "version": "4.5.5",- "resolved": "https://registry.npmjs.org/@trigger.dev/react-hooks/-/react-hooks-4.5.5.tgz",- "integrity": "sha512-hEXzILWQrOxUamTqjQWLU1xYTi96+Nx6hwI25MVGE2eFuODo3ykQdSjQEM05AfkfHI1ktH5Q07ZksE3xfeorWQ==",+ "version": "4.5.6",+ "resolved": "https://registry.npmjs.org/@trigger.dev/react-hooks/-/react-hooks-4.5.6.tgz",+ "integrity": "sha512-VaAMd6jRFOH2J3EbqY8yFBP8JIgVKJkIK7R3bC+RAGGqwHJNTQplQxpuNI1tecOicZDV6/ozo6psh4QsY0wVmQ==","license": "MIT","dependencies": {- "@trigger.dev/core": "^4.5.5",+ "@trigger.dev/core": "^4.5.6","swr": "^2.2.5"},"engines": {@@ -9524,14 +9547,14 @@}},"node_modules/@trigger.dev/sdk": {- "version": "4.5.5",- "resolved": "https://registry.npmjs.org/@trigger.dev/sdk/-/sdk-4.5.5.tgz",- "integrity": "sha512-4aJDjJe+l3rxOqSUlLAjQB9aCyuGd0ABH8ASxfLXZeU65pJ0pVh51NJTaAH5NdYitBbFnLjm/dSZN79u+Z0y2w==",+ "version": "4.5.6",+ "resolved": "https://registry.npmjs.org/@trigger.dev/sdk/-/sdk-4.5.6.tgz",+ "integrity": "sha512-RktMdYsJkZgOZaemhWax6i0sCiDAUNPOMej41DZlC73NISBFkRNutIL91ngt0TjD733Xe+a+wKD7Ei+u8uvsVA==","license": "MIT","dependencies": {"@opentelemetry/api": "1.9.1","@opentelemetry/semantic-conventions": "1.41.1",- "@trigger.dev/core": "4.5.5",+ "@trigger.dev/core": "4.5.6","chalk": "^5.2.0","cronstrue": "^2.21.0","debug": "^4.3.4",@@ -11023,6 +11046,18 @@"node": ">= 8"}},+ "node_modules/anynum": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/anynum/-/anynum-1.0.1.tgz",+ "integrity": "sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT"+ },"node_modules/app-root-path": {"version": "3.1.0","license": "MIT",@@ -14980,9 +15015,9 @@}},"node_modules/fast-xml-parser": {- "version": "5.7.2",- "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.7.2.tgz",- "integrity": "sha512-P7oW7tLbYnhOLQk/Gv7cZgzgMPP/XN03K02/Jy6Y/NHzyIAIpxuZIM/YqAkfiXFPxA2CTm7NtCijK9EDu09u2w==",+ "version": "5.10.1",+ "resolved": "https://registry.npmjs.org/fast-xml-parser/-/fast-xml-parser-5.10.1.tgz",+ "integrity": "sha512-IEMIf7298kXuZSRFoGfMYrl7is8LpavODgbNz1cwIudv7KwVFnuU+UsMporfq6PD6aXSlawZlARiA3UywCTfMw==","funding": [{"type": "github",@@ -14991,15 +15026,45 @@],"license": "MIT","dependencies": {- "@nodable/entities": "^2.1.0",- "fast-xml-builder": "^1.1.5",- "path-expression-matcher": "^1.5.0",- "strnum": "^2.2.3"+ "@nodable/entities": "^3.0.0",+ "fast-xml-builder": "^1.2.0",+ "is-unsafe": "^2.0.0",+ "path-expression-matcher": "^1.6.2",+ "strnum": "^2.4.1",+ "xml-naming": "^0.3.0"},"bin": {"fxparser": "src/cli/cli.js"}},+ "node_modules/fast-xml-parser/node_modules/@nodable/entities": {+ "version": "3.0.0",+ "resolved": "https://registry.npmjs.org/@nodable/entities/-/entities-3.0.0.tgz",+ "integrity": "sha512-8L9xFeTYKhm49xfIypoe2W5wV1m/3Z58kT+7kR9A8OyFxcPduI4VmxaUMQyKYrRjUoLLSXv6EKKID5Tvj9cUVw==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/nodable"+ }+ ],+ "license": "MIT"+ },+ "node_modules/fast-xml-parser/node_modules/fast-xml-builder": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/fast-xml-builder/-/fast-xml-builder-1.3.0.tgz",+ "integrity": "sha512-F74cZEdCvuw9P41GAC3rod4X04jjWGM1JPEv/GWSqFTWLsdyMSBMBMlm9Hk3GLBgLBbdBNY8yee0pQh2RBVESQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "path-expression-matcher": "^1.6.2",+ "xml-naming": "^0.3.0"+ }+ },"node_modules/fastq": {"version": "1.20.1","license": "ISC",@@ -16287,9 +16352,9 @@}},"node_modules/import-in-the-middle": {- "version": "3.3.1",- "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-3.3.1.tgz",- "integrity": "sha512-0rymlHSFLwZ0ixx8DaQkoIyZojJPY2a0K2nEYslhKJ6jIYO/m0IcCb7iQsFPmS7WmKwISZiIrv5Icstrw/CmqA==",+ "version": "3.3.2",+ "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-3.3.2.tgz",+ "integrity": "sha512-jTd2FfOgOWOdgjkHuk/1Ms8VKFXkPs15ymYBETw1sAOrO/dY3XeGVRWir9qBbw7pXr0T2eTFwfCZ+N02HmiNGA==","license": "Apache-2.0","dependencies": {"cjs-module-lexer": "^2.2.0",@@ -16882,6 +16947,18 @@"url": "https://github.com/sponsors/sindresorhus"}},+ "node_modules/is-unsafe": {+ "version": "2.0.0",+ "resolved": "https://registry.npmjs.org/is-unsafe/-/is-unsafe-2.0.0.tgz",+ "integrity": "sha512-2LdV822R+wmI86unXA93WCFpL6g+av8ynWk0nrHyJqGop5VoocYsSLFgN8jrfalT6iGeLNM4KXuVSsULP53kEA==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT"+ },"node_modules/is-url-superb": {"version": "6.1.0","license": "MIT",@@ -19934,9 +20011,9 @@}},"node_modules/path-expression-matcher": {- "version": "1.5.0",- "resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.5.0.tgz",- "integrity": "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ==",+ "version": "1.6.2",+ "resolved": "https://registry.npmjs.org/path-expression-matcher/-/path-expression-matcher-1.6.2.tgz",+ "integrity": "sha512-enSlaiat05iasnzmgNxRj8reFdj3puY2QpNgP1aPIaVfT6nn9ICuPoFlKHk8EN22HcwewshO+mN2DGbkCEOtqQ==","funding": [{"type": "github",@@ -23423,16 +23500,19 @@}},"node_modules/strnum": {- "version": "2.3.0",- "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.3.0.tgz",- "integrity": "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q==",+ "version": "2.4.1",+ "resolved": "https://registry.npmjs.org/strnum/-/strnum-2.4.1.tgz",+ "integrity": "sha512-M9eUSMT2dCB2cTNPG7UYj6KuK7RJR2SN2+yCV/fTW3xzTCS6EaGZ5pSMgDIjB7r8zSfTGk+dvvn9rTjpVS9Mwg==","funding": [{"type": "github","url": "https://github.com/sponsors/NaturalIntelligence"}],- "license": "MIT"+ "license": "MIT",+ "dependencies": {+ "anynum": "^1.0.1"+ }},"node_modules/stubborn-fs": {"version": "2.0.0",@@ -25301,6 +25381,21 @@"node": ">=0.6.0"}},+ "node_modules/xml-naming": {+ "version": "0.3.0",+ "resolved": "https://registry.npmjs.org/xml-naming/-/xml-naming-0.3.0.tgz",+ "integrity": "sha512-ghig2TBE/H11aOVgmahA3MhimvkBr6JIYknH/Dhdk10nXwdbIqBJsbfMxpvFPG8bAw77gN29aQWvKpmVoPlvPQ==",+ "funding": [+ {+ "type": "github",+ "url": "https://github.com/sponsors/NaturalIntelligence"+ }+ ],+ "license": "MIT",+ "engines": {+ "node": ">=16.0.0"+ }+ },"node_modules/xml2js": {"version": "0.6.2","license": "MIT",diff --git a/package.json b/package.jsonindex 65289e33..6326574c 100644--- a/package.json+++ b/package.json@@ -81,9 +81,9 @@"@tiptap/react": "^3.22.5","@tiptap/starter-kit": "^3.22.5","@tremor/react": "^3.18.7",- "@trigger.dev/python": "4.5.5",- "@trigger.dev/react-hooks": "4.5.5",- "@trigger.dev/sdk": "4.5.5",+ "@trigger.dev/python": "4.5.6",+ "@trigger.dev/react-hooks": "4.5.6",+ "@trigger.dev/sdk": "4.5.6","@tus/s3-store": "^1.9.1","@tus/server": "^1.10.2","@tus/utils": "^0.5.1",@@ -111,12 +111,14 @@"eslint": "8.57.0","eslint-config-next": "^14.2.35","exceljs": "^4.4.0",+ "fast-xml-parser": "^5.8.0","fluent-ffmpeg": "^2.1.3","html2canvas": "^1.4.1","i18next": "^26.3.0","input-otp": "^1.4.2","js-cookie": "^3.0.7","jsonwebtoken": "^9.0.3",+ "jszip": "^3.10.1","lucide-react": "^1.16.0","mime-types": "^3.0.2","motion": "^12.40.0",@@ -179,7 +181,7 @@"devDependencies": {"@react-email/ui": "^6.3.2","@tailwindcss/forms": "^0.5.11",- "@trigger.dev/build": "4.5.5",+ "@trigger.dev/build": "4.5.6","@trivago/prettier-plugin-sort-imports": "^6.0.2","@types/bcryptjs": "^2.4.6","@types/cookie": "^0.6.0",diff --git a/pages/api/teams/[teamId]/documents/[id]/preview-data.ts b/pages/api/teams/[teamId]/documents/[id]/preview-data.tsindex f40826d5..922ab8cb 100644--- a/pages/api/teams/[teamId]/documents/[id]/preview-data.ts+++ b/pages/api/teams/[teamId]/documents/[id]/preview-data.ts@@ -6,6 +6,7 @@ import { getTeamStorageConfigById } from "@/ee/features/storage/config";import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";import { getFile } from "@/lib/files/get-file";+import { signPageLinks } from "@/lib/files/sign-page-links";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";import { log } from "@/lib/utils";@@ -125,12 +126,16 @@ export default async function handle(returnData.pages = await Promise.all(primaryVersion.pages.map(async (page, index) => {const { storageType, ...otherPageData } = page;+ const inWindow = index < INITIAL_PAGES_TO_LOAD;return {...otherPageData,- file:- index < INITIAL_PAGES_TO_LOAD- ? await getFile({ data: page.file, type: storageType })- : null,+ file: inWindow+ ? await getFile({ data: page.file, type: storageType })+ : null,+ pageLinks: inWindow+ ? (await signPageLinks(otherPageData.pageLinks)) ??+ otherPageData.pageLinks+ : otherPageData.pageLinks,};}),);diff --git a/pages/api/teams/[teamId]/documents/[id]/preview-pages.ts b/pages/api/teams/[teamId]/documents/[id]/preview-pages.tsindex 6b648343..8d752855 100644--- a/pages/api/teams/[teamId]/documents/[id]/preview-pages.ts+++ b/pages/api/teams/[teamId]/documents/[id]/preview-pages.ts@@ -4,6 +4,7 @@ import { getServerSession } from "next-auth/next";import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";import { getFile } from "@/lib/files/get-file";+import { signPageLinks } from "@/lib/files/sign-page-links";import prisma from "@/lib/prisma";import { CustomUser } from "@/lib/types";import { log } from "@/lib/utils";@@ -95,15 +96,18 @@ export default async function handle(file: true,storageType: true,pageNumber: true,+ pageLinks: true,},});const pagesWithUrls = await Promise.all(documentPages.map(async (page) => {- const { storageType, ...otherPage } = page;+ const { storageType, pageLinks } = page;+ const signedLinks = await signPageLinks(pageLinks);return {- pageNumber: otherPage.pageNumber,+ pageNumber: page.pageNumber,file: await getFile({ data: page.file, type: storageType }),+ ...(signedLinks ? { pageLinks: signedLinks } : {}),};}),);diff --git a/pages/api/teams/[teamId]/documents/[id]/versions/index.ts b/pages/api/teams/[teamId]/documents/[id]/versions/index.tsindex b06d5bc0..bd8b1444 100644--- a/pages/api/teams/[teamId]/documents/[id]/versions/index.ts+++ b/pages/api/teams/[teamId]/documents/[id]/versions/index.ts@@ -1,5 +1,7 @@import { NextApiRequest, NextApiResponse } from "next";+import { tasks } from "@trigger.dev/sdk";+import { isTeamPausedById } from "@/ee/features/billing/cancellation/lib/is-team-paused";import { authOptions } from "@/pages/api/auth/[...nextauth]";import { getServerSession } from "next-auth/next";@@ -8,7 +10,8 @@ import { hashToken } from "@/lib/api/auth/token";import { enforceDocumentMemberScope } from "@/lib/api/rbac/guard";import { copyFileToBucketServer } from "@/lib/files/copy-file-to-bucket-server";import prisma from "@/lib/prisma";-import { convertFilesToPdfTask } from "@/lib/trigger/convert-files";++import type { convertFilesToPdfTask } from "@/ee/features/conversions/lib/trigger/convert-files";import { processVideo } from "@/lib/trigger/optimize-video-files";import { convertPdfToImageRoute } from "@/lib/trigger/pdf-to-image-route";import { CustomUser } from "@/lib/types";@@ -173,7 +176,8 @@ export default async function handle(!isDownloadOnlyByExtension &&!isMarkdown) {- await convertFilesToPdfTask.trigger(+ await tasks.trigger<typeof convertFilesToPdfTask>(+ "convert-files-to-pdf",{documentVersionId: version.id,teamId,diff --git a/pages/api/teams/[teamId]/documents/agreement.ts b/pages/api/teams/[teamId]/documents/agreement.tsindex 500c9078..1edfb624 100644--- a/pages/api/teams/[teamId]/documents/agreement.ts+++ b/pages/api/teams/[teamId]/documents/agreement.ts@@ -1,10 +1,12 @@import { NextApiRequest, NextApiResponse } from "next";+import { tasks } from "@trigger.dev/sdk";+import { getServerSession } from "next-auth/next";import { errorhandler } from "@/lib/errorHandler";import prisma from "@/lib/prisma";-import { convertFilesToPdfTask } from "@/lib/trigger/convert-files";+import type { convertFilesToPdfTask } from "@/ee/features/conversions/lib/trigger/convert-files";import { convertPdfToImageRoute } from "@/lib/trigger/pdf-to-image-route";import { CustomUser } from "@/lib/types";import { getExtension, log, serializeFileSize } from "@/lib/utils";@@ -134,7 +136,8 @@ export default async function handle(/\.(log|err|prj|jgw|tif|tiff|ecw|bak)$/i.test(name);if (type === "docs" && !isDownloadOnlyByExtension) {- await convertFilesToPdfTask.trigger(+ await tasks.trigger<typeof convertFilesToPdfTask>(+ "convert-files-to-pdf",{documentId: document.id,documentVersionId: document.versions[0].id,