gulp.config.mjsjavascript
/**
 * Modify these configurations to match your project specifications.
 * @file
 * @author Joshua Heagle <joshuaheagle@gmail.com>
 * @version 3.0.0
 * @module gulpConfig
 * @memberOf module:js-build-tools
 */
import { fileExists } from 'test-filesystem'

/**
 * A setting that may be an array of strings or a string only.
 * @typedef {Array<string>|string} module:gulpConfig~ArrayableSetting
 */
/**
 * A setting that may be true or false.
 * @typedef {boolean} module:gulpConfig~BooleanSetting
 */
/**
 * A setting that may be flag 'false' or provide a number
 * @typedef {false|number} module:gulpConfig~FlagNumberSetting
 */
/**
 * A setting that may be flag 'false' or provide a StringSetting
 * @typedef {false|StringSetting} module:gulpConfig~FlagStringSetting
 */
/**
 * An object of boolean settings used as flags.
 * @typedef {Object<string, BooleanSetting>} module:gulpConfig~FlagsSetting
 */
/**
 * Configure cli options for running Jest.
 * @typedef {FlagsSetting} module:gulpConfig~JestTestFlags
 * @property {BooleanSetting} clearCache
 * @property {BooleanSetting} debug
 * @property {BooleanSetting} ignoreProjects:
 * @property {BooleanSetting} json
 * @property {BooleanSetting} selectProjects
 * @property {BooleanSetting} showConfig
 * @property {BooleanSetting} useStderr
 * @property {BooleanSetting} watch
 * @property {BooleanSetting} watchAll
 */
/**
 * A setting that may only be a string.
 * @typedef {string} module:gulpConfig~StringSetting
 */
/**
 * Any single configuration option is a Setting.
 * @typedef {ArrayableSetting|BooleanSetting|FlagNumberSetting|FlagsSetting|StringSetting} Setting
 */
/**
 * One copy-files entry: a glob (or array of globs) to copy, and where to copy it.
 * @typedef {Object} module:gulpConfig~CopyFilesEntry
 * @property {ArrayableSetting} from - The glob pattern(s) of files to copy.
 * @property {StringSetting} to - The directory to copy them into.
 * @property {FlagStringSetting} base - Optional base for gulp's own src(pattern, {base}), to preserve a glob's
 * own subdirectory structure in the destination instead of flattening it. false (the default) uses gulp's own
 * default base behaviour.
 */
/**
 * Configurations for building the browser files.
 * @typedef {Object<string, Setting>} module:gulpConfig~BrowserConfig
 * @property {BooleanSetting} enabled - 'true' to generate browser bundled files; 'false' for node environment only
 * @property {StringSetting} from - The search pattern used for retrieving compiled distribution files.
 * @property {StringSetting} name - The name to use for the browser-bundled output file (.js will be appended).
 * @property {StringSetting} to - The output directory for browser-bundled files.
 * @property {ArrayableSetting} ignore - Module names or file paths which resolve to an empty object ({}) in the
 * bundle instead of their real contents. For a dependency which is only reached because it is the default value of
 * an option you always override (for example a selector engine's default DOM adapter, when you always pass your
 * own), this keeps it (and anything only it requires) out of the bundle, as long as your code never actually reaches
 * the real module by not overriding that option. Matches browserify's b.ignore(file): a module name (also any file
 * inside that package), or a file path with its extension, starting with './' or '/'.
 * @property {ArrayableSetting} exclude - Module names or file paths left out of the bundle entirely; requiring one at
 * runtime throws unless something else provides it (for example a script tag loading it separately). Passed to
 * esbuild's `external` (a module name also covers its subpaths, such as `name/lib/file`).
 * @property {Array<module:gulpConfig~AdditionalBundleConfig>} bundles - Additional bundles to produce alongside the
 * primary one (name/dist.main/ignore/exclude above) - for example a render-only variant built from a different
 * entry point than the full bundle. Empty by default: a project that never sets this gets exactly the one bundle it
 * always did.
 */
/**
 * One additional bundle - everything but `name` falls back to the primary bundle's own value when omitted, so an
 * additional bundle only has to specify what's actually different about it.
 * @typedef {Object<string, Setting>} module:gulpConfig~AdditionalBundleConfig
 * @property {StringSetting} name - The name for this bundle's output file and standalone export - must be unique
 * among all of a project's bundles.
 * @property {StringSetting} [main] - This bundle's own entry point. Falls back to dist.main when omitted.
 * @property {ArrayableSetting} [ignore] - This bundle's own ignore list. Falls back to browser.ignore when omitted.
 * @property {ArrayableSetting} [exclude] - This bundle's own exclude list. Falls back to browser.exclude when omitted.
 */
