diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml index 5ade98b91..c05b08f73 100644 --- a/.github/workflows/docker-build.yml +++ b/.github/workflows/docker-build.yml @@ -15,7 +15,7 @@ on: - 'v*.*.*' # Only build when files in these directories have been changed paths: - - client/** + - scripts/fetch-client-react-runtime.js - server/** - index.js - package.json diff --git a/.github/workflows/integration-test.yml b/.github/workflows/integration-test.yml index 31eada873..7a34c55b9 100644 --- a/.github/workflows/integration-test.yml +++ b/.github/workflows/integration-test.yml @@ -7,12 +7,13 @@ on: - 'dependabot/**' # Don't run dependabot branches, as they are already covered by pull requests # Only build when files in these directories have been changed paths: - - client/** - server/** - test/** - index.js - package.json - tsconfig.server.json + - scripts/fetch-client-react-runtime.js + - .github/workflows/integration-test.yml jobs: build: @@ -30,24 +31,19 @@ jobs: - name: install pkg (using yao-pkg fork for targeting node24) run: npm install -g @yao-pkg/pkg - - name: get client dependencies - working-directory: client - run: npm ci - - - name: build client - working-directory: client - run: npm run generate - - name: get server dependencies and compile server run: npm ci && npm run build:server && npm prune --omit=dev - name: build binary - run: pkg --config package.json -t node24-linux-x64 -o audiobookshelf dist-server/index.js + run: pkg --config package.json -t node24-linux-x64 -o dist/pkg/audiobookshelf dist-server/index.js + + - name: fetch the React client runtime + run: node scripts/fetch-client-react-runtime.js --out dist/pkg/client-react - name: run audiobookshelf run: | - ./audiobookshelf & + REACT_CLIENT_PATH="$PWD/dist/pkg/client-react" ./dist/pkg/audiobookshelf & sleep 5 - name: test if server is available - run: curl -sf http://127.0.0.1:3333 | grep Audiobookshelf + run: curl -sf --retry 30 --retry-delay 2 --retry-connrefused http://127.0.0.1:3333/healthcheck diff --git a/Dockerfile b/Dockerfile index 23a6a7bbb..5bd70d26a 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,13 +1,13 @@ ARG NUSQLITE3_DIR="/usr/local/lib/nusqlite3" ARG NUSQLITE3_PATH="${NUSQLITE3_DIR}/libnusqlite3.so" -### STAGE 0: Build client ### -FROM node:24-alpine AS build-client +### STAGE 0: Fetch the pinned React client runtime. ### +FROM node:24-alpine AS fetch-client -WORKDIR /client -COPY /client /client -RUN npm ci && npm cache clean --force -RUN npm run generate +WORKDIR /fetch +COPY package.json /fetch/package.json +COPY scripts/fetch-client-react-runtime.js /fetch/scripts/fetch-client-react-runtime.js +RUN node scripts/fetch-client-react-runtime.js --out /out/client-react ### STAGE 1: Compile server on the builder CPU (avoid QEMU SIGILL from tsc on arm64) ### FROM --platform=$BUILDPLATFORM node:24-alpine AS compile-server @@ -63,8 +63,10 @@ RUN apk add --no-cache --update \ WORKDIR /app -# Copy compiled frontend and server from build stages -COPY --from=build-client /client/dist /app/client/dist +# The React runtime must be writable: startup rewrites the base-path placeholder +# and Next writes its cache under .next. +COPY --from=fetch-client /out/client-react /app/client-react +RUN chmod -R a+rwX /app/client-react/.next COPY --from=build-server /server /app COPY --from=build-server ${NUSQLITE3_PATH} ${NUSQLITE3_PATH} @@ -75,6 +77,7 @@ ENV NODE_ENV=production ENV CONFIG_PATH="/config" ENV METADATA_PATH="/metadata" ENV SOURCE="docker" +ENV REACT_CLIENT_PATH="/app/client-react" ENV NUSQLITE3_DIR=${NUSQLITE3_DIR} ENV NUSQLITE3_PATH=${NUSQLITE3_PATH} diff --git a/build/debian/DEBIAN/postinst b/build/debian/DEBIAN/postinst index b80d18c68..1694aa63c 100644 --- a/build/debian/DEBIAN/postinst +++ b/build/debian/DEBIAN/postinst @@ -44,4 +44,10 @@ if [ ! -d "$ABS_LOG_DIR" ]; then chown -R 'audiobookshelf:audiobookshelf' "$ABS_LOG_DIR" fi +# Startup rewrites the React client's base-path placeholder and Next writes its cache under .next. +CLIENT_REACT_DIR="/usr/share/audiobookshelf/client-react" +if [ -d "$CLIENT_REACT_DIR" ]; then + chown -R 'audiobookshelf:audiobookshelf' "$CLIENT_REACT_DIR" +fi + start_service 'audiobookshelf' diff --git a/build/debian/DEBIAN/postrm b/build/debian/DEBIAN/postrm new file mode 100644 index 000000000..e11384d51 --- /dev/null +++ b/build/debian/DEBIAN/postrm @@ -0,0 +1,10 @@ +#!/bin/bash +set -e +set -o pipefail + +# dpkg removes the packaged files. This deletes the base-path snapshot and Next +# cache, which are created at runtime and are not in the package file list. +# postrm upgrade runs after the new package is unpacked, so leave the directory in place then. +if [ "$1" = "remove" ] || [ "$1" = "purge" ]; then + rm -rf /usr/share/audiobookshelf/client-react +fi diff --git a/build/debian/DEBIAN/preinst b/build/debian/DEBIAN/preinst index 241a47010..aa5a77fe5 100644 --- a/build/debian/DEBIAN/preinst +++ b/build/debian/DEBIAN/preinst @@ -46,19 +46,18 @@ add_group() { } setup_config() { + if [ ! -d "$DEFAULT_DATA_DIR" ]; then + # Create directory and set permissions + echo "Creating default data dir at $DEFAULT_DATA_DIR" + mkdir -p "$DEFAULT_DATA_DIR" + fi + chown 'audiobookshelf:audiobookshelf' "$DEFAULT_DATA_DIR" + if [ -f "$CONFIG_PATH" ]; then echo "Existing config found." cat $CONFIG_PATH else - - if [ ! -d "$DEFAULT_DATA_DIR" ]; then - # Create directory and set permissions - echo "Creating default data dir at $DEFAULT_DATA_DIR" - mkdir "$DEFAULT_DATA_DIR" - chown -R 'audiobookshelf:audiobookshelf' "$DEFAULT_DATA_DIR" - fi - echo "Creating default config." config_text="METADATA_PATH=$DEFAULT_DATA_DIR/metadata diff --git a/build/debian/lib/systemd/system/audiobookshelf.service b/build/debian/lib/systemd/system/audiobookshelf.service index dd5be8770..bbb975020 100644 --- a/build/debian/lib/systemd/system/audiobookshelf.service +++ b/build/debian/lib/systemd/system/audiobookshelf.service @@ -12,6 +12,7 @@ Restart=always User=audiobookshelf Group=audiobookshelf Environment=HOME=/var/cache/audiobookshelf +Environment=REACT_CLIENT_PATH=/usr/share/audiobookshelf/client-react CacheDirectory=audiobookshelf [Install] diff --git a/build/linuxpackager b/build/linuxpackager index 622a00550..4f8f29f5b 100755 --- a/build/linuxpackager +++ b/build/linuxpackager @@ -11,15 +11,6 @@ VERSION="$( eval echo $( jq '.version' package.json) )" DESCRIPTION="$( eval echo $( jq '.description' package.json) )" OUTPUT_FILE="audiobookshelf_${VERSION}_amd64.deb" -echo ">>> Building Client" -echo "--------------------" - -cd client -rm -rf node_modules -npm ci -npm run generate -cd .. - echo ">>> Building Server" echo "--------------------" @@ -47,11 +38,17 @@ Description: $DESCRIPTION" echo "$controlfile" > dist/debian/DEBIAN/control; +echo ">>> Fetching React client runtime" +echo "--------------------" + +mkdir -p dist/debian/usr/share/audiobookshelf +node scripts/fetch-client-react-runtime.js --out dist/debian/usr/share/audiobookshelf/client-react + # Package contents: directories 0755, files 0644 (including the systemd unit). # Maintainer scripts must stay executable so dpkg can run them. find dist/debian -type d -exec chmod 755 {} + find dist/debian -type f -exec chmod 644 {} + -chmod 755 dist/debian/DEBIAN/preinst dist/debian/DEBIAN/postinst dist/debian/DEBIAN/prerm +chmod 755 dist/debian/DEBIAN/preinst dist/debian/DEBIAN/postinst dist/debian/DEBIAN/prerm dist/debian/DEBIAN/postrm # Package debian pkg --config package.json -t node24-linux-x64 -o dist/debian/usr/share/audiobookshelf/audiobookshelf dist-server/index.js diff --git a/index.js b/index.js index 7c42e30ae..ea80ab8ba 100644 --- a/index.js +++ b/index.js @@ -43,12 +43,21 @@ const inputMetadata = options.metadata ? Path.resolve(options.metadata) : null const PORT = options.port || process.env.PORT || 3333 const HOST = options.host || process.env.HOST +// Keep process.env in sync so the embedded React client calls this server when CLI flags are used. +process.env.PORT = String(PORT) +if (HOST) process.env.HOST = HOST const CONFIG_PATH = inputConfig || process.env.CONFIG_PATH || Path.resolve('config') const METADATA_PATH = inputMetadata || process.env.METADATA_PATH || Path.resolve('metadata') const SOURCE = options.source || process.env.SOURCE || 'debian' const ROUTER_BASE_PATH = process.env.ROUTER_BASE_PATH ?? '/audiobookshelf' +// v3 serves only the React client. +if (!String(process.env.REACT_CLIENT_PATH || '').trim()) { + console.error('REACT_CLIENT_PATH is required') + process.exit(1) +} + console.log(`Running in ${process.env.NODE_ENV} mode.`) console.log(`Options: CONFIG_PATH=${CONFIG_PATH}, METADATA_PATH=${METADATA_PATH}, PORT=${PORT}, HOST=${HOST}, SOURCE=${SOURCE}, ROUTER_BASE_PATH=${ROUTER_BASE_PATH}`) diff --git a/package.json b/package.json index 2c1cfbc5e..8aacb5659 100644 --- a/package.json +++ b/package.json @@ -2,6 +2,7 @@ "name": "audiobookshelf", "version": "3.0.0-beta", "buildNumber": 1, + "clientReactRelease": "v0.2.0", "description": "Self-hosted audiobook and podcast server", "main": "dist-server/index.js", "scripts": { @@ -10,9 +11,9 @@ "start": "node dist-server/index.js", "start-dev": "node dist-server/index.js --prod-with-dev-env", "client": "cd client && npm ci && npm run generate", - "prod": "npm run client && npm ci && npm run build:server && npm run start", - "build-win": "npm run client && npm run build:server && pkg --config package.json -t node24-win-x64 -o ./dist/win/audiobookshelf -C GZip dist-server/index.js", - "build-win-no-compress": "npm run client && npm run build:server && pkg --config package.json -t node24-win-x64 -o ./dist/win/audiobookshelf dist-server/index.js", + "prod": "npm ci && npm run build:server && npm run start", + "build-win": "node scripts/fetch-client-react-runtime.js --out dist/win/client-react && npm run build:server && pkg --config package.json -t node24-win-x64 -o ./dist/win/audiobookshelf -C GZip dist-server/index.js", + "build-win-no-compress": "node scripts/fetch-client-react-runtime.js --out dist/win/client-react && npm run build:server && pkg --config package.json -t node24-win-x64 -o ./dist/win/audiobookshelf dist-server/index.js", "build-linux": "build/linuxpackager", "docker": "docker buildx build --platform linux/amd64,linux/arm64 --push . -t advplyr/audiobookshelf", "docker-amd64-local": "docker buildx build --platform linux/amd64 --load . -t advplyr/audiobookshelf-amd64-local", @@ -25,7 +26,6 @@ "bin": "dist-server/index.js", "pkg": { "assets": [ - "client/dist/**/*", "node_modules/sqlite3/lib/binding/**/*.node", "dist-server/server/migrations/*.js" ], diff --git a/scripts/fetch-client-react-runtime.js b/scripts/fetch-client-react-runtime.js new file mode 100644 index 000000000..ecb81e08c --- /dev/null +++ b/scripts/fetch-client-react-runtime.js @@ -0,0 +1,126 @@ +/** + * Download the pinned audiobookshelf-client-react runtime archive and extract it. + * + * The tag comes from package.json "clientReactRelease" unless CLIENT_REACT_RELEASE is set. + * CLIENT_REACT_REPOSITORY overrides the GitHub repo (default audiobookshelf/audiobookshelf-client-react). + * + * Usage: node scripts/fetch-client-react-runtime.js --out + */ +const fs = require('fs') +const os = require('os') +const path = require('path') +const { Readable } = require('stream') +const { pipeline } = require('stream/promises') +const { spawnSync } = require('child_process') + +const ARCHIVE_NAME = 'audiobookshelf-client-runtime.tar.gz' +const DEFAULT_REPOSITORY = 'audiobookshelf/audiobookshelf-client-react' +const REPOSITORY_PATTERN = /^[\w.-]+\/[\w.-]+$/ + +function fail(message) { + const error = new Error(message) + error.userFacing = true + throw error +} + +function parseArgs(argv) { + let out = null + for (let i = 2; i < argv.length; i++) { + const arg = argv[i] + if (arg === '--out') { + const value = argv[++i] + if (!value) fail('Missing value for --out') + out = value + continue + } + fail(`Unknown argument: ${arg}\nUsage: node scripts/fetch-client-react-runtime.js --out `) + } + if (!out) fail('Usage: node scripts/fetch-client-react-runtime.js --out ') + return path.resolve(out) +} + +function readPinnedTag() { + const fromEnv = process.env.CLIENT_REACT_RELEASE + if (fromEnv && fromEnv.trim()) return fromEnv.trim() + + const packagePath = path.join(__dirname, '..', 'package.json') + let pkg + try { + pkg = JSON.parse(fs.readFileSync(packagePath, 'utf8')) + } catch (error) { + fail(`Cannot read ${packagePath}: ${error.message}`) + } + const tag = typeof pkg.clientReactRelease === 'string' ? pkg.clientReactRelease.trim() : '' + if (!tag || /[\s]/.test(tag)) { + fail(`package.json "clientReactRelease" must be one release tag, for example v0.1.0.`) + } + return tag +} + +function readRepository() { + const repository = (process.env.CLIENT_REACT_REPOSITORY || DEFAULT_REPOSITORY).trim() + if (!REPOSITORY_PATTERN.test(repository)) { + fail(`CLIENT_REACT_REPOSITORY must be owner/name. Got: ${repository}`) + } + return repository +} + +function archiveUrl(repository, tag) { + return `https://github.com/${repository}/releases/download/${encodeURIComponent(tag)}/${ARCHIVE_NAME}` +} + +async function downloadArchive(url, destination) { + const response = await fetch(url, { + redirect: 'follow', + headers: { 'User-Agent': 'audiobookshelf-fetch-client-runtime' } + }) + if (!response.ok) { + fail(`Failed to download ${url} (${response.status} ${response.statusText}). The client release must include ${ARCHIVE_NAME}.`) + } + if (!response.body) fail(`Failed to download ${url}: empty response body.`) + await pipeline(Readable.fromWeb(response.body), fs.createWriteStream(destination)) +} + +function extractArchive(archivePath, outDir) { + fs.rmSync(outDir, { recursive: true, force: true }) + fs.mkdirSync(outDir, { recursive: true }) + const result = spawnSync('tar', ['-xzf', archivePath, '-C', outDir, '--strip-components=1'], { stdio: 'inherit' }) + if (result.error) { + fail(`Failed to run tar: ${result.error.message}. tar is required to extract the client runtime.`) + } + if (result.status !== 0) { + fail(`tar exited with status ${result.status} while extracting ${archivePath}`) + } +} + +function assertRuntime(outDir) { + const required = ['node_modules/next/package.json', '.next/BUILD_ID', 'next.config.mjs'] + const missing = required.filter((relative) => !fs.existsSync(path.join(outDir, relative))) + if (missing.length) { + fail(`Extracted client runtime at ${outDir} is missing:\n${missing.join('\n')}`) + } +} + +async function main() { + const outDir = parseArgs(process.argv) + const tag = readPinnedTag() + const repository = readRepository() + const url = archiveUrl(repository, tag) + const archivePath = path.join(os.tmpdir(), `audiobookshelf-client-runtime-${process.pid}.tar.gz`) + + console.log(`Fetching React client ${tag} from ${repository}`) + console.log(url) + try { + await downloadArchive(url, archivePath) + extractArchive(archivePath, outDir) + assertRuntime(outDir) + } finally { + fs.rmSync(archivePath, { force: true }) + } + console.log(`React client runtime extracted to ${outDir}`) +} + +main().catch((error) => { + console.error(error && error.userFacing ? error.message : error && error.stack ? error.stack : String(error)) + process.exit(1) +}) diff --git a/server/Server.js b/server/Server.js index 327cc94bf..f0f263441 100644 --- a/server/Server.js +++ b/server/Server.js @@ -1,4 +1,5 @@ const Path = require('path') +const Module = require('module') const Sequelize = require('sequelize') const express = require('express') const http = require('http') @@ -68,6 +69,51 @@ function normalizeBasePath(basePath) { * one more `.server` down. Older react clients have no basePath and must keep * Express-stripped URLs. */ +/** + * Next 16's production custom server loads `start-server.js` during prepare(). + * That file loads `app-info-log.js`, which requires `inspector` at module scope + * to print a debugger URL. pkg's Node binary has no inspector, and calling the + * real builtin throws ERR_INSPECTOR_NOT_AVAILABLE. Return a stub instead of + * calling it. Outside pkg, Next gets the real module. + */ +function inspectorStub() { + const stub = { + url: () => undefined, + open() {}, + close() {}, + waitForDebugger() {}, + console + } + stub.Session = class Session { + connect() {} + disconnect() {} + post(_method, callback) { + if (typeof callback === 'function') callback(null, {}) + } + } + return stub +} + +function isInspectorRequest(id) { + return id === 'inspector' || id === 'node:inspector' +} + +function allowPkgWithoutInspector() { + if (!process.pkg || Module.prototype.require.__absInspectorPatched) return + const originalRequire = Module.prototype.require + const originalLoad = Module._load + function requireWithInspectorFallback(id) { + if (isInspectorRequest(id)) return inspectorStub() + return originalRequire.apply(this, arguments) + } + requireWithInspectorFallback.__absInspectorPatched = true + Module.prototype.require = requireWithInspectorFallback + Module._load = function (request, parent, isMain) { + if (isInspectorRequest(request)) return inspectorStub() + return originalLoad.call(this, request, parent, isMain) + } +} + function getPreparedNextBasePath(nextApp) { const nodeServer = nextApp.server?.server const basePath = nodeServer?.nextConfig?.basePath @@ -395,65 +441,43 @@ class Server { }) router.get('/healthcheck', (req, res) => res.sendStatus(200)) + // v3 serves only the React client. REACT_CLIENT_PATH is required. + // Next joins process.cwd() with dir. On Windows, path.join does not reset + // when dir is an absolute drive path, so the manifest lookup becomes + // cwd\D:\client\D:\client\.next\.... Run Next from the client directory + // and pass a relative dir. const ReactClientPath = process.env.REACT_CLIENT_PATH - if (!ReactClientPath) { - // Static path to generated nuxt - const distPath = Path.join(global.appRoot, '/client/dist') - router.use(express.static(distPath)) - - // Client dynamic routes - const dynamicRoutes = [ - '/item/:id', - '/author/:id', - '/audiobook/:id/chapters', - '/audiobook/:id/edit', - '/audiobook/:id/manage', - '/library/:library', - '/library/:library/search', - '/library/:library/bookshelf/:id?', - '/library/:library/authors', - '/library/:library/narrators', - '/library/:library/stats', - '/library/:library/series/:id?', - '/library/:library/podcast/search', - '/library/:library/podcast/latest', - '/library/:library/podcast/download-queue', - '/config/users/:id', - '/config/users/:id/sessions', - '/config/item-metadata-utils/:id', - '/collection/:id', - '/playlist/:id', - '/share/:slug' - ] - dynamicRoutes.forEach((route) => router.get(route, (req, res) => res.sendFile(Path.join(distPath, 'index.html')))) - } else { - // This is for using the experimental Next.js client - Logger.info(`Using React client at ${ReactClientPath}`) - const nextPath = Path.join(ReactClientPath, 'node_modules/next') - const next = require(nextPath) - const nextApp = next({ dev: Logger.isDev, dir: ReactClientPath }) - const handle = nextApp.getRequestHandler() - await nextApp.prepare() - const nextBasePath = getPreparedNextBasePath(nextApp) - if (nextBasePath) { - Logger.info(`[Server] Next client basePath is "${nextBasePath}"`) - } else { - Logger.info(`[Server] Next client has no basePath; leaving Express-stripped URLs as-is`) - } - router.all('*', (req, res) => { - // Next is configured with the same base path as this router, but Express strips the mount - // prefix from req.url, so put it back. The bare mount path is passed through without a - // trailing slash, which Next would otherwise redirect away from on every request. - // Skip when Next has no basePath (older client on master). - if (nextBasePath && req.baseUrl) { - const queryIndex = req.url.indexOf('?') - const pathname = queryIndex === -1 ? req.url : req.url.slice(0, queryIndex) - const search = queryIndex === -1 ? '' : req.url.slice(queryIndex) - req.url = `${req.baseUrl}${pathname === '/' ? '' : pathname}${search}` - } - handle(req, res) - }) + if (!String(ReactClientPath || '').trim()) { + throw new Error('REACT_CLIENT_PATH is required') } + const reactClientDir = Path.resolve(ReactClientPath) + process.chdir(reactClientDir) + Logger.info(`Using React client at ${reactClientDir}`) + allowPkgWithoutInspector() + const nextPath = Path.join(reactClientDir, 'node_modules', 'next') + const next = require(nextPath) + const nextApp = next({ dev: Logger.isDev, dir: '.' }) + const handle = nextApp.getRequestHandler() + await nextApp.prepare() + const nextBasePath = getPreparedNextBasePath(nextApp) + if (nextBasePath) { + Logger.info(`[Server] Next client basePath is "${nextBasePath}"`) + } else { + Logger.info(`[Server] Next client has no basePath; leaving Express-stripped URLs as-is`) + } + router.all('*', (req, res) => { + // Next is configured with the same base path as this router, but Express strips the mount + // prefix from req.url, so put it back. The bare mount path is passed through without a + // trailing slash, which Next would otherwise redirect away from on every request. + // Skip when Next has no basePath (older client on master). + if (nextBasePath && req.baseUrl) { + const queryIndex = req.url.indexOf('?') + const pathname = queryIndex === -1 ? req.url : req.url.slice(0, queryIndex) + const search = queryIndex === -1 ? '' : req.url.slice(queryIndex) + req.url = `${req.baseUrl}${pathname === '/' ? '' : pathname}${search}` + } + handle(req, res) + }) const unixSocketPrefix = 'unix/' if (this.Host?.startsWith(unixSocketPrefix)) {