# Lexidraw — single service: the timber.js (RSC + nitro) server that renders
# and serves the whole app, replacing the old nginx-static + timber-sidecar
# pair. Serving policy (CSP nonce, rate limit, caching headers) lives in
# excalidraw-app/app/proxy.ts and excalidraw-app/timber.config.ts.
# Keep in sync with ./Dockerfile.dev (draw-dev service) — only the Railway
# cache-mount service-id prefix may differ between the two.
FROM node:24-slim AS build

WORKDIR /repo

COPY . .

ENV COREPACK_ENABLE_DOWNLOAD_PROMPT=0

# pnpm has no --network-timeout flag (that was yarn); fetchTimeout is the
# equivalent setting, raised from its 60s default for slow CI networks.
ENV pnpm_config_fetch_timeout=600000

# the cache id must be prefixed with the Railway service id that builds this
# image (lexidraw-timber) — Railway rejects mismatched cache keys
RUN --mount=type=cache,id=s/934c8dcd-ba8c-4a93-9cd5-92a3f399c79d-/root/.local/share/pnpm/store,target=/root/.local/share/pnpm/store \
    corepack enable pnpm && \
    pnpm install --frozen-lockfile

# Injected by Railway from the service's variables at build time so Vite can
# bake them into the client bundle / the version meta. The key lives only in
# Railway; the sha comes from RAILWAY_GIT_COMMIT_SHA (there is no .git in the
# build context — vite.config.ts falls back to VITE_APP_GIT_SHA).
ARG VITE_APP_IROH_API_KEY
ENV VITE_APP_IROH_API_KEY=${VITE_APP_IROH_API_KEY}
ARG VITE_APP_GIT_SHA
ENV VITE_APP_GIT_SHA=${VITE_APP_GIT_SHA}

RUN pnpm -C excalidraw-app build

# The nitro bundle leaves `takumi-js` (OG-card rendering, native binding) as
# a bare external import — derive a minimal runtime manifest for it from the
# app manifest so the versions can never drift.
RUN node -e "const p=require('/repo/excalidraw-app/package.json'); \
  const out={name:'lexidraw-runtime',private:true,dependencies:{ \
    'takumi-js':p.dependencies['takumi-js'], \
    '@takumi-rs/core':p.dependencies['@takumi-rs/core']}, \
    optionalDependencies:p.optionalDependencies}; \
  require('fs').writeFileSync('/repo/runtime-package.json',JSON.stringify(out,null,2))"

FROM node:24-slim AS runtime
RUN groupadd --system timber && useradd --system --gid timber --create-home timber
WORKDIR /app

COPY --from=build --chown=timber:timber /repo/excalidraw-app/.timber/dist/nitro/.output ./.output
COPY --from=build --chown=timber:timber /repo/runtime-package.json ./package.json
RUN npm install --omit=dev --no-audit --no-fund && chown -R timber:timber node_modules

USER timber
ENV NODE_ENV=production PORT=3000 HOST=0.0.0.0
EXPOSE 3000
HEALTHCHECK CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||3000)+'/manifest.webmanifest').then(r=>process.exit(r.ok?0:1),()=>process.exit(1))"
CMD ["node", ".output/server/index.mjs"]
