// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

/**
 * Stringify an object into a valid `.env` file format.
 *
 * @example Usage
 * ```ts
 * import { stringify } from "@std/dotenv/stringify";
 * import { assertEquals } from "@std/assert";
 *
 * const object = { GREETING: "hello world" };
 * assertEquals(stringify(object), "GREETING='hello world'");
 * ```
 *
 * @param object object to be stringified
 * @returns string of object
 */
export function stringify(object: Record<string, string>): string {
  const lines: string[] = [];
  for (const [key, value] of Object.entries(object)) {
    let quote;

    let escapedValue = value ?? "";
    if (key.startsWith("#")) {
      console.warn(
        `key starts with a '#' indicates a comment and is ignored: '${key}'`,
      );
      continue;
    } else if (escapedValue.includes("\n")) {
      // escape inner new lines
      escapedValue = escapedValue.replaceAll("\n", "\\n");
      quote = `"`;
    } else if (escapedValue.match(/\W/)) {
      quote = "'";
    }

    if (quote) {
      // escape inner quotes
      escapedValue = escapedValue.replaceAll(quote, `\\${quote}`);
      escapedValue = `${quote}${escapedValue}${quote}`;
    }
    const line = `${key}=${escapedValue}`;
    lines.push(line);
  }
  return lines.join("\n");
}

// denoCacheMetadata={"headers":{"date":"Tue, 28 Jul 2026 12:31:14 GMT","content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","etag":"\"67e50df9b57848466d9dcc46021d7d29\"","alt-svc":"h3=\":443\"; ma=86400","x-robots-tag":"noindex","cross-origin-resource-policy":"cross-origin","content-type":"text/typescript","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=4Pzgku9SkoWsxrfFSeCvTwkcCnyVc7Bu5dXz%2BU1GbQGgDhR67rIuZxlz2mpReMM2j%2FQ8hHfob1vfJ0cLqlNy20BHfUkK22aQIBNaYL%2BIgBVprB%2Brwvh6uks%3D\"}]}","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","content-length":"1359","set-cookie":"__cf_bm=4xTO8u8f6DRKb.I9FuO4CIBW.kUBi9hB_Pc63O9rzoY-1785241874.9731534-1.0.1.1-x0xP_zHi85qPDShoZmK8dyAsw2_FKxzlNnbmV4KRcSMmxsod8K0Mu_j2ecnwMtTFGPncWZVIap5ruUOeYzU4pXmgV3fw.._aOuYfQG.SX8DEngpuzzeGPh7xkoHhJozJ; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:14 GMT","access-control-allow-origin":"*","access-control-expose-headers":"*","age":"43236","cf-cache-status":"HIT","vary":"Origin","x-content-type-options":"nosniff","x-jsr-backend":"modules","cf-ray":"a223e6564f677db6-LAX","cache-control":"public, max-age=31536000, immutable","accept-ranges":"bytes","server":"cloudflare"},"url":"https://jsr.io/@std/dotenv/0.224.2/stringify.ts","time":1785241874}