/**
 * Configurations for building the node distribution files.
 * @typedef {Object<string, Setting>} module:gulpConfig~DistConfig
 * @property {StringSetting} from - The search pattern used for gathering source files for distribution.
 * @property {StringSetting} main - Name of the entry the distribution file.
 * @property {StringSetting} to - The output directory for the distribution files.
 */
/**
 * Configurations for copying the font files.
 * @typedef {Object<string, Setting>} module:gulpConfig~FontConfig
 * @property {BooleanSetting} enabled - Toggle copy directory of fonts on.
 * @property {StringSetting} from - Path to search for fonts.
 * @property {StringSetting} to - Path to output fonts.
 */
/**
 * Configurations to minify and copy the images.
 * @typedef {Object<string, Setting>} module:gulpConfig~ImageConfig
 * @property {StringSetting} cacheDir - Where optimized images are cached between runs, so an image that hasn't
 * changed isn't optimized again. An upgrade of imagemin (or its plugins) or other settings starts new results. Inside
 * node_modules by default, so it's never committed; old entries aren't pruned, so delete it now and then to start
 * over.
 * @property {BooleanSetting} enabled - Toggle image minify and copy process.
 * @property {StringSetting} from - Path to search for images.
 * @property {FlagNumberSetting} jpegQuality - The JPEG quality (0 to 100) mozjpeg compresses to. False (the
 * default) keeps mozjpeg's own default, 75. Raise it (85 is usually indistinguishable from the original) when 75
 * visibly bands smooth gradients.
 * @property {StringSetting} to - Path to output images.
 */
/**
 * Configurations for linting (see {@link module:partials.neostandardLint}).
 * @typedef {Object<string, Setting>} module:gulpConfig~LintConfig
 * @property {ArrayableSetting} include - Extra folders to lint alongside srcPath, for hand-written code that lives
 * outside it (for example `scripts`). Linted with the same rules, and fixed in place, like srcPath. Empty by default:
 * a project that never sets this lints srcPath only, as before.
 * @property {Object<string, *>} rules - ESLint rule overrides layered on top of neostandard's own config, scoped
 * to the same files neostandard itself lints. For a rule that is wrong for your project specifically (for example
 * a test fixture that deliberately contains text neostandard mistakes for a real syntax problem), rather than
 * something to fix in your code. Empty by default: a project that never sets this gets exactly neostandard's own
 * rules, unchanged. Keyed and valued exactly as ESLint's own `rules` object - see
 * https://eslint.org/docs/latest/use/configure/rules.
 */
/**
 * Configurations to compile and generate the Readme file.
 * @typedef {Object<string, Setting>} module:gulpConfig~ReadmeConfig
 * @property {BooleanSetting} enabled - Generate the readme from the jsdoc comments, in build and in the readme task.
 * False (the default) keeps a hand-written readme, or none. Independent of docs.enabled: turn on either, both, or
 * neither.
 * @property {StringSetting} file - The name of the output documentation markdown file.
 * @property {StringSetting} from - Location of files to use for compiling documentation into the readme.
 * @property {ArrayableSetting} fromEsm - Additional `.mjs` files to document alongside `from`, converted on the
 * fly since the readme generator only recognizes `.js` files - see 'Configure including ESM files in the
 * generated readme'. Empty by default: a project that never sets this gets exactly the readme it always did.
 * @property {ArrayableSetting} options - Options for formatting the output readme.
 * @property {StringSetting} template - The file which will be pre-fixed to your README.md output. When it doesn't
 * exist, the readme holds only the generated documentation.
 * @property {StringSetting} to - The directory to output the readme file in.
 */
