# syntax=docker/dockerfile:1

# {{ parent_stack }}.{{ layer_name }}'s base image, built from a Node + TypeScript project
# (BUILD_CONTEXT in image.env) on a hardened Wolfi base. The TypeScript is compiled to
# dist/ (`npm run build`) in the build stage and the dev dependencies are pruned; the
# runtime keeps Node, the production dependencies and dist/. Each environment's overlay
# (<env>/Dockerfile) builds FROM it. The source layer's own Operations lint, test and
# scan the source; this layer builds, scans and pushes the image. The runtime runs as a
# non-root user and has no package manager.
#
# The base is pinned by digest, but `apk upgrade` and `apk add` fetch the current Wolfi
# packages on every build, so each rebuild picks up new fixes.

# The Node release line. Wolfi ships its latest patch.
ARG NODE_PACKAGE=nodejs-22
# cgr.dev/chainguard/wolfi-base:latest, pinned. Bump it by digest.
ARG WOLFI_BASE=cgr.dev/chainguard/wolfi-base@sha256:256c88bb066424045021090932d50be93c8e3f2ce3586707702a401b146f3e43

FROM ${WOLFI_BASE} AS build
ARG NODE_PACKAGE
RUN apk upgrade --no-cache && apk add --no-cache "${NODE_PACKAGE}" npm ca-certificates
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --no-audit --no-fund
COPY tsconfig.json tsconfig.build.json ./
COPY src ./src
RUN npm run build && npm prune --omit=dev --no-audit --no-fund \
    && find node_modules -depth -type d -empty -delete

FROM ${WOLFI_BASE} AS runtime
ARG NODE_PACKAGE
# Node and its CA bundle and a non-root user; then drop the package manager.
# wolfi-baselayout and busybox are added by name so that removing the wolfi-base
# meta-package (which pulls in apk) keeps them.
RUN apk upgrade --no-cache \
    && apk add --no-cache "${NODE_PACKAGE}" busybox wolfi-baselayout ca-certificates \
    && addgroup -g 1000 app \
    && adduser -D -u 1000 -G app -h /app -s /sbin/nologin app \
    && apk del --no-cache wolfi-base apk-tools wolfi-keys \
    && rm -rf /var/cache/apk /etc/apk /lib/apk
WORKDIR /app
COPY --from=build --chown=1000:1000 /app/node_modules ./node_modules
COPY --from=build --chown=1000:1000 /app/dist ./dist
COPY --chown=1000:1000 package.json ./

ENV NODE_ENV=production \
    PORT={{ container_port }}
USER 1000
EXPOSE {{ container_port }}
CMD ["node", "dist/index.js"]
