// Ported and adapted from js-yaml-js-types v1.0.0:
// https://github.com/nodeca/js-yaml-js-types/tree/ac537e7bbdd3c2cbbd9882ca3919c520c2dc022b
// Copyright 2011-2015 by Vitaly Puzrin. All rights reserved. MIT license.
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.

import type { Type } from "../_type.ts";

const REGEXP = /^\/(?<regexp>[\s\S]+)\/(?<modifiers>[gismuy]*)$/;

export const regexp: Type<"scalar", RegExp> = {
  tag: "tag:yaml.org,2002:js/regexp",
  kind: "scalar",
  resolve(data: string | null): boolean {
    if (data === null || !data.length) return false;

    if (data.charAt(0) === "/") {
      // Ensure regex is properly terminated
      const groups = data.match(REGEXP)?.groups;
      if (!groups) return false;
      // Check no duplicate modifiers
      const modifiers = groups.modifiers ?? "";
      if (new Set(modifiers).size < modifiers.length) return false;
    }

    return true;
  },
  construct(data: string): RegExp {
    const { regexp = data, modifiers = "" } = data.match(REGEXP)?.groups ?? {};
    return new RegExp(regexp, modifiers);
  },
  predicate: (object: unknown): object is RegExp => object instanceof RegExp,
  represent: (object: RegExp): string => object.toString(),
};

// denoCacheMetadata={"headers":{"x-jsr-backend":"modules","access-control-allow-origin":"*","cache-control":"public, max-age=31536000, immutable","vary":"Origin","content-type":"text/typescript","cross-origin-resource-policy":"cross-origin","x-robots-tag":"noindex","set-cookie":"__cf_bm=VlymwVEaRqZ3cVrFwMQ4G9vJ_NotlTVBNssCGn48.Os-1785241875.3738441-1.0.1.1-JP82kw.m4Y9KnanFojezwKU2GU869JR73gcWyaqG_r0hE5D6.AvXaWb6JHuFoA2OqugbN5t1wOAoykiMRZFOucxlb2W2wc4_jSNVXaJhDCsWumUmIt67Mn4Kzl1BEdH9; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","date":"Tue, 28 Jul 2026 12:31:15 GMT","cf-cache-status":"HIT","cf-ray":"a223e6590e597db6-LAX","age":"4275641","etag":"\"853c14aea04447085332229d26ec246f\"","accept-ranges":"bytes","x-content-type-options":"nosniff","content-length":"1252","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=bzYqatnpfysOmrCr%2FAxGxPPqHVzsgy6BBle1ysYC%2FJ6pQkEmyN7AcDv7TFXPU8t%2Bv6Na12D8AVnT1yDU%2FYl%2FfJ3SibDiXnGTSgNgp3yaMUoXzNlqbuER318%3D\"}]}","alt-svc":"h3=\":443\"; ma=86400","access-control-expose-headers":"*","server":"cloudflare","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';"},"url":"https://jsr.io/@std/yaml/1.0.5/_type/regexp.ts","time":1785241875}