/**
 * Configurations for generating the HTML documentation of a project's own source, with either TypeDoc (real
 * TypeScript types) or jsdoc (a modern theme over jsdoc's own classic default) - see docs.method.
 * @typedef {Object<string, Setting>} module:gulpConfig~DocsConfig
 * @property {FlagStringSetting} basePath - The path the documentation is served from, such as '/projects/my-lib/docs/'
 * (jsdoc with clean-jsdoc-theme 5.x only). The theme's links start at the site root, so documentation served below it
 * needs this. False (the default) serves it from the site root.
 * @property {FlagStringSetting} bodyHtml - HTML added to every page of the documentation just before `</body>`, with
 * either engine, for example the analytics script the rest of the site has. False (the default) adds nothing.
 * @property {BooleanSetting} enabled - Toggle generating the documentation from the source. Independent of
 * readme.enabled: turn on either, both, or neither.
 * @property {ArrayableSetting} from - The directory holding the source, each folder in it becomes a module (TypeDoc) or
 * is scanned recursively (jsdoc). jsdoc also takes a list of directories and files.
 * @property {FlagStringSetting} gitRevision - The git revision TypeDoc's "Defined in" source links point to (TypeDoc
 * only). False (the default) is TypeDoc's own: the current commit, which changes every page on every commit. A
 * branch name such as 'main' keeps the pages unchanged until the documentation itself changes; '{branch}' is the
 * branch being built.
 * @property {FlagStringSetting} headHtml - HTML added to every page of the documentation just before `</head>`, with
 * either engine. False (the default) adds nothing.
 * @property {BooleanSetting} inBuild - Generate the documentation as part of build (the default). Turn it off to only
 * generate it when you run the docs task yourself (gulp docs), for example when docs.to points into another
 * repository and you only want to publish the documentation of a release.
 * @property {StringSetting} index - The markdown file used as the front page of the documentation.
 * @property {StringSetting} logLevel - How much TypeDoc reports: Verbose, Info, Warn, Error or None. Not used by jsdoc.
 * @property {FlagStringSetting} method - 'typedoc' or 'jsdoc'. False (the default) infers it from typescript.enabled -
 * 'typedoc' when on, 'jsdoc' when off - so an existing TypeScript project's config needs no change to keep working
 * exactly as it already does; set this explicitly to override that inference either way.
 * @property {StringSetting} theme - The jsdoc theme package to use (only meaningful when method is 'jsdoc' - TypeDoc
 * keeps its own default regardless). Defaults to 'clean-jsdoc-theme'.
 * @property {StringSetting} title - The name of the documentation, defaults to the name in the package.json.
 * @property {StringSetting} to - The directory to generate the documentation in (it is cleared first).
 * @property {FlagStringSetting} tsconfig - The tsconfig file to read the source with (TypeDoc only), defaults to the
 * one of typescript.config.
 */
/**
 * Configurations to compile and copy the sass files into css.
 * @typedef {Object<string, Setting>} module:gulpConfig~SassConfig
 * @property {BooleanSetting} enabled - Toggle SASS to CSS process on.
 * @property {StringSetting} from - The pattern for finding all sass files.
 * @property {StringSetting} path - The directory were sass files will be stored.
 * @property {StringSetting} to - The destination path for where generated CSS (from SASS files) should go.
 */
/**
 * Configurations for running the test suite.
 * @typedef {Object<string, Setting>} module:gulpConfig~TestConfig
 * @property {JestTestFlags} options - Additional flags for programmatically running Jest Cli.
 * @property {ArrayableSetting} path - The directory where Jest test files are stored.
 * By default, stored as *.test.js adjacent to the files they are testing.
 * @property {ArrayableSetting} watch - The search pattern for watching files for changes.
 */
/**
 * Configurations for compiling typescript into JS files.
 * @typedef {Object<string, Setting>} module:gulpConfig~TsConfig
 * @property {FlagStringSetting} config - The path the tsconfig file for running typescript or false if no ts file given.
 * @property {BooleanSetting} enabled - Toggle usage of typescript parsing.
 * @property {StringSetting} from - Pattern for finding the TypeScript files.
 * @property {StringSetting} to - Directory where parsed typescript files go.
 */
/**
 * A set of Configurations options defined by Settings.
 * @typedef {Object<string, Setting>} module:gulpConfig~Configurations
 * @property {BrowserConfig} browser - Browser bundling configuration group.
 * @property {ArrayableSetting} cleanPaths - The paths for directories to delete before build.
 * @property {Array<CopyFilesEntry>} copyFiles - Files to copy elsewhere, run via the copyFiles task - never
 * automatically as part of build, since what this copies is often the live, publicly-reachable version of
 * something (e.g. a bundle), and publishing it should be a deliberate step.
 * @property {DistConfig} dist - Distribution file generation configuration group.
 * @property {DocsConfig} docs - Generate the documentation of a TypeScript project configuration group.
 * @property {FontConfig} fonts - Fonts copy configuration group.
 * @property {ImageConfig} images - Minify and copy the images configuration.
 * @property {LintConfig} lint - Linting configuration group.
 * @property {ReadmeConfig} readme - Build readme files configuration.
 * @property {StringSetting} rootPath - Base directory of the project.
 * @property {SassConfig} sass - Compile CSS from SASS configuration.
 * @property {StringSetting} srcPath - The directory where your source files are stored (the files you manually created).
 * @property {TestConfig} test - Run test suite configuration.
 * @property {TsConfig} typescript - Compile from typescript configuration.
 */
