{"version":3,"sources":["../../../src/server/node-environment-extensions/console-dim.external.tsx"],"sourcesContent":["import * as inspector from 'node:inspector'\nimport { dim } from '../../lib/picocolors'\nimport {\n  consoleAsyncStorage,\n  type ConsoleStore,\n} from '../app-render/console-async-storage.external'\nimport { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.external'\nimport { getServerReact, getClientReact } from '../runtime-reacts.external'\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars -- we may use later and want parity with the HIDDEN_STYLE value\nconst DIMMED_STYLE = 'dimmed'\nconst HIDDEN_STYLE = 'hidden'\n\ntype LogStyle = typeof DIMMED_STYLE | typeof HIDDEN_STYLE\n\nlet currentAbortedLogsStyle: LogStyle = 'dimmed'\nexport function setAbortedLogsStyle(style: LogStyle) {\n  currentAbortedLogsStyle = style\n}\n\ntype InterceptableConsoleMethod =\n  | 'error'\n  | 'assert'\n  | 'debug'\n  | 'dir'\n  | 'dirxml'\n  | 'group'\n  | 'groupCollapsed'\n  | 'groupEnd'\n  | 'info'\n  | 'log'\n  | 'table'\n  | 'trace'\n  | 'warn'\n\nconst isColorSupported = dim('test') !== 'test'\n\n// 50% opacity for dimmed text\nconst dimStyle = 'color: color(from currentColor xyz x y z / 0.5);'\nconst reactBadgeFormat = '\\x1b[0m\\x1b[7m%c%s\\x1b[0m%c '\n\nfunction dimmedConsoleArgs(...inputArgs: any[]): any[] {\n  if (!isColorSupported) {\n    return inputArgs\n  }\n\n  const newArgs = inputArgs.slice(0)\n  let template = ''\n  let argumentsPointer = 0\n  if (typeof inputArgs[0] === 'string') {\n    const originalTemplateString = inputArgs[0]\n    // Remove the original template string from the args.\n    newArgs.splice(argumentsPointer, 1)\n    argumentsPointer += 1\n\n    let i = 0\n    if (originalTemplateString.startsWith(reactBadgeFormat)) {\n      i = reactBadgeFormat.length\n      // for `format` we already moved the pointer earlier\n      // style, badge, reset style\n      argumentsPointer += 3\n      template += reactBadgeFormat\n      // React's badge reset styles, reapply dimming\n      template += '\\x1b[2m%c'\n      // argumentsPointer includes template\n      newArgs.splice(argumentsPointer - 1, 0, dimStyle)\n      // dim the badge\n      newArgs[0] += `;${dimStyle}`\n    }\n\n    for (i; i < originalTemplateString.length; i++) {\n      const currentChar = originalTemplateString[i]\n      if (currentChar !== '%') {\n        template += currentChar\n        continue\n      }\n\n      const nextChar = originalTemplateString[i + 1]\n      ++i\n\n      switch (nextChar) {\n        case 'f':\n        case 'O':\n        case 'o':\n        case 'd':\n        case 's':\n        case 'i':\n        case 'c':\n          ++argumentsPointer\n          template += `%${nextChar}`\n          break\n        default:\n          template += `%${nextChar}`\n      }\n    }\n  }\n\n  for (\n    argumentsPointer;\n    argumentsPointer < inputArgs.length;\n    ++argumentsPointer\n  ) {\n    const arg = inputArgs[argumentsPointer]\n    const argType = typeof arg\n    if (argumentsPointer > 0) {\n      template += ' '\n    }\n    switch (argType) {\n      case 'boolean':\n      case 'string':\n        template += '%s'\n        break\n      case 'bigint':\n        template += '%s'\n        break\n      case 'number':\n        if (arg % 0) {\n          template += '%f'\n        } else {\n          template += '%d'\n        }\n        break\n      case 'object':\n        template += '%O'\n        break\n      case 'symbol':\n      case 'undefined':\n      case 'function':\n        template += '%s'\n        break\n      default:\n        // deopt to string for new, unknown types\n        template += '%s'\n    }\n  }\n\n  template += '\\x1b[22m'\n\n  return [dim(`%c${template}`), dimStyle, ...newArgs]\n}\n\nfunction convertToDimmedArgs(\n  methodName: InterceptableConsoleMethod,\n  args: any[]\n): any[] {\n  // When the Node.js inspector is open (e.g. --inspect), skip dimming entirely.\n  // Dimming wraps arguments in a format string which defeats inspector\n  // affordances such as collapsible objects and clickable/linkified stack\n  // traces. Ideally we would only skip dimming when a debugger frontend is\n  // actually attached, but Node.js does not expose a synchronous API for that.\n  // Detecting would require async polling of the /json/list HTTP endpoint.\n  if (inspector.url() !== undefined) {\n    return args\n  }\n\n  switch (methodName) {\n    case 'dir':\n    case 'dirxml':\n    case 'group':\n    case 'groupCollapsed':\n    case 'groupEnd':\n    case 'table': {\n      // These methods cannot be colorized because they don't take a formatting string.\n      return args\n    }\n    case 'assert': {\n      // assert takes formatting options as the second argument.\n      return [args[0]].concat(...dimmedConsoleArgs(args[1], ...args.slice(2)))\n    }\n    case 'error':\n    case 'debug':\n    case 'info':\n    case 'log':\n    case 'trace':\n    case 'warn':\n      return dimmedConsoleArgs(args[0], ...args.slice(1))\n    default:\n      return methodName satisfies never\n  }\n}\n\n// Based on https://github.com/facebook/react/blob/28dc0776be2e1370fe217549d32aee2519f0cf05/packages/react-server/src/ReactFlightServer.js#L248\nfunction patchConsoleMethod(methodName: InterceptableConsoleMethod): void {\n  const descriptor = Object.getOwnPropertyDescriptor(console, methodName)\n  if (\n    descriptor &&\n    (descriptor.configurable || descriptor.writable) &&\n    typeof descriptor.value === 'function'\n  ) {\n    const originalMethod = descriptor.value\n    const originalName = Object.getOwnPropertyDescriptor(originalMethod, 'name')\n    const wrapperMethod = function (this: typeof console, ...args: any[]) {\n      const consoleStore = consoleAsyncStorage.getStore()\n\n      // First we see if there is a cache signal for our current scope. If we're in a client render it'll\n      // come from the client React cacheSignal implementation. If we are in a server render it'll come from\n      // the server React cacheSignal implementation. Any particular console call will be in one, the other, or neither\n      // scope and these signals return null if you are out of scope so this can be called from a single global patch\n      // and still work properly.\n      const signal =\n        getClientReact()?.cacheSignal() ?? getServerReact()?.cacheSignal()\n      if (signal) {\n        // We are in a React Server render and can consult the React cache signal to determine if logs\n        // are now dimmable.\n        if (signal.aborted) {\n          if (currentAbortedLogsStyle === HIDDEN_STYLE) {\n            return\n          }\n          return applyWithDimming.call(\n            this,\n            consoleStore,\n            originalMethod,\n            methodName,\n            args\n          )\n        } else if (consoleStore?.dim === true) {\n          return applyWithDimming.call(\n            this,\n            consoleStore,\n            originalMethod,\n            methodName,\n            args\n          )\n        } else {\n          return originalMethod.apply(this, args)\n        }\n      }\n\n      // We need to fall back to checking the work unit store for two reasons.\n      // 1. Client React does not yet implement cacheSignal (it always returns null)\n      // 2. route.ts files aren't rendered with React but do have prerender semantics\n      // TODO in the future we should be able to remove this once there is a runnable cache\n      // scope independent of actual React rendering.\n      const workUnitStore = workUnitAsyncStorage.getStore()\n      switch (workUnitStore?.type) {\n        case 'prerender':\n        case 'prerender-runtime':\n        // These can be hit in a route handler. In the future we can use potential React.createCache API\n        // to create a cache scope for arbitrary computation and can move over to cacheSignal exclusively.\n        // fallthrough\n        case 'prerender-client':\n        case 'validation-client': {\n          // This is a react-dom/server render and won't have a cacheSignal until React adds this for the client world.\n          const renderSignal = workUnitStore.renderSignal\n          if (renderSignal.aborted) {\n            if (currentAbortedLogsStyle === HIDDEN_STYLE) {\n              return\n            }\n            return applyWithDimming.call(\n              this,\n              consoleStore,\n              originalMethod,\n              methodName,\n              args\n            )\n          }\n        }\n        // intentional fallthrough\n        case 'prerender-legacy':\n        case 'prerender-ppr':\n        case 'cache':\n        case 'unstable-cache':\n        case 'private-cache':\n        case 'request':\n        case 'generate-static-params':\n        case undefined:\n          if (consoleStore?.dim === true) {\n            return applyWithDimming.call(\n              this,\n              consoleStore,\n              originalMethod,\n              methodName,\n              args\n            )\n          } else {\n            return originalMethod.apply(this, args)\n          }\n        default:\n          workUnitStore satisfies never\n      }\n    }\n    if (originalName) {\n      Object.defineProperty(wrapperMethod, 'name', originalName)\n    }\n    Object.defineProperty(console, methodName, {\n      value: wrapperMethod,\n    })\n  }\n}\n\nfunction applyWithDimming<F extends (this: Console, ...args: any[]) => any>(\n  this: Console,\n  consoleStore: undefined | ConsoleStore,\n  method: F,\n  methodName: InterceptableConsoleMethod,\n  args: Parameters<F>\n): ReturnType<F> {\n  if (consoleStore?.dim === true) {\n    return method.apply(this, convertToDimmedArgs(methodName, args))\n  } else {\n    return consoleAsyncStorage.run(\n      DIMMED_STORE,\n      method.bind(this, ...convertToDimmedArgs(methodName, args))\n    )\n  }\n}\n\nconst DIMMED_STORE = { dim: true }\n\npatchConsoleMethod('error')\npatchConsoleMethod('assert')\npatchConsoleMethod('debug')\npatchConsoleMethod('dir')\npatchConsoleMethod('dirxml')\npatchConsoleMethod('group')\npatchConsoleMethod('groupCollapsed')\npatchConsoleMethod('groupEnd')\npatchConsoleMethod('info')\npatchConsoleMethod('log')\npatchConsoleMethod('table')\npatchConsoleMethod('trace')\npatchConsoleMethod('warn')\n"],"names":["setAbortedLogsStyle","DIMMED_STYLE","HIDDEN_STYLE","currentAbortedLogsStyle","style","isColorSupported","dim","dimStyle","reactBadgeFormat","dimmedConsoleArgs","inputArgs","newArgs","slice","template","argumentsPointer","originalTemplateString","splice","i","startsWith","length","currentChar","nextChar","arg","argType","convertToDimmedArgs","methodName","args","inspector","url","undefined","concat","patchConsoleMethod","descriptor","Object","getOwnPropertyDescriptor","console","configurable","writable","value","originalMethod","originalName","wrapperMethod","getClientReact","getServerReact","consoleStore","consoleAsyncStorage","getStore","signal","cacheSignal","aborted","applyWithDimming","call","apply","workUnitStore","workUnitAsyncStorage","type","renderSignal","defineProperty","method","run","DIMMED_STORE","bind"],"mappings":";;;;+BAgBgBA;;;eAAAA;;;uEAhBW;4BACP;6CAIb;8CAC8B;uCACU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAE/C,6HAA6H;AAC7H,MAAMC,eAAe;AACrB,MAAMC,eAAe;AAIrB,IAAIC,0BAAoC;AACjC,SAASH,oBAAoBI,KAAe;IACjDD,0BAA0BC;AAC5B;AAiBA,MAAMC,mBAAmBC,IAAAA,eAAG,EAAC,YAAY;AAEzC,8BAA8B;AAC9B,MAAMC,WAAW;AACjB,MAAMC,mBAAmB;AAEzB,SAASC,kBAAkB,GAAGC,SAAgB;IAC5C,IAAI,CAACL,kBAAkB;QACrB,OAAOK;IACT;IAEA,MAAMC,UAAUD,UAAUE,KAAK,CAAC;IAChC,IAAIC,WAAW;IACf,IAAIC,mBAAmB;IACvB,IAAI,OAAOJ,SAAS,CAAC,EAAE,KAAK,UAAU;QACpC,MAAMK,yBAAyBL,SAAS,CAAC,EAAE;QAC3C,qDAAqD;QACrDC,QAA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