version: 2.1
jobs:
  build:
    docker:
      - image: cimg/node:current
    working_directory: ~/repo
    steps:
      - checkout
      - restore_cache:
          key: dependency-cache-{{ checksum "package-lock.json" }}
      - run:
          name: Install dependencies
          command: npm ci
      - save_cache:
          key: dependency-cache-{{ checksum "package-lock.json" }}
          paths:
            - ./node_modules
      - run:
          name: Ensure coding standards
          command: |
            npm run style
            npm run lint
      - run:
          name: Run tests
          command: |
            mkdir -p ~/repo/test_results
            npm run test:ci
      - store_test_results:
          path: ~/repo/test_results
      - run: npm pack
      - run:
          command: |
            mkdir -p /tmp/circle-artifacts
            cp *.tgz /tmp/circle-artifacts
      - store_artifacts:
          path: /tmp/circle-artifacts
      - run:
          name: Move compiled app to workspace
          command: |
            set -exu
            mkdir -p /tmp/workspace/pkg
            mv *.tgz /tmp/workspace/pkg/
      - persist_to_workspace:
          root: /tmp/workspace
          paths:
            - pkg
  deploy:
    docker:
      - image: cimg/node:current
    working_directory: ~/repo
    steps:
      - attach_workspace:
          at: /tmp/workspace
      - checkout
      - run:
          name: Authenticate with registry
          command: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > ~/repo/.npmrc
      - run:
          name: Publish package
          command: npm publish $(echo /tmp/workspace/pkg/*.tgz)
workflows:
  build-and-deploy:
    jobs:
      - build
      - hold:
          type: approval
          requires:
            - build
          filters:
            branches:
              only: main
      - deploy:
          context: npm
          requires:
            - hold