import { dotGet } from './functions/utilities/dotGet.mjs'
import { dotSet } from './functions/utilities/dotSet.mjs'
import { dotNotate } from './functions/utilities/dotNotate.mjs'
import { readFileSync } from 'fs'

const setDefaults = {
  browser: {
    bundles: [],
    enabled: true,
    exclude: [],
    from: 'dist/**/*.js',
    ignore: [],
    name: 'default',
    to: 'browser',
  },
  cleanPaths: ['dist', 'browser'],
  copyFiles: [],
  dist: {
    from: 'src/**/!(*.test).js',
    main: 'dist/main',
    to: 'dist',
  },
  docs: {
    basePath: false,
    bodyHtml: false,
    enabled: false,
    from: 'src',
    gitRevision: false,
    headHtml: false,
    inBuild: true,
    index: 'MAIN.md',
    logLevel: 'Warn',
    method: false,
    theme: 'clean-jsdoc-theme',
    title: '',
    to: 'docs',
    tsconfig: false,
  },
  fonts: {
    enabled: false,
    from: 'src/fonts/**/*',
    to: 'browser/fonts',
  },
  images: {
    cacheDir: 'node_modules/.cache/js-build-tools/images',
    enabled: false,
    from: 'src/img/**/*.+(png|jpg|jpeg|gif|svg)',
    jpegQuality: false,
    to: 'browser/img',
  },
  lint: {
    include: [],
    rules: {},
  },
  readme: {
    enabled: false,
    file: 'README.md',
    from: 'src/**/!(*.test).js',
    fromEsm: [],
    options: 'utf8',
    template: 'MAIN.md',
    to: './'
  },
  rootPath: './',
  sass: {
    enabled: false,
    from: 'sass/**/*.+(scss|sass)',
    path: 'sass',
    to: 'browser/css',
  },
  srcPath: 'src',
  test: {
    options: {
      clearCache: false,
      debug: false,
      ignoreProjects: false,
      json: false,
      selectProjects: false,
      showConfig: false,
      useStderr: false,
      watch: false,
      watchAll: false,
    },
    path: ['src'],
    watch: 'src/**/*.js'
  },
  typescript: {
    config: false,
    enabled: false,
    from: 'src/**/*.ts',
    to: 'dist',
  },
}

/**
 * All the available configuration setting options for running the build.
 * @memberOf module:gulpConfig` `
 * @type {Configurations}
 */
// Starts empty: with no build-tools.config.json, every setting falls back to its default below
let gulpConfigurations = {}
if (fileExists(process.cwd() + '/build-tools.config.json')) {
  gulpConfigurations = JSON.parse(readFileSync(process.cwd() + '/build-tools.config.json').toString())
} else {
  if (fileExists('./build-tools.config.json')) {
    gulpConfigurations = JSON.parse(readFileSync('./build-tools.config.json').toString())
  } else {
    console.warn('Missing build-tools.config.json in your project root, using the default settings')
  }
}

const notation = dotNotate(setDefaults)
for (let notationKey in notation) {
  const arrayEnding = /(\.\d+)$/
  if (arrayEnding.test(notationKey)) {
    // ends in number a key then it must be an array; use the entire array
    notationKey = notationKey.replace(arrayEnding, '')
  }
  const defaultValue = dotGet(setDefaults, notationKey)
  const existingConfig = dotGet(gulpConfigurations, notationKey, defaultValue)
  dotSet(gulpConfigurations, notationKey, existingConfig)
}

/**
 * Retrieve a value from the configurations, default may be returned.
 * @memberOf module:gulpConfig
 * @param {string|null} path
 * @param {*} defaultValue
 * @returns {*|null}
 */
export const get = (path = null, defaultValue = null) => dotGet(gulpConfigurations, path, defaultValue)

/**
 * Specify a value for the configurations to use.
 * @memberOf module:gulpConfig
 * @param path
 * @param value
 * @returns {*}
 */
export const set = (path, value) => dotSet(gulpConfigurations, path, value)