diff --git a/.gitignore b/.gitignore index c2e19a5b..dd586ac7 100644 --- a/.gitignore +++ b/.gitignore @@ -50,4 +50,7 @@ yarn-error.log* .idea # codex -.codex \ No newline at end of file +.codex + +# PDF.js assets copied from the installed dependency during dev/build +/public/pdfjs/ diff --git a/package.json b/package.json index 0aeb6177..33a3266e 100644 --- a/package.json +++ b/package.json @@ -5,8 +5,8 @@ "type": "module", "scripts": { "preinstall": "npx -y only-allow pnpm", - "build": "cross-env SKIP_ENV_VALIDATION=true next build", - "dev": "cross-env PORT=3002 next dev", + "build": "node scripts/copy-pdf-assets.mjs && cross-env SKIP_ENV_VALIDATION=true next build", + "dev": "node scripts/copy-pdf-assets.mjs && cross-env PORT=3002 next dev", "preview": "pnpm build && pnpm start", "start": "node .next/standalone/server.js", "typecheck": "tsc --noEmit", @@ -17,7 +17,7 @@ }, "dependencies": { "@polinetwork/auth-kit": "^1.1.0", - "@polinetwork/backend": "^4.0.0", + "@polinetwork/backend": "^9.3.0", "@radix-ui/react-accordion": "^1.2.12", "@radix-ui/react-select": "^2.2.6", "@radix-ui/react-separator": "^1.1.8", @@ -40,6 +40,7 @@ "react-dom": "19.3.0", "react-hook-form": "^7.68.0", "react-icons": "^5.6.0", + "react-pdf": "^11.0.0", "superjson": "^2.2.6", "tailwind-merge": "^3.4.0", "tailwindcss-animate": "^1.0.7", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 94f4f76b..c98582b1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -12,8 +12,8 @@ importers: specifier: ^1.1.0 version: 1.1.0 '@polinetwork/backend': - specifier: ^4.0.0 - version: 4.0.0 + specifier: ^9.3.0 + version: 9.3.0 '@radix-ui/react-accordion': specifier: ^1.2.12 version: 1.2.12(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) @@ -80,6 +80,9 @@ importers: react-icons: specifier: ^5.6.0 version: 5.6.0(react@19.3.0) + react-pdf: + specifier: ^11.0.0 + version: 11.0.0(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) superjson: specifier: ^2.2.6 version: 2.2.6 @@ -401,6 +404,81 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@napi-rs/canvas-android-arm64@1.1.0': + resolution: {integrity: sha512-mKrSmRyhWK4q699Q1xthbZIZi7JBvLtsRNnOZAeFaLPOFT1yo8y82aRC2nNZbXTGJXU7fVDONgGQPr0vo3kerw==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [android] + + '@napi-rs/canvas-darwin-arm64@1.1.0': + resolution: {integrity: sha512-iqwST4g0oH+x8VCpBIYh+MYokv/mVvkM+v9oJGB0d9A3P2qBh42ogJlVyWq9SpPCrAjS7tplMb1D3OIfxl+utw==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [darwin] + + '@napi-rs/canvas-darwin-x64@1.1.0': + resolution: {integrity: sha512-jkeA8eVTxDum03LTvc32YJ28F6KB1U0gYwnWMfOAUQZvWWEh/kvONby4iWGJx3+Tw45UqMGMXjtw2GKNVZDhVg==} + engines: {node: '>= 10'} + cpu: [x64] + os: [darwin] + + '@napi-rs/canvas-linux-arm-gnueabihf@1.1.0': + resolution: {integrity: sha512-Y4YkKG1ijoqkgUdTEEBNG4k+2BK5bR5jGL6S56YxCXYPwGfUd5nED8/74xyc7z+bpixPasCjSYoP3xYPOIGNxw==} + engines: {node: '>= 10'} + cpu: [arm] + os: [linux] + + '@napi-rs/canvas-linux-arm64-gnu@1.1.0': + resolution: {integrity: sha512-dE/XthqYkiWcBVtKFlZbUXwAYfDuQGqDWixznipJNmevLGpprNnTVQZyftm1RZJudkIOn2EkzYZDMMETM08Row==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@napi-rs/canvas-linux-arm64-musl@1.1.0': + resolution: {integrity: sha512-DqZ/CMcHlhU56pPjv9AP0h3U7MFQ5LzC1HzMyRMotL+PFsJmZJA/ziApPYVyyz78DaVLhI8t3So3ztqtijbYpg==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@napi-rs/canvas-linux-riscv64-gnu@1.1.0': + resolution: {integrity: sha512-kJ7m5n2VffxWXM5QGa5lfq8ZN4LdOJEoz3aAJAmIqYvKiZw1gRdXqpucnRXsF6D9nLYiiIlevaAtAclR7c5ilg==} + engines: {node: '>= 10'} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@napi-rs/canvas-linux-x64-gnu@1.1.0': + resolution: {integrity: sha512-uQ9JuJlRhQdHyttcMWOiwLkfIqkqaB0YFUVe835LUe12THt2b51HXkTItq0fxWT1jdhUPX2ylWZ1walkJyD6GQ==} + engines: {node: '>= 10'} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@napi-rs/canvas-linux-x64-musl@1.1.0': + resolution: {integrity: sha512-has4CPPAkkCac/LZ13VAw5p+MJLdaKVoyrhumN/A7uJd6960xYkJNDZgUebyxiha82AFzXx6RV+QJg5qGG079g==} + engines: {node: '>= 10'} + cpu: [x64] + os: [linux] + libc: [musl] + + '@napi-rs/canvas-win32-arm64-msvc@1.1.0': + resolution: {integrity: sha512-MJnktLKNijmXqdjTughHDZ9TDLZ9uUm2hvFXqaOqn0+w7lphXFnft6bpSgQAc9U1exc20UGIBlzGu9+kiCj9Ag==} + engines: {node: '>= 10'} + cpu: [arm64] + os: [win32] + + '@napi-rs/canvas-win32-x64-msvc@1.1.0': + resolution: {integrity: sha512-08575bFk7iiadxap4h+JxgGut9xDCHAGum6wh0eInN53zEMImkmEHi5MushX2FOmNO7qRNX7BPiDC5ZYBwHeEg==} + engines: {node: '>= 10'} + cpu: [x64] + os: [win32] + + '@napi-rs/canvas@1.1.0': + resolution: {integrity: sha512-k+ph/D8H9GS8ZZ48okvHrKeJynkqAA1kMUZRuzRWNlQUDHXngq7oRaWMZBdmSfd9ZhVy9bwNKei/7wMboI/uMg==} + engines: {node: '>= 10'} + '@next/env@16.4.1': resolution: {integrity: sha512-5sUUrrSvs/2/2LnLoesybMGx12EtPB46fdZ6RhAw0XDGSPxU2LFyQBB7yuEiOFFJPKmBY6+q2jTr1/AMbnp0/g==} @@ -460,8 +538,8 @@ packages: resolution: {integrity: sha512-SAf/cVSF4wW7UqP3EP/3IFPAJgYTL9po9qOXcJ9OvbRPCi9X4bmMTDDHYzuPCKMAQkHybuPbI6tzcKFBekw0Ag==} engines: {node: '>=20.19'} - '@polinetwork/backend@4.0.0': - resolution: {integrity: sha512-hKvjzwMMm8qZJojEhIGOA9sHg29xlw2Tu/XH2Wlq9xdkyucEFHp5QNLzGWccjzjHd8fja4qF20OQJppaFrEVtA==} + '@polinetwork/backend@9.3.0': + resolution: {integrity: sha512-07NF/p0w/5JgIWbPDD8Gvv9lzFdrBN0h4IizcLfLK0DZDjeMBw1aSHiyyQ2QzOW732rmSj7E3l8jPBumJPmZqw==} '@radix-ui/number@1.1.1': resolution: {integrity: sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==} @@ -1559,6 +1637,10 @@ packages: csstype@3.2.3: resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + dequal@2.0.3: + resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} + engines: {node: '>=6'} + detect-libc@2.1.2: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} @@ -1583,6 +1665,9 @@ packages: resolution: {integrity: sha512-LgQMM4WXU3QI+SYgEc2liRgznaD5ojbmY3sb8LxyguVkIg5FxdpTkvk72te2R38/TGKxH634oLxXRGY6d7AP+Q==} engines: {node: '>=10.13.0'} + es-toolkit@1.53.1: + resolution: {integrity: sha512-VhMc6IXmexu8iYFfL2aaAww6IvJTdHlqBLruLoEUs33YD4IcP5DdZcLOybMsMmmLsiy1c8PsiLsrM0DdIuuRUA==} + geist@1.5.1: resolution: {integrity: sha512-mAHZxIsL2o3ZITFaBVFBnwyDOw+zNLYum6A6nIjpzCGIO8QtC3V76XF2RnZTyLx1wlDTmMDy8jg3Ib52MIjGvQ==} peerDependencies: @@ -1609,6 +1694,9 @@ packages: jose@6.2.12: resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==} + js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + lightningcss-android-arm64@1.30.2: resolution: {integrity: sha512-BH9sEdOCahSgmkVhBLeU7Hc9DWeZ1Eb6wNS6Da8igvUwAe0sqROHddIlvU06q3WyXVEOYDZ6ykBZQnjTbmo4+A==} engines: {node: '>= 12.0.0'} @@ -1683,9 +1771,27 @@ packages: resolution: {integrity: sha512-utfs7Pr5uJyyvDETitgsaqSyjCb2qNRAtuqUeWIAKztsOYdcACf2KtARYXg2pSvhkt+9NfoaNY7fxjl6nuMjIQ==} engines: {node: '>= 12.0.0'} + loose-envify@1.4.0: + resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==} + hasBin: true + magic-string@0.30.21: resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + make-cancellable-promise@2.0.0: + resolution: {integrity: sha512-3SEQqTpV9oqVsIWqAcmDuaNeo7yBO3tqPtqGRcKkEo0lrzD3wqbKG9mkxO65KoOgXqj+zH2phJ2LiAsdzlogSw==} + + make-event-props@2.0.0: + resolution: {integrity: sha512-G/hncXrl4Qt7mauJEXSg3AcdYzmpkIITTNl5I+rH9sog5Yw0kK6vseJjCaPfOXqOqQuPUP89Rkhfz5kPS8ijtw==} + + merge-refs@2.0.0: + resolution: {integrity: sha512-3+B21mYK2IqUWnd2EivABLT7ueDhb0b8/dGK8LoFQPrU61YITeCMn14F7y7qZafWNZhUEKb24cJdiT5Wxs3prg==} + peerDependencies: + '@types/react': ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + nanoid@3.3.18: resolution: {integrity: sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -1722,6 +1828,10 @@ packages: resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} engines: {node: '>=8'} + pdfjs-dist@6.3.289: + resolution: {integrity: sha512-ZHjSVpDa3D6izMq8/04lvkhkATUmL9px6ChPaXc1k6nU2Mrhlg1/7F0bdUqCwUjw3NsPTfPZsMDUU6ZIcRaeQw==} + engines: {node: '>=22.13.0 || >=24'} + picocolors@1.1.1: resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} @@ -1758,6 +1868,16 @@ packages: peerDependencies: react: '*' + react-pdf@11.0.0: + resolution: {integrity: sha512-x4Ierg3Sl+gOoqd0pVOQndiuFKeGcXQmUNtaSH0D/cs2nUW1HBDlFBT2Z8jDsDJv0Kh//jlOJT21ERyQtlRe7A==} + peerDependencies: + '@types/react': ^19.0.0 + react: ^19.0.0 + react-dom: ^19.0.0 + peerDependenciesMeta: + '@types/react': + optional: true + react-remove-scroll-bar@2.3.8: resolution: {integrity: sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q==} engines: {node: '>=10'} @@ -1853,6 +1973,9 @@ packages: resolution: {integrity: sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg==} engines: {node: '>=6'} + tiny-invariant@1.3.3: + resolution: {integrity: sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg==} + tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} @@ -1892,6 +2015,9 @@ packages: peerDependencies: react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 + warning@4.0.3: + resolution: {integrity: sha512-rpJyN222KWIvHJ/F53XSZv0Zl/accqHR8et1kpaMTD/fLCRxtV8iX8czMzY7sVZupTI3zcUTg8eycS2kNF9l6w==} + which@2.0.2: resolution: {integrity: sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==} engines: {node: '>= 8'} @@ -2101,6 +2227,54 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 + '@napi-rs/canvas-android-arm64@1.1.0': + optional: true + + '@napi-rs/canvas-darwin-arm64@1.1.0': + optional: true + + '@napi-rs/canvas-darwin-x64@1.1.0': + optional: true + + '@napi-rs/canvas-linux-arm-gnueabihf@1.1.0': + optional: true + + '@napi-rs/canvas-linux-arm64-gnu@1.1.0': + optional: true + + '@napi-rs/canvas-linux-arm64-musl@1.1.0': + optional: true + + '@napi-rs/canvas-linux-riscv64-gnu@1.1.0': + optional: true + + '@napi-rs/canvas-linux-x64-gnu@1.1.0': + optional: true + + '@napi-rs/canvas-linux-x64-musl@1.1.0': + optional: true + + '@napi-rs/canvas-win32-arm64-msvc@1.1.0': + optional: true + + '@napi-rs/canvas-win32-x64-msvc@1.1.0': + optional: true + + '@napi-rs/canvas@1.1.0': + optionalDependencies: + '@napi-rs/canvas-android-arm64': 1.1.0 + '@napi-rs/canvas-darwin-arm64': 1.1.0 + '@napi-rs/canvas-darwin-x64': 1.1.0 + '@napi-rs/canvas-linux-arm-gnueabihf': 1.1.0 + '@napi-rs/canvas-linux-arm64-gnu': 1.1.0 + '@napi-rs/canvas-linux-arm64-musl': 1.1.0 + '@napi-rs/canvas-linux-riscv64-gnu': 1.1.0 + '@napi-rs/canvas-linux-x64-gnu': 1.1.0 + '@napi-rs/canvas-linux-x64-musl': 1.1.0 + '@napi-rs/canvas-win32-arm64-msvc': 1.1.0 + '@napi-rs/canvas-win32-x64-msvc': 1.1.0 + optional: true + '@next/env@16.4.1': {} '@next/swc-darwin-arm64@16.4.1': @@ -2132,7 +2306,7 @@ snapshots: jose: 6.2.12 zod: 4.2.1 - '@polinetwork/backend@4.0.0': {} + '@polinetwork/backend@9.3.0': {} '@radix-ui/number@1.1.1': {} @@ -3162,6 +3336,8 @@ snapshots: csstype@3.2.3: {} + dequal@2.0.3: {} + detect-libc@2.1.2: {} detect-node-es@1.1.0: {} @@ -3183,6 +3359,8 @@ snapshots: graceful-fs: 4.2.11 tapable: 2.3.0 + es-toolkit@1.53.1: {} + geist@1.5.1(next@16.4.1(@types/node@24.10.4)(babel-plugin-react-compiler@1.0.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)): dependencies: next: 16.4.1(@types/node@24.10.4)(babel-plugin-react-compiler@1.0.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) @@ -3199,6 +3377,8 @@ snapshots: jose@6.2.12: {} + js-tokens@4.0.0: {} + lightningcss-android-arm64@1.30.2: optional: true @@ -3248,10 +3428,22 @@ snapshots: lightningcss-win32-arm64-msvc: 1.30.2 lightningcss-win32-x64-msvc: 1.30.2 + loose-envify@1.4.0: + dependencies: + js-tokens: 4.0.0 + magic-string@0.30.21: dependencies: '@jridgewell/sourcemap-codec': 1.5.5 + make-cancellable-promise@2.0.0: {} + + make-event-props@2.0.0: {} + + merge-refs@2.0.0(@types/react@19.3.0): + optionalDependencies: + '@types/react': 19.3.0 + nanoid@3.3.18: {} next-themes@0.4.6(react-dom@19.3.0(react@19.3.0))(react@19.3.0): @@ -3287,6 +3479,10 @@ snapshots: path-key@3.1.1: {} + pdfjs-dist@6.3.289: + optionalDependencies: + '@napi-rs/canvas': 1.1.0 + picocolors@1.1.1: {} postcss@8.5.23: @@ -3371,6 +3567,22 @@ snapshots: dependencies: react: 19.3.0 + react-pdf@11.0.0(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0): + dependencies: + clsx: 2.1.1 + dequal: 2.0.3 + es-toolkit: 1.53.1 + make-cancellable-promise: 2.0.0 + make-event-props: 2.0.0 + merge-refs: 2.0.0(@types/react@19.3.0) + pdfjs-dist: 6.3.289 + react: 19.3.0 + react-dom: 19.3.0(react@19.3.0) + tiny-invariant: 1.3.3 + warning: 4.0.3 + optionalDependencies: + '@types/react': 19.3.0 + react-remove-scroll-bar@2.3.8(@types/react@19.3.0)(react@19.3.0): dependencies: react: 19.3.0 @@ -3466,6 +3678,8 @@ snapshots: tapable@2.3.0: {} + tiny-invariant@1.3.3: {} + tslib@2.8.1: {} tw-animate-css@1.4.0: {} @@ -3514,6 +3728,10 @@ snapshots: dependencies: react: 19.3.0 + warning@4.0.3: + dependencies: + loose-envify: 1.4.0 + which@2.0.2: dependencies: isexe: 2.0.0 diff --git a/scripts/copy-pdf-assets.mjs b/scripts/copy-pdf-assets.mjs new file mode 100644 index 00000000..63219ccf --- /dev/null +++ b/scripts/copy-pdf-assets.mjs @@ -0,0 +1,14 @@ +import { cp, mkdir } from "node:fs/promises" +import { createRequire } from "node:module" +import { dirname, join } from "node:path" + +// Resolve PDF.js from React-PDF so the renderer and worker always use the same version. +const require = createRequire(import.meta.url) +const reactPdfRequire = createRequire(require.resolve("react-pdf")) +const source = dirname(reactPdfRequire.resolve("pdfjs-dist/package.json")) +const destination = new URL("../public/pdfjs/", import.meta.url) +await mkdir(destination, { recursive: true }) +for (const name of ["cmaps", "standard_fonts", "wasm"]) { + await cp(join(source, name), new URL(name, destination), { recursive: true }) +} +await cp(join(source, "build/pdf.worker.min.mjs"), new URL("pdf.worker.min.mjs", destination)) diff --git a/src/app/documents/file/[slug]/route.ts b/src/app/documents/file/[slug]/route.ts new file mode 100644 index 00000000..c657d24e --- /dev/null +++ b/src/app/documents/file/[slug]/route.ts @@ -0,0 +1,61 @@ +import { findDocument } from "@/queries/documents" + +type Context = { params: Promise<{ slug: string }> } + +const UPSTREAM_TIMEOUT_MS = 15_000 +const FORWARDED_HEADERS = ["etag", "last-modified"] + +/** + * Serves a catalog PDF from the site's own origin. PDF.js can only read cross-origin files the host allows (GitHub + * release downloads don't), and browsers ignore `download` on cross-origin links. Only slugs in the catalog resolve, + * so this never fetches an arbitrary URL. + */ +export async function GET(request: Request, { params }: Context) { + const { slug } = await params + const { document, backendUnavailable } = await findDocument(slug) + if (!document) { + return backendUnavailable + ? new Response("Documenti temporaneamente non disponibili", { + status: 503, + headers: { "Retry-After": "60", "Cache-Control": "no-store" }, + }) + : new Response("Documento non trovato", { status: 404, headers: { "Cache-Control": "no-store" } }) + } + + // The timeout bounds only the wait for the upstream headers: the body then streams at the client's pace, and a + // deadline on the whole transfer would truncate large PDFs on slow connections. A client that leaves cancels it. + const timeout = new AbortController() + const timer = setTimeout( + () => timeout.abort(new DOMException("Upstream timeout", "TimeoutError")), + UPSTREAM_TIMEOUT_MS + ) + const upstream = await fetch(document.source, { + cache: "no-store", + signal: AbortSignal.any([timeout.signal, request.signal]), + }) + .catch((error) => { + console.error(`Failed to fetch document ${slug}`, error) + return null + }) + .finally(() => clearTimeout(timer)) + if (!upstream?.ok || !upstream.body) { + if (upstream) console.error(`Document ${slug} answered ${upstream.status}`) + return new Response("Documento non disponibile", { status: 502, headers: { "Cache-Control": "no-store" } }) + } + + // The latest file and even its version label can change after an admin deletes or replaces an upload. + const headers = new Headers({ + "Content-Type": "application/pdf", + "Content-Disposition": `inline; filename="${slug}.pdf"`, + "Cache-Control": "no-store", + "X-Content-Type-Options": "nosniff", + }) + for (const name of FORWARDED_HEADERS) { + const value = upstream.headers.get(name) + if (value) headers.set(name, value) + } + // fetch decompresses encoded bodies: their original Content-Length no longer describes the streamed bytes. + const length = upstream.headers.get("content-length") + if (length && !upstream.headers.has("content-encoding")) headers.set("Content-Length", length) + return new Response(upstream.body, { headers }) +} diff --git a/src/app/documents/page.tsx b/src/app/documents/page.tsx new file mode 100644 index 00000000..7ecf97a4 --- /dev/null +++ b/src/app/documents/page.tsx @@ -0,0 +1,46 @@ +import type { Metadata } from "next" +import { DocumentCategoryCard } from "@/components/documents/document-category-card" +import { getCategoryAnchor } from "@/components/documents/utils" +import { CONTAINER, PAGE_HERO, PAGE_MAIN } from "@/components/layout/page" +import { Hero } from "@/components/ui/hero" +import { getDocumentCategories } from "@/queries/documents" + +export const metadata: Metadata = { + title: "Documenti", + description: "Tutti i documenti che cerchi, in un unico posto.", +} + +// Uploaded from the admin dashboard: read from the backend at request time, like /projects +export const dynamic = "force-dynamic" + +export default async function DocumentsPage() { + const categories = await getDocumentCategories() + + return ( +
+
+ +
+ +
+ + {categories.map((category) => ( + + ))} +
+
+ ) +} diff --git a/src/app/documents/view/[slug]/page.tsx b/src/app/documents/view/[slug]/page.tsx new file mode 100644 index 00000000..bc11bfbc --- /dev/null +++ b/src/app/documents/view/[slug]/page.tsx @@ -0,0 +1,56 @@ +import type { Metadata } from "next" +import Link from "next/link" +import { notFound } from "next/navigation" +import { PdfViewerLoader } from "@/components/documents/pdf-viewer-loader" +import { Glass } from "@/components/glass" +import { CONTAINER } from "@/components/layout/page" +import { Button } from "@/components/ui/button" +import { findDocument } from "@/queries/documents" + +type Props = { params: Promise<{ slug: string }> } + +// Uploaded from the admin dashboard: a new version or document shows up without a rebuild +export const dynamic = "force-dynamic" + +export async function generateMetadata({ params }: Props): Promise { + const { document } = await findDocument((await params).slug) + // The outage page answers 200: keep it out of search results + return { title: document?.title ?? "Documenti", robots: document ? undefined : { index: false } } +} + +export default async function DocumentViewerPage({ params }: Props) { + const { slug } = await params + const { document, backendUnavailable } = await findDocument(slug) + // A backend outage is not a missing document: say so and offer a retry instead of a 404 + if (!document && backendUnavailable) return + if (!document) notFound() + + return ( +
+ +
+ ) +} + +function DocumentsUnavailable({ slug }: { slug: string }) { + return ( +
+ +

+ Documento temporaneamente non disponibile +

+

+ Non riusciamo a raggiungere l’archivio dei documenti in questo momento. Riprova tra qualche minuto. +

+
+ + +
+
+
+ ) +} diff --git a/src/components/conditional-footer.tsx b/src/components/conditional-footer.tsx index 35ce8eb5..8d52c38e 100644 --- a/src/components/conditional-footer.tsx +++ b/src/components/conditional-footer.tsx @@ -5,7 +5,7 @@ import type { ReactNode } from "react" import { matchesAnyRoutePrefix } from "@/utils/route-match" const HIDDEN_EXACT = ["/matricole/guida"] -const HIDDEN_PREFIXES = ["/groups"] +const HIDDEN_PREFIXES = ["/groups", "/documents/view"] /** * Hides the footer on full-screen routes. The footer itself is passed as `children` so it stays a server component diff --git a/src/components/documents/document-category-card.tsx b/src/components/documents/document-category-card.tsx new file mode 100644 index 00000000..746bf93b --- /dev/null +++ b/src/components/documents/document-category-card.tsx @@ -0,0 +1,85 @@ +import Link from "next/link" +import { FiDownload, FiEye, FiFile } from "react-icons/fi" +import { Glass } from "@/components/glass" +import { Button } from "@/components/ui/button" +import type { DocumentCategory } from "./types" +import { + getCategoryAnchor, + getCategoryHeadingId, + getDocumentFileHref, + getDocumentFileName, + getDocumentViewerHref, +} from "./utils" + +// Dates are plain YYYY-MM-DD (UTC midnight): format them in UTC so no server timezone shifts the day +const dateFormat = new Intl.DateTimeFormat("it-IT", { dateStyle: "long", timeZone: "UTC" }) + +function formatDate(date: string) { + return dateFormat.format(new Date(date)) +} + +export function DocumentCategoryCard({ category }: { category: DocumentCategory }) { + const anchor = getCategoryAnchor(category.id) + const headingId = getCategoryHeadingId(category.id) + return ( +
+ +
+

+ {category.title} +

+

{category.description}

+
+
    + {category.documents.map((document) => ( +
  • +
    +
    +
    + + +
    +
  • + ))} +
+
+
+ ) +} diff --git a/src/components/documents/pdf-viewer-loader.tsx b/src/components/documents/pdf-viewer-loader.tsx new file mode 100644 index 00000000..aeaee614 --- /dev/null +++ b/src/components/documents/pdf-viewer-loader.tsx @@ -0,0 +1,13 @@ +"use client" + +import dynamic from "next/dynamic" +import type { DocumentItem } from "./types" + +const PdfViewer = dynamic(() => import("./pdf-viewer"), { + ssr: false, + loading: () => Caricamento del visualizzatore…, +}) + +export function PdfViewerLoader({ document }: { document: DocumentItem }) { + return +} diff --git a/src/components/documents/pdf-viewer.tsx b/src/components/documents/pdf-viewer.tsx new file mode 100644 index 00000000..afa9b2e9 --- /dev/null +++ b/src/components/documents/pdf-viewer.tsx @@ -0,0 +1,222 @@ +"use client" + +import Link from "next/link" +import { useEffect, useRef, useState } from "react" +import { FiArrowLeft, FiChevronLeft, FiChevronRight, FiDownload, FiZoomIn, FiZoomOut } from "react-icons/fi" +import { Document, Page, pdfjs } from "react-pdf" +import "react-pdf/dist/Page/AnnotationLayer.css" +import "react-pdf/dist/Page/TextLayer.css" +import { Glass } from "@/components/glass" +import { Button } from "@/components/ui/button" +import type { DocumentItem } from "./types" +import { getDocumentFileHref, getDocumentFileName, getPdfPixelRatio } from "./utils" + +pdfjs.GlobalWorkerOptions.workerSrc = "/pdfjs/pdf.worker.min.mjs" +const pdfOptions = { cMapUrl: "/pdfjs/cmaps/", standardFontDataUrl: "/pdfjs/standard_fonts/", wasmUrl: "/pdfjs/wasm/" } + +export default function PdfViewer({ document }: { document: DocumentItem }) { + const [zoom, setZoom] = useState(1) + const [page, setPage] = useState(1) + const [pageCount, setPageCount] = useState(0) + const [width, setWidth] = useState(0) + const [pageSize, setPageSize] = useState<{ page: number; width: number; height: number } | null>(null) + // The whole document failed to load: nothing to page or zoom through + const [failed, setFailed] = useState(false) + // Only the current page failed to draw: cleared when the page or zoom changes, so the controls stay usable + const [pageError, setPageError] = useState(false) + const viewport = useRef(null) + const fileHref = getDocumentFileHref(document) + const pageWidth = Math.min(width, 900) * zoom + const pageMeasured = pageSize?.page === page + + useEffect(() => { + const element = viewport.current + if (!element) return + const observer = new ResizeObserver(([entry]) => { + if (entry) setWidth(Math.max(1, entry.contentRect.width - 32)) + }) + observer.observe(element) + return () => observer.disconnect() + }, []) + + return ( + +
+
+ +

+ {document.title} +

+
+
+ + + + +
+
+
+ {width > 0 && ( + { + setPageCount(numPages) + setFailed(false) + }} + onLoadError={() => setFailed(true)} + externalLinkTarget="_blank" + externalLinkRel="noopener noreferrer" + // Links to another page of the same PDF: this viewer shows one page at a time + onItemClick={({ pageNumber }) => { + setPageError(false) + setPage(pageNumber) + viewport.current?.scrollTo(0, 0) + }} + loading={Caricamento del PDF…} + error={ +

+ Impossibile visualizzare il PDF. Puoi scaricarlo con il pulsante in alto. +

+ } + className="flex min-w-full justify-start p-4" + > + { + const dimensions = loadedPage.getViewport({ scale: 1 }) + setPageSize((previous) => + previous?.page === page && + previous.width === dimensions.width && + previous.height === dimensions.height + ? previous + : { page, width: dimensions.width, height: dimensions.height } + ) + }} + onRenderError={() => setPageError(true)} + onRenderSuccess={() => setPageError(false)} + loading={Caricamento della pagina…} + error={ +

+ Impossibile visualizzare questa pagina. Puoi scaricare il PDF con il pulsante in alto. +

+ } + className="mx-auto shrink-0 shadow-sm" + /> +
+ )} +
+ {pageError && ( +

+ Impossibile visualizzare questa pagina a questo zoom. Prova a ridurre lo zoom, cambiare pagina o scaricare il + PDF. +

+ )} + {pageCount > 0 && !failed && ( +
+ + + Pagina {page} di {pageCount} + + +
+ )} +
+ ) +} diff --git a/src/components/documents/types.ts b/src/components/documents/types.ts new file mode 100644 index 00000000..514f08b2 --- /dev/null +++ b/src/components/documents/types.ts @@ -0,0 +1,19 @@ +export type DocumentItem = { + /** Stable id in the site's URLs: `/documents/view/` and `/documents/file/`. */ + slug: string + title: string + description?: string | null + /** Where the latest PDF lives: the backend's blob storage, or GitHub for the fallback catalog. */ + source: string + /** Latest version, when the document comes from the backend. */ + version?: string + /** ISO date (YYYY-MM-DD) of the latest version. */ + date?: string +} + +export type DocumentCategory = { + id: string + title: string + description: string + documents: DocumentItem[] +} diff --git a/src/components/documents/utils.ts b/src/components/documents/utils.ts new file mode 100644 index 00000000..784eae5d --- /dev/null +++ b/src/components/documents/utils.ts @@ -0,0 +1,30 @@ +import type { DocumentItem } from "./types" + +export function getDocumentViewerHref(document: DocumentItem) { + return `/documents/view/${document.slug}` +} + +/** Same-origin URL of the PDF: the viewer can read it without CORS and `download` saves it instead of navigating. */ +export function getDocumentFileHref(document: DocumentItem) { + const path = `/documents/file/${document.slug}` + // A different version also makes PDF.js reload when navigating to an updated document. + return document.version ? `${path}?v=${encodeURIComponent(document.version)}` : path +} + +/** HTML id of a category's section: prefixed so a category slug can't collide with other ids on the page. */ +export function getCategoryAnchor(id: string) { + return `documenti-categoria-${id}` +} + +export function getCategoryHeadingId(id: string) { + return `documenti-titolo-${id}` +} + +/** Bound both canvas dimensions to keep large or unusually tall pages within mobile canvas budgets. */ +export function getPdfPixelRatio(width: number, height: number, devicePixelRatio: number) { + return Math.min(devicePixelRatio, 2, 4096 / Math.max(width, height)) +} + +export function getDocumentFileName(document: DocumentItem) { + return `${document.slug}.pdf` +} diff --git a/src/components/header/constants.ts b/src/components/header/constants.ts index 6f61f1f1..77fc22b2 100644 --- a/src/components/header/constants.ts +++ b/src/components/header/constants.ts @@ -11,6 +11,7 @@ export const headerMenuItems: HeaderMenuItem[] = [ // Leaves the site: ↗ instead of ›, as in the rest of the site { title: "Appunti", href: MATERIALS_URL, icon: FiArrowUpRight }, { title: "Guide", href: "/guides", icon: FiChevronRight }, + { title: "Documenti", href: "/documents", icon: FiChevronRight }, { title: "FAQs", href: "/faqs", icon: FiChevronRight }, ], }, diff --git a/src/queries/documents.ts b/src/queries/documents.ts new file mode 100644 index 00000000..afa0d546 --- /dev/null +++ b/src/queries/documents.ts @@ -0,0 +1,121 @@ +import { cache } from "react" +import type { DocumentCategory, DocumentItem } from "@/components/documents/types" +import { trpc } from "@/lib/backend" +import { memberPrivacyHref } from "@/lib/documents" + +const RAW = "https://raw.githubusercontent.com/PoliNetworkOrg" + +/** + * Shown while the backend has no documents (they are uploaded from the admin dashboard) or can't be reached, like the + * Guida della Matricola's fallback: the official PDFs published on PoliNetworkOrg's public repositories. + * Not listed: the internal regulations (their repository is private) and the financial statements (not published). + */ +const FALLBACK_CATALOG: DocumentCategory[] = [ + { + id: "associazione", + title: "Associazione", + description: "Chi siamo e su quali principi ci fondiamo.", + documents: [ + { + slug: "cos-e-polinetwork", + title: "Cos’è PoliNetwork", + description: "Una panoramica dell’associazione e delle sue attività.", + source: `${RAW}/documents/main/exported/PoliNetwork.pdf`, + }, + { + slug: "statuto", + title: "Statuto dell’associazione", + description: "Finalità, organizzazione e principi associativi.", + source: `${RAW}/Statuto/main/full.pdf`, + }, + ], + }, + { + id: "privacy", + title: "Privacy e Informative", + description: "Come trattiamo e proteggiamo i dati personali.", + documents: [ + { + slug: "privacy-policy", + title: "Privacy Policy", + description: "Come PoliNetwork tratta i dati personali di chi usa i suoi servizi.", + source: `${RAW}/documents/main/exported/privacy-policy-principale.pdf`, + }, + { + slug: "privacy-soci", + title: "Associati e candidati soci", + description: "Il trattamento dei dati personali di chi è socio o richiede di diventarlo.", + source: memberPrivacyHref, + }, + { + slug: "privacy-volontari", + title: "Admin e volontari", + description: "Il trattamento dei dati personali di admin e volontari.", + source: `${RAW}/documents/main/exported/PrivacyPolicy_Volontari.pdf`, + }, + { + slug: "privacy-recruitment", + title: "Candidati al recruitment", + description: "Il trattamento dei dati personali di chi si candida per entrare in un team.", + source: `${RAW}/documents/main/exported/informativa-privacy-recruitment.pdf`, + }, + ], + }, +] + +type Catalog = { categories: DocumentCategory[]; backendUnavailable: boolean } + +/** + * Backend documents first; fallback entries fill in only the slugs the backend doesn't have yet, so publishing one + * document from admin doesn't hide the others. Once every fallback document has been uploaded, delete the fallback. + */ +function withFallback(backend: DocumentCategory[]): DocumentCategory[] { + const published = new Set(backend.flatMap((category) => category.documents.map((document) => document.slug))) + const merged = backend.map((category) => ({ ...category, documents: [...category.documents] })) + for (const fallback of FALLBACK_CATALOG) { + const missing = fallback.documents.filter((document) => !published.has(document.slug)) + if (missing.length === 0) continue + // Admin may give the same category another slug: match its title too, so it doesn't show up twice + const target = merged.find( + (category) => category.id === fallback.id || category.title.trim().toLowerCase() === fallback.title.toLowerCase() + ) + if (target) target.documents.push(...missing) + else merged.push({ ...fallback, documents: missing }) + } + return merged +} + +// Share the catalog between the viewer's metadata and page during a server render. The file route is a separate request. +const loadCatalog = cache(async (): Promise => { + try { + const catalog = await trpc.web.documents.getCatalog.query() + const categories = catalog.map((category) => ({ + id: category.slug, + title: category.title, + description: category.description, + documents: category.documents.map((document) => ({ + slug: document.slug, + title: document.title, + description: document.description, + source: document.latest.file, + version: document.latest.version, + date: document.latest.date, + })), + })) + return { categories: withFallback(categories), backendUnavailable: false } + } catch (error) { + console.error("Failed to fetch documents", error) + return { categories: FALLBACK_CATALOG, backendUnavailable: true } + } +}) + +export async function getDocumentCategories(): Promise { + return (await loadCatalog()).categories +} + +/** `backendUnavailable` tells a missing document apart from one the backend couldn't be asked about. */ +export async function findDocument(slug: string): Promise<{ document?: DocumentItem; backendUnavailable: boolean }> { + const { categories, backendUnavailable } = await loadCatalog() + const document = categories.flatMap((category) => category.documents).find((item) => item.slug === slug) + return { document, backendUnavailable } +} diff --git a/tests/documents.test.mjs b/tests/documents.test.mjs new file mode 100644 index 00000000..19852dbb --- /dev/null +++ b/tests/documents.test.mjs @@ -0,0 +1,147 @@ +import assert from "node:assert/strict" +import { readFileSync } from "node:fs" +import { registerHooks, stripTypeScriptTypes } from "node:module" +import test from "node:test" + +// Exercise the real query and route without contacting the IdP or a database. +const backend = "data:text/javascript," + encodeURIComponent( + "export const trpc = { web: { documents: { getCatalog: { query: () => globalThis.documentCatalogQuery() } } } }" +) +registerHooks({ + resolve(specifier, context, nextResolve) { + if (specifier === "@/lib/backend") return { url: backend, shortCircuit: true } + if (specifier.startsWith("@/")) { + return { url: new URL(`../src/${specifier.slice(2)}.ts`, import.meta.url).href, shortCircuit: true } + } + return nextResolve(specifier, context) + }, + load(url, context, nextLoad) { + if (url.endsWith(".ts")) { + return { format: "module", source: stripTypeScriptTypes(readFileSync(new URL(url), "utf8")), shortCircuit: true } + } + return nextLoad(url, context) + }, +}) + +const { getDocumentCategories, findDocument } = await import("../src/queries/documents.ts") +const { GET } = await import("../src/app/documents/file/[slug]/route.ts") +const { getCategoryAnchor, getCategoryHeadingId, getPdfPixelRatio } = await import("../src/components/documents/utils.ts") +const category = (slug = "statuto") => [{ + slug: "associazione", title: "Associazione", description: "Documenti ufficiali", + documents: [{ slug, title: "Statuto caricato", description: null, + latest: { version: "2.0", date: "2026-11-13", file: "https://files.example/statuto.pdf" } }], +}] + +function backendReturns(catalog) { + globalThis.documentCatalogQuery = async () => catalog +} + +function requestFile(slug, query = "") { + return GET(new Request(`https://example.org/documents/file/${slug}${query}`), { params: Promise.resolve({ slug }) }) +} + +test("publishing the first document preserves other fallback documents without duplicating the uploaded slug", async () => { + backendReturns(category()) + const documents = (await getDocumentCategories()).flatMap((item) => item.documents) + assert.equal(documents.length, 6) + assert.equal(documents.filter((item) => item.slug === "statuto").length, 1) + assert.equal(documents.find((item) => item.slug === "statuto").title, "Statuto caricato") + assert.ok(documents.find((item) => item.slug === "privacy-soci")) +}) + +test("backend outage differs from a missing document while official fallback PDFs remain available", async (t) => { + t.mock.method(console, "error", () => {}) + backendReturns([]) + assert.equal((await requestFile("unknown")).status, 404) + globalThis.documentCatalogQuery = async () => { throw new Error("offline") } + assert.equal((await findDocument("statuto")).document.slug, "statuto") + const response = await requestFile("uploaded-only") + assert.equal(response.status, 503) + assert.equal(response.headers.get("retry-after"), "60") + assert.equal(response.headers.get("cache-control"), "no-store") +}) + +test("PDFs recheck storage and cannot remain cached after replacement or deletion", async (t) => { + backendReturns(category()) + let fetchOptions + t.mock.method(globalThis, "fetch", async (_url, options) => { + fetchOptions = options + return new Response("%PDF-latest", { headers: { "content-type": "application/pdf", "etag": '"latest"' } }) + }) + // Version labels may be deleted and reused, so even a matching label is mutable. + const response = await requestFile("statuto", "?v=2.0") + assert.equal(response.status, 200) + assert.equal(response.headers.get("cache-control"), "no-store") + assert.equal(fetchOptions.cache, "no-store") + assert.ok(fetchOptions.signal instanceof AbortSignal) + assert.equal(await response.text(), "%PDF-latest") +}) + +test("upstream failures produce a retryable, uncached error", async (t) => { + backendReturns(category()) + t.mock.method(console, "error", () => {}) + t.mock.method(globalThis, "fetch", async () => { throw new Error("timeout") }) + const response = await requestFile("statuto") + assert.equal(response.status, 502) + assert.equal(response.headers.get("cache-control"), "no-store") +}) + +test("the upstream timeout bounds the wait for headers, not the streamed body", async (t) => { + backendReturns(category()) + t.mock.method(console, "error", () => {}) + t.mock.timers.enable({ apis: ["setTimeout"] }) + let signal + t.mock.method(globalThis, "fetch", async (_url, options) => { + signal = options.signal + return new Response("%PDF-slow", { headers: { "content-type": "application/pdf" } }) + }) + const response = await requestFile("statuto") + t.mock.timers.tick(60_000) + assert.equal(signal.aborted, false) + assert.equal(await response.text(), "%PDF-slow") + + t.mock.method(globalThis, "fetch", (_url, options) => new Promise((_resolve, reject) => { + options.signal.addEventListener("abort", () => reject(options.signal.reason)) + })) + const pending = requestFile("statuto") + await new Promise((resolve) => setImmediate(resolve)) + t.mock.timers.tick(15_000) + assert.equal((await pending).status, 502) +}) + +test("a client that disconnects cancels the upstream download", async (t) => { + backendReturns(category()) + let signal + t.mock.method(globalThis, "fetch", async (_url, options) => { + signal = options.signal + return new Response("%PDF") + }) + const client = new AbortController() + await GET(new Request("https://example.org/documents/file/statuto", { signal: client.signal }), { + params: Promise.resolve({ slug: "statuto" }), + }) + client.abort() + assert.equal(signal.aborted, true) +}) + +test("a fallback category is merged into the admin category with the same title", async () => { + globalThis.documentCatalogQuery = async () => [{ ...category()[0], slug: "chi-siamo" }] + const categories = await getDocumentCategories() + assert.deepEqual(categories.map((item) => item.id), ["chi-siamo", "privacy"]) +}) + +test("a category slug cannot collide with another category's heading", () => { + const slugs = ["privacy", "privacy-title", "titolo-privacy", "categoria-privacy"] + const ids = slugs.flatMap((slug) => [getCategoryAnchor(slug), getCategoryHeadingId(slug)]) + assert.equal(new Set(ids).size, ids.length) +}) + +test("canvas resolution respects both dimensions at high zoom on retina displays", () => { + for (const [width, height] of [[900, 1273], [2700, 3819], [2700, 12000], [12000, 2700]]) { + const ratio = getPdfPixelRatio(width, height, 3) + assert.ok(width * ratio <= 4096) + assert.ok(height * ratio <= 4096) + assert.ok(ratio > 0 && ratio <= 2) + } + assert.equal(getPdfPixelRatio(300, 424, 1), 1) +}) diff --git a/tsconfig.json b/tsconfig.json index ca124295..326e81a0 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -46,6 +46,7 @@ ".next/dev/types/**/*.ts" ], "exclude": [ - "node_modules" + "node_modules", + "public/pdfjs" ] }