writePolicy = async (file, policy, { fs = nodeFs } = {}) => {
  const filepath = toPath(file)
  const policyDir = nodePath.dirname(filepath)
  /**
   * @type {string | undefined}
   */
  let createdDir
  try {
    // eslint-disable-next-line @jessie.js/safe-await-separator
    createdDir = await fs.promises.mkdir(policyDir, {
      recursive: true,
    })
  } catch (err) {
    throw new Error(`Failed to create policy directory ${hrPath(policyDir)}`, {
      cause: err,
    })
  }
  try {
    await fs.promises.writeFile(filepath, jsonStringifySortedPolicy(policy))
  } catch (err) {
    if (createdDir) {
      try {
        await fs.promises.rm(createdDir, { recursive: true })
      } catch (err) {
        const rmErr = new Error(
          `Failed to remove created directory ${hrPath(createdDir)}`,
          { cause: err }
        )
        throw new AggregateError([err, rmErr])
      }
    }
    throw err
  }
}
Writes a diff-friendly LavaMoat policy to file

Creates the destination directory if it does not exist

@param {string | URL} file Path to write to
@param {LavaMoatPolicy | LavaMoatPolicyDebug | LavaMoatPolicy} policy Any
  policy
@param {{ fs?: WritableFsInterface }} opts Options
@returns {Promise<void>}
@internal