// 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 } from "../type.ts";
import type { Any } from "../_utils.ts";

// Note: original implementation used Esprima to handle functions
// To avoid dependencies, we'll just try to check if we can construct a function from given string
function reconstructFunction(code: string) {
  const func = new Function(`return ${code}`)();
  if (!(func instanceof Function)) {
    throw new TypeError(`Expected function but got ${typeof func}: ${code}`);
  }
  return func;
}

export const func = new Type("tag:yaml.org,2002:js/function", {
  kind: "scalar",
  resolve(data: Any) {
    if (data === null) {
      return false;
    }
    try {
      reconstructFunction(`${data}`);
      return true;
    } catch (_err) {
      return false;
    }
  },
  construct(data: string) {
    return reconstructFunction(data);
  },
  predicate(object: unknown) {
    return object instanceof Function;
  },
  represent(object: (...args: Any[]) => Any) {
    return object.toString();
  },
});

// denoCacheMetadata={"headers":{"x-robots-tag":"noindex","x-jsr-backend":"modules","content-type":"text/typescript","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","access-control-allow-origin":"*","date":"Tue, 28 Jul 2026 12:31:15 GMT","cf-ray":"a223e6589ce47db6-LAX","age":"1613543","cf-cache-status":"HIT","x-content-type-options":"nosniff","set-cookie":"__cf_bm=MM4ysXn50KZjKT6rxAD1CDHwTotfsWwbEjDYKMewsqo-1785241875.2977965-1.0.1.1-InQnm_z4xKf8hQF0eFnwF5BzRiJKIxvZadZH13oohBeesf1prnZ9ibmcblcLNbFDtPyH.dFmKTyL3ZuIK0v7smjQAV_ZLKMULmHcGoOSDwonBTICjwJtNlGhEFLUnHD0; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","etag":"\"2d75ae3767f34079645bd6c10e4bb3f2\"","vary":"Origin","server":"cloudflare","accept-ranges":"bytes","content-length":"1275","cache-control":"public, max-age=31536000, immutable","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';","cross-origin-resource-policy":"cross-origin","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=sGXq9ovWP90tcijcw8L6JGYOyR%2Fe5473vyJXW0XDcLilDjJ1moSLWNc7j4ghIJjUFJU%2BWF2iOSxL37lkjq5JWxUZGfCutl%2FFm1I2IOFerORmgMv%2FAybufLs%3D\"}]}","alt-svc":"h3=\":443\"; ma=86400","access-control-expose-headers":"*"},"url":"https://jsr.io/@std/yaml/0.224.3/_type/function.ts","time":1785241875}