version: 2

defaults: &defaults
  working_directory: ~/repo
  docker:
    - image: circleci/node:10

jobs:
  build:
    <<: *defaults
    steps:
      - checkout
      - restore_cache:
          keys:
            - v1-dependencies-{{ checksum "package.json" }}
            - v1-dependencies-
      - run: npm install --force
      - save_cache:
          paths:
            - node_modules
          key: v1-dependencies-{{ checksum "package.json" }}
      - run: npm run lint
      - run:
          name: Jest Suite
          command: npm test -- --ci --testResultsProcessor="jest-junit"
          environment:
            JEST_JUNIT_OUTPUT: "reports/junit/js-test-results.xml"
      - store_test_results:
          path: reports
      - persist_to_workspace:
          root: ~/repo
          paths: .
  deploy:
    <<: *defaults
    steps:
      - attach_workspace:
          at: ~/repo
      - run:
          name: Prepare
          command: npm run prepare
      - run:
          name: Authenticate with registry
          command: echo "//registry.npmjs.org/:_authToken=$NPM_TOKEN" > ~/repo/.npmrc
      - run:
          name: Publish package
          command: npm publish

workflows:
  version: 2
  build-and-deploy:
    jobs:
      - build:
          filters:
            tags:
              only: /.*/
      - deploy:
          context: open-source
          requires:
            - build
          filters:
            tags:
              only: /^v.*/
            branches:
              ignore: /.*/
