/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/@nnao45/jsq@0.2.18/dist/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
#!/usr/bin/env node
var OutputFormatter,__defProp=Object.defineProperty,__getOwnPropNames=Object.getOwnPropertyNames,__require=(e=>"undefined"!=typeof require?require:"undefined"!=typeof Proxy?new Proxy(e,{get:(e,t)=>("undefined"!=typeof require?require:e)[t]}):e)((function(e){if("undefined"!=typeof require)return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')})),__esm=(e,t)=>function(){return e&&(t=(0,e[__getOwnPropNames(e)[0]])(e=0)),t},__export=(e,t)=>{for(var n in t)__defProp(e,n,{get:t[n],enumerable:!0})};import pc from"picocolors";var LODASH_METHODS,init_output_formatter=__esm({"src/utils/output-formatter.ts"(){OutputFormatter=class e{constructor(e){this.options={oneline:e.oneline,noColor:e.noColor,indent:e.indent,compact:e.compact,isReplMode:e.isReplMode},this.indentSize=this.parseIndentSize(e.indent),this.useColor=this.shouldUseColor(e),this.verbose=e.verbose||!1}parseIndentSize(e){if(void 0===e)return 2;const t="string"==typeof e?parseInt(e,10):e;return Number.isNaN(t)||t<0?2:t}shouldUseColor(e){return!e.noColor&&(!process.env.NO_COLOR&&(process.stdout.isTTY||!1))}format(e){if(this.options.oneline)return this.formatOneline(e);if(this.options.compact)return this.formatCompact(e);if(this.options.isReplMode)return this.formatPretty(e);const t=process.stdin.isTTY;return this.verbose?this.formatPretty(e):t?this.formatSimple(e):this.formatPretty(e)}static format(t,n={}){return new e(n).format(t)}formatOneline(e){const t=this.formatCompact(e);if(!t)return"undefined";const n=t.replace(/\n\s*/g," "),r=(process.stdout.columns||80)-5;return n.length>r?`${n.substring(0,r-3)}...`:n}formatCompact(e){const t=JSON.stringify(e,this.getReplacer());return this.useColor?this.colorize(t):t}formatPretty(e){const t=JSON.stringify(e,this.getReplacer(),this.indentSize);return this.useColor?this.colorize(t):t}formatSimple(e){return Array.isArray(e)?e.map((e=>JSON.stringify(e,this.getReplacer()))).join("\n"):JSON.stringify(e,this.getReplacer())}getReplacer(){}colorize(e){let t="";let n=!1;for(let r=0;r<e.length;r++){const s=e.charAt(r),i=e.slice(r);if(n)t+=s,n=!1;else{if('"'===s&&!n){const e=i.match(/^"([^"\\]|\\.)*"\s*:/);if(e){const n=e[0].substring(0,e[0].lastIndexOf(":"));t+=pc.green(n),r+=n.length-1;continue}const n=i.match(/^"([^"\\]|\\.)*"/);if(n){t+=pc.magenta(n[0]),r+=n[0].length-1;continue}}{const e=i.match(/^-?\d+\.?\d*([eE][+-]?\d+)?/);if(e){t+=pc.cyanBright(e[0]),r+=e[0].length-1;continue}const n=i.match(/^(true|false)/);if(n){t+=pc.yellowBright(n[0]),r+=n[0].length-1;continue}const a=i.match(/^null/);if(a){t+=pc.gray(a[0]),r+=a[0].length-1;continue}if(/[{}[\]:,]/.test(s)){t+=pc.dim(s);continue}}t+=s}}return t}}}}),init_lodash_shared_methods=__esm({"src/core/lodash/lodash-shared-methods.ts"(){LODASH_METHODS="\n// Always define lodashMethods\nglobalThis.lodashMethods = {\n  // Array methods from lodash\n  filter: function(predicate) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const filtered = [];\n    for (let i = 0; i < arr.length; i++) {\n      if (predicate(arr[i], i, this._value)) {\n        filtered.push(arr[i]);\n      }\n    }\n    return new this.constructor(filtered);\n  },\n  \n  map: function(iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const mapped = [];\n    for (let i = 0; i < arr.length; i++) {\n      mapped.push(iteratee(arr[i], i, this._value));\n    }\n    return new this.constructor(mapped);\n  },\n  \n  find: function(predicate) {\n    if (this._value === null || this._value === undefined) {\n      return undefined;\n    }\n    const arr = Array.from(this._value);\n    for (let i = 0; i < arr.length; i++) {\n      if (predicate(arr[i], i, this._value)) {\n        return arr[i];\n      }\n    }\n    return undefined;\n  },\n  \n  findIndex: function(predicate) {\n    if (this._value === null || this._value === undefined) {\n      return -1;\n    }\n    const arr = Array.from(this._value);\n    for (let i = 0; i < arr.length; i++) {\n      if (predicate(arr[i], i, this._value)) {\n        return i;\n      }\n    }\n    return -1;\n  },\n  \n  findLast: function(predicate) {\n    if (this._value === null || this._value === undefined) {\n      return undefined;\n    }\n    const arr = Array.from(this._value);\n    for (let i = arr.length - 1; i >= 0; i--) {\n      if (predicate(arr[i], i, this._value)) {\n        return arr[i];\n      }\n    }\n    return undefined;\n  },\n  \n  findLastIndex: function(predicate) {\n    if (this._value === null || this._value === undefined) {\n      return -1;\n    }\n    const arr = Array.from(this._value);\n    for (let i = arr.length - 1; i >= 0; i--) {\n      if (predicate(arr[i], i, this._value)) {\n        return i;\n      }\n    }\n    return -1;\n  },\n  \n  nth: function(n) {\n    if (this._value === null || this._value === undefined) {\n      return undefined;\n    }\n    const arr = Array.from(this._value);\n    const index = n >= 0 ? n : arr.length + n;\n    return arr[index];\n  },\n  \n  pullAt: function(indexes) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const pulled = [];\n    const indexArr = Array.isArray(indexes) ? indexes : [indexes];\n    \n    // Collect elements at specified indexes\n    for (let i = 0; i < indexArr.length; i++) {\n      const index = indexArr[i];\n      if (index >= 0 && index < arr.length) {\n        pulled.push(arr[index]);\n      }\n    }\n    \n    return new this.constructor(pulled);\n  },\n  \n  reduce: function(iteratee, accumulator) {\n    if (this._value === null || this._value === undefined) {\n      return accumulator;\n    }\n    const arr = Array.from(this._value);\n    let result = accumulator;\n    const startIndex = accumulator !== undefined ? 0 : 1;\n    if (accumulator === undefined && arr.length > 0) {\n      result = arr[0];\n    }\n    for (let i = startIndex; i < arr.length; i++) {\n      result = iteratee(result, arr[i], i, this._value);\n    }\n    return result;\n  },\n  \n  // Lodash specific array methods\n  where: function(properties) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const filtered = [];\n    for (let i = 0; i < arr.length; i++) {\n      const item = arr[i];\n      if (!item || typeof item !== 'object') continue;\n      let matches = true;\n      for (const [key, val] of Object.entries(properties)) {\n        if (item[key] !== val) {\n          matches = false;\n          break;\n        }\n      }\n      if (matches) {\n        filtered.push(item);\n      }\n    }\n    return new this.constructor(filtered);\n  },\n  \n  pluck: function(property) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const plucked = [];\n    for (let i = 0; i < arr.length; i++) {\n      plucked.push(arr[i] ? arr[i][property] : undefined);\n    }\n    return new this.constructor(plucked);\n  },\n  \n  sortBy: function(iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const sorted = [];\n    for (let i = 0; i < arr.length; i++) {\n      sorted.push(arr[i]);\n    }\n    // Simple bubble sort for VM compatibility\n    for (let i = 0; i < sorted.length - 1; i++) {\n      for (let j = 0; j < sorted.length - i - 1; j++) {\n        const aVal = typeof iteratee === 'function' ? iteratee(sorted[j]) : sorted[j][iteratee];\n        const bVal = typeof iteratee === 'function' ? iteratee(sorted[j + 1]) : sorted[j + 1][iteratee];\n        if (aVal > bVal) {\n          const temp = sorted[j];\n          sorted[j] = sorted[j + 1];\n          sorted[j + 1] = temp;\n        }\n      }\n    }\n    return new this.constructor(sorted);\n  },\n  \n  orderBy: function(iteratees, orders) {\n    const iterateeArr = Array.isArray(iteratees) ? iteratees : [iteratees];\n    const orderArr = Array.isArray(orders) ? orders : [orders];\n    \n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const sorted = [];\n    for (let i = 0; i < arr.length; i++) {\n      sorted.push(arr[i]);\n    }\n    \n    // Bubble sort with multiple keys\n    for (let i = 0; i < sorted.length - 1; i++) {\n      for (let j = 0; j < sorted.length - i - 1; j++) {\n        let shouldSwap = false;\n        \n        for (let k = 0; k < iterateeArr.length; k++) {\n          const iteratee = iterateeArr[k];\n          const order = orderArr[k] || 'asc';\n          const aVal = typeof iteratee === 'function' ? iteratee(sorted[j]) : sorted[j][iteratee];\n          const bVal = typeof iteratee === 'function' ? iteratee(sorted[j + 1]) : sorted[j + 1][iteratee];\n          \n          if (aVal < bVal) {\n            shouldSwap = order === 'desc';\n            break;\n          }\n          if (aVal > bVal) {\n            shouldSwap = order === 'asc';\n            break;\n          }\n        }\n        \n        if (shouldSwap) {\n          const temp = sorted[j];\n          sorted[j] = sorted[j + 1];\n          sorted[j + 1] = temp;\n        }\n      }\n    }\n    return new this.constructor(sorted);\n  },\n  \n  groupBy: function(iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor({});\n    }\n    const arr = Array.from(this._value);\n    const grouped = {};\n    for (let i = 0; i < arr.length; i++) {\n      const item = arr[i];\n      const key = typeof iteratee === 'function' ? iteratee(item) : item[iteratee];\n      if (!grouped[key]) grouped[key] = [];\n      grouped[key].push(item);\n    }\n    return new this.constructor(grouped);\n  },\n  \n  countBy: function(iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor({});\n    }\n    const arr = Array.from(this._value);\n    const counted = {};\n    for (let i = 0; i < arr.length; i++) {\n      const item = arr[i];\n      const key = typeof iteratee === 'function' ? iteratee(item) : item[iteratee];\n      counted[key] = (counted[key] || 0) + 1;\n    }\n    return new this.constructor(counted);\n  },\n  \n  keyBy: function(iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor({});\n    }\n    const arr = Array.from(this._value);\n    const keyed = {};\n    for (let i = 0; i < arr.length; i++) {\n      const item = arr[i];\n      const key = typeof iteratee === 'function' ? iteratee(item) : item[iteratee];\n      keyed[key] = item;\n    }\n    return new this.constructor(keyed);\n  },\n  \n  take: function(n) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const taken = [];\n    for (let i = 0; i < Math.min(n, arr.length); i++) {\n      taken.push(arr[i]);\n    }\n    return new this.constructor(taken);\n  },\n  \n  skip: function(n) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const skipped = [];\n    for (let i = n; i < arr.length; i++) {\n      skipped.push(arr[i]);\n    }\n    return new this.constructor(skipped);\n  },\n  \n  drop: function(n) {\n    return this.skip(n);\n  },\n  \n  takeWhile: function(predicate) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const taken = [];\n    for (let i = 0; i < arr.length; i++) {\n      if (!predicate(arr[i], i, arr)) break;\n      taken.push(arr[i]);\n    }\n    return new this.constructor(taken);\n  },\n  \n  dropWhile: function(predicate) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    let dropIndex = 0;\n    for (let i = 0; i < arr.length; i++) {\n      if (!predicate(arr[i], i, arr)) {\n        dropIndex = i;\n        break;\n      }\n    }\n    const result = [];\n    for (let i = dropIndex; i < arr.length; i++) {\n      result.push(arr[i]);\n    }\n    return new this.constructor(result);\n  },\n  \n  takeRight: function(n) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const startIndex = Math.max(0, arr.length - n);\n    const result = [];\n    for (let i = startIndex; i < arr.length; i++) {\n      result.push(arr[i]);\n    }\n    return new this.constructor(result);\n  },\n  \n  takeRightWhile: function(predicate) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const result = [];\n    for (let i = arr.length - 1; i >= 0; i--) {\n      if (!predicate(arr[i], i, arr)) break;\n      result.unshift(arr[i]);\n    }\n    return new this.constructor(result);\n  },\n  \n  dropRight: function(n) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const endIndex = Math.max(0, arr.length - n);\n    const result = [];\n    for (let i = 0; i < endIndex; i++) {\n      result.push(arr[i]);\n    }\n    return new this.constructor(result);\n  },\n  \n  dropRightWhile: function(predicate) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    let endIndex = arr.length;\n    for (let i = arr.length - 1; i >= 0; i--) {\n      if (!predicate(arr[i], i, arr)) {\n        endIndex = i + 1;\n        break;\n      }\n    }\n    const result = [];\n    for (let i = 0; i < endIndex; i++) {\n      result.push(arr[i]);\n    }\n    return new this.constructor(result);\n  },\n  \n  uniq: function() {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const unique = [];\n    const seen = {};\n    for (let i = 0; i < arr.length; i++) {\n      const val = arr[i];\n      const key = typeof val === 'object' ? JSON.stringify(val) : String(val);\n      if (!seen[key]) {\n        seen[key] = true;\n        unique.push(val);\n      }\n    }\n    return new this.constructor(unique);\n  },\n  \n  uniqBy: function(iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const seen = {};\n    const unique = [];\n    for (let i = 0; i < arr.length; i++) {\n      const item = arr[i];\n      const key = typeof iteratee === 'function' ? iteratee(item) : item[iteratee];\n      const keyStr = typeof key === 'object' ? JSON.stringify(key) : String(key);\n      if (!seen[keyStr]) {\n        seen[keyStr] = true;\n        unique.push(item);\n      }\n    }\n    return new this.constructor(unique);\n  },\n  \n  sample: function() {\n    if (this._value === null || this._value === undefined) {\n      return undefined;\n    }\n    const arr = Array.from(this._value);\n    if (arr.length === 0) return undefined;\n    return arr[Math.floor(Math.random() * arr.length)];\n  },\n  \n  sampleSize: function(n) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const shuffled = [];\n    for (let i = 0; i < arr.length; i++) {\n      shuffled.push(arr[i]);\n    }\n    // Fisher-Yates shuffle\n    for (let i = shuffled.length - 1; i > 0; i--) {\n      const j = Math.floor(Math.random() * (i + 1));\n      const temp = shuffled[i];\n      shuffled[i] = shuffled[j];\n      shuffled[j] = temp;\n    }\n    const result = [];\n    for (let i = 0; i < Math.min(n, shuffled.length); i++) {\n      result.push(shuffled[i]);\n    }\n    return new this.constructor(result);\n  },\n  \n  shuffle: function() {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const shuffled = [];\n    for (let i = 0; i < arr.length; i++) {\n      shuffled.push(arr[i]);\n    }\n    // Fisher-Yates shuffle\n    for (let i = shuffled.length - 1; i > 0; i--) {\n      const j = Math.floor(Math.random() * (i + 1));\n      const temp = shuffled[i];\n      shuffled[i] = shuffled[j];\n      shuffled[j] = temp;\n    }\n    return new this.constructor(shuffled);\n  },\n  \n  flatten: function() {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const flattened = [];\n    for (let i = 0; i < arr.length; i++) {\n      const val = arr[i];\n      if (Array.isArray(val)) {\n        for (let j = 0; j < val.length; j++) {\n          flattened.push(val[j]);\n        }\n      } else {\n        flattened.push(val);\n      }\n    }\n    return new this.constructor(flattened);\n  },\n  \n  flattenDeep: function() {\n    const flattenDeepRecursive = (arr) => {\n      const result = [];\n      for (let i = 0; i < arr.length; i++) {\n        const val = arr[i];\n        if (Array.isArray(val)) {\n          const nested = flattenDeepRecursive(val);\n          for (let j = 0; j < nested.length; j++) {\n            result.push(nested[j]);\n          }\n        } else {\n          result.push(val);\n        }\n      }\n      return result;\n    };\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const flattened = flattenDeepRecursive(Array.from(this._value));\n    return new this.constructor(flattened);\n  },\n  \n  flatMap: function(iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const result = [];\n    for (let i = 0; i < arr.length; i++) {\n      const mapped = iteratee(arr[i], i, arr);\n      if (Array.isArray(mapped)) {\n        for (let j = 0; j < mapped.length; j++) {\n          result.push(mapped[j]);\n        }\n      } else {\n        result.push(mapped);\n      }\n    }\n    return new this.constructor(result);\n  },\n  \n  flatMapDeep: function(iteratee) {\n    const flattenDeepRecursive = (val) => {\n      const result = [];\n      if (Array.isArray(val)) {\n        for (let i = 0; i < val.length; i++) {\n          const nested = flattenDeepRecursive(val[i]);\n          for (let j = 0; j < nested.length; j++) {\n            result.push(nested[j]);\n          }\n        }\n      } else {\n        result.push(val);\n      }\n      return result;\n    };\n    \n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const result = [];\n    for (let i = 0; i < arr.length; i++) {\n      const mapped = iteratee(arr[i], i, arr);\n      const flattened = flattenDeepRecursive(mapped);\n      for (let j = 0; j < flattened.length; j++) {\n        result.push(flattened[j]);\n      }\n    }\n    return new this.constructor(result);\n  },\n  \n  invokeMap: function(path, ...args) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const result = [];\n    for (let i = 0; i < arr.length; i++) {\n      const item = arr[i];\n      if (typeof path === 'function') {\n        result.push(path.apply(item, args));\n      } else if (item && typeof item[path] === 'function') {\n        result.push(item[path](...args));\n      } else {\n        result.push(undefined);\n      }\n    }\n    return new this.constructor(result);\n  },\n  \n  partition: function(predicate) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([[], []]);\n    }\n    const arr = Array.from(this._value);\n    const truthy = [];\n    const falsy = [];\n    for (let i = 0; i < arr.length; i++) {\n      if (predicate(arr[i], i, arr)) {\n        truthy.push(arr[i]);\n      } else {\n        falsy.push(arr[i]);\n      }\n    }\n    return new this.constructor([truthy, falsy]);\n  },\n  \n  compact: function() {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const compacted = [];\n    for (let i = 0; i < arr.length; i++) {\n      if (arr[i]) {\n        compacted.push(arr[i]);\n      }\n    }\n    return new this.constructor(compacted);\n  },\n  \n  chunk: function(size) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const chunks = [];\n    for (let i = 0; i < arr.length; i += size) {\n      const chunk = [];\n      for (let j = i; j < Math.min(i + size, arr.length); j++) {\n        chunk.push(arr[j]);\n      }\n      chunks.push(chunk);\n    }\n    return new this.constructor(chunks);\n  },\n  \n  reverse: function() {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const reversed = [];\n    for (let i = arr.length - 1; i >= 0; i--) {\n      reversed.push(arr[i]);\n    }\n    return new this.constructor(reversed);\n  },\n  \n  pullAll: function(values) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const result = [];\n    for (let i = 0; i < arr.length; i++) {\n      let shouldInclude = true;\n      for (let j = 0; j < values.length; j++) {\n        if (arr[i] === values[j]) {\n          shouldInclude = false;\n          break;\n        }\n      }\n      if (shouldInclude) {\n        result.push(arr[i]);\n      }\n    }\n    return new this.constructor(result);\n  },\n  \n  pullAllBy: function(values, iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const result = [];\n    const valueKeys = [];\n    for (let i = 0; i < values.length; i++) {\n      const key = typeof iteratee === 'function' ? iteratee(values[i]) : values[i][iteratee];\n      valueKeys.push(key);\n    }\n    \n    for (let i = 0; i < arr.length; i++) {\n      const itemKey = typeof iteratee === 'function' ? iteratee(arr[i]) : arr[i][iteratee];\n      let shouldInclude = true;\n      for (let j = 0; j < valueKeys.length; j++) {\n        if (itemKey === valueKeys[j]) {\n          shouldInclude = false;\n          break;\n        }\n      }\n      if (shouldInclude) {\n        result.push(arr[i]);\n      }\n    }\n    return new this.constructor(result);\n  },\n  \n  differenceBy: function(values, iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const result = [];\n    const valueKeys = [];\n    for (let i = 0; i < values.length; i++) {\n      const key = typeof iteratee === 'function' ? iteratee(values[i]) : values[i][iteratee];\n      valueKeys.push(key);\n    }\n    \n    for (let i = 0; i < arr.length; i++) {\n      const itemKey = typeof iteratee === 'function' ? iteratee(arr[i]) : arr[i][iteratee];\n      let shouldInclude = true;\n      for (let j = 0; j < valueKeys.length; j++) {\n        if (itemKey === valueKeys[j]) {\n          shouldInclude = false;\n          break;\n        }\n      }\n      if (shouldInclude) {\n        result.push(arr[i]);\n      }\n    }\n    return new this.constructor(result);\n  },\n  \n  differenceWith: function(values, comparator) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const result = [];\n    \n    for (let i = 0; i < arr.length; i++) {\n      let shouldInclude = true;\n      for (let j = 0; j < values.length; j++) {\n        if (comparator(arr[i], values[j])) {\n          shouldInclude = false;\n          break;\n        }\n      }\n      if (shouldInclude) {\n        result.push(arr[i]);\n      }\n    }\n    return new this.constructor(result);\n  },\n  \n  intersectionBy: function(values, iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const result = [];\n    const seen = {};\n    \n    for (let i = 0; i < arr.length; i++) {\n      const itemKey = typeof iteratee === 'function' ? iteratee(arr[i]) : arr[i][iteratee];\n      const keyStr = typeof itemKey === 'object' ? JSON.stringify(itemKey) : String(itemKey);\n      \n      for (let j = 0; j < values.length; j++) {\n        const valueKey = typeof iteratee === 'function' ? iteratee(values[j]) : values[j][iteratee];\n        const valueKeyStr = typeof valueKey === 'object' ? JSON.stringify(valueKey) : String(valueKey);\n        \n        if (keyStr === valueKeyStr && !seen[keyStr]) {\n          seen[keyStr] = true;\n          result.push(arr[i]);\n          break;\n        }\n      }\n    }\n    return new this.constructor(result);\n  },\n  \n  intersectionWith: function(values, comparator) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const result = [];\n    \n    for (let i = 0; i < arr.length; i++) {\n      for (let j = 0; j < values.length; j++) {\n        if (comparator(arr[i], values[j])) {\n          result.push(arr[i]);\n          break;\n        }\n      }\n    }\n    return new this.constructor(result);\n  },\n  \n  unionBy: function(arrays, iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const result = [];\n    const seen = {};\n    \n    // Process first array\n    for (let i = 0; i < arr.length; i++) {\n      const key = typeof iteratee === 'function' ? iteratee(arr[i]) : arr[i][iteratee];\n      const keyStr = typeof key === 'object' ? JSON.stringify(key) : String(key);\n      if (!seen[keyStr]) {\n        seen[keyStr] = true;\n        result.push(arr[i]);\n      }\n    }\n    \n    // Process additional arrays\n    for (let i = 0; i < arrays.length; i++) {\n      const key = typeof iteratee === 'function' ? iteratee(arrays[i]) : arrays[i][iteratee];\n      const keyStr = typeof key === 'object' ? JSON.stringify(key) : String(key);\n      if (!seen[keyStr]) {\n        seen[keyStr] = true;\n        result.push(arrays[i]);\n      }\n    }\n    \n    return new this.constructor(result);\n  },\n  \n  unionWith: function(arrays, comparator) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arr = Array.from(this._value);\n    const result = [];\n    \n    // Add all items from first array\n    for (let i = 0; i < arr.length; i++) {\n      result.push(arr[i]);\n    }\n    \n    // Add items from additional arrays if not already present\n    for (let i = 0; i < arrays.length; i++) {\n      let shouldAdd = true;\n      for (let j = 0; j < result.length; j++) {\n        if (comparator(arrays[i], result[j])) {\n          shouldAdd = false;\n          break;\n        }\n      }\n      if (shouldAdd) {\n        result.push(arrays[i]);\n      }\n    }\n    \n    return new this.constructor(result);\n  },\n  \n  xor: function(...arrays) {\n    const allArrays = [this._value || []].concat(arrays);\n    const result = [];\n    const counts = {};\n    \n    // Count occurrences\n    for (let i = 0; i < allArrays.length; i++) {\n      const arr = Array.from(allArrays[i]);\n      const seen = {};\n      for (let j = 0; j < arr.length; j++) {\n        const key = typeof arr[j] === 'object' ? JSON.stringify(arr[j]) : String(arr[j]);\n        if (!seen[key]) {\n          seen[key] = true;\n          counts[key] = (counts[key] || 0) + 1;\n        }\n      }\n    }\n    \n    // Add items that appear in exactly one array\n    for (let i = 0; i < allArrays.length; i++) {\n      const arr = Array.from(allArrays[i]);\n      for (let j = 0; j < arr.length; j++) {\n        const key = typeof arr[j] === 'object' ? JSON.stringify(arr[j]) : String(arr[j]);\n        if (counts[key] === 1) {\n          counts[key] = -1; // Mark as added\n          result.push(arr[j]);\n        }\n      }\n    }\n    \n    return new this.constructor(result);\n  },\n  \n  xorBy: function(arrays, iteratee) {\n    const allArrays = [this._value || [], arrays];\n    const result = [];\n    const counts = {};\n    const items = {};\n    \n    // Count occurrences by key\n    for (let i = 0; i < allArrays.length; i++) {\n      const arr = Array.from(allArrays[i]);\n      const seen = {};\n      for (let j = 0; j < arr.length; j++) {\n        const key = typeof iteratee === 'function' ? iteratee(arr[j]) : arr[j][iteratee];\n        const keyStr = typeof key === 'object' ? JSON.stringify(key) : String(key);\n        if (!seen[keyStr]) {\n          seen[keyStr] = true;\n          counts[keyStr] = (counts[keyStr] || 0) + 1;\n          if (!items[keyStr]) {\n            items[keyStr] = arr[j];\n          }\n        }\n      }\n    }\n    \n    // Add items that appear in exactly one array\n    for (const keyStr in counts) {\n      if (counts[keyStr] === 1) {\n        result.push(items[keyStr]);\n      }\n    }\n    \n    return new this.constructor(result);\n  },\n  \n  xorWith: function(arrays, comparator) {\n    const allArrays = [this._value || [], arrays];\n    const result = [];\n    \n    for (let i = 0; i < allArrays.length; i++) {\n      const arr = Array.from(allArrays[i]);\n      for (let j = 0; j < arr.length; j++) {\n        let count = 0;\n        \n        // Count how many arrays contain this item\n        for (let k = 0; k < allArrays.length; k++) {\n          const otherArr = Array.from(allArrays[k]);\n          for (let l = 0; l < otherArr.length; l++) {\n            if (comparator(arr[j], otherArr[l])) {\n              count++;\n              break;\n            }\n          }\n        }\n        \n        // Add if appears in exactly one array and not already in result\n        if (count === 1) {\n          let alreadyAdded = false;\n          for (let k = 0; k < result.length; k++) {\n            if (comparator(arr[j], result[k])) {\n              alreadyAdded = true;\n              break;\n            }\n          }\n          if (!alreadyAdded) {\n            result.push(arr[j]);\n          }\n        }\n      }\n    }\n    \n    return new this.constructor(result);\n  },\n  \n  // Math methods\n  sum: function(iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return 0;\n    }\n    const arr = Array.from(this._value);\n    let sum = 0;\n    for (let i = 0; i < arr.length; i++) {\n      const val = arr[i];\n      let num;\n      if (iteratee && typeof iteratee === 'string') {\n        num = Number(val?.[iteratee]) || 0;\n      } else if (iteratee && typeof iteratee === 'function') {\n        num = Number(iteratee(val)) || 0;\n      } else {\n        num = Number(val) || 0;\n      }\n      sum += num;\n    }\n    return sum;\n  },\n  \n  sumBy: function(iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return 0;\n    }\n    const arr = Array.from(this._value);\n    let sum = 0;\n    for (let i = 0; i < arr.length; i++) {\n      const val = arr[i];\n      let num;\n      if (typeof iteratee === 'string') {\n        num = Number(val?.[iteratee]) || 0;\n      } else if (typeof iteratee === 'function') {\n        num = Number(iteratee(val)) || 0;\n      } else {\n        num = Number(val) || 0;\n      }\n      sum += num;\n    }\n    return sum;\n  },\n  \n  mean: function() {\n    if (this._value === null || this._value === undefined) {\n      return NaN;\n    }\n    const arr = Array.from(this._value);\n    if (arr.length === 0) return NaN;\n    let sum = 0;\n    for (let i = 0; i < arr.length; i++) {\n      sum += Number(arr[i]) || 0;\n    }\n    return sum / arr.length;\n  },\n  \n  meanBy: function(iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return NaN;\n    }\n    const arr = Array.from(this._value);\n    if (arr.length === 0) return NaN;\n    let sum = 0;\n    for (let i = 0; i < arr.length; i++) {\n      const val = arr[i];\n      let num;\n      if (typeof iteratee === 'string') {\n        num = Number(val?.[iteratee]) || 0;\n      } else if (typeof iteratee === 'function') {\n        num = Number(iteratee(val)) || 0;\n      } else {\n        num = Number(val) || 0;\n      }\n      sum += num;\n    }\n    return sum / arr.length;\n  },\n  \n  add: function(addend) {\n    const augend = Number(this._value) || 0;\n    return augend + (Number(addend) || 0);\n  },\n  \n  subtract: function(subtrahend) {\n    const minuend = Number(this._value) || 0;\n    return minuend - (Number(subtrahend) || 0);\n  },\n  \n  multiply: function(multiplicand) {\n    const multiplier = Number(this._value) || 0;\n    return multiplier * (Number(multiplicand) || 0);\n  },\n  \n  divide: function(divisor) {\n    const dividend = Number(this._value) || 0;\n    return dividend / (Number(divisor) || 1);\n  },\n  \n  ceil: function(precision) {\n    const num = Number(this._value) || 0;\n    precision = precision || 0;\n    const factor = Math.pow(10, precision);\n    return Math.ceil(num * factor) / factor;\n  },\n  \n  floor: function(precision) {\n    const num = Number(this._value) || 0;\n    precision = precision || 0;\n    const factor = Math.pow(10, precision);\n    return Math.floor(num * factor) / factor;\n  },\n  \n  round: function(precision) {\n    const num = Number(this._value) || 0;\n    precision = precision || 0;\n    const factor = Math.pow(10, precision);\n    return Math.round(num * factor) / factor;\n  },\n  \n  min: function() {\n    if (this._value === null || this._value === undefined) {\n      return undefined;\n    }\n    const arr = Array.from(this._value);\n    if (arr.length === 0) return undefined;\n    let min = Number(arr[0]) || 0;\n    for (let i = 1; i < arr.length; i++) {\n      const num = Number(arr[i]) || 0;\n      if (num < min) min = num;\n    }\n    return min;\n  },\n  \n  max: function() {\n    if (this._value === null || this._value === undefined) {\n      return undefined;\n    }\n    const arr = Array.from(this._value);\n    if (arr.length === 0) return undefined;\n    let max = Number(arr[0]) || 0;\n    for (let i = 1; i < arr.length; i++) {\n      const num = Number(arr[i]) || 0;\n      if (num > max) max = num;\n    }\n    return max;\n  },\n  \n  minBy: function(iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return undefined;\n    }\n    const arr = Array.from(this._value);\n    if (arr.length === 0) return undefined;\n    let min = arr[0];\n    let minVal = typeof iteratee === 'function' ? iteratee(min) : min[iteratee];\n    for (let i = 1; i < arr.length; i++) {\n      const item = arr[i];\n      const itemVal = typeof iteratee === 'function' ? iteratee(item) : item[iteratee];\n      if (itemVal < minVal) {\n        min = item;\n        minVal = itemVal;\n      }\n    }\n    return min;\n  },\n  \n  maxBy: function(iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return undefined;\n    }\n    const arr = Array.from(this._value);\n    if (arr.length === 0) return undefined;\n    let max = arr[0];\n    let maxVal = typeof iteratee === 'function' ? iteratee(max) : max[iteratee];\n    for (let i = 1; i < arr.length; i++) {\n      const item = arr[i];\n      const itemVal = typeof iteratee === 'function' ? iteratee(item) : item[iteratee];\n      if (itemVal > maxVal) {\n        max = item;\n        maxVal = itemVal;\n      }\n    }\n    return max;\n  },\n  \n  // Object methods\n  pick: function(...args) {\n    const result = {};\n    const obj = this._value;\n    // Support both array syntax and spread syntax\n    const keys = args.length === 1 && Array.isArray(args[0]) ? args[0] : args;\n    if (obj && typeof obj === 'object') {\n      for (const key of keys) {\n        if (key in obj) {\n          result[key] = obj[key];\n        }\n      }\n    }\n    return new this.constructor(result);\n  },\n  \n  omit: function(...args) {\n    const result = {};\n    const obj = this._value;\n    // Support both array syntax and spread syntax\n    const keys = args.length === 1 && Array.isArray(args[0]) ? args[0] : args;\n    if (obj && typeof obj === 'object') {\n      for (const key in obj) {\n        if (!keys.includes(key)) {\n          result[key] = obj[key];\n        }\n      }\n    }\n    return new this.constructor(result);\n  },\n  \n  keys: function() {\n    if (this._value && typeof this._value === 'object') {\n      return new this.constructor(Object.keys(this._value));\n    }\n    return new this.constructor([]);\n  },\n  \n  values: function() {\n    if (this._value && typeof this._value === 'object') {\n      return new this.constructor(Object.values(this._value));\n    }\n    return new this.constructor([]);\n  },\n  \n  entries: function() {\n    if (this._value && typeof this._value === 'object') {\n      return new this.constructor(Object.entries(this._value));\n    }\n    return new this.constructor([]);\n  },\n  \n  fromPairs: function() {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor({});\n    }\n    const pairs = Array.from(this._value);\n    const result = {};\n    for (let i = 0; i < pairs.length; i++) {\n      const pair = pairs[i];\n      if (Array.isArray(pair) && pair.length >= 2) {\n        result[pair[0]] = pair[1];\n      }\n    }\n    return new this.constructor(result);\n  },\n  \n  zipObject: function(values) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor({});\n    }\n    const keys = Array.from(this._value);\n    const vals = values || [];\n    const result = {};\n    for (let i = 0; i < keys.length; i++) {\n      result[keys[i]] = vals[i];\n    }\n    return new this.constructor(result);\n  },\n  \n  zipObjectDeep: function(values) {\n    const setDeep = (obj, path, value) => {\n      const keys = path.split('.');\n      let current = obj;\n      for (let i = 0; i < keys.length - 1; i++) {\n        const key = keys[i];\n        if (!current[key] || typeof current[key] !== 'object') {\n          current[key] = {};\n        }\n        current = current[key];\n      }\n      current[keys[keys.length - 1]] = value;\n    };\n    \n    if (this._value === null || this._value === undefined) {\n      return new this.constructor({});\n    }\n    const paths = Array.from(this._value);\n    const vals = values || [];\n    const result = {};\n    for (let i = 0; i < paths.length; i++) {\n      setDeep(result, paths[i], vals[i]);\n    }\n    return new this.constructor(result);\n  },\n  \n  unzip: function() {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arrays = Array.from(this._value);\n    if (arrays.length === 0) return new this.constructor([]);\n    \n    const result = [];\n    const maxLength = Math.max(...arrays.map(arr => arr ? arr.length : 0));\n    \n    for (let i = 0; i < maxLength; i++) {\n      const group = [];\n      for (let j = 0; j < arrays.length; j++) {\n        group.push(arrays[j] ? arrays[j][i] : undefined);\n      }\n      result.push(group);\n    }\n    return new this.constructor(result);\n  },\n  \n  unzipWith: function(iteratee) {\n    if (this._value === null || this._value === undefined) {\n      return new this.constructor([]);\n    }\n    const arrays = Array.from(this._value);\n    if (arrays.length === 0) return new this.constructor([]);\n    \n    const result = [];\n    const maxLength = Math.max(...arrays.map(arr => arr ? arr.length : 0));\n    \n    for (let i = 0; i < maxLength; i++) {\n      const group = [];\n      for (let j = 0; j < arrays.length; j++) {\n        group.push(arrays[j] ? arrays[j][i] : undefined);\n      }\n      result.push(iteratee(...group));\n    }\n    return new this.constructor(result);\n  },\n  \n  invert: function() {\n    const result = {};\n    const obj = this._value;\n    if (obj && typeof obj === 'object') {\n      for (const [key, value] of Object.entries(obj)) {\n        result[String(value)] = key;\n      }\n    }\n    return new this.constructor(result);\n  },\n  \n  merge: function(...sources) {\n    const merged = Object.assign({}, this._value, ...sources);\n    return new this.constructor(merged);\n  },\n  \n  defaults: function(...sources) {\n    const result = { ...this._value };\n    for (const source of sources) {\n      if (source && typeof source === 'object') {\n        for (const [key, value] of Object.entries(source)) {\n          if (!(key in result)) {\n            result[key] = value;\n          }\n        }\n      }\n    }\n    return new this.constructor(result);\n  },\n  \n  get: function(path, defaultValue) {\n    const pathArray = Array.isArray(path) ? path : path.split('.');\n    let current = this._value;\n    \n    for (let i = 0; i < pathArray.length; i++) {\n      if (current === null || current === undefined || typeof current !== 'object') {\n        return defaultValue;\n      }\n      current = current[pathArray[i]];\n    }\n    \n    return current === undefined ? defaultValue : current;\n  },\n  \n  set: function(path, value) {\n    const pathArray = Array.isArray(path) ? path : path.split('.');\n    const obj = this._value && typeof this._value === 'object' ? { ...this._value } : {};\n    let current = obj;\n    \n    for (let i = 0; i < pathArray.length - 1; i++) {\n      const key = pathArray[i];\n      if (!current[key] || typeof current[key] !== 'object') {\n        current[key] = {};\n      }\n      current = current[key];\n    }\n    \n    current[pathArray[pathArray.length - 1]] = value;\n    return new this.constructor(obj);\n  },\n  \n  has: function(path) {\n    const pathArray = Array.isArray(path) ? path : path.split('.');\n    let current = this._value;\n    \n    for (let i = 0; i < pathArray.length; i++) {\n      if (current === null || current === undefined || typeof current !== 'object') {\n        return false;\n      }\n      if (!(pathArray[i] in current)) {\n        return false;\n      }\n      current = current[pathArray[i]];\n    }\n    \n    return true;\n  },\n  \n  hasIn: function(path) {\n    const pathArray = Array.isArray(path) ? path : path.split('.');\n    let current = this._value;\n    \n    for (let i = 0; i < pathArray.length; i++) {\n      if (current === null || current === undefined) {\n        return false;\n      }\n      if (!(pathArray[i] in current)) {\n        return false;\n      }\n      current = current[pathArray[i]];\n    }\n    \n    return true;\n  },\n  \n  mapKeys: function(iteratee) {\n    const result = {};\n    const obj = this._value;\n    \n    if (obj && typeof obj === 'object') {\n      for (const [key, value] of Object.entries(obj)) {\n        const newKey = typeof iteratee === 'function' ? iteratee(value, key, obj) : value[iteratee];\n        result[newKey] = value;\n      }\n    }\n    \n    return new this.constructor(result);\n  },\n  \n  mapValues: function(iteratee) {\n    const result = {};\n    const obj = this._value;\n    \n    if (obj && typeof obj === 'object') {\n      for (const [key, value] of Object.entries(obj)) {\n        result[key] = typeof iteratee === 'function' ? iteratee(value, key, obj) : value[iteratee];\n      }\n    }\n    \n    return new this.constructor(result);\n  },\n  \n  toPairs: function() {\n    if (this._value && typeof this._value === 'object') {\n      return new this.constructor(Object.entries(this._value));\n    }\n    return new this.constructor([]);\n  },\n  \n  toPairsIn: function() {\n    const result = [];\n    if (this._value && typeof this._value === 'object') {\n      for (const key in this._value) {\n        result.push([key, this._value[key]]);\n      }\n    }\n    return new this.constructor(result);\n  },\n  \n  assignIn: function(...sources) {\n    const result = {};\n    const objects = [this._value, ...sources];\n    \n    for (const obj of objects) {\n      if (obj && typeof obj === 'object') {\n        for (const key in obj) {\n          result[key] = obj[key];\n        }\n      }\n    }\n    \n    return new this.constructor(result);\n  },\n  \n  assignWith: function(...args) {\n    // Extract customizer (last argument if it's a function)\n    const customizer = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n    const sources = args;\n    \n    const result = { ...this._value };\n    \n    for (const source of sources) {\n      if (source && typeof source === 'object') {\n        for (const [key, value] of Object.entries(source)) {\n          if (customizer) {\n            const customized = customizer(result[key], value, key, result, source);\n            result[key] = customized !== undefined ? customized : value;\n          } else {\n            result[key] = value;\n          }\n        }\n      }\n    }\n    \n    return new this.constructor(result);\n  },\n  \n  mergeWith: function(...args) {\n    // Extract customizer (last argument if it's a function)\n    const customizer = typeof args[args.length - 1] === 'function' ? args.pop() : undefined;\n    const sources = args.map(source => {\n      // Auto-unwrap ChainableWrapper/SmartDollar instances\n      if (source && typeof source === 'object') {\n        if (source.__isSmartDollar || source.__isChainableWrapper) {\n          return source.valueOf();\n        }\n      }\n      return source;\n    });\n    \n    const unwrapValue = (val) => {\n      if (val && typeof val === 'object') {\n        if (val.__isSmartDollar || val.__isChainableWrapper) {\n          return val.valueOf();\n        }\n      }\n      return val;\n    };\n    \n    const deepMergeWithCustomizer = (target, source, customizer, key, object, sourceObj) => {\n      // Unwrap values before processing\n      target = unwrapValue(target);\n      source = unwrapValue(source);\n      \n      const customized = customizer ? customizer(target, source, key, object, sourceObj) : undefined;\n      if (customized !== undefined) {\n        return customized;\n      }\n      \n      if (typeof target === 'object' && typeof source === 'object' && target !== null && source !== null) {\n        let result;\n        if (Array.isArray(target)) {\n          result = [];\n          for (let i = 0; i < target.length; i++) {\n            result[i] = target[i];\n          }\n        } else {\n          result = {};\n          for (const key in target) {\n            if (Object.prototype.hasOwnProperty.call(target, key)) {\n              result[key] = target[key];\n            }\n          }\n        }\n        \n        for (const k in source) {\n          if (Object.prototype.hasOwnProperty.call(source, k)) {\n            result[k] = deepMergeWithCustomizer(result[k], source[k], customizer, k, object, sourceObj);\n          }\n        }\n        return result;\n      }\n      \n      return source;\n    };\n    \n    let result = this._value;\n    for (const source of sources) {\n      result = deepMergeWithCustomizer(result, source, customizer, undefined, this._value, source);\n    }\n    \n    return new this.constructor(result);\n  },\n  \n  at: function(...paths) {\n    const result = [];\n    const flatPaths = paths.flat();\n    \n    for (const path of flatPaths) {\n      const pathArray = Array.isArray(path) ? path : path.split('.');\n      let current = this._value;\n      \n      for (let i = 0; i < pathArray.length; i++) {\n        if (current === null || current === undefined || typeof current !== 'object') {\n          current = undefined;\n          break;\n        }\n        current = current[pathArray[i]];\n      }\n      \n      result.push(current);\n    }\n    \n    return new this.constructor(result);\n  },\n  \n  // String methods\n  camelCase: function() {\n    const str = String(this._value);\n    const camelCased = str\n      .replace(/[^a-zA-Z0-9]+(.)/g, (_, chr) => chr.toUpperCase())\n      .replace(/^./, chr => chr.toLowerCase());\n    return new this.constructor(camelCased);\n  },\n  \n  kebabCase: function() {\n    const str = String(this._value);\n    // Simpler approach: insert hyphen before any capital letter that follows a lowercase or digit\n    let result = str\n    .replace(/([a-z])([A-Z])/g, '$1-$2') // Add hyphen between lower/uppercase\n    .replace(/[\\s_]+/g, '-')             // Replace spaces/underscores with hyphen\n    .toLowerCase();\n      \n    return new this.constructor(result);\n  },\n  \n  snakeCase: function() {\n    const str = String(this._value);\n    const result = str && str\n    .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)\n    .map(s => s.toLowerCase())\n    .join('_');\n      \n    return new this.constructor(result);\n  },\n  \n  startCase: function() {\n    const str = String(this._value);\n    const startCased = str\n      .replace(/([a-z])([A-Z])/g, '$1 $2')\n      .replace(/[_-]+/g, ' ')\n      .split(' ')\n      .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())\n      .join(' ');\n    return new this.constructor(startCased);\n  },\n  \n  upperFirst: function() {\n    const str = String(this._value);\n    return new this.constructor(str.charAt(0).toUpperCase() + str.slice(1));\n  },\n  \n  lowerFirst: function() {\n    const str = String(this._value);\n    return new this.constructor(str.charAt(0).toLowerCase() + str.slice(1));\n  },\n  \n  capitalize: function() {\n    const str = String(this._value);\n    return new this.constructor(str.charAt(0).toUpperCase() + str.slice(1).toLowerCase());\n  },\n  \n  upperCase: function() {\n    const str = String(this._value);\n    // 単語境界で分割するが、URL記号は保持\n    const result = str\n      .replace(/([a-z])([A-Z])/g, '$1 $2') // camelCase境界\n      .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2') // 連続する大文字の境界\n      .replace(/([a-zA-Z])([0-9])/g, '$1 $2') // 文字と数字の境界\n      .replace(/([0-9])([a-zA-Z])/g, '$1 $2') // 数字と文字の境界\n      .toUpperCase();\n    return new this.constructor(result);\n  },\n  \n  lowerCase: function() {\n    const str = String(this._value);\n    // 単語境界で分割するが、URL記号は保持\n    const result = str\n      .replace(/([a-z])([A-Z])/g, '$1 $2') // camelCase境界\n      .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2') // 連続する大文字の境界\n      .replace(/([a-zA-Z])([0-9])/g, '$1 $2') // 文字と数字の境界\n      .replace(/([0-9])([a-zA-Z])/g, '$1 $2') // 数字と文字の境界\n      .toLowerCase();\n    return new this.constructor(result);\n  },\n  \n  pad: function(length, chars) {\n    const str = String(this._value);\n    const padChars = chars || ' ';\n    const targetLength = Number(length) || 0;\n    \n    if (str.length >= targetLength) {\n      return new this.constructor(str);\n    }\n    \n    const totalPadding = targetLength - str.length;\n    const leftPadding = Math.floor(totalPadding / 2);\n    const rightPadding = totalPadding - leftPadding;\n    \n    let leftPad = '';\n    let rightPad = '';\n    \n    // Build left padding\n    while (leftPad.length < leftPadding) {\n      leftPad += padChars;\n    }\n    leftPad = leftPad.slice(0, leftPadding);\n    \n    // Build right padding\n    while (rightPad.length < rightPadding) {\n      rightPad += padChars;\n    }\n    rightPad = rightPad.slice(0, rightPadding);\n    \n    return new this.constructor(leftPad + str + rightPad);\n  },\n  \n  padStart: function(length, chars) {\n    const str = String(this._value);\n    const padChars = chars || ' ';\n    const targetLength = Number(length) || 0;\n    \n    if (str.length >= targetLength) {\n      return new this.constructor(str);\n    }\n    \n    const paddingLength = targetLength - str.length;\n    let padding = '';\n    \n    while (padding.length < paddingLength) {\n      padding += padChars;\n    }\n    padding = padding.slice(0, paddingLength);\n    \n    return new this.constructor(padding + str);\n  },\n  \n  padEnd: function(length, chars) {\n    const str = String(this._value);\n    const padChars = chars || ' ';\n    const targetLength = Number(length) || 0;\n    \n    if (str.length >= targetLength) {\n      return new this.constructor(str);\n    }\n    \n    const paddingLength = targetLength - str.length;\n    let padding = '';\n    \n    while (padding.length < paddingLength) {\n      padding += padChars;\n    }\n    padding = padding.slice(0, paddingLength);\n    \n    return new this.constructor(str + padding);\n  },\n  \n  trim: function(chars) {\n    const str = String(this._value);\n    if (!chars) {\n      return new this.constructor(str.trim());\n    }\n    \n    const charSet = chars.split('');\n    let start = 0;\n    let end = str.length;\n    \n    // Trim from start\n    while (start < str.length && charSet.includes(str[start])) {\n      start++;\n    }\n    \n    // Trim from end\n    while (end > start && charSet.includes(str[end - 1])) {\n      end--;\n    }\n    \n    return new this.constructor(str.slice(start, end));\n  },\n  \n  trimStart: function(chars) {\n    const str = String(this._value);\n    if (!chars) {\n      return new this.constructor(str.trimStart());\n    }\n    \n    const charSet = chars.split('');\n    let start = 0;\n    \n    while (start < str.length && charSet.includes(str[start])) {\n      start++;\n    }\n    \n    return new this.constructor(str.slice(start));\n  },\n  \n  trimEnd: function(chars) {\n    const str = String(this._value);\n    if (!chars) {\n      return new this.constructor(str.trimEnd());\n    }\n    \n    const charSet = chars.split('');\n    let end = str.length;\n    \n    while (end > 0 && charSet.includes(str[end - 1])) {\n      end--;\n    }\n    \n    return new this.constructor(str.slice(0, end));\n  },\n  \n  truncate: function(options) {\n    const str = String(this._value);\n    const opts = options || {};\n    const length = opts.length || 30;\n    const omission = opts.omission || '...';\n    const separator = opts.separator;\n    \n    if (str.length <= length) {\n      return new this.constructor(str);\n    }\n    \n    let end = length - omission.length;\n    if (end < 1) {\n      return new this.constructor(omission);\n    }\n    \n    let result = str.slice(0, end);\n    \n    if (separator) {\n      const sepRegex = typeof separator === 'string' ? new RegExp(separator, 'g') : separator;\n      let lastMatch = null;\n      let match;\n      \n      while ((match = sepRegex.exec(result)) !== null) {\n        lastMatch = match.index;\n      }\n      \n      if (lastMatch !== null) {\n        result = result.slice(0, lastMatch);\n      }\n    }\n    \n    return new this.constructor(result + omission);\n  },\n  \n  escape: function() {\n    const str = String(this._value);\n    const htmlEscapes = {\n      '&': '&amp;',\n      '<': '&lt;',\n      '>': '&gt;',\n      '\"': '&quot;',\n      \"'\": '&#39;'\n    };\n    \n    return new this.constructor(str.replace(/[&<>\"']/g, match => htmlEscapes[match]));\n  },\n  \n  unescape: function() {\n    const str = String(this._value);\n    const htmlUnescapes = {\n      '&amp;': '&',\n      '&lt;': '<',\n      '&gt;': '>',\n      '&quot;': '\"',\n      '&#39;': \"'\"\n    };\n    \n    return new this.constructor(str.replace(/&(?:amp|lt|gt|quot|#39);/g, match => htmlUnescapes[match]));\n  },\n  \n  words: function(pattern) {\n    const str = String(this._value);\n    const regex = pattern || /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g;\n    return new this.constructor(str.match(regex) || []);\n  },\n  \n  deburr: function() {\n    const str = String(this._value);\n    const deburredLetters = {\n      'À': 'A', 'Á': 'A', 'Â': 'A', 'Ã': 'A', 'Ä': 'A', 'Å': 'A',\n      'à': 'a', 'á': 'a', 'â': 'a', 'ã': 'a', 'ä': 'a', 'å': 'a',\n      'Ç': 'C', 'ç': 'c',\n      'Ð': 'D', 'ð': 'd',\n      'È': 'E', 'É': 'E', 'Ê': 'E', 'Ë': 'E',\n      'è': 'e', 'é': 'e', 'ê': 'e', 'ë': 'e',\n      'Ì': 'I', 'Í': 'I', 'Î': 'I', 'Ï': 'I',\n      'ì': 'i', 'í': 'i', 'î': 'i', 'ï': 'i',\n      'Ñ': 'N', 'ñ': 'n',\n      'Ò': 'O', 'Ó': 'O', 'Ô': 'O', 'Õ': 'O', 'Ö': 'O', 'Ø': 'O',\n      'ò': 'o', 'ó': 'o', 'ô': 'o', 'õ': 'o', 'ö': 'o', 'ø': 'o',\n      'Ù': 'U', 'Ú': 'U', 'Û': 'U', 'Ü': 'U',\n      'ù': 'u', 'ú': 'u', 'û': 'u', 'ü': 'u',\n      'Ý': 'Y', 'ý': 'y', 'ÿ': 'y',\n      'Æ': 'Ae', 'æ': 'ae',\n      'Þ': 'Th', 'þ': 'th',\n      'ß': 'ss'\n    };\n    \n    return new this.constructor(str.replace(/[À-ÿ]/g, match => deburredLetters[match] || match));\n  },\n  \n  // Utility methods\n  isArray: function() {\n    return Array.isArray(this._value);\n  },\n  \n  isObject: function() {\n    return this._value !== null && typeof this._value === 'object';\n  },\n  \n  isString: function() {\n    return typeof this._value === 'string';\n  },\n  \n  isNumber: function() {\n    return typeof this._value === 'number';\n  },\n  \n  isFunction: function() {\n    return typeof this._value === 'function';\n  },\n  \n  isNull: function() {\n    return this._value === null;\n  },\n  \n  isUndefined: function() {\n    return this._value === undefined;\n  },\n  \n  size: function() {\n    if (Array.isArray(this._value) || typeof this._value === 'string') {\n      return this._value.length;\n    }\n    if (this._value && typeof this._value === 'object') {\n      return Object.keys(this._value).length;\n    }\n    return 0;\n  },\n  \n  isEmpty: function() {\n    if (this._value === null || this._value === undefined) return true;\n    if (Array.isArray(this._value)) return this._value.length === 0;\n    if (typeof this._value === 'string') return this._value.length === 0;\n    if (typeof this._value === 'object') return Object.keys(this._value).length === 0;\n    return false;\n  },\n  \n  includes: function(value, fromIndex) {\n    if (Array.isArray(this._value)) {\n      return this._value.includes(value, fromIndex);\n    }\n    if (typeof this._value === 'string' && typeof value === 'string') {\n      return this._value.includes(value, fromIndex);\n    }\n    if (this._value && typeof this._value === 'object') {\n      return Object.values(this._value).includes(value);\n    }\n    return false;\n  },\n  \n  // Function utilities\n  identity: function() {\n    return this._value;\n  },\n  \n  constant: function() {\n    const val = this._value;\n    return function() { return val; };\n  },\n  \n  times: function(iteratee) {\n    const n = Number(this._value) || 0;\n    const results = [];\n    for (let i = 0; i < n; i++) {\n      results.push(iteratee(i));\n    }\n    return new this.constructor(results);\n  },\n  \n  range: function(end, step) {\n    const start = Number(this._value) || 0;\n    const endNum = end !== undefined ? Number(end) : start;\n    const startNum = end !== undefined ? start : 0;\n    const stepNum = step || (startNum < endNum ? 1 : -1);\n    \n    const result = [];\n    if (stepNum > 0) {\n      for (let i = startNum; i < endNum; i += stepNum) {\n        result.push(i);\n      }\n    } else {\n      for (let i = startNum; i > endNum; i += stepNum) {\n        result.push(i);\n      }\n    }\n    return new this.constructor(result);\n  },\n  \n  clamp: function(lower, upper) {\n    const num = Number(this._value) || 0;\n    return Math.max(lower, Math.min(upper, num));\n  },\n  \n  random: function(upper, floating) {\n    const lower = Number(this._value) || 0;\n    const upperNum = upper !== undefined ? Number(upper) : 1;\n    \n    if (floating || lower % 1 || upperNum % 1) {\n      const rand = Math.random();\n      return lower + rand * (upperNum - lower);\n    }\n    return lower + Math.floor(Math.random() * (upperNum - lower + 1));\n  },\n  \n  // Chain\n  chain: function() {\n    // Return this for chaining\n    return this;\n  },\n  \n  value: function() {\n    // Also update public value property for VM unwrapping\n    this.value = this._value;\n    return this._value;\n  },\n  \n  valueOf: function() {\n    return this._value;\n  },\n  \n  // Function utilities\n  debounce: function(wait, options) {\n    const func = this._value;\n    if (typeof func !== 'function') {\n      throw new TypeError('Expected a function');\n    }\n    \n    wait = Number(wait) || 0;\n    const opts = options || {};\n    const leading = !!opts.leading;\n    const trailing = opts.trailing !== false;\n    const maxing = 'maxWait' in opts;\n    const maxWait = maxing ? Math.max(Number(opts.maxWait) || 0, wait) : null;\n    \n    let lastCallTime;\n    let lastInvokeTime = 0;\n    let timerId;\n    let lastArgs;\n    let lastThis;\n    let result;\n    \n    function invokeFunc(time) {\n      const args = lastArgs;\n      const thisArg = lastThis;\n      \n      lastArgs = lastThis = undefined;\n      lastInvokeTime = time;\n      result = func.apply(thisArg, args);\n      return result;\n    }\n    \n    function leadingEdge(time) {\n      lastInvokeTime = time;\n      timerId = setTimeout(timerExpired, wait);\n      return leading ? invokeFunc(time) : result;\n    }\n    \n    function remainingWait(time) {\n      const timeSinceLastCall = time - lastCallTime;\n      const timeSinceLastInvoke = time - lastInvokeTime;\n      const timeWaiting = wait - timeSinceLastCall;\n      \n      return maxing\n        ? Math.min(timeWaiting, maxWait - timeSinceLastInvoke)\n        : timeWaiting;\n    }\n    \n    function shouldInvoke(time) {\n      const timeSinceLastCall = time - lastCallTime;\n      const timeSinceLastInvoke = time - lastInvokeTime;\n      \n      return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n        (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n    }\n    \n    function timerExpired() {\n      const time = Date.now();\n      if (shouldInvoke(time)) {\n        return trailingEdge(time);\n      }\n      timerId = setTimeout(timerExpired, remainingWait(time));\n    }\n    \n    function trailingEdge(time) {\n      timerId = undefined;\n      \n      if (trailing && lastArgs) {\n        return invokeFunc(time);\n      }\n      lastArgs = lastThis = undefined;\n      return result;\n    }\n    \n    function cancel() {\n      if (timerId !== undefined) {\n        clearTimeout(timerId);\n      }\n      lastInvokeTime = 0;\n      lastArgs = lastCallTime = lastThis = timerId = undefined;\n    }\n    \n    function flush() {\n      return timerId === undefined ? result : trailingEdge(Date.now());\n    }\n    \n    function debounced() {\n      const time = Date.now();\n      const isInvoking = shouldInvoke(time);\n      \n      lastArgs = arguments;\n      lastThis = this;\n      lastCallTime = time;\n      \n      if (isInvoking) {\n        if (timerId === undefined) {\n          return leadingEdge(lastCallTime);\n        }\n        if (maxing) {\n          clearTimeout(timerId);\n          timerId = setTimeout(timerExpired, wait);\n          return invokeFunc(lastCallTime);\n        }\n      }\n      if (timerId === undefined) {\n        timerId = setTimeout(timerExpired, wait);\n      }\n      return result;\n    }\n    \n    debounced.cancel = cancel;\n    debounced.flush = flush;\n    return debounced;\n  },\n  \n  throttle: function(wait, options) {\n    const func = this._value;\n    if (typeof func !== 'function') {\n      throw new TypeError('Expected a function');\n    }\n    \n    const leading = options && options.leading !== false;\n    const trailing = options && options.trailing !== false;\n    \n    return this.debounce(wait, {\n      leading: leading,\n      maxWait: wait,\n      trailing: trailing\n    });\n  },\n  \n  curry: function(arity) {\n    const func = this._value;\n    if (typeof func !== 'function') {\n      throw new TypeError('Expected a function');\n    }\n    \n    const n = arity !== undefined ? arity : func.length;\n    \n    function curried() {\n      const args = Array.from(arguments);\n      if (args.length >= n) {\n        return func.apply(this, args);\n      }\n      return function() {\n        return curried.apply(this, args.concat(Array.from(arguments)));\n      };\n    }\n    \n    return curried;\n  },\n  \n  curryRight: function(arity) {\n    const func = this._value;\n    if (typeof func !== 'function') {\n      throw new TypeError('Expected a function');\n    }\n    \n    const n = arity !== undefined ? arity : func.length;\n    \n    function curried() {\n      const args = Array.from(arguments);\n      if (args.length >= n) {\n        return func.apply(this, args);\n      }\n      return function() {\n        return curried.apply(this, Array.from(arguments).concat(args));\n      };\n    }\n    \n    return curried;\n  },\n  \n  partial: function(...partials) {\n    const func = this._value;\n    if (typeof func !== 'function') {\n      throw new TypeError('Expected a function');\n    }\n    \n    return function() {\n      const args = [];\n      let partialIndex = 0;\n      let argIndex = 0;\n      \n      for (let i = 0; i < partials.length; i++) {\n        args.push(partials[i]);\n      }\n      \n      for (let i = 0; i < arguments.length; i++) {\n        args.push(arguments[i]);\n      }\n      \n      return func.apply(this, args);\n    };\n  },\n  \n  partialRight: function(...partials) {\n    const func = this._value;\n    if (typeof func !== 'function') {\n      throw new TypeError('Expected a function');\n    }\n    \n    return function() {\n      const args = Array.from(arguments);\n      for (let i = 0; i < partials.length; i++) {\n        args.push(partials[i]);\n      }\n      return func.apply(this, args);\n    };\n  },\n  \n  memoize: function(resolver) {\n    const func = this._value;\n    if (typeof func !== 'function') {\n      throw new TypeError('Expected a function');\n    }\n    \n    const memoized = function() {\n      const key = resolver ? resolver.apply(this, arguments) : arguments[0];\n      const cache = memoized.cache;\n      \n      if (cache.has(key)) {\n        return cache.get(key);\n      }\n      const result = func.apply(this, arguments);\n      memoized.cache = cache.set(key, result) || cache;\n      return result;\n    };\n    \n    memoized.cache = new Map();\n    return memoized;\n  },\n  \n  once: function() {\n    const func = this._value;\n    if (typeof func !== 'function') {\n      throw new TypeError('Expected a function');\n    }\n    \n    let called = false;\n    let result;\n    \n    return function() {\n      if (!called) {\n        called = true;\n        result = func.apply(this, arguments);\n      }\n      return result;\n    };\n  },\n  \n  flow: function(...funcs) {\n    const firstFunc = this._value;\n    if (typeof firstFunc !== 'function') {\n      throw new TypeError('Expected a function');\n    }\n    \n    const allFuncs = [firstFunc, ...funcs];\n    \n    return function() {\n      let result = allFuncs[0].apply(this, arguments);\n      for (let i = 1; i < allFuncs.length; i++) {\n        result = allFuncs[i].call(this, result);\n      }\n      return result;\n    };\n  },\n  \n  flowRight: function(...funcs) {\n    const lastFunc = this._value;\n    if (typeof lastFunc !== 'function') {\n      throw new TypeError('Expected a function');\n    }\n    \n    const allFuncs = [...funcs, lastFunc];\n    \n    return function() {\n      let result = allFuncs[allFuncs.length - 1].apply(this, arguments);\n      for (let i = allFuncs.length - 2; i >= 0; i--) {\n        result = allFuncs[i].call(this, result);\n      }\n      return result;\n    };\n  }\n};\n"}});function hrtime(e){if("undefined"!=typeof process&&process.hrtime)return process.hrtime(e);const t=1e6*("undefined"!=typeof performance&&performance.now?performance.now():Date.now()),n=Math.floor(t/1e9),r=Math.floor(t%1e9);if(!e)return[n,r];let s=n-e[0],i=r-e[1];return i<0&&(s--,i+=1e9),[s,i]}var isExiting,init_hrtime_polyfill=__esm({"src/core/utils/hrtime-polyfill.ts"(){}});function markProcessExiting(){isExiting=!0}function isProcessExiting(){return isExiting||void 0!==process.exitCode}function setupProcessExitHandlers(){const e=()=>{markProcessExiting()};process.on("beforeExit",e),process.on("exit",e),process.on("SIGINT",e),process.on("SIGTERM",e),process.on("SIGHUP",e),process.env.NODE_ENV}var QuickJSMarshaller,QuickJSExecutionContext,QuickJSEngine,VMEngineFactory,init_quickjs_gc_workaround=__esm({"src/core/vm/quickjs-gc-workaround.ts"(){isExiting=!1}}),init_QuickJSMarshaller=__esm({"src/core/vm/engines/quickjs/QuickJSMarshaller.ts"(){QuickJSMarshaller=class{serialize(e){return null===e?{type:"null",value:null}:void 0===e?{type:"undefined",value:void 0}:"function"==typeof e?{type:"function",value:e.toString(),metadata:{name:e.name}}:Array.isArray(e)?{type:"array",value:e}:"object"==typeof e?{type:"object",value:e}:{type:"primitive",value:e}}deserialize(e){var t;const{type:n,value:r}=e;switch(n){case"null":return null;case"undefined":return;case"primitive":case"object":case"array":return r;case"function":return`[Function: ${(null==(t=e.metadata)?void 0:t.name)||"anonymous"}]`;default:throw new Error(`Cannot deserialize type: ${n}`)}}}}}),init_QuickJSEngine=__esm({"src/core/vm/engines/quickjs/QuickJSEngine.ts"(){init_hrtime_polyfill(),init_quickjs_gc_workaround(),init_QuickJSMarshaller(),QuickJSExecutionContext=class{constructor(e,t,n){this.vm=e,this.runtime=t,this.handles=[]}async setGlobal(e,t){if(null==t){const n=null===t?this.vm.null:this.vm.undefined;return void this.vm.setProp(this.vm.global,e,n)}if("string"==typeof t){const n=this.vm.newString(t);return this.vm.setProp(this.vm.global,e,n),void n.dispose()}if("number"==typeof t){const n=this.vm.newNumber(t);return this.vm.setProp(this.vm.global,e,n),void n.dispose()}if("boolean"==typeof t){const n=t?this.vm.true:this.vm.false;return void this.vm.setProp(this.vm.global,e,n)}if(t instanceof Date){const n=`new Date('${t.toISOString()}')`,r=this.vm.evalCode(n);if("error"in r&&r.error){const t=this.vm.dump(r.error);throw r.error.dispose(),new Error(`Failed to create Date for global ${e}: ${t}`)}return void("value"in r&&(this.vm.setProp(this.vm.global,e,r.value),r.value.dispose()))}const n=JSON.stringify(t),r=this.vm.global,s=this.vm.newString(n),i=this.vm.getProp(r,"JSON"),a=this.vm.getProp(i,"parse"),o=this.vm.callFunction(a,i,s);if(s.dispose(),a.dispose(),i.dispose(),"error"in o&&o.error){const t=this.vm.dump(o.error);let n;throw o.error.dispose(),n="object"==typeof t&&null!==t?`${t.name||"Error"}: ${t.message||"Unknown error"}`:String(t),new Error(`Failed to parse JSON for global ${e}: ${n}`)}"value"in o&&(this.vm.setProp(r,e,o.value),o.value.dispose())}async eval(e,t){const n=this.vm.evalCode(e,null==t?void 0:t.filename);if("error"in n&&n.error){let t="Unknown error",r="",s="Unknown";try{const e=this.vm.getProp(n.error,"name");"string"===this.vm.typeof(e)&&(s=this.vm.getString(e)),e.dispose()}catch(e){}try{const e=null!=n.error?this.vm.dump(n.error):null;e&&"object"==typeof e?("message"in e&&(t=e.message||t),"stack"in e&&(r=e.stack||""),t=JSON.stringify(e)):"string"==typeof e&&(t=e)}catch(e){try{const e=this.vm.getProp(n.error,"message");"string"===this.vm.typeof(e)&&(t=this.vm.getString(e)),e.dispose()}catch(e){}}n.error&&n.error.dispose();const i=e.length>100?`${e.substring(0,100)}...`:e;throw new Error(`${s}: ${t}\nCode: ${i}${r?`\nStack: ${r}`:""}`)}if(!("value"in n)||!n.value)throw new Error("No result value from eval");let r=-1;for(let e=0;e<100;e++){const e=this.runtime.executePendingJobs();if("error"in e&&e.error)throw"value"in n&&n.value.dispose(),e.error.dispose(),e.dispose(),new Error("Error executing pending jobs");const t="value"in e?e.value:0;if(e.dispose(),0===t)break;if(t===r)break;r=t}try{if("value"in n){const e=this.vm.dump(n.value);return n.value.dispose(),e}throw new Error("No value in result")}catch(e){throw"value"in n&&n.value.dispose(),e instanceof Error&&e.message.includes("Lifetime not alive")?new Error("Failed to resolve async operation: Promise may have been resolved but handle was disposed"):new Error(`Failed to dump result: ${e}`)}}release(){if(this.vm)try{const e="\n          if (typeof globalThis.__consoleCalls !== 'undefined') {\n            globalThis.__consoleCalls = null;\n            delete globalThis.__consoleCalls;\n          }\n        ",t=this.vm.evalCode(e);"error"in t&&t.error?t.error.dispose():"value"in t&&t.value&&t.value.dispose()}catch{}const e=[...this.handles];this.handles=[];for(let t=e.length-1;t>=0;t--){const n=e[t];try{n&&"function"==typeof n.dispose&&n.dispose()}catch{}}if(this.vm&&"function"==typeof this.vm.dispose)try{this.vm.dispose()}catch{}this.vm=void 0}},QuickJSEngine=class{constructor(e){this.quickjs=null,this.runtime=null,this.config=null,this.marshaller=new QuickJSMarshaller,this.activeContexts=[],this.cpuTimeUsed=0,this.shouldInterrupt=!1,this.appContext=e}async initialize(e){this.config=e,this.quickjs=await this.appContext.getQuickJSModule(),this.runtime=this.quickjs.newRuntime(),e.memoryLimit&&this.runtime.setMemoryLimit(1024*e.memoryLimit*1024),e.cpuLimit&&(this.cpuTimeLimit=e.cpuLimit,this.setupCpuTimeInterruptHandler()),this.runtime.setMaxStackSize(1048576)}async createContext(){if(!this.quickjs||!this.runtime)throw new Error("Engine not initialized");const e=this.runtime.newContext();try{const t="\n        globalThis.__consoleCalls = [];\n        globalThis.console = {\n          log: function(...args) {\n            globalThis.__consoleCalls.push({ method: 'log', args: args });\n          },\n          error: function(...args) {\n            globalThis.__consoleCalls.push({ method: 'error', args: args });\n          },\n          warn: function(...args) {\n            globalThis.__consoleCalls.push({ method: 'warn', args: args });\n          },\n          info: function(...args) {\n            globalThis.__consoleCalls.push({ method: 'info', args: args });\n          },\n          debug: function(...args) {\n            globalThis.__consoleCalls.push({ method: 'debug', args: args });\n          }\n        };\n      ",n=e.evalCode(t);"error"in n&&n.error?n.error.dispose():"value"in n&&n.value&&n.value.dispose()}catch{}const t=new QuickJSExecutionContext(e,this.runtime,this.marshaller);return this.activeContexts.push(t),t}async execute(e,t,n,r){const s=performance.now();for(const[t,r]of Object.entries(n))await e.setGlobal(t,r);let i=null;r.timeout&&(i=setTimeout((()=>{}),r.timeout)),this.cpuTimeLimit&&this.startCpuTimeTracking();try{const n=await e.eval(t);if(this.shouldInterrupt){const e=this.stopCpuTimeTracking(),t=new Error(`CPU time limit exceeded: ${e.toFixed(2)}ms > ${this.cpuTimeLimit}ms`);throw t.code="CPU_LIMIT",t}return{value:n,executionTime:performance.now()-s,memoryUsed:this.getMemoryUsage().used}}catch(e){throw this.cpuTimeLimit&&this.stopCpuTimeTracking(),e}finally{i&&clearTimeout(i),this.cpuTimeLimit&&this.stopCpuTimeTracking()}}getMemoryUsage(){var e,t;if(!this.runtime)return{used:0,limit:0};const n=this.runtime.computeMemoryUsage();let r;return r="number"==typeof n?{used:n,limit:(null==(e=this.config)?void 0:e.memoryLimit)||0}:{used:(n&&"object"==typeof n&&"memory_used_size"in n?n.memory_used_size:0)||0,limit:(null==(t=this.config)?void 0:t.memoryLimit)||0,external:n&&"object"==typeof n&&"malloc_size"in n?n.malloc_size:0},n&&"object"==typeof n&&"dispose"in n&&"function"==typeof n.dispose&&n.dispose(),r}async dispose(){if(isProcessExiting())return;const e=[...this.activeContexts];if(this.activeContexts=[],this.runtime){try{const e=this.runtime.executePendingJobs();"dispose"in e&&"function"==typeof e.dispose&&e.dispose()}catch{}try{"collectGarbage"in this.runtime&&"function"==typeof this.runtime.collectGarbage&&this.runtime.collectGarbage()}catch{}for(const t of e)try{t.release()}catch{}try{this.runtime.dispose()}catch(e){if("test"===process.env.NODE_ENV);else if(e&&"object"==typeof e&&"message"in e){if(!String(e.message).includes("Assertion failed: list_empty(&rt->gc_obj_list)"))throw e}}this.runtime=null}this.quickjs=null,this.config=null}setupCpuTimeInterruptHandler(){this.runtime&&this.cpuTimeLimit&&this.runtime.setInterruptHandler((()=>{if(!this.lastCheckTime||!this.cpuTimeLimit)return!1;const e=hrtime(),t=this.calculateElapsedTime(this.lastCheckTime,e);return this.lastCheckTime=e,this.cpuTimeUsed+=t,this.cpuTimeUsed>this.cpuTimeLimit&&(this.shouldInterrupt=!0,!0)}))}calculateElapsedTime(e,t){return 1e3*(t[0]-e[0])+(t[1]-e[1])/1e6}startCpuTimeTracking(){this.cpuTimeUsed=0,this.shouldInterrupt=!1,this.executionStartTime=hrtime(),this.lastCheckTime=this.executionStartTime}stopCpuTimeTracking(){if(!this.executionStartTime)return 0;const e=hrtime(),t=this.calculateElapsedTime(this.executionStartTime,e);return this.executionStartTime=void 0,this.lastCheckTime=void 0,t}}}}),VMEngineFactory_exports={};function getVMEngineType(){return"quickjs"}__export(VMEngineFactory_exports,{VMEngineFactory:()=>VMEngineFactory,getVMEngineType:()=>getVMEngineType});var VMSandboxSimple,init_VMEngineFactory=__esm({"src/core/vm/VMEngineFactory.ts"(){init_QuickJSEngine(),VMEngineFactory=class{constructor(e){this.appContext=e}create(e){return new QuickJSEngine(this.appContext)}}}}),vm_sandbox_simple_exports={};__export(vm_sandbox_simple_exports,{VMSandboxSimple:()=>VMSandboxSimple});var QuickJSVMPool,init_vm_sandbox_simple=__esm({"src/core/vm/vm-sandbox-simple.ts"(){init_VMEngineFactory(),VMSandboxSimple=class{constructor(e,t={}){this.appContext=e,this.config={memoryLimit:this.validatePositiveNumber(t.memoryLimit,128),timeout:this.validatePositiveNumber(t.timeout,3e4),enableAsync:t.enableAsync??!0,enableGenerators:t.enableGenerators??!1,enableProxies:t.enableProxies??!1,enableSymbols:t.enableSymbols??!0,maxContextSize:this.validatePositiveNumber(t.maxContextSize,10485760),recycleIsolates:t.recycleIsolates??!1,isolatePoolSize:this.validatePositiveNumber(t.isolatePoolSize,1)}}async execute(e,t={},n={}){const r=Date.now();let s=null,i=null;try{i=new VMEngineFactory(this.appContext).create("quickjs"),await i.initialize(this.config),s=await i.createContext();try{await s.eval("\n          globalThis.__consoleCalls = [];\n          globalThis.console = {\n            log: function(...args) {\n              globalThis.__consoleCalls.push({ method: 'log', args: args });\n            },\n            error: function(...args) {\n              globalThis.__consoleCalls.push({ method: 'error', args: args });\n            },\n            warn: function(...args) {\n              globalThis.__consoleCalls.push({ method: 'warn', args: args });\n            },\n            info: function(...args) {\n              globalThis.__consoleCalls.push({ method: 'info', args: args });\n            },\n            debug: function(...args) {\n              globalThis.__consoleCalls.push({ method: 'debug', args: args });\n            }\n          };\n        ")}catch(e){}for(const[e,n]of Object.entries(t))["console","JSON","Math","Date","Array","Object","String","Number","Boolean"].includes(e)||await s.setGlobal(e,n);const a={log:(...e)=>console.log(...e),error:(...e)=>console.error(...e),warn:(...e)=>console.warn(...e),info:(...e)=>console.info(...e),debug:(...e)=>console.debug(...e)},o=await i.execute(s,e,{},{...n,timeout:n.timeout??this.config.timeout});try{const e=await s.eval("globalThis.__consoleCalls");if(Array.isArray(e))for(const t of e)if(t&&"object"==typeof t&&"method"in t&&"args"in t){const e=t.method;e in a&&Array.isArray(t.args)&&a[e](...t.args)}}catch(e){}const l=Math.max(1,Date.now()-r);return{value:o.value,executionTime:l,memoryUsed:0}}catch(e){const t=Math.max(1,Date.now()-r);throw this.createSandboxError(e,t)}finally{if(s)try{s.release()}catch(e){}if(i)try{await i.dispose()}catch(e){}}}createSandboxError(e,t){let n="EXECUTION_ERROR",r="Unknown error";e instanceof Error?(r=e.message,"TimeoutError"!==e.name&&"TimeoutError"!==e.constructor.name||(n="TIMEOUT")):"string"==typeof e?r=e:e&&"object"==typeof e&&"message"in e&&(r=String(e.message));const s=r.toLowerCase();s.includes("timeout")||s.includes("timed out")||s.includes("execution timed out")||s.includes("script execution timed out")||s.includes("timeout exceeded")||s.includes("execution timeout")||s.includes("script timed out")||s.includes("script execution cancelled")||s.includes("execution was cancelled")||s.includes("cancelled")||r.includes("Script execution timed out")?n="TIMEOUT":s.includes("memory")||s.includes("isolate was disposed")||s.includes("isolate is already disposed")?n="MEMORY_LIMIT":s.includes("syntax")||s.includes("syntaxerror")?n="SYNTAX_ERROR":s.includes("reference")||s.includes("referenceerror")||s.includes("is not defined")?n="REFERENCE_ERROR":s.includes("type")||s.includes("typeerror")?n="TYPE_ERROR":t>=45&&(n="TIMEOUT");const i=new Error(r);return i.code=n,i.details={executionTime:t},i.name="SandboxError",i}async dispose(){}getConfig(){return{memoryLimit:this.config.memoryLimit,timeout:this.config.timeout,enableAsync:this.config.enableAsync,enableGenerators:this.config.enableGenerators,enableProxies:this.config.enableProxies,enableSymbols:this.config.enableSymbols,maxContextSize:this.config.maxContextSize,recycleIsolates:this.config.recycleIsolates,isolatePoolSize:this.config.isolatePoolSize}}getCapabilities(){const e=this.config.memoryLimit<64;return{console:!0,json:!0,math:!0,array:!0,object:!0,promises:this.config.enableAsync,generators:this.config.enableGenerators,proxies:this.config.enableProxies,symbols:this.config.enableSymbols,buffer:!1,crypto:!1,timers:!e,weakmap:!e,intl:!e,number:!0}}getPoolStatus(){return{size:0,maxSize:this.config.isolatePoolSize,available:0,busy:0}}validateContextValue(e){try{const t=this.estimateValueSize(e);return t>this.config.maxContextSize?{valid:!1,error:`Context value too large: ${t} bytes > ${this.config.maxContextSize} bytes`}:{valid:!0}}catch(e){return{valid:!1,error:`Validation error: ${e instanceof Error?e.message:"Unknown error"}`}}}estimateValueSize(e,t=new Set){if(null==e)return 8;if("object"==typeof e&&null!==e&&t.has(e))return 8;switch(typeof e){case"boolean":return 4;case"number":default:return 8;case"string":return 2*e.length;case"bigint":case"function":return 2*e.toString().length;case"object":{if(t.has(e))return 8;t.add(e);let n=16;if(Array.isArray(e))for(const r of e)n+=this.estimateValueSize(r,t);else if(e instanceof Date)n+=8;else if(e instanceof RegExp)n+=2*e.toString().length;else if(e instanceof Map)for(const[r,s]of e)n+=this.estimateValueSize(r,t),n+=this.estimateValueSize(s,t);else if(e instanceof Set)for(const r of e)n+=this.estimateValueSize(r,t);else for(const[r,s]of Object.entries(e))n+=2*r.length,n+=this.estimateValueSize(s,t);return t.delete(e),n}}}validatePositiveNumber(e,t){return"number"==typeof e&&e>0&&!Number.isNaN(e)?e:t}}}}),init_quickjs_vm_pool=__esm({"src/core/vm/quickjs-vm-pool.ts"(){init_QuickJSEngine(),QuickJSVMPool=class{constructor(e,t,n=4,r=100){this.pool=[],this.appContext=e,this.config=t,this.maxPoolSize=n,this.maxUseCount=r}async acquire(){const e=this.pool.find((e=>!e.inUse&&e.useCount<this.maxUseCount));if(e)return e.inUse=!0,e.lastUsed=Date.now(),e.useCount++,await this.resetContext(e.context),{engine:e.engine,execContext:e.execContext};if(this.pool.length<this.maxPoolSize){const e=await this.createNewVM();return this.pool.push(e),{engine:e.engine,execContext:e.execContext}}const t=new QuickJSEngine(this.appContext);await t.initialize(this.config);const n=await t.createContext();return{engine:t,execContext:n}}release(e){const t=this.pool.find((t=>t.engine===e));t?(t.inUse=!1,t.lastUsed=Date.now(),t.useCount>=this.maxUseCount&&(this.disposeVM(t),this.pool=this.pool.filter((e=>e!==t)))):e.dispose()}async createNewVM(){const e=new QuickJSEngine(this.appContext);await e.initialize(this.config);const t=await e.createContext();return{engine:e,runtime:e.runtime,context:t.vm,execContext:t,inUse:!0,lastUsed:Date.now(),useCount:1}}async resetContext(e){try{const t="\n        // Clear console calls\n        if (typeof globalThis.__consoleCalls !== 'undefined') {\n          globalThis.__consoleCalls = [];\n        }\n        \n        // Clear SmartDollar-related globals explicitly\n        // Use a more thorough cleanup approach\n        const smartDollarGlobals = [\n          'smartDollarModule',\n          'createSmartDollar', \n          'SmartDollar',\n          '$',\n          '_',\n          '__objectMethodsOverridden',\n          '__result__',\n          'smartDollarMethods'\n        ];\n        \n        smartDollarGlobals.forEach(key => {\n          try {\n            if (typeof globalThis[key] !== 'undefined') {\n              delete globalThis[key];\n            }\n          } catch (e) {\n            // Some properties might be non-configurable\n            try {\n              globalThis[key] = undefined;\n            } catch {}\n          }\n        });\n        \n        // Reset Object method overrides\n        if (typeof Object.__originalKeys !== 'undefined') {\n          Object.keys = Object.__originalKeys;\n          delete Object.__originalKeys;\n        }\n        if (typeof Object.__originalValues !== 'undefined') {\n          Object.values = Object.__originalValues;\n          delete Object.__originalValues;\n        }\n        if (typeof Object.__originalEntries !== 'undefined') {\n          Object.entries = Object.__originalEntries;\n          delete Object.__originalEntries;\n        }\n        \n        // Clear any user-defined globals\n        const userGlobals = Object.keys(globalThis).filter(key => {\n          const builtins = ['Object', 'Function', 'Array', 'String', 'Boolean', 'Number',\n            'Date', 'RegExp', 'Error', 'Math', 'JSON', 'Promise', 'Symbol', 'Map', 'Set',\n            'WeakMap', 'WeakSet', 'ArrayBuffer', 'DataView', 'Int8Array', 'Uint8Array',\n            'Uint8ClampedArray', 'Int16Array', 'Uint16Array', 'Int32Array', 'Uint32Array',\n            'Float32Array', 'Float64Array', 'undefined', 'null', 'Infinity', 'NaN',\n            'console', 'globalThis', 'eval', 'parseInt', 'parseFloat', 'isNaN', 'isFinite',\n            'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent'];\n          return !builtins.includes(key);\n        });\n        \n        userGlobals.forEach(key => {\n          try { \n            delete globalThis[key]; \n          } catch {\n            try {\n              globalThis[key] = undefined;\n            } catch {}\n          }\n        });\n      ",n=e.evalCode(t);"error"in n&&n.error?n.error.dispose():"value"in n&&n.value&&n.value.dispose()}catch{}try{e.runtime.executePendingJobs()}catch{}}disposeVM(e){try{e.engine.dispose()}catch{}}async dispose(){for(const e of this.pool)this.disposeVM(e);this.pool=[]}getPoolStats(){const e=this.pool.filter((e=>!e.inUse)).length,t=this.pool.filter((e=>e.inUse)).length;return{totalVMs:this.pool.length,availableVMs:e,inUseVMs:t}}}}}),lodash_vm_exports={};function createVMLodashCode(){return`\n${LODASH_METHODS}\n\n// Simplified Lodash class for VM environment\nif (typeof Lodash === 'undefined') {\n  globalThis.Lodash = class Lodash {\n    constructor(value) {\n      this._value = value;\n      // Don't set this.value here - it conflicts with the value() method\n      this.__isLodash = true;\n    }\n    \n    [Symbol.iterator]() {\n      if (this._value === null || this._value === undefined) {\n        return [][Symbol.iterator]();\n      }\n      if (Array.isArray(this._value) || typeof this._value === 'string') {\n        return this._value[Symbol.iterator]();\n      }\n      if (this._value && typeof this._value === 'object') {\n        return Object.entries(this._value)[Symbol.iterator]();\n      }\n      return [][Symbol.iterator]();\n    }\n    \n    toJSON() {\n      return this._value;\n    }\n    \n    valueOf() {\n      return this._value;\n    }\n    \n    toString() {\n      if (this._value === null) return 'null';\n      if (this._value === undefined) return 'undefined';\n      return String(this._value);\n    }\n    \n    [Symbol.toPrimitive](hint) {\n      if (hint === 'string') {\n        return this.toString();\n      }\n      return this._value;\n    }\n  };\n}\n\n// Apply all methods to Lodash prototype\nif (typeof globalThis.lodashMethods !== 'undefined' && typeof globalThis.Lodash !== 'undefined') {\n  Object.entries(globalThis.lodashMethods).forEach(([name, fn]) => {\n    // Create a wrapper function to override toString\n    const prototypeMethod = function(...args) {\n      return fn.apply(this, args);\n    };\n    \n    // Override toString to display [native code] like built-in functions\n    prototypeMethod.toString = function() {\n      return 'function bound ' + name + '() {[native code]}';\n    };\n    \n    globalThis.Lodash.prototype[name] = prototypeMethod;\n  });\n}\n\n// Create _ function with Proxy support\nglobalThis.createLodash = function(value) {\n  if (value === null || value === undefined) {\n    return value;\n  }\n  \n  // Create lodash instance without proxy\n  const lodash = new globalThis.Lodash(value);\n  \n  // Add property access directly to the instance\n  if (value !== null && value !== undefined && typeof value === 'object') {\n    // For arrays, add numeric indices\n    if (Array.isArray(value)) {\n      for (let i = 0; i < value.length; i++) {\n        Object.defineProperty(lodash, i, {\n          get() {\n            return this._value[i];\n          },\n          set(val) {\n            this._value[i] = val;\n          },\n          enumerable: true,\n          configurable: true\n        });\n      }\n    }\n    \n    // For objects, add property access\n    for (const key in value) {\n      if (Object.prototype.hasOwnProperty.call(value, key) && !(key in lodash)) {\n        Object.defineProperty(lodash, key, {\n          get() {\n            const val = this._value[key];\n            if (val !== null && val !== undefined && typeof val === 'object') {\n              return globalThis.createLodash(val);\n            }\n            return val;\n          },\n          set(val) {\n            this._value[key] = val;\n          },\n          enumerable: true,\n          configurable: true\n        });\n      }\n    }\n  }\n  \n  return lodash;\n};\n\n// Set up _ for direct use (always override)\n// Create _ as a function that wraps values\nglobalThis._ = function(value) {\n  if (arguments.length === 0) {\n    // If called without arguments and data exists AND is not null, use data\n    if (typeof globalThis.data !== 'undefined' && globalThis.data !== null) {\n      return globalThis.createLodash(globalThis.data);\n    }\n    // Otherwise return undefined\n    return undefined;\n  }\n  return globalThis.createLodash(value);\n};\n\n// Override toString to display [native code]\nglobalThis._.toString = function() {\n  return 'function() {[native code]}';\n};\n\n// Add static methods to _ (like _.chunk, _.filter, etc)\nObject.entries(globalThis.lodashMethods).forEach(([name, fn]) => {\n  const staticMethod = function(...args) {\n    // Special handling for pure utility functions that don't operate on data\n    if (name === 'range') {\n      // _.range(end) or _.range(start, end, step)\n      if (args.length === 0) return [];\n      if (args.length === 1) {\n        // _.range(5) -> [0, 1, 2, 3, 4]\n        const end = Number(args[0]) || 0;\n        const result = [];\n        for (let i = 0; i < end; i++) {\n          result.push(i);\n        }\n        return result;\n      } else {\n        // _.range(2, 8) or _.range(2, 8, 2)\n        const start = Number(args[0]) || 0;\n        const end = Number(args[1]) || 0;\n        const step = Number(args[2]) || 1;\n        const result = [];\n        if (step > 0) {\n          for (let i = start; i < end; i += step) {\n            result.push(i);\n          }\n        } else {\n          for (let i = start; i > end; i += step) {\n            result.push(i);\n          }\n        }\n        return result;\n      }\n    }\n    \n    if (name === 'times') {\n      // _.times(n, iteratee)\n      if (args.length === 0) return [];\n      const n = Number(args[0]) || 0;\n      const iteratee = args[1] || ((i) => i);\n      const results = [];\n      for (let i = 0; i < n; i++) {\n        results.push(iteratee(i));\n      }\n      return results;\n    }\n    \n    // Type checking functions - operate directly on first argument\n    if (name === 'isArray' || name === 'isObject' || name === 'isString' || \n        name === 'isNumber' || name === 'isFunction' || name === 'isNull' || \n        name === 'isUndefined') {\n      if (args.length === 0) return false;\n      let value = args[0];\n      // Auto-unwrap SmartDollar/ChainableWrapper instances\n      if (value && typeof value === 'object') {\n        if (value.__isSmartDollar || value.__isChainableWrapper) {\n          value = value.valueOf();\n        }\n      }\n      const wrapped = new globalThis.Lodash(value);\n      return wrapped[name]();\n    }\n    \n    // For static methods, wrap the first argument\n    if (args.length > 0) {\n      let dataToWrap = args[0];\n      \n      // If the first argument is a SmartDollar instance, unwrap it\n      if (dataToWrap && typeof dataToWrap === 'object' && dataToWrap.__isSmartDollar) {\n        dataToWrap = dataToWrap.valueOf();\n      }\n      \n      const wrapped = new globalThis.Lodash(dataToWrap);\n      const result = wrapped[name](...args.slice(1));\n      // If result is a Lodash instance, unwrap it for static methods\n      if (result && typeof result === 'object' && result.__isLodash) {\n        return result._value;\n      }\n      return result;\n    }\n    // For methods that don't need arguments\n    return fn.call({_value: undefined, constructor: globalThis.Lodash});\n  };\n  \n  // Override toString to display [native code] like built-in functions\n  staticMethod.toString = function() {\n    return 'function bound ' + name + '() {[native code]}';\n  };\n  \n  globalThis._[name] = staticMethod;\n});\n`}__export(lodash_vm_exports,{createVMLodashCode:()=>createVMLodashCode});var SMART_DOLLAR_METHODS,init_lodash_vm=__esm({"src/core/lodash/lodash-vm.ts"(){init_lodash_shared_methods()}}),init_smart_dollar_shared_methods=__esm({"src/core/smart-dollar/smart-dollar-shared-methods.ts"(){SMART_DOLLAR_METHODS="\nif (typeof smartDollarMethods === 'undefined') {\n  // Helper function to create new instances  \n  const createNewInstance = function(data) {\n    // Check if we can use the constructor\n    if (this && this.constructor) {\n      try {\n        return new this.constructor(data);\n      } catch (e) {\n        // Constructor might not work properly in all contexts\n      }\n    }\n    \n    // If we have access to global SmartDollar with createInstance, use it\n    if (typeof globalThis.SmartDollar !== 'undefined' && \n        typeof globalThis.SmartDollar.createInstance === 'function') {\n      return globalThis.SmartDollar.createInstance(data);\n    }\n    \n    // Otherwise try direct SmartDollar constructor\n    if (typeof globalThis.SmartDollar !== 'undefined') {\n      return new globalThis.SmartDollar(data);\n    }\n    \n    // Fallback: return raw data\n    return data;\n  };\n  \n  globalThis.smartDollarMethods = {\n  // Array methods\n  map: function(dataOrFn, fn) {\n    // Handle both $.map(array, fn) and array.map(fn) usage\n    let data, mapFn;\n    if (arguments.length === 1) {\n      // Instance method: array.map(fn)\n      data = this._value;\n      mapFn = dataOrFn;\n    } else {\n      // Static method: $.map(array, fn)\n      data = dataOrFn;\n      mapFn = fn;\n    }\n    \n    if (data === null || data === undefined) {\n      return createNewInstance.call(this, []);\n    }\n    const mapped = Array.from(data).map((item, index) => mapFn(item, index, data));\n    return createNewInstance.call(this, mapped);\n  },\n  \n  filter: function(dataOrFn, fn) {\n    // Handle both $.filter(array, fn) and array.filter(fn) usage\n    let data, filterFn;\n    if (arguments.length === 1) {\n      // Instance method: array.filter(fn)\n      data = this._value;\n      filterFn = dataOrFn;\n    } else {\n      // Static method: $.filter(array, fn)\n      data = dataOrFn;\n      filterFn = fn;\n    }\n    \n    if (data === null || data === undefined) {\n      return createNewInstance.call(this, []);\n    }\n    const filtered = Array.from(data).filter((item, index) => filterFn(item, index, data));\n    return createNewInstance.call(this, filtered);\n  },\n  \n  reduce: function(fn, initial) {\n    if (this._value === null || this._value === undefined) {\n      return initial;\n    }\n    const arr = Array.from(this._value);\n    if (arguments.length === 1) {\n      // initialが省略された場合\n      return arr.reduce(fn);\n    }\n    return arr.reduce(fn, initial);\n  },\n  \n  slice: function(start, end) {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, []);\n    }\n    const sliced = Array.from(this._value).slice(start, end);\n    return createNewInstance.call(this, sliced);\n  },\n  \n  concat: function(...args) {\n    // Unwrap any SmartDollar instances in the arguments\n    const unwrappedArgs = args.map(arg => {\n      if (arg && typeof arg === 'object' && arg.__isSmartDollar) {\n        return arg._value;\n      }\n      return arg;\n    });\n    const concatenated = Array.from(this._value).concat(...unwrappedArgs);\n    return createNewInstance.call(this, concatenated);\n  },\n  \n  push: function(...elements) {\n    // Mutate the original array if it's an array\n    if (Array.isArray(this._value)) {\n      return this._value.push(...elements);\n    }\n    // Fallback for non-arrays\n    const arr = Array.from(this._value);\n    arr.push(...elements);\n    return arr.length;\n  },\n  \n  pop: function() {\n    // Mutate the original array if it's an array\n    if (Array.isArray(this._value)) {\n      return this._value.pop();\n    }\n    // Fallback for non-arrays\n    const arr = Array.from(this._value);\n    return arr.pop();\n  },\n  \n  shift: function() {\n    // Mutate the original array if it's an array\n    if (Array.isArray(this._value)) {\n      return this._value.shift();\n    }\n    // Fallback for non-arrays\n    const arr = Array.from(this._value);\n    return arr.shift();\n  },\n  \n  unshift: function(...elements) {\n    // Mutate the original array if it's an array\n    if (Array.isArray(this._value)) {\n      return this._value.unshift(...elements);\n    }\n    // Fallback for non-arrays\n    const arr = Array.from(this._value);\n    arr.unshift(...elements);\n    return arr.length;\n  },\n  \n  splice: function(start, deleteCount, ...items) {\n    // Mutate the original array if it's an array\n    if (Array.isArray(this._value)) {\n      return this._value.splice(start, deleteCount, ...items);\n    }\n    // Fallback for non-arrays\n    const arr = Array.from(this._value);\n    return arr.splice(start, deleteCount, ...items);\n  },\n  \n  find: function(fn) {\n    const found = Array.from(this._value).find((item, index) => fn(item, index, this._value));\n    return found !== undefined ? new this.constructor(found) : new this.constructor(null);\n  },\n  \n  some: function(fn) {\n    return Array.from(this._value).some((item, index) => fn(item, index, this._value));\n  },\n  \n  every: function(fn) {\n    return Array.from(this._value).every((item, index) => fn(item, index, this._value));\n  },\n  \n  includes: function(searchElement, fromIndex) {\n    return Array.from(this._value).includes(searchElement, fromIndex);\n  },\n  \n  indexOf: function(searchElement, fromIndex) {\n    return Array.from(this._value).indexOf(searchElement, fromIndex);\n  },\n  \n  lastIndexOf: function(searchElement, fromIndex) {\n    // Manual implementation due to weird issue with Array.from and new Function\n    const arr = Array.isArray(this._value) ? this._value : Array.from(this._value);\n    const len = arr.length;\n    \n    if (len === 0) return -1;\n    \n    let n = fromIndex == null ? len - 1 : Number(fromIndex);\n    \n    if (n >= len) {\n      n = len - 1;\n    } else if (n < 0) {\n      n = len + n;\n      if (n < 0) return -1;\n    }\n    \n    for (let i = n; i >= 0; i--) {\n      if (arr[i] === searchElement) {\n        return i;\n      }\n    }\n    \n    return -1;\n  },\n  \n  findIndex: function(predicate, thisArg) {\n    return Array.from(this._value).findIndex(predicate, thisArg);\n  },\n  \n  join: function(separator) {\n    return Array.from(this._value).join(separator);\n  },\n  \n  reverse: function() {\n    // Mutate the original array if it's an array\n    if (Array.isArray(this._value)) {\n      this._value.reverse();\n      return this; // Return this for chaining\n    }\n    // Fallback for non-arrays\n    const reversed = Array.from(this._value).reverse();\n    return createNewInstance.call(this, reversed);\n  },\n  \n  sort: function(compareFn) {\n    // Mutate the original array if it's an array\n    if (Array.isArray(this._value)) {\n      this._value.sort(compareFn);\n      return this; // Return this for chaining\n    }\n    // Fallback for non-arrays\n    const sorted = Array.from(this._value).sort(compareFn);\n    return createNewInstance.call(this, sorted);\n  },\n  \n  // Object methods\n  keys: function() {\n    const keys = Object.keys(this._value);\n    return createNewInstance.call(this, keys);\n  },\n  \n  values: function() {\n    const values = Object.values(this._value);\n    return createNewInstance.call(this, values);\n  },\n  \n  entries: function() {\n    const entries = Object.entries(this._value);\n    return createNewInstance.call(this, entries);\n  },\n  \n  hasOwn: function(prop) {\n    return Object.hasOwn(this._value, prop);\n  },\n  \n  assign: function(...sources) {\n    const assigned = Object.assign({}, this._value, ...sources);\n    return createNewInstance.call(this, assigned);\n  },\n  \n  // String methods\n  split: function(separator, limit) {\n    const parts = String(this._value).split(separator, limit);\n    return createNewInstance.call(this, parts);\n  },\n  \n  replace: function(search, replacement) {\n    const replaced = String(this._value).replace(search, replacement);\n    return createNewInstance.call(this, replaced);\n  },\n  \n  replaceAll: function(search, replacement) {\n    const replaced = String(this._value).replaceAll(search, replacement);\n    return createNewInstance.call(this, replaced);\n  },\n  \n  toLowerCase: function() {\n    const lowered = String(this._value).toLowerCase();\n    return createNewInstance.call(this, lowered);\n  },\n  \n  toUpperCase: function() {\n    const uppered = String(this._value).toUpperCase();\n    return createNewInstance.call(this, uppered);\n  },\n  \n  trim: function() {\n    const trimmed = String(this._value).trim();\n    return createNewInstance.call(this, trimmed);\n  },\n  \n  substring: function(start, end) {\n    const sub = String(this._value).substring(start, end);\n    return createNewInstance.call(this, sub);\n  },\n  \n  charAt: function(index) {\n    return String(this._value).charAt(index);\n  },\n  \n  charCodeAt: function(index) {\n    return String(this._value).charCodeAt(index);\n  },\n  \n  startsWith: function(searchString, position) {\n    return String(this._value).startsWith(searchString, position);\n  },\n  \n  endsWith: function(searchString, position) {\n    return String(this._value).endsWith(searchString, position);\n  },\n  \n  padStart: function(targetLength, padString) {\n    const padded = String(this._value).padStart(targetLength, padString);\n    return createNewInstance.call(this, padded);\n  },\n  \n  padEnd: function(targetLength, padString) {\n    const padded = String(this._value).padEnd(targetLength, padString);\n    return createNewInstance.call(this, padded);\n  },\n  \n  match: function(regexp) {\n    const matches = String(this._value).match(regexp);\n    return matches ? new this.constructor(matches) : new this.constructor(null);\n  },\n  \n  search: function(regexp) {\n    return String(this._value).search(regexp);\n  },\n  \n  // Number methods\n  toFixed: function(digits) {\n    return Number(this._value).toFixed(digits);\n  },\n  \n  toExponential: function(fractionDigits) {\n    return Number(this._value).toExponential(fractionDigits);\n  },\n  \n  toPrecision: function(precision) {\n    return Number(this._value).toPrecision(precision);\n  },\n  \n  // Type conversion methods\n  toString: function() {\n    if (this._value === null || this._value === undefined) {\n      return '';\n    }\n    return String(this._value);\n  },\n  \n  toNumber: function() {\n    return Number(this._value);\n  },\n  \n  toBoolean: function() {\n    return Boolean(this._value);\n  },\n  \n  toArray: function() {\n    if (Array.isArray(this._value)) {\n      return Array.from(this._value);\n    }\n    if (this._value && typeof this._value === 'object' && this._value.constructor === Object) {\n      return Object.entries(this._value);\n    }\n    return [this._value];\n  },\n  \n  // Object methods\n  pick: function(...args) {\n    const result = {};\n    const obj = this._value;\n    // Support both array syntax and spread syntax\n    const keys = args.length === 1 && Array.isArray(args[0]) ? args[0] : args;\n    if (obj && typeof obj === 'object') {\n      for (const key of keys) {\n        if (key in obj) {\n          result[key] = obj[key];\n        }\n      }\n    }\n    return createNewInstance.call(this, result);\n  },\n  \n  omit: function(...args) {\n    const result = {};\n    const obj = this._value;\n    // Support both array syntax and spread syntax\n    const keys = args.length === 1 && Array.isArray(args[0]) ? args[0] : args;\n    if (obj && typeof obj === 'object') {\n      for (const key in obj) {\n        if (!keys.includes(key)) {\n          result[key] = obj[key];\n        }\n      }\n    }\n    return createNewInstance.call(this, result);\n  },\n  \n  // Utility methods\n  pipe: function(...fns) {\n    return fns.reduce((acc, fn) => new this.constructor(fn(acc._value)), this);\n  },\n  \n  tap: function(fn) {\n    fn(this._value);\n    return this;\n  },\n  \n  value: function() {\n    // Also update public value property for VM unwrapping\n    this.value = this._value;\n    return this._value;\n  },\n  \n  valueOf: function() {\n    return this._value;\n  },\n  \n  isNull: function() {\n    return this._value === null;\n  },\n  \n  isUndefined: function() {\n    return this._value === undefined;\n  },\n  \n  isNullOrUndefined: function() {\n    return this._value === null || this._value === undefined;\n  },\n  \n  isEmpty: function() {\n    if (this._value === null || this._value === undefined) return true;\n    if (Array.isArray(this._value)) return this._value.length === 0;\n    if (typeof this._value === 'string') return this._value.length === 0;\n    if (typeof this._value === 'object') return Object.keys(this._value).length === 0;\n    return false;\n  },\n  \n  // Chainable conditions\n  when: function(condition, trueFn, falseFn) {\n    if (condition) {\n      return trueFn ? new this.constructor(trueFn(this._value)) : this;\n    } else {\n      return falseFn ? new this.constructor(falseFn(this._value)) : this;\n    }\n  },\n  \n  unless: function(condition, fn) {\n    return this.when(!condition, fn);\n  },\n  \n  // Lodash-like methods\n  where: function(properties, value) {\n    const filtered = Array.from(this._value).filter(item => {\n      if (!item || typeof item !== 'object') return false;\n      \n      // If called with two arguments (key, value)\n      if (typeof properties === 'string' && value !== undefined) {\n        return item[properties] === value;\n      }\n      \n      // If called with object (properties)\n      if (typeof properties === 'object' && properties !== null) {\n        return Object.entries(properties).every(([key, val]) => item[key] === val);\n      }\n      \n      return false;\n    });\n    return createNewInstance.call(this, filtered);\n  },\n  \n  pluck: function(property) {\n    const plucked = Array.from(this._value).map(item => item ? item[property] : undefined);\n    return createNewInstance.call(this, plucked);\n  },\n  \n  sortBy: function(iteratee) {\n    const sorted = Array.from(this._value).sort((a, b) => {\n      const aVal = typeof iteratee === 'function' ? iteratee(a) : a[iteratee];\n      const bVal = typeof iteratee === 'function' ? iteratee(b) : b[iteratee];\n      if (aVal < bVal) return -1;\n      if (aVal > bVal) return 1;\n      return 0;\n    });\n    return createNewInstance.call(this, sorted);\n  },\n  \n  groupBy: function(iteratee) {\n    const grouped = Array.from(this._value).reduce((acc, item) => {\n      const key = typeof iteratee === 'function' ? iteratee(item) : item[iteratee];\n      if (!acc[key]) acc[key] = [];\n      acc[key].push(item);\n      return acc;\n    }, {});\n    return createNewInstance.call(this, grouped);\n  },\n  \n  countBy: function(iteratee) {\n    const counted = Array.from(this._value).reduce((acc, item) => {\n      const key = typeof iteratee === 'function' ? iteratee(item) : item[iteratee];\n      acc[key] = (acc[key] || 0) + 1;\n      return acc;\n    }, {});\n    return createNewInstance.call(this, counted);\n  },\n  \n  take: function(n) {\n    const taken = Array.from(this._value).slice(0, n);\n    return createNewInstance.call(this, taken);\n  },\n  \n  skip: function(n) {\n    const skipped = Array.from(this._value).slice(n);\n    return createNewInstance.call(this, skipped);\n  },\n  \n  uniqBy: function(iteratee) {\n    const seen = new Map();\n    const unique = Array.from(this._value).filter(item => {\n      const key = typeof iteratee === 'function' ? iteratee(item) : item[iteratee];\n      if (seen.has(key)) return false;\n      seen.set(key, true);\n      return true;\n    });\n    return createNewInstance.call(this, unique);\n  },\n  \n  flatten: function() {\n    const flattened = Array.from(this._value).reduce((acc, val) => \n      acc.concat(Array.isArray(val) ? val : [val]), []);\n    return createNewInstance.call(this, flattened);\n  },\n  \n  flatMap: function(fn) {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, []);\n    }\n    const mapped = Array.from(this._value).flatMap((item, index) => fn(item, index, this._value));\n    return createNewInstance.call(this, mapped);\n  },\n  \n  flattenDeep: function(data) {\n    const flattenDeepRecursive = (arr) => {\n      return arr.reduce((acc, val) => \n        acc.concat(Array.isArray(val) ? flattenDeepRecursive(val) : val), []);\n    };\n    // If called with an argument, use that instead of this._value\n    const target = arguments.length > 0 ? data : this._value;\n    const flattened = flattenDeepRecursive(Array.from(target));\n    return createNewInstance.call(this, flattened);\n  },\n  \n  compact: function(data) {\n    // If called with an argument, use that instead of this._value\n    const target = arguments.length > 0 ? data : this._value;\n    const compacted = Array.from(target).filter(Boolean);\n    return createNewInstance.call(this, compacted);\n  },\n  \n  chunk: function(size) {\n    const arr = Array.from(this._value);\n    const chunks = [];\n    for (let i = 0; i < arr.length; i += size) {\n      chunks.push(arr.slice(i, i + size));\n    }\n    return createNewInstance.call(this, chunks);\n  },\n  \n  sum: function(key) {\n    const arr = Array.from(this._value);\n    if (key && typeof key === 'string') {\n      return arr.reduce((acc, val) => acc + (Number(val?.[key]) || 0), 0);\n    }\n    return arr.reduce((acc, val) => acc + (Number(val) || 0), 0);\n  },\n  \n  mean: function() {\n    const arr = Array.from(this._value);\n    if (arr.length === 0) return NaN;\n    let sum = 0;\n    for (let i = 0; i < arr.length; i++) {\n      sum += Number(arr[i]) || 0;\n    }\n    return sum / arr.length;\n  },\n  \n  size: function() {\n    if (Array.isArray(this._value) || typeof this._value === 'string') {\n      return this._value.length;\n    }\n    if (this._value && typeof this._value === 'object') {\n      return Object.keys(this._value).length;\n    }\n    return 0;\n  },\n  \n  orderBy: function(iteratees, orders) {\n    const arr = Array.from(this._value);\n    const iterateeArr = Array.isArray(iteratees) ? iteratees : [iteratees];\n    const orderArr = Array.isArray(orders) ? orders : [orders];\n    \n    const sorted = arr.sort((a, b) => {\n      for (let i = 0; i < iterateeArr.length; i++) {\n        const iteratee = iterateeArr[i];\n        const order = orderArr[i] || 'asc';\n        const aVal = typeof iteratee === 'function' ? iteratee(a) : a[iteratee];\n        const bVal = typeof iteratee === 'function' ? iteratee(b) : b[iteratee];\n        \n        if (aVal < bVal) return order === 'asc' ? -1 : 1;\n        if (aVal > bVal) return order === 'asc' ? 1 : -1;\n      }\n      return 0;\n    });\n    return createNewInstance.call(this, sorted);\n  },\n  \n  keyBy: function(iteratee) {\n    const keyed = Array.from(this._value).reduce((acc, item) => {\n      const key = typeof iteratee === 'function' ? iteratee(item) : item[iteratee];\n      acc[key] = item;\n      return acc;\n    }, {});\n    return createNewInstance.call(this, keyed);\n  },\n  \n  takeWhile: function(predicate) {\n    const arr = Array.from(this._value);\n    const taken = [];\n    for (let i = 0; i < arr.length; i++) {\n      if (!predicate(arr[i], i, arr)) break;\n      taken.push(arr[i]);\n    }\n    return createNewInstance.call(this, taken);\n  },\n  \n  dropWhile: function(predicate) {\n    const arr = Array.from(this._value);\n    let dropIndex = 0;\n    for (let i = 0; i < arr.length; i++) {\n      if (!predicate(arr[i], i, arr)) {\n        dropIndex = i;\n        break;\n      }\n    }\n    return createNewInstance.call(this, arr.slice(dropIndex));\n  },\n  \n  min: function() {\n    const arr = Array.from(this._value);\n    if (arr.length === 0) return undefined;\n    return Math.min(...arr);\n  },\n  \n  max: function() {\n    const arr = Array.from(this._value);\n    if (arr.length === 0) return undefined;\n    return Math.max(...arr);\n  },\n  \n  minBy: function(iteratee) {\n    const arr = Array.from(this._value);\n    if (arr.length === 0) return undefined;\n    return arr.reduce((min, item) => {\n      const itemVal = typeof iteratee === 'function' ? iteratee(item) : item[iteratee];\n      const minVal = typeof iteratee === 'function' ? iteratee(min) : min[iteratee];\n      return itemVal < minVal ? item : min;\n    });\n  },\n  \n  maxBy: function(iteratee) {\n    const arr = Array.from(this._value);\n    if (arr.length === 0) return undefined;\n    return arr.reduce((max, item) => {\n      const itemVal = typeof iteratee === 'function' ? iteratee(item) : item[iteratee];\n      const maxVal = typeof iteratee === 'function' ? iteratee(max) : max[iteratee];\n      return itemVal > maxVal ? item : max;\n    });\n  },\n  \n  sample: function() {\n    const arr = Array.from(this._value);\n    if (arr.length === 0) return undefined;\n    return arr[Math.floor(Math.random() * arr.length)];\n  },\n  \n  sampleSize: function(n) {\n    const arr = Array.from(this._value);\n    const shuffled = [...arr].sort(() => Math.random() - 0.5);\n    return createNewInstance.call(this, shuffled.slice(0, n));\n  },\n  \n  shuffle: function() {\n    const arr = Array.from(this._value);\n    const shuffled = [...arr].sort(() => Math.random() - 0.5);\n    return createNewInstance.call(this, shuffled);\n  },\n  \n  // Async methods\n  mapAsync: async function(fn) {\n    // Convert to array using same logic as toArray method\n    let arr;\n    if (Array.isArray(this._value)) {\n      arr = Array.from(this._value);\n    } else {\n      // For non-arrays, treat as single value\n      arr = [this._value];\n    }\n    const promises = arr.map((item, index) => fn(item, index, arr));\n    const results = await Promise.all(promises);\n    return createNewInstance.call(this, results);\n  },\n  \n  mapAsyncSeq: async function(fn) {\n    const results = [];\n    // Convert to array using same logic as toArray method\n    let arr;\n    if (Array.isArray(this._value)) {\n      arr = Array.from(this._value);\n    } else {\n      // For non-arrays, treat as single value\n      arr = [this._value];\n    }\n    for (let i = 0; i < arr.length; i++) {\n      results.push(await fn(arr[i], i, arr));\n    }\n    return createNewInstance.call(this, results);\n  },\n  \n  forEachAsync: async function(fn) {\n    // Convert to array using same logic as toArray method\n    let arr;\n    if (Array.isArray(this._value)) {\n      arr = Array.from(this._value);\n    } else {\n      // For non-arrays, treat as single value\n      arr = [this._value];\n    }\n    const promises = arr.map((item, index) => fn(item, index, arr));\n    await Promise.all(promises);\n  },\n  \n  forEachAsyncSeq: async function(fn) {\n    // Convert to array using same logic as toArray method\n    let arr;\n    if (Array.isArray(this._value)) {\n      arr = Array.from(this._value);\n    } else {\n      // For non-arrays, treat as single value\n      arr = [this._value];\n    }\n    for (let i = 0; i < arr.length; i++) {\n      await fn(arr[i], i, arr);\n    }\n  },\n  \n  // === Modern Functional Programming Methods ===\n  \n  // 1. fold/foldLeft - left associative fold (Scala/Haskell style)\n  fold: function(fn, initial) {\n    return this.reduce(fn, initial);\n  },\n  \n  foldLeft: function(fn, initial) {\n    return this.reduce(fn, initial);\n  },\n  \n  // 2. foldRight - right associative fold \n  foldRight: function(fn, initial) {\n    if (this._value === null || this._value === undefined) {\n      return initial;\n    }\n    const arr = Array.from(this._value);\n    let result = initial;\n    for (let i = arr.length - 1; i >= 0; i--) {\n      result = fn(arr[i], result, i, arr);\n    }\n    return result;\n  },\n  \n  // 3. scan/scanLeft - like fold but returns all intermediate results\n  scan: function(fn, initial) {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, [initial]);\n    }\n    const arr = Array.from(this._value);\n    const results = [initial];\n    let acc = initial;\n    for (let i = 0; i < arr.length; i++) {\n      acc = fn(acc, arr[i], i, arr);\n      results.push(acc);\n    }\n    return createNewInstance.call(this, results);\n  },\n  \n  scanLeft: function(fn, initial) {\n    return this.scan(fn, initial);\n  },\n  \n  // 4. scanRight - right associative scan\n  scanRight: function(fn, initial) {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, [initial]);\n    }\n    const arr = Array.from(this._value);\n    const results = [initial];\n    let acc = initial;\n    for (let i = arr.length - 1; i >= 0; i--) {\n      acc = fn(arr[i], acc, i, arr);\n      results.unshift(acc);\n    }\n    return createNewInstance.call(this, results);\n  },\n  \n  // 5. zip - combine two arrays into array of pairs\n  zip: function(other) {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, []);\n    }\n    const arr1 = Array.from(this._value);\n    const arr2 = Array.isArray(other) ? other : \n                 (other && typeof other === 'object' && other.__isSmartDollar) ? \n                 Array.from(other._value) : [other];\n    const length = Math.min(arr1.length, arr2.length);\n    const zipped = [];\n    for (let i = 0; i < length; i++) {\n      zipped.push([arr1[i], arr2[i]]);\n    }\n    return createNewInstance.call(this, zipped);\n  },\n  \n  // 6. zipWith - zip with custom combining function\n  zipWith: function(other, fn) {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, []);\n    }\n    const arr1 = Array.from(this._value);\n    const arr2 = Array.isArray(other) ? other : \n                 (other && typeof other === 'object' && other.__isSmartDollar) ? \n                 Array.from(other._value) : [other];\n    const length = Math.min(arr1.length, arr2.length);\n    const zipped = [];\n    for (let i = 0; i < length; i++) {\n      zipped.push(fn(arr1[i], arr2[i], i));\n    }\n    return createNewInstance.call(this, zipped);\n  },\n  \n  // 7. unzip - convert array of pairs into two arrays\n  unzip: function() {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, [[], []]);\n    }\n    const arr = Array.from(this._value);\n    const first = [];\n    const second = [];\n    for (let i = 0; i < arr.length; i++) {\n      if (Array.isArray(arr[i]) && arr[i].length >= 2) {\n        first.push(arr[i][0]);\n        second.push(arr[i][1]);\n      }\n    }\n    return createNewInstance.call(this, [first, second]);\n  },\n  \n  // 8. intersperse - insert separator between elements\n  intersperse: function(separator) {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, []);\n    }\n    const arr = Array.from(this._value);\n    if (arr.length <= 1) {\n      return createNewInstance.call(this, arr);\n    }\n    const result = [arr[0]];\n    for (let i = 1; i < arr.length; i++) {\n      result.push(separator);\n      result.push(arr[i]);\n    }\n    return createNewInstance.call(this, result);\n  },\n  \n  // 9. sliding/windows - sliding window over array\n  sliding: function(size, step) {\n    if (step === undefined) step = 1;\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, []);\n    }\n    const arr = Array.from(this._value);\n    const result = [];\n    for (let i = 0; i <= arr.length - size; i += step) {\n      result.push(arr.slice(i, i + size));\n    }\n    return createNewInstance.call(this, result);\n  },\n  \n  windows: function(size, step) {\n    return this.sliding(size, step);\n  },\n  \n  // 10. enumerate - add index to each element as [index, value] pairs\n  enumerate: function() {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, []);\n    }\n    const arr = Array.from(this._value);\n    const enumerated = [];\n    for (let i = 0; i < arr.length; i++) {\n      enumerated.push([i, arr[i]]);\n    }\n    return createNewInstance.call(this, enumerated);\n  },\n  \n  // === Haskell/FP Style Methods ===\n  \n  // 11. head - get first element\n  head: function() {\n    if (this._value === null || this._value === undefined) {\n      return undefined;\n    }\n    const arr = Array.from(this._value);\n    return arr[0];\n  },\n  \n  // 12. tail - get all elements except first\n  tail: function() {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, []);\n    }\n    const arr = Array.from(this._value);\n    return createNewInstance.call(this, arr.slice(1));\n  },\n  \n  // 13. init - get all elements except last\n  init: function() {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, []);\n    }\n    const arr = Array.from(this._value);\n    return createNewInstance.call(this, arr.slice(0, -1));\n  },\n  \n  // 14. last - get last element\n  last: function() {\n    if (this._value === null || this._value === undefined) {\n      return undefined;\n    }\n    const arr = Array.from(this._value);\n    return arr[arr.length - 1];\n  },\n  \n  // 15. cons - prepend element to list\n  cons: function(element) {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, [element]);\n    }\n    const arr = Array.from(this._value);\n    return createNewInstance.call(this, [element, ...arr]);\n  },\n  \n  // 16. snoc - append element to list\n  snoc: function(element) {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, [element]);\n    }\n    const arr = Array.from(this._value);\n    return createNewInstance.call(this, [...arr, element]);\n  },\n  \n  // 17. span - split array at first element that doesn't match predicate\n  span: function(predicate) {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, [[], []]);\n    }\n    const arr = Array.from(this._value);\n    let i = 0;\n    while (i < arr.length && predicate(arr[i], i, arr)) {\n      i++;\n    }\n    return createNewInstance.call(this, [arr.slice(0, i), arr.slice(i)]);\n  },\n  \n  // 18. breakAt - split array at first element that matches predicate (renamed from 'break' as it's a reserved word)\n  breakAt: function(predicate) {\n    return this.span((...args) => !predicate(...args));\n  },\n  \n  // 19. iterate - generate array by repeatedly applying function\n  iterate: function(fn, times) {\n    const results = [];\n    let current = this._value;\n    for (let i = 0; i < times; i++) {\n      results.push(current);\n      current = fn(current, i);\n    }\n    return createNewInstance.call(this, results);\n  },\n  \n  // 20. unfold - generate array from a seed value\n  unfold: function(fn, seed) {\n    if (seed === undefined) seed = this._value;\n    const results = [];\n    let current = seed;\n    let next = fn(current);\n    while (next !== null && next !== undefined) {\n      if (Array.isArray(next) && next.length === 2) {\n        results.push(next[0]);\n        current = next[1];\n        next = fn(current);\n      } else {\n        break;\n      }\n    }\n    return createNewInstance.call(this, results);\n  },\n  \n  // === More Modern & Innovative Methods ===\n  \n  // 21. cycle - create infinite cycle of array elements (with limit)\n  cycle: function(times) {\n    if (times === undefined) times = 1;\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, []);\n    }\n    const arr = Array.from(this._value);\n    if (arr.length === 0) {\n      return createNewInstance.call(this, []);\n    }\n    const result = [];\n    for (let i = 0; i < times; i++) {\n      result.push(...arr);\n    }\n    return createNewInstance.call(this, result);\n  },\n  \n  // 22. intercalate - join array of arrays with separator\n  intercalate: function(separator) {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, []);\n    }\n    const arr = Array.from(this._value);\n    const result = [];\n    for (let i = 0; i < arr.length; i++) {\n      if (i > 0 && separator !== undefined) {\n        if (Array.isArray(separator)) {\n          result.push(...separator);\n        } else {\n          result.push(separator);\n        }\n      }\n      if (Array.isArray(arr[i])) {\n        result.push(...arr[i]);\n      } else {\n        result.push(arr[i]);\n      }\n    }\n    return createNewInstance.call(this, result);\n  },\n  \n  // 23. transpose - transpose matrix (array of arrays)\n  transpose: function() {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, []);\n    }\n    const matrix = Array.from(this._value);\n    if (matrix.length === 0) {\n      return createNewInstance.call(this, []);\n    }\n    const maxLength = Math.max(...matrix.map(row => Array.isArray(row) ? row.length : 0));\n    const result = [];\n    for (let col = 0; col < maxLength; col++) {\n      const column = [];\n      for (let row = 0; row < matrix.length; row++) {\n        if (Array.isArray(matrix[row]) && col < matrix[row].length) {\n          column.push(matrix[row][col]);\n        }\n      }\n      result.push(column);\n    }\n    return createNewInstance.call(this, result);\n  },\n  \n  // 24. distinctBy - remove duplicates by custom key function\n  distinctBy: function(keyFn) {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, []);\n    }\n    const arr = Array.from(this._value);\n    const seen = new Set();\n    const result = [];\n    for (let i = 0; i < arr.length; i++) {\n      const key = keyFn(arr[i], i, arr);\n      if (!seen.has(key)) {\n        seen.add(key);\n        result.push(arr[i]);\n      }\n    }\n    return createNewInstance.call(this, result);\n  },\n  \n  // 25. groupByMultiple - group by multiple key functions\n  groupByMultiple: function(...keyFns) {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, {});\n    }\n    const arr = Array.from(this._value);\n    const groups = {};\n    for (let i = 0; i < arr.length; i++) {\n      const keys = keyFns.map(fn => fn(arr[i], i, arr));\n      const keyStr = JSON.stringify(keys);\n      if (!groups[keyStr]) {\n        groups[keyStr] = { keys, items: [] };\n      }\n      groups[keyStr].items.push(arr[i]);\n    }\n    return createNewInstance.call(this, Object.values(groups));\n  },\n  \n  // 26. tee - split stream into multiple branches (returns array of results)\n  tee: function(...fns) {\n    const results = [];\n    for (let i = 0; i < fns.length; i++) {\n      results.push(fns[i](this._value));\n    }\n    return createNewInstance.call(this, results);\n  },\n  \n  // 27. debug - log value and return it (for debugging chains)\n  debug: function(label) {\n    const prefix = label ? '[' + label + '] ' : '';\n    if (typeof console !== 'undefined' && console.log) {\n      console.log(prefix + 'Debug:', this._value);\n    }\n    return this;\n  },\n  \n  // 28. benchmark - measure execution time of function\n  benchmark: function(fn, label) {\n    const start = typeof performance !== 'undefined' ? performance.now() : Date.now();\n    const result = fn(this._value);\n    const end = typeof performance !== 'undefined' ? performance.now() : Date.now();\n    const duration = end - start;\n    if (typeof console !== 'undefined' && console.log) {\n      const prefix = label ? '[' + label + '] ' : '';\n      console.log(prefix + 'Benchmark: ' + duration + 'ms');\n    }\n    return createNewInstance.call(this, result);\n  },\n  \n  // 29. memoize - create memoized version of function\n  memoize: function(fn, keyFn) {\n    const cache = new Map();\n    const memoized = (value) => {\n      const key = keyFn ? keyFn(value) : JSON.stringify(value);\n      if (cache.has(key)) {\n        return cache.get(key);\n      }\n      const result = fn(value);\n      cache.set(key, result);\n      return result;\n    };\n    return createNewInstance.call(this, memoized(this._value));\n  },\n  \n  // 30. partition - enhanced partition with multiple predicates\n  partitionBy: function(...predicates) {\n    if (this._value === null || this._value === undefined) {\n      return createNewInstance.call(this, Array(predicates.length + 1).fill([]));\n    }\n    const arr = Array.from(this._value);\n    const partitions = Array(predicates.length + 1).fill(null).map(() => []);\n    \n    for (let i = 0; i < arr.length; i++) {\n      let matched = false;\n      for (let j = 0; j < predicates.length; j++) {\n        if (predicates[j](arr[i], i, arr)) {\n          partitions[j].push(arr[i]);\n          matched = true;\n          break;\n        }\n      }\n      if (!matched) {\n        partitions[predicates.length].push(arr[i]);\n      }\n    }\n    return createNewInstance.call(this, partitions);\n  }\n};\n}\n"}}),smart_dollar_vm_v2_exports={};function createVMSmartDollarCodeV2(){return`\n// SmartDollar implementation without global variables\n(function() {\n  ${SMART_DOLLAR_METHODS}\n  \n  // Forward declare createSmartDollar\n  let createSmartDollar;\n  \n  // Define SmartDollar class\n  class SmartDollar {\n    constructor(value) {\n      // If createSmartDollar is available and we're not already in it, use it\n      if (createSmartDollar && !this.__bypassProxy) {\n        return createSmartDollar(value);\n      }\n      \n      this._value = value;\n      this.__isSmartDollar = true;\n    }\n    \n    get length() {\n      if (Array.isArray(this._value)) {\n        return this._value.length;\n      }\n      if (typeof this._value === 'string') {\n        return this._value.length;\n      }\n      if (this._value && typeof this._value === 'object') {\n        return Object.keys(this._value).length;\n      }\n      return 0;\n    }\n    \n    valueOf() {\n      return this._value;\n    }\n    \n    toString() {\n      if (this._value === null) return '';\n      if (this._value === undefined) return '';\n      if (typeof this._value === 'string') return this._value;\n      return JSON.stringify(this._value);\n    }\n    \n    toJSON() {\n      return this._value;\n    }\n    \n    [Symbol.iterator]() {\n      if (this._value === null || this._value === undefined) {\n        return [][Symbol.iterator]();\n      }\n      if (Array.isArray(this._value) || typeof this._value === 'string') {\n        return this._value[Symbol.iterator]();\n      }\n      if (this._value && typeof this._value === 'object') {\n        return Object.entries(this._value)[Symbol.iterator]();\n      }\n      return [][Symbol.iterator]();\n    }\n  }\n  \n  \n  // Add static method to create instances (will be defined after createSmartDollar)\n  SmartDollar.createInstance = null;\n  \n  // Apply all shared methods to SmartDollar prototype\n  // smartDollarMethods should be defined by SMART_DOLLAR_METHODS above\n  if (typeof globalThis.smartDollarMethods !== 'undefined') {\n    Object.keys(globalThis.smartDollarMethods).forEach(method => {\n      SmartDollar.prototype[method] = globalThis.smartDollarMethods[method];\n    });\n  }\n  \n  // Create $ function with Proxy wrapper\n  createSmartDollar = function(data) {\n    if (data === null || data === undefined) {\n      return data;\n    }\n    \n    // Create raw instance without proxy\n    const smartDollar = Object.create(SmartDollar.prototype);\n    smartDollar._value = data;\n    smartDollar.__isSmartDollar = true;\n    \n    // Create proxy to handle property access\n    return new Proxy(smartDollar, {\n      get(target, prop, receiver) {\n        // Special properties that should always come from SmartDollar\n        const smartDollarOnlyProps = ['_value', '__isSmartDollar', 'constructor', 'length', Symbol.iterator, Symbol.toPrimitive];\n        \n        // Check SmartDollar-only properties FIRST\n        if (smartDollarOnlyProps.includes(prop)) {\n          const value = target[prop];\n          if (typeof value === 'function') {\n            return value.bind(target);\n          }\n          return value;\n        }\n        \n        // Handle numeric indices for arrays\n        if (typeof prop === 'string' && !isNaN(Number(prop))) {\n          const index = Number(prop);\n          if (Array.isArray(target._value) && index >= 0 && index < target._value.length) {\n            const item = target._value[index];\n            return item !== null && item !== undefined && typeof item === 'object'\n              ? createSmartDollar(item)\n              : item;\n          }\n        }\n        \n        // Check wrapped value properties FIRST for non-method properties\n        // This ensures properties like 'value' on the data object are accessible\n        if (target._value !== null && target._value !== undefined && typeof target._value === 'object' && prop in target._value) {\n          const valueFromData = target._value[prop];\n          \n          // If it's a method on SmartDollar AND a property on the data,\n          // prioritize SmartDollar methods ONLY for array/collection methods\n          const smartDollarMethod = target[prop];\n          const isArrayMethod = ['filter', 'map', 'reduce', 'find', 'some', 'every', 'forEach', \n                                'pluck', 'where', 'sortBy', 'groupBy', 'countBy', 'take', 'skip',\n                                'uniqBy', 'flatten', 'compact', 'chunk', 'orderBy', 'keyBy',\n                                'takeWhile', 'dropWhile', 'flattenDeep', 'reverse', 'sum',\n                                'mean', 'min', 'max', 'minBy', 'maxBy', 'sample', 'sampleSize',\n                                'size', 'isEmpty', 'includes', 'flatMap', 'concat', 'slice', \n                                'push', 'pop', 'shift', 'unshift', 'splice', 'indexOf', \n                                'lastIndexOf', 'join', 'sort', 'fill'].includes(prop);\n          \n          if (smartDollarMethod && typeof smartDollarMethod === 'function' && isArrayMethod) {\n            return smartDollarMethod.bind(target);\n          }\n          \n          // Otherwise, return the data property\n          if (valueFromData !== undefined) {\n            return valueFromData !== null && typeof valueFromData === 'object'\n              ? createSmartDollar(valueFromData)\n              : valueFromData;\n          }\n        }\n        \n        // Then check if property exists on SmartDollar instance (methods)\n        if (prop in target) {\n          const value = target[prop];\n          if (typeof value === 'function') {\n            return value.bind(target);\n          }\n          return value;\n        }\n        \n        return undefined;\n      },\n      \n      set(target, prop, value) {\n        // Allow setting properties on the wrapped value\n        if (target._value !== null && target._value !== undefined && typeof target._value === 'object') {\n          target._value[prop] = value;\n          return true;\n        }\n        return false;\n      },\n      \n      has(target, prop) {\n        if (prop in target) return true;\n        if (target._value !== null && target._value !== undefined) {\n          return prop in target._value;\n        }\n        return false;\n      },\n      \n      ownKeys(target) {\n        // Return keys from the wrapped value, not SmartDollar's properties\n        if (target._value !== null && target._value !== undefined && typeof target._value === 'object') {\n          return Reflect.ownKeys(target._value);\n        }\n        return [];\n      },\n      \n      getOwnPropertyDescriptor(target, prop) {\n        // Return descriptor from the wrapped value for Object.keys() to work\n        if (target._value !== null && target._value !== undefined && typeof target._value === 'object' && prop in target._value) {\n          return Object.getOwnPropertyDescriptor(target._value, prop);\n        }\n        return undefined;\n      }\n    });\n  };\n  \n  // Now that createSmartDollar is defined, set the static method\n  SmartDollar.createInstance = createSmartDollar;\n  \n  // Return the creator function and class\n  return { createSmartDollar, SmartDollar };\n})();\n`}__export(smart_dollar_vm_v2_exports,{createVMSmartDollarCodeV2:()=>createVMSmartDollarCodeV2});var getCpuCount,_VMSandboxQuickJS,VMSandboxQuickJS,init_smart_dollar_vm_v2=__esm({"src/core/smart-dollar/smart-dollar-vm-v2.ts"(){init_smart_dollar_shared_methods()}}),vm_sandbox_quickjs_exports={};__export(vm_sandbox_quickjs_exports,{VMSandboxQuickJS:()=>VMSandboxQuickJS});var DefaultFileSystemProvider,DefaultWorkerProvider,DefaultPromptsProvider,DefaultConsoleProvider,init_vm_sandbox_quickjs=__esm({"src/core/vm/vm-sandbox-quickjs.ts"(){init_quickjs_vm_pool(),init_VMEngineFactory(),getCpuCount=()=>{var e;return"undefined"!=typeof globalThis&&(null==(e=globalThis.navigator)?void 0:e.hardwareConcurrency)?globalThis.navigator.hardwareConcurrency:4},(_VMSandboxQuickJS=class e{constructor(t,n={}){if(this.appContext=t,this.config={memoryLimit:this.validatePositiveNumber(n.memoryLimit,128),timeout:this.validatePositiveNumber(n.timeout,3e4),cpuLimit:void 0!==n.cpuLimit?this.validatePositiveNumber(n.cpuLimit,0):void 0,enableAsync:n.enableAsync??!0,enableGenerators:n.enableGenerators??!1,enableProxies:n.enableProxies??!1,enableSymbols:n.enableSymbols??!0,maxContextSize:this.validatePositiveNumber(n.maxContextSize,10485760),recycleIsolates:n.recycleIsolates??!1,isolatePoolSize:this.validatePositiveNumber(n.isolatePoolSize,1)},this.useVMPool="true"!==process.env.DISABLE_VM_POOL&&"test"!==process.env.NODE_ENV,this.useVMPool&&!e.vmPool){const n=getCpuCount(),r=Math.min(Math.floor(n/2),8);e.vmPool=new QuickJSVMPool(t,this.config,r,100)}}async execute(t,n={},r={}){let s=null,i=null;const a=process.env.DEBUG&&"production"!==process.env.NODE_ENV;try{if(this.useVMPool&&e.vmPool){const t=await e.vmPool.acquire();i=t.engine,s=t.execContext}else{i=new VMEngineFactory(this.appContext).create("quickjs"),await i.initialize(this.config),s=await i.createContext()}const o=n.console||r.enableConsole,l=n.console||{log:(...e)=>console.log(...e),error:(...e)=>console.error(...e),warn:(...e)=>console.warn(...e),info:(...e)=>console.info(...e),debug:(...e)=>console.debug(...e)};if(o)try{await s.eval("\n            globalThis.console = {\n              log: function(...args) {\n                // Convert args to a format that can be passed back to host\n                const serializedArgs = args.map(arg => {\n                  if (typeof arg === 'object' && arg !== null) {\n                    try { return JSON.stringify(arg); } catch { return String(arg); }\n                  }\n                  return String(arg);\n                });\n                // Store for later processing\n                if (!globalThis.__consoleCalls) globalThis.__consoleCalls = [];\n                globalThis.__consoleCalls.push({ method: 'log', args: serializedArgs });\n                return undefined;\n              },\n              error: function(...args) {\n                const serializedArgs = args.map(arg => {\n                  if (typeof arg === 'object' && arg !== null) {\n                    try { return JSON.stringify(arg); } catch { return String(arg); }\n                  }\n                  return String(arg);\n                });\n                if (!globalThis.__consoleCalls) globalThis.__consoleCalls = [];\n                globalThis.__consoleCalls.push({ method: 'error', args: serializedArgs });\n                return undefined;\n              },\n              warn: function(...args) {\n                const serializedArgs = args.map(arg => {\n                  if (typeof arg === 'object' && arg !== null) {\n                    try { return JSON.stringify(arg); } catch { return String(arg); }\n                  }\n                  return String(arg);\n                });\n                if (!globalThis.__consoleCalls) globalThis.__consoleCalls = [];\n                globalThis.__consoleCalls.push({ method: 'warn', args: serializedArgs });\n                return undefined;\n              },\n              info: function(...args) {\n                const serializedArgs = args.map(arg => {\n                  if (typeof arg === 'object' && arg !== null) {\n                    try { return JSON.stringify(arg); } catch { return String(arg); }\n                  }\n                  return String(arg);\n                });\n                if (!globalThis.__consoleCalls) globalThis.__consoleCalls = [];\n                globalThis.__consoleCalls.push({ method: 'info', args: serializedArgs });\n                return undefined;\n              },\n              debug: function(...args) {\n                const serializedArgs = args.map(arg => {\n                  if (typeof arg === 'object' && arg !== null) {\n                    try { return JSON.stringify(arg); } catch { return String(arg); }\n                  }\n                  return String(arg);\n                });\n                if (!globalThis.__consoleCalls) globalThis.__consoleCalls = [];\n                globalThis.__consoleCalls.push({ method: 'debug', args: serializedArgs });\n                return undefined;\n              }\n            };\n          ")}catch(e){}let u=!1;for(const[e,t]of Object.entries(n))["JSON","Math","Date","Array","Object","String","Number","Boolean","console"].includes(e)||("$"===e?await this.setupSmartDollar(s,t):"_"===e?u=!0:await s.setGlobal(e,t));if(u){const{createVMLodashCode:e}=await Promise.resolve().then((()=>(init_lodash_vm(),lodash_vm_exports))),t=e();await s.eval(t),a&&await s.eval("typeof globalThis._")}const c=this.wrapCode(t),h=await i.execute(s,c,{},{...r,timeout:r.timeout??this.config.timeout});if(o)try{const e=await s.eval("globalThis.__consoleCalls");if(Array.isArray(e))for(const t of e)if(t&&"object"==typeof t&&"method"in t&&"args"in t){const e=t,n=e.method;"log"!==n&&"error"!==n&&"warn"!==n&&"info"!==n&&"debug"!==n||Array.isArray(e.args)&&l[n](...e.args)}}catch(e){}let p=h.value;if(null!=p&&"object"==typeof p)try{const e="\n            (function(obj) {\n              if (obj && obj.__isSmartDollar) {\n                return obj._value || obj.value;\n              }\n              return obj;\n            })(globalThis.__result__)\n          ";await s.setGlobal("__result__",p);p=await s.eval(e),await s.eval("delete globalThis.__result__")}catch(e){}try{await s.eval("\n          delete globalThis.__result__;\n          delete globalThis.__consoleCalls;\n        ")}catch(e){}return{value:p,executionTime:h.executionTime,memoryUsed:h.memoryUsed||0}}catch(e){if(e instanceof Error&&(e.message.includes("dynamic import callback")||e.message.includes("experimental-vm-modules")||e.message.includes("ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG"))){const e=new Error("QuickJS initialization failed: Dynamic imports are not supported in the current Jest environment. QuickJS requires --experimental-vm-modules flag which may not be compatible with your Node.js version. Run tests with NODE_OPTIONS=--experimental-vm-modules.");throw this.createSandboxError(e,0)}throw this.createSandboxError(e,0)}finally{if(i)if(this.useVMPool&&e.vmPool)e.vmPool.release(i);else try{"test"!==process.env.NODE_ENV&&await i.dispose()}catch{}}}async setupSmartDollar(e,t){let n;if(Array.isArray(t))n=[...t];else if("function"==typeof t){n=t.valueOf?t.valueOf():t()}else n=t;const{createVMSmartDollarCodeV2:r}=await Promise.resolve().then((()=>(init_smart_dollar_vm_v2(),smart_dollar_vm_v2_exports))),s=`\n      // Check if smartDollarModule already exists to avoid redefinition\n      if (typeof globalThis.smartDollarModule === 'undefined') {\n        globalThis.smartDollarModule = ${r()};\n      }\n      \n      // Use existing module or extract from newly created one\n      // Use IIFE to avoid const redeclaration issues\n      (function() {\n        const { createSmartDollar, SmartDollar } = globalThis.smartDollarModule;\n        const $_data = ${JSON.stringify(n)};\n        \n        // Store SmartDollar class and creator globally for cleanup and method access\n        if (typeof globalThis.SmartDollar === 'undefined') {\n          globalThis.SmartDollar = SmartDollar;\n        }\n        if (typeof globalThis.createSmartDollar === 'undefined') {\n          globalThis.createSmartDollar = createSmartDollar;\n        }\n      \n        // Only override Object methods if not already overridden\n        if (!globalThis.__objectMethodsOverridden) {\n          // Save original methods\n          Object.__originalKeys = Object.keys;\n          Object.__originalValues = Object.values;\n          Object.__originalEntries = Object.entries;\n          \n          // Override Object.keys to handle SmartDollar objects\n          Object.keys = function(obj) {\n            if (obj && obj.__isSmartDollar && obj._value !== null && obj._value !== undefined) {\n              return Object.__originalKeys(obj._value);\n            }\n            return Object.__originalKeys(obj);\n          };\n          \n          // Override Object.values to handle SmartDollar objects\n          Object.values = function(obj) {\n            if (obj && obj.__isSmartDollar && obj._value !== null && obj._value !== undefined) {\n              return Object.__originalValues(obj._value);\n            }\n            return Object.__originalValues(obj);\n          };\n          \n          // Override Object.entries to handle SmartDollar objects\n          Object.entries = function(obj) {\n            if (obj && obj.__isSmartDollar && obj._value !== null && obj._value !== undefined) {\n              return Object.__originalEntries(obj._value);\n            }\n            return Object.__originalEntries(obj);\n          };\n          \n          globalThis.__objectMethodsOverridden = true;\n        }\n        \n        // Create SmartDollar instance\n        if ($_data === null || $_data === undefined) {\n          globalThis.$ = $_data;\n        } else {\n          // Always use Proxy-based SmartDollar for consistent behavior\n          globalThis.$ = createSmartDollar($_data);\n        }\n      })();\n    `;await e.eval(s)}wrapCode(e){const t=e.trim();if(e.includes("await")||e.includes("async")||e.includes("Promise."))return`(async () => {\n        try {\n          const result = ${e};\n          // Unwrap SmartDollar if needed\n          if (result && result.__isSmartDollar) {\n            return result._value || result.value;\n          }\n          return result;\n        } catch (e) {\n          throw e;\n        }\n      })()`;if(/^\s*(const|let|var|function|class|if|for|while|do|switch)\s+/.test(t)||/;\s*$/.test(t)){const n=[];let r="",s=!1,i=null,a=0;for(let e=0;e<t.length;e++){const o=t[e],l=e>0?t[e-1]:"";s||'"'!==o&&"'"!==o&&"`"!==o?s&&o===i&&"\\"!==l&&(s=!1):(s=!0,i=o),s||("("!==o&&"{"!==o&&"["!==o||a++,")"!==o&&"}"!==o&&"]"!==o||a--,";"!==o||0!==a)?r+=o:(n.push(r.trim()),r="")}if(r.trim()&&n.push(r.trim()),n.length>1){const e=n[n.length-1];if(e&&!e.startsWith("const ")&&!e.startsWith("let ")&&!e.startsWith("var ")&&!e.startsWith("function ")&&!e.startsWith("class ")&&!e.startsWith("if ")&&!e.startsWith("for ")&&!e.startsWith("while ")&&!e.startsWith("return ")){return`(() => {\n              try {\n                ${n.slice(0,-1).join(";\n")};\n                return (${e});\n              } catch (error) {\n                if (error instanceof Error) {\n                  throw new Error(error.message);\n                }\n                throw error;\n              }\n            })()`}}return`(() => {\n          try {\n            ${e}\n          } catch (error) {\n            if (error instanceof Error) {\n              throw new Error(error.message);\n            }\n            throw error;\n          }\n        })()`}return`(() => {\n          try {\n            return (${e});\n          } catch (error) {\n            if (error instanceof Error) {\n              throw new Error(error.message);\n            }\n            throw error;\n          }\n        })()`}createSandboxError(e,t){var n;let r="EXECUTION_ERROR",s="Unknown error";e instanceof Error?(s=e.message,"TimeoutError"===e.name?r="TIMEOUT":"code"in e&&"CPU_LIMIT"===e.code&&(r="CPU_LIMIT")):"string"==typeof e&&(s=e);const i=s.toLowerCase();i.includes("timeout")||i.includes("timed out")?r="TIMEOUT":i.includes("cpu time limit")||i.includes("cpu limit")||i.includes("interrupted")?(r="CPU_LIMIT","interrupted"===i&&(null==(n=this.config)?void 0:n.cpuLimit)&&(s=`CPU time limit exceeded (limit: ${this.config.cpuLimit}ms)`)):i.includes("memory")?r="MEMORY_LIMIT":i.includes("syntax")?r="SYNTAX_ERROR":i.includes("reference")||i.includes("is not defined")?r="REFERENCE_ERROR":i.includes("type")&&(r="TYPE_ERROR");const a=new Error(s);return a.code=r,a.details={executionTime:t},a.name="SandboxError",a}async dispose(){this.useVMPool&&e.vmPool&&(await e.vmPool.dispose(),e.vmPool=null)}getConfig(){return{...this.config}}getCapabilities(){return{console:!0,json:!0,math:!0,array:!0,object:!0,promises:this.config.enableAsync,generators:this.config.enableGenerators,proxies:this.config.enableProxies,symbols:this.config.enableSymbols,buffer:!1,crypto:!1,timers:!1,weakmap:!0,intl:!1,number:!0}}getPoolStatus(){return{size:0,maxSize:0,available:0,busy:0}}validateContextValue(e){try{const t=this.estimateValueSize(e);return t>this.config.maxContextSize?{valid:!1,error:`Context value too large: ${t} bytes > ${this.config.maxContextSize} bytes`}:{valid:!0}}catch(e){return{valid:!1,error:`Validation error: ${e instanceof Error?e.message:"Unknown error"}`}}}estimateValueSize(e,t=new Set){if(null==e)return 8;if("object"==typeof e&&null!==e&&t.has(e))return 8;switch(typeof e){case"boolean":return 4;case"number":default:return 8;case"string":return 2*e.length;case"bigint":case"function":return 2*e.toString().length;case"object":{if(t.has(e))return 8;t.add(e);let n=16;if(Array.isArray(e))for(const r of e)n+=this.estimateValueSize(r,t);else if(e instanceof Date)n+=8;else if(e instanceof RegExp)n+=2*e.toString().length;else if(e instanceof Map)for(const[r,s]of e)n+=this.estimateValueSize(r,t),n+=this.estimateValueSize(s,t);else if(e instanceof Set)for(const r of e)n+=this.estimateValueSize(r,t);else for(const[r,s]of Object.entries(e))n+=2*r.length,n+=this.estimateValueSize(s,t);return t.delete(e),n}}}validatePositiveNumber(e,t){return"number"==typeof e&&e>0&&!Number.isNaN(e)?e:t}}).vmPool=null,VMSandboxQuickJS=_VMSandboxQuickJS}});import{promises as fs}from"node:fs";import{join as join2}from"node:path";import{Worker as Worker2}from"node:worker_threads";import prompts from"prompts";var Pager,init_default_providers=__esm({"src/utils/default-providers.ts"(){DefaultFileSystemProvider=class{async readFile(e){return fs.readFile(e,"utf-8")}async writeFile(e,t){await fs.writeFile(e,t,"utf-8")}async exists(e){try{return await fs.access(e),!0}catch{return!1}}},DefaultWorkerProvider=class{constructor(e=__dirname){this.basePath=e}createWorker(e,t){const n=join2(this.basePath,e);return new Worker2(n,t)}},DefaultPromptsProvider=class{async prompt(e){return prompts(e)}},DefaultConsoleProvider=class{log(...e){console.log(...e)}error(...e){console.error(...e)}clear(){console.clear()}}}});import*as readline from"node:readline";var AutocompleteEngine,init_pager=__esm({"src/utils/pager.ts"(){Pager=class{constructor(e,t){this.currentLine=0,this.isSearchMode=!1,this.searchQuery="",this.searchResults=[],this.currentSearchIndex=0,this.terminalRows=process.stdout.rows||24,this.terminalCols=process.stdout.columns||80,this.inputStream=t||process.stdin;const n=e.split("\n");this.lines=[],this.coloredLines=[];for(const e of n){const t=e.replace(new RegExp(`${String.fromCharCode(27)}\\[[^m]*m`,"g"),"");if(t.length<=this.terminalCols)this.lines.push(t),this.coloredLines.push(e);else{let n=0,r=0;for(;n<t.length;){const s=t.substring(n,n+this.terminalCols);this.lines.push(s);const i=this.extractColoredChunk(e,r,s.length);this.coloredLines.push(i.text),r=i.endIndex,n+=this.terminalCols}}}}clearScreen(){process.stdout.write("[2J[H")}drawContent(){this.clearScreen();const e=this.terminalRows-1,t=Math.min(this.currentLine+e,this.lines.length),n=this.lines.slice(this.currentLine,t);n.forEach(((e,t)=>{const n=this.currentLine+t,r=this.coloredLines[n]||e;if(this.searchResults.length>0&&this.searchQuery.length>0){const t=this.searchResults.filter((e=>e.line===n));if(t.length>0){let s="",i=0,a=0;t.forEach((t=>{const o=e.substring(i,t.column),l=this.extractColoredSubstring(r,a,o.length);s+=l.text,a=l.endIndex;const u=this.searchResults[this.currentSearchIndex].line===n&&this.searchResults[this.currentSearchIndex].column===t.column;s+=u?"[43m[37m":"[43m[30m";const c=e.substring(t.column,t.column+this.searchQuery.length),h=this.extractColoredSubstring(r,a,c.length),p=h.text.replace(new RegExp(`${String.fromCharCode(27)}\\[[^m]*m`,"g"),"");s+=p,s+="[0m",a=h.endIndex,i=t.column+this.searchQuery.length}));const o=e.substring(i);if(o){const e=this.extractColoredSubstring(r,a,o.length);s+=e.text}console.log(s)}else console.log(r)}else console.log(r)}));const r=e-n.length;for(let e=0;e<r;e++)console.log("~");if(this.isSearchMode)process.stdout.write(`[7m/${this.searchQuery}[0m`);else{const t=this.lines.length>0?Math.round((this.currentLine+e)/this.lines.length*100):100,n=this.currentLine+e>=this.lines.length?"(END)":`${t}%`;let r="";this.searchResults.length>0&&this.searchQuery.length>0&&(r=` [${this.currentSearchIndex+1}/${this.searchResults.length}]`),process.stdout.write(`[7m-- ${n}${r} -- (q to quit, j/k or arrows to scroll, / to search, n/N for next/prev)[0m`)}}scrollUp(e=1){this.currentLine=Math.max(0,this.currentLine-e),this.drawContent()}scrollDown(e=1){const t=Math.max(0,this.lines.length-(this.terminalRows-1));this.currentLine=Math.min(t,this.currentLine+e),this.drawContent()}pageUp(){this.scrollUp(this.terminalRows-2)}pageDown(){this.scrollDown(this.terminalRows-2)}performSearch(){if(this.searchResults=[],this.currentSearchIndex=0,0!==this.searchQuery.length){for(let e=0;e<this.lines.length;e++){const t=this.lines[e];let n=0;for(;n=t.indexOf(this.searchQuery,n),-1!==n;)this.searchResults.push({line:e,column:n}),n+=this.searchQuery.length}this.searchResults.length>0&&this.jumpToSearchResult(0)}}jumpToSearchResult(e){if(e>=0&&e<this.searchResults.length){this.currentSearchIndex=e;const t=this.searchResults[e];this.currentLine=Math.max(0,t.line-Math.floor((this.terminalRows-1)/2)),this.drawContent()}}nextSearchResult(){if(this.searchResults.length>0){const e=(this.currentSearchIndex+1)%this.searchResults.length;this.jumpToSearchResult(e)}}previousSearchResult(){if(this.searchResults.length>0){const e=(this.currentSearchIndex-1+this.searchResults.length)%this.searchResults.length;this.jumpToSearchResult(e)}}extractColoredSubstring(e,t,n){let r="",s=t,i=0;for(;s<e.length&&i<n;){if(""===e[s]&&"["===e[s+1]){const t=e.indexOf("m",s);if(-1!==t){r+=e.substring(s,t+1),s=t+1;continue}}r+=e[s],i++,s++}return{text:r,endIndex:s}}extractColoredChunk(e,t,n){let r="",s=t,i=0,a="";for(;s<e.length&&i<n;){if(""===e[s]&&"["===e[s+1]){const t=e.indexOf("m",s);if(-1!==t){a=e.substring(s,t+1),r+=a,s=t+1;continue}}r+=e[s],i++,s++}return{text:r,endIndex:s}}async show(){var e,t;let n=!1;this.inputStream.isTTY&&"isRaw"in this.inputStream&&(n=this.inputStream.isRaw??!1),this.inputStream.isTTY&&"setRawMode"in this.inputStream&&"function"==typeof this.inputStream.setRawMode&&(null==(t=(e=this.inputStream).setRawMode)||t.call(e,!0));let r=[];return"listeners"in this.inputStream&&(r=this.inputStream.listeners("keypress"),this.inputStream.removeAllListeners("keypress")),"read"in this.inputStream&&readline.emitKeypressEvents(this.inputStream),this.drawContent(),new Promise((e=>{const t=()=>{"removeListener"in this.inputStream?this.inputStream.removeListener("keypress",s):"off"in this.inputStream&&this.inputStream.off("keypress",s),"on"in this.inputStream&&r.forEach((e=>{this.inputStream.on("keypress",e)}))},s=(r,s)=>{var i,a;if(this.isSearchMode){if(!s)return;switch(s.name){case"escape":this.isSearchMode=!1,this.searchQuery="",this.searchResults=[],this.currentSearchIndex=0,this.drawContent();break;case"return":case"enter":this.performSearch(),this.isSearchMode=!1;break;case"backspace":this.searchQuery.length>0&&(this.searchQuery=this.searchQuery.slice(0,-1),this.drawContent());break;default:!r||1!==r.length||s.ctrl||s.meta||(this.searchQuery+=r,this.drawContent())}}else if(s)switch(s.name){case"q":case"escape":this.inputStream.isTTY&&"setRawMode"in this.inputStream&&"function"==typeof this.inputStream.setRawMode&&(null==(a=(i=this.inputStream).setRawMode)||a.call(i,n)),this.clearScreen(),t(),e();break;case"j":case"down":this.scrollDown();break;case"k":case"up":this.scrollUp();break;case"space":case"pagedown":this.pageDown();break;case"b":case"pageup":this.pageUp();break;case"g":if(s.shift){const e=Math.max(0,this.lines.length-(this.terminalRows-1));this.currentLine=e,this.drawContent()}else this.currentLine=0,this.drawContent();break;case"n":this.searchResults.length>0&&(s.shift?this.previousSearchResult():this.nextSearchResult());break;default:"/"===r&&(this.isSearchMode=!0,this.searchQuery="",this.drawContent())}};this.inputStream.on("keypress",s)}))}}}});function extractMethodNamesFromSource(e){const t=/^\s*(\w+):\s*function\s*\(/gm,n=/^\s*(\w+):\s*async\s*function\s*\(/gm,r=[];let s=t.exec(e);for(;null!==s;){const n=s[1];n&&!r.includes(n)&&r.push(n),s=t.exec(e)}for(s=n.exec(e);null!==s;){const t=s[1];t&&!r.includes(t)&&r.push(t),s=n.exec(e)}return r.sort()}var PromptsReplManager,init_autocomplete_engine=__esm({"src/core/repl/autocomplete-engine.ts"(){init_lodash_shared_methods(),init_smart_dollar_shared_methods(),AutocompleteEngine=class{constructor(){this.maxCompletions=100,this.maxDepth=3,this.cache=new Map,this.jsArrayMethods=["concat","every","filter","find","findIndex","flat","flatMap","forEach","includes","indexOf","join","lastIndexOf","map","pop","push","reduce","reduceRight","reverse","shift","slice","some","sort","splice","unshift","at","fill","copyWithin","entries","keys","values","toLocaleString","toString","length"],this.jsObjectMethods=["hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","constructor"],this.jsStringMethods=["charAt","charCodeAt","concat","endsWith","includes","indexOf","lastIndexOf","match","padEnd","padStart","repeat","replace","search","slice","split","startsWith","substring","toLowerCase","toUpperCase","trim","trimEnd","trimStart","valueOf","toString","length","localeCompare","normalize"],this.lodashMethodNames=extractMethodNamesFromSource(LODASH_METHODS),this.smartDollarMethodNames=extractMethodNamesFromSource(SMART_DOLLAR_METHODS)}getSuggestions(e){const{input:t,cursorPosition:n}=e,{expression:r,replaceStart:s,replaceEnd:i}=this.extractExpression(t,n);if(!r)return{completions:[],replaceStart:n,replaceEnd:n};let a=s;const o=t.lastIndexOf(".",n-1);o>=0&&o>=s&&(a=o+1);const l=`${r}:${this.getDataHash(e.currentData)}`;if(this.cache.has(l)){const e=this.cache.get(l);if(e)return{...e,replaceStart:a,replaceEnd:i}}try{const t={completions:this.generateCompletions(r,e).slice(0,this.maxCompletions),replaceStart:a,replaceEnd:i};return t.completions.length>0&&this.cache.set(l,t),t}catch{return{completions:[],replaceStart:s,replaceEnd:i}}}extractExpression(e,t){let n=t,r=0;for(;n>0;){const s=e[n-1];if(")"===s?r++:"("===s&&r--,r>0)n--;else{if("]"===s?r++:"["===s&&r--,0===r&&!/[a-zA-Z0-9_.$[\]()=>,\s"']/.test(s)){if(["+","-","*","/","&","|","%","^"].includes(s)){const r=e.slice(n,t).trim();if(r.startsWith("_")||r.startsWith("$"))break}break}n--}}const s=e.slice(n,t).trim();let i=t;for(;i<e.length&&/[a-zA-Z0-9_]/.test(e[i]);)i++;const a=e.slice(n,t).search(/\S/);return{expression:s,replaceStart:a>=0?n+a:n,replaceEnd:i}}generateCompletions(e,t){const n=[];if("$.."===e)return this.getPropertyCompletions("$","",t);const r=e.match(/^(.+)\.([^.]*)$/);if(r){const[,e,n]=r;return"$."===e?this.getPropertyCompletions("$",n,t):"_"===e?this.getMethodCompletions(n):e.startsWith("_")?"_."===e?[]:this.getLodashChainCompletions(e,n,t):e.match(/^\[.*\]$/)?this.getArrayLiteralCompletions(n):this.getPropertyCompletions(e,n,t)}if("$"===e)return this.getPropertyCompletions("$","",t);if("_"===e)return this.getMethodCompletions("");if(e.startsWith("$.")){const n=e.slice(2);return this.getPropertyCompletions("$",n,t)}if(e.startsWith("_.")){const t=e.slice(2);return this.getMethodCompletions(t)}return e&&!e.includes(".")&&n.push(...this.getGlobalCompletions(e)),n}getPropertyCompletions(e,t,n){if(!n.currentData)return[];try{const r=this.evaluateObjectPath(e,n);if(null==r)return[];const s=[],i=t.toLowerCase();if(r&&"object"==typeof r){const e=this.getObjectKeys(r);s.push(...e.filter((e=>e.toLowerCase().startsWith(i))).map((e=>e)))}return Array.isArray(r)&&s.push(...this.jsArrayMethods.filter((e=>e.toLowerCase().startsWith(i))).map((e=>e))),"string"==typeof r&&s.push(...this.jsStringMethods.filter((e=>e.toLowerCase().startsWith(i))).map((e=>e))),"boolean"==typeof r&&s.push(...["toString","valueOf"].filter((e=>e.toLowerCase().startsWith(i))).map((e=>e))),"number"==typeof r&&s.push(...["toString","valueOf","toFixed","toExponential","toPrecision","toLocaleString"].filter((e=>e.toLowerCase().startsWith(i))).map((e=>e))),null!=r&&s.push(...this.jsObjectMethods.filter((e=>e.toLowerCase().startsWith(i))).map((e=>e))),[...new Set(s)].sort()}catch{return[]}}getMethodCompletions(e){const t=e.toLowerCase(),n=[];return n.push(...this.lodashMethodNames.filter((e=>e.toLowerCase().startsWith(t))).map((e=>e))),n.push(...this.smartDollarMethodNames.filter((e=>e.toLowerCase().startsWith(t))).map((e=>e))),[...new Set(n)].sort()}getArrayLiteralCompletions(e){const t=e.toLowerCase(),n=[];return n.push(...this.jsArrayMethods.filter((e=>e.toLowerCase().startsWith(t)))),n.push(...this.jsObjectMethods.filter((e=>e.toLowerCase().startsWith(t)))),[...new Set(n)].sort()}getLodashChainCompletions(e,t,n){const r=this.parsePathSegments(e.slice(1));let s="unknown";n.currentData&&(s=this.getDataType(n.currentData));for(const e of r)if("method"===e.type&&e.name){const t=this.inferMethodReturnType(e.name,s);t&&(s=t)}const i=[],a=t.toLowerCase();let o=[];"array"===s?o=["concat","slice","join","reverse","sort","indexOf","lastIndexOf","first","last","nth","take","drop","chunk","zip","unzip","difference","intersection","union","without","pluck","where","findIndex","pull","remove","sample","shuffle","size","countBy","partition","reject","takeWhile","dropWhile"]:"object"===s?o=["has","hasIn","keys","values","entries","pairs","toPairs","fromPairs","invert","invertBy","mapKeys","mapValues","extend","assign","defaults","defaultsDeep","forOwn","forOwnRight","functions","result","transform","update","updateWith"]:"string"===s?o=["split","replace","trim","trimStart","trimEnd","pad","padStart","padEnd","repeat","toLower","toLowerCase","toUpper","toUpperCase","camelCase","kebabCase","snakeCase","startCase","capitalize","deburr","escape","unescape","truncate","words","parseInt","template"]:"number"===s&&(o=["add","subtract","multiply","divide","sum","sumBy","mean","meanBy","min","minBy","max","maxBy","round","floor","ceil","inRange","random","clamp"]);const l=[...new Set(["chain","value","tap","thru","each","forEach","map","filter","reduce","find","some","every","includes","sortBy","groupBy","uniq","flatten","compact","keys","values","pick","omit","merge","clone","isEmpty","isArray","isObject","get","set",...o])];return i.push(...l.filter((e=>e.toLowerCase().startsWith(a)))),[...new Set(i)].sort()}getGlobalCompletions(e){const t=e.toLowerCase(),n=[];"$".startsWith(e)&&n.push("$"),"_".startsWith(e)&&n.push("_");return n.push(...["console","JSON","Math","Date","Array","Object","String"].filter((e=>e.toLowerCase().startsWith(t)))),n}evaluateObjectPath(e,t){if("$"===e&&t.currentData)return t.currentData;if(e.startsWith("$")&&t.currentData)try{const n=e.slice(1);if(!n)return t.currentData;const r=this.parsePathSegments(n);let s=t.currentData,i=this.getDataType(s);for(const e of r)if(e){if("property"===e.type){if(!s||"object"!=typeof s||!(e.name in s))return;s=s[e.name],i=this.getDataType(s)}else if("method"===e.type){const t=this.inferMethodReturnType(e.name,i);if(!t)return;i=t,s=this.createMockDataForType(i,s)}else if("index"===e.type){if(!Array.isArray(s)||void 0===e.index)return;s=s[e.index],i=this.getDataType(s)}if(null==s)return}return s}catch{return}}getDataType(e){return Array.isArray(e)?"array":"string"==typeof e?"string":"number"==typeof e?"number":"boolean"==typeof e?"boolean":e&&"object"==typeof e?"object":"unknown"}inferMethodReturnType(e,t){const n=["join","toString","toLocaleString"],r=["indexOf","lastIndexOf","findIndex","push","unshift"],s=["every","some","includes"],i=["find","at","pop","shift"],a=["slice","substring","substr","toLowerCase","toUpperCase","trim","trimStart","trimEnd","padStart","padEnd","repeat","replace","concat","normalize","toString","valueOf"],o=["split","match"],l=["indexOf","lastIndexOf","search","charCodeAt","localeCompare"],u=["startsWith","endsWith","includes"];if("array"===t){if(["map","filter","slice","concat","flat","flatMap","reverse","sort","splice","fill","copyWithin"].includes(e))return"array";if(n.includes(e))return"string";if(r.includes(e))return"number";if(s.includes(e))return"boolean";if(i.includes(e))return"unknown";if("reduce"===e||"reduceRight"===e)return"unknown"}if("string"===t){if(a.includes(e))return"string";if(o.includes(e))return"array";if(l.includes(e))return"number";if(u.includes(e))return"boolean";if("charAt"===e)return"string"}return"pluck"===e||"where"===e||"sortBy"===e?"array":"groupBy"===e||"countBy"===e||"keyBy"===e||"indexBy"===e?"object":"partition"===e||"chunk"===e||"zip"===e||"unzip"===e?"array":"fromPairs"===e?"object":"toPairs"===e||"keys"===e||"values"===e||"entries"===e?"array":"pick"===e||"omit"===e||"merge"===e||"extend"===e||"assign"===e||"defaults"===e?"object":"clone"===e||"cloneDeep"===e?"unknown":"mapValues"===e||"mapKeys"===e||"invert"===e||"invertBy"===e?"object":"value"===e?"unknown":"join"===e||"toString"===e||"camelCase"===e||"kebabCase"===e||"snakeCase"===e||"lowerCase"===e||"upperCase"===e||"startCase"===e||"capitalize"===e||"escape"===e||"unescape"===e||"template"===e?"string":"size"===e||"sum"===e||"mean"===e||"min"===e||"max"===e||"round"===e||"floor"===e||"ceil"===e?"number":"isEmpty"===e||"isArray"===e||"isObject"===e||"isString"===e||"isNumber"===e||"isBoolean"===e||"isFunction"===e||"isNull"===e||"isUndefined"===e||"isNaN"===e||"isFinite"===e||"isEqual"===e||"isMatch"===e||"has"===e||"hasIn"===e?"boolean":null}createMockDataForType(e,t){switch(e){case"array":return[];case"string":return"";case"number":return 0;case"boolean":return!1;case"object":return{};default:return Array.isArray(t)&&t.length>0?t[0]:{}}}parsePathSegments(e){const t=[];let n="",r=0;for(;r<e.length;){const s=e[r];if("."===s)n&&(t.push(this.createSegment(n)),n=""),r++;else if("("===s){n&&(t.push({type:"method",name:n}),n="");let s=1;for(r++;r<e.length&&s>0;)"("===e[r]?s++:")"===e[r]&&s--,r++}else if("["===s){n&&(t.push(this.createSegment(n)),n=""),r++;let s="";for(;r<e.length&&"]"!==e[r];)s+=e[r],r++;if("]"===e[r]){r++;const e=parseInt(s,10);Number.isNaN(e)||t.push({type:"index",index:e})}}else n+=s,r++}return n&&t.push(this.createSegment(n)),t}createSegment(e){const t=e.match(/^(\w+)\[(\d+)\]$/);if(t){const[,e]=t;return{type:"property",name:e}}return{type:"property",name:e}}getObjectKeys(e,t=0){if(t>=this.maxDepth||!e||"object"!=typeof e)return[];const n=[],r=new WeakSet;return(e=>{if(!r.has(e)){r.add(e);try{if(n.push(...Object.keys(e)),Array.isArray(e)&&e.length>0){for(let t=0;t<Math.min(e.length,10);t++)n.push(`[${t}]`);n.push("length")}}catch{}}})(e),[...new Set(n)]}clearCache(){this.cache.clear()}getDataHash(e){if(null===e)return"null";if(void 0===e)return"undefined";const t=typeof e;if("object"===t)try{if(Array.isArray(e))return`array:${e.length}`;return`object:${Object.keys(e).sort().slice(0,10).join(",")}`}catch{return"object:unknown"}return`${t}:${String(e).slice(0,20)}`}}}}),prompts_repl_manager_exports={};__export(prompts_repl_manager_exports,{PromptsReplManager:()=>PromptsReplManager});import*as readline2 from"node:readline";import pc3 from"picocolors";var init_prompts_repl_manager=__esm({"src/core/repl/prompts/prompts-repl-manager.ts"(){init_default_providers(),init_output_formatter(),init_pager(),init_autocomplete_engine(),PromptsReplManager=class{constructor(e){this.history=[],this.shouldExit=!1,this.currentData=null,this.initialData=null,this.hasPreviewLine=!1,this.isEvaluating=!1,this.lastSigintTime=0,this.hasCompletionStatus=!1,this.completionState=null,this.ignoringKeypress=!1,this.evaluator=e.evaluator,this.historyFile=e.historyFile,this.initialData=e.initialData||null,this.currentData=this.initialData,this.lastResult=e.initialData||void 0,this.inputStream=e.inputStream,this.fileSystem=e.fileSystem||new DefaultFileSystemProvider,this.promptsProvider=e.promptsProvider||new DefaultPromptsProvider,this.console=e.console||new DefaultConsoleProvider,this.autocompleteEngine=new AutocompleteEngine,this.realTimeEvaluation=e.realTimeEvaluation??!0,this.outputFormatter=new OutputFormatter({compact:!0,noColor:!1,isReplMode:!0}),this.historyFile&&this.loadHistory().catch((()=>{}))}async start(){var e;this.console.log(pc3.cyan("Welcome to jsq REPL (experimental) 🚀")),this.console.log(pc3.gray("Type .help for commands, .exit to quit\n"));if(null==(e=this.inputStream)?void 0:e.isTTY)await this.startInteractiveMode();else for(;!this.shouldExit;)try{const e=await this.promptUser();if(null==e)continue;await this.processInput(e)}catch(e){if(e instanceof Error&&e.message.includes("cancelled")){this.console.log("\nUse .exit to quit");continue}this.console.error(pc3.red("Error:"),e)}this.console.log(pc3.yellow("\nBye! 👋"))}async promptUser(){if(!this.inputStream||!this.inputStream.isTTY)return new Promise(((e,t)=>{let n="";const r=setTimeout((()=>{this.inputStream&&(this.inputStream.removeListener("data",i),this.inputStream.removeListener("end",s)),t(new Error("Timeout waiting for input"))}),3e4),s=()=>{clearTimeout(r),this.inputStream&&(this.inputStream.removeListener("data",i),this.inputStream.removeListener("end",s)),this.shouldExit=!0,e(".exit")},i=t=>{const a=t.toString();if(a.includes("\n")){clearTimeout(r),this.inputStream&&(this.inputStream.removeListener("data",i),this.inputStream.removeListener("end",s));const t=(n+a).trim();(null==t?void 0:t.trim())&&(this.history.push(t),this.saveHistory().catch((()=>{}))),e(t)}else n+=a};if(this.inputStream){if(!this.inputStream.readable)return clearTimeout(r),this.shouldExit=!0,void e(".exit");this.inputStream.on("data",i),this.inputStream.on("end",s)}else clearTimeout(r),t(new Error("No input stream available"));process.stdout.write("> ")}));const e=(await this.promptsProvider.prompt({type:"text",name:"command",message:">"})).command;return(null==e?void 0:e.trim())&&(this.history.push(e),this.saveHistory().catch((()=>{}))),e}async getSuggestions(e){if(!e)return[];const t=[".exit",".help",".clear",".history",".save",".load",".config"];if(e.startsWith("."))return t.filter((t=>t.startsWith(e)));try{const t={input:e,cursorPosition:e.length,currentData:this.currentData};return this.autocompleteEngine.getSuggestions(t).completions}catch(e){return this.console.error("Autocomplete error:",e),[]}}async processInput(e){if(e.startsWith("."))await this.handleCommand(e);else try{const t=await this.evaluator.evaluate(e,this.currentData,this.lastResult);if(t.error)this.displayError(t.error);else{const e=this.outputFormatter.format(t.value);this.console.log(pc3.green("→"),e),this.lastResult=t.value}}catch(e){this.displayError(e)}}async handleCommand(e){const t=e.trim().toLowerCase();switch(t){case".exit":this.shouldExit=!0,this.rl&&this.rl.close();break;case".help":this.showHelp();break;case".clear":this.console.clear();break;case".history":this.showHistory();break;case".save":await this.saveSession(e);break;case".load":await this.loadSession(e);break;case".config":this.showConfig();break;default:t.startsWith(".save ")?await this.saveSession(e):t.startsWith(".load ")?await this.loadSession(e):(this.console.log(pc3.yellow(`Unknown command: ${e}`)),this.console.log(pc3.gray("Type .help for available commands")))}}showHelp(){this.console.log(pc3.cyan("\nAvailable commands:")),this.console.log("  .exit           - Exit the REPL"),this.console.log("  .help           - Show this help message"),this.console.log("  .clear          - Clear the screen"),this.console.log("  .history        - Show command history"),this.console.log("  .save [file]    - Save current data to file"),this.console.log("  .load [file]    - Load data from file"),this.console.log("  .config         - Show current configuration"),this.console.log(""),this.console.log(pc3.gray("Start typing to see autocomplete suggestions"))}showHistory(){const e=this.history.filter((e=>".history"!==e));0!==e.length?(this.console.log(pc3.cyan("\nCommand history:")),e.forEach(((e,t)=>{this.console.log(pc3.gray(`${t+1}:`),e)}))):this.console.log(pc3.gray("No history yet"))}async startInteractiveMode(){var e;let t,n="";if(!this.inputStream)throw new Error("Input stream is not available");this.rl=readline2.createInterface({input:this.inputStream,output:process.stdout,prompt:pc3.bold("> "),terminal:this.inputStream.isTTY||!1}),(null==(e=this.inputStream)?void 0:e.isTTY)&&(readline2.emitKeypressEvents(this.inputStream),this.inputStream.setRawMode&&this.inputStream.setRawMode(!0)),this.rl.on("line",(async e=>{if(n="",t&&(clearTimeout(t),t=void 0),this.clearPreviewLine(),this.clearCompletionStatus(),this.completionStatusTimer&&(clearTimeout(this.completionStatusTimer),this.completionStatusTimer=void 0),this.completionState=null,this.autocompleteEngine.clearCache(),this.isEvaluating=!1,this.hasPreviewLine=!1,e.trim()){this.history.push(e),this.saveHistory().catch((()=>{}));try{await this.processInput(e)}catch(e){this.console.error(pc3.red("Error:"),e)}}else this.currentData=this.initialData;!this.shouldExit&&this.rl&&this.rl.prompt()})),this.rl.on("SIGINT",(()=>{const e=this.rl.line||"",t=Date.now();if(""===e.trim()){if(t-this.lastSigintTime<1e3)return this.shouldExit=!0,void(this.rl&&this.rl.close());this.console.log("\n(To exit, press Ctrl+C again)"),this.lastSigintTime=t,this.rl&&this.rl.prompt()}else this.console.log("\n"),this.lastSigintTime=0,this.rl&&(this.rl.line="",this.rl.cursor=0,this.rl.prompt())})),this.rl.on("close",(()=>{this.shouldExit=!0,this.completionStatusTimer&&(clearTimeout(this.completionStatusTimer),this.completionStatusTimer=void 0)})),this.keypressHandler=async(e,r)=>{var s;if(!this.ignoringKeypress)if(!r||"tab"!==r.name||r.ctrl||r.meta)(r&&"tab"!==r.name||!r&&e)&&(this.completionState=null,this.clearCompletionStatus(),this.completionStatusTimer&&(clearTimeout(this.completionStatusTimer),this.completionStatusTimer=void 0)),(null==r?void 0:r.ctrl)&&"r"===r.name?await this.showLastResultInPager():!r||"return"===r.name||"tab"===r.name||r.ctrl&&"r"!==r.name||r.meta?r&&"return"===r.name&&(this.clearPreviewLine(),this.hasPreviewLine=!1):(n=this.rl.line||"",t&&clearTimeout(t),this.realTimeEvaluation&&n.trim()&&(t=setTimeout((async()=>{(this.rl.line||"")===n&&n.trim()&&await this.performImmediateEvaluation(n)}),100)));else{let e=this.rl.line||"";const t=this.rl.cursor||0;e.includes("\t")&&(e=e.replace(/\t/g,""),this.rl.line=e,this.rl.cursor=Math.min(t,e.length));if((null==(s=this.completionState)?void 0:s.isActive)&&this.completionState.lastLine===e&&this.completionState.lastCompletions.length>1&&this.completionState){const e=this.completionState.lastCompletions;this.completionState.currentIndex=(this.completionState.currentIndex+1)%e.length;const t=e[this.completionState.currentIndex],n=this.applyCompletion(this.completionState.lastPrefix,t);return this.rl.line=n,this.rl.cursor=n.length,this.completionState.lastLine=n,void(this.realTimeEvaluation&&n.trim()&&setTimeout((async()=>{await this.performImmediateEvaluation(n)}),50))}const n=await this.getSuggestions(e);if(0===n.length)return void(this.completionState=null);if(1===n.length){const t=this.applyCompletion(e,n[0]);this.rl.line=t,this.rl.cursor=t.length,this.refreshCurrentLine(),this.completionState=null,this.realTimeEvaluation&&t.trim()&&setTimeout((async()=>{await this.performImmediateEvaluation(t)}),50)}else{this.completionState={lastCompletions:n,currentIndex:0,lastPrefix:e,lastCursorPos:t,lastLine:e,isActive:!0};const r=n[0],s=this.applyCompletion(e,r);this.rl.line=s,this.rl.cursor=s.length,this.completionState.lastLine=s,this.realTimeEvaluation&&s.trim()&&setTimeout((async()=>{await this.performImmediateEvaluation(s)}),50)}}},this.inputStream&&"function"==typeof this.inputStream.on&&this.inputStream.on("keypress",this.keypressHandler),this.rl.prompt(),await new Promise((e=>{const t=setInterval((()=>{!this.shouldExit&&this.rl||(clearInterval(t),e())}),100)}))}applyCompletion(e,t){const n=e.lastIndexOf(".");if(n>=0){return e.substring(0,n+1)+t}const r=e.match(/(\$|_|\w+)\.?(\w*)$/);if(r){const n=e.substring(0,r.index||0);return t.startsWith("$")||t.startsWith("_")?t:n+t}return t}clearPreviewLine(){if(this.hasPreviewLine){const e=this.rl&&this.rl.line||"",t=this.rl&&this.rl.cursor||0;if(process.stdout.write("\n"),process.stdout.write("[2K"),process.stdout.write("[0G"),process.stdout.write("[A"),this.rl){process.stdout.write("[2K"),process.stdout.write("[0G");const n=pc3.bold("> ");process.stdout.write(n+e),process.stdout.write(`[${2+t+1}G`)}this.hasPreviewLine=!1}}refreshCurrentLine(){if(!this.rl)return;const e=this.rl.cursor||0,t=this.rl.line||"";process.stdout.write("[2K"),process.stdout.write("[0G");const n=pc3.bold("> ");process.stdout.write(n+t),process.stdout.write(`[${2+e+1}G`)}clearCompletionStatus(){this.hasCompletionStatus&&this.rl&&(this.completionStatusTimer&&(clearTimeout(this.completionStatusTimer),this.completionStatusTimer=void 0),process.stdout.write("\n"),process.stdout.write("[2K"),process.stdout.write("[A"),process.stdout.write("[0G"),this.refreshCurrentLine(),this.hasCompletionStatus=!1)}async performImmediateEvaluation(e){if(!e.trim()||!this.rl||this.isEvaluating)return;const t=e.trim();if(t.startsWith("."))return;this.clearPreviewLine();if((this.rl.line||"")===e){this.isEvaluating=!0;try{const e=await this.evaluator.evaluate(t,this.currentData,this.lastResult);if(!e.error&&void 0!==e.value){let t;t="string"==typeof e.value?e.value:e.value instanceof Error?e.value.toString():this.outputFormatter.format(e.value),t=t.replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t");const n=process.stdout.columns||80,r="→ ",s=2,i=n-r.length-2;t.length>i&&(t=`${t.substring(0,i-3)}...`);const a=this.rl.cursor||0,o=this.rl.line||"";process.stdout.write("\n"),process.stdout.write(pc3.gray(r)+pc3.dim(t)),process.stdout.write("[A"),process.stdout.write("[0G"),process.stdout.write(pc3.bold("> ")+o),process.stdout.write(`[${s+a+1}G`),this.hasPreviewLine=!0}}catch(e){}finally{this.isEvaluating=!1}}}stop(){this.shouldExit=!0,this.completionStatusTimer&&(clearTimeout(this.completionStatusTimer),this.completionStatusTimer=void 0),this.rl&&this.rl.close()}displayError(e){var t;const n=(null==(t=null==e?void 0:e.toString)?void 0:t.call(e))||"Unknown error";n.includes("SyntaxError")?this.displaySyntaxError(n):n.includes("ReferenceError")?this.displayReferenceError(n):n.includes("TypeError")?this.displayTypeError(n):n.includes("RangeError")?this.displayRangeError(n):this.console.error(pc3.red("❌ Error:"),n),e&&"object"==typeof e&&"stack"in e&&"string"==typeof e.stack&&(this.console.error(pc3.gray("\nStack trace:")),this.console.error(pc3.gray(e.stack)))}displaySyntaxError(e){this.console.error(pc3.red("❌ Syntax Error:")),e.includes("Unexpected token")?this.console.error(pc3.yellow("  → Check for missing brackets, quotes, or semicolons")):e.includes("Unexpected end of input")&&this.console.error(pc3.yellow("  → Expression seems incomplete. Did you forget to close a bracket?")),this.console.error(pc3.gray(`  ${e}`))}displayReferenceError(e){this.console.error(pc3.red("❌ Reference Error:"));const t=e.match(/(\w+) is not defined/);if(t){const e=t[1];this.console.error(pc3.yellow(`  → "${e}" is not defined`)),this.console.error(pc3.gray(`  Did you mean to reference a property? Try: $.${e} or _.${e}`))}else this.console.error(pc3.gray(`  ${e}`))}displayTypeError(e){this.console.error(pc3.red("❌ Type Error:")),e.includes("Cannot read property")?(this.console.error(pc3.yellow("  → Trying to access a property of null or undefined")),this.console.error(pc3.gray("  Use optional chaining (?.) to safely access nested properties"))):e.includes("is not a function")&&this.console.error(pc3.yellow("  → Trying to call something that is not a function")),this.console.error(pc3.gray(`  ${e}`))}displayRangeError(e){this.console.error(pc3.red("❌ Range Error:")),e.includes("Maximum call stack")?this.console.error(pc3.yellow("  → Infinite recursion detected")):e.includes("Invalid array length")&&this.console.error(pc3.yellow("  → Array size is too large or negative")),this.console.error(pc3.gray(`  ${e}`))}async saveSession(e){const t=e.split(/\s+/)[1]||"jsq-session.json";try{const e={data:this.currentData,timestamp:(new Date).toISOString(),history:this.history.filter((e=>!e.startsWith(".")))};await this.fileSystem.writeFile(t,JSON.stringify(e,null,2)),this.console.log(pc3.green(`✅ Session saved to: ${t}`))}catch(e){this.console.error(pc3.red("❌ Failed to save session:"),e)}}async loadSession(e){const t=e.split(/\s+/)[1];if(!t)return this.console.error(pc3.red("❌ Please specify a filename")),void this.console.log(pc3.gray("  Usage: .load <filename>"));try{const e=await this.fileSystem.readFile(t),n=JSON.parse(e);n.data?(this.currentData=n.data,this.console.log(pc3.green(`✅ Session loaded from: ${t}`)),n.timestamp&&this.console.log(pc3.gray(`  Saved at: ${n.timestamp}`)),this.console.log(pc3.cyan("  Data is now available as $"))):this.console.error(pc3.yellow("⚠️  No data found in session file"))}catch(e){e&&"object"==typeof e&&"code"in e&&"ENOENT"===e.code?this.console.error(pc3.red(`❌ File not found: ${t}`)):e instanceof SyntaxError?this.console.error(pc3.red("❌ Invalid JSON file")):this.console.error(pc3.red("❌ Failed to load session:"),e)}}showConfig(){if(this.console.log(pc3.cyan("\nCurrent configuration:")),this.console.log(pc3.gray("  History file:"),this.historyFile||".jsq_history"),this.console.log(pc3.gray("  Autocomplete:"),"Enabled"),null!==this.currentData){const e=Array.isArray(this.currentData)?"Array":typeof this.currentData,t=JSON.stringify(this.currentData).length;this.console.log(pc3.gray("  Current data:"),`${e} (${t} bytes)`)}else this.console.log(pc3.gray("  Current data:"),"None")}async loadHistory(){if(this.historyFile)try{const e=await this.fileSystem.readFile(this.historyFile);this.history=e.split("\n").filter((e=>e.trim()))}catch(e){}}async saveHistory(){if(this.historyFile)try{const e=this.history.slice(-1e3).join("\n");await this.fileSystem.writeFile(this.historyFile,e)}catch(e){}}async showLastResultInPager(){var e,t;if(void 0===this.lastResult)return;const n=(null==(e=this.rl)?void 0:e.line)||"",r=(null==(t=this.rl)?void 0:t.cursor)||0,s=OutputFormatter.format(this.lastResult,{isReplMode:!1,oneline:!1,noColor:!1}),i=new Pager(s,this.inputStream);if(await i.show(),this.rl&&(process.stdout.write("[2J[H"),this.rl.prompt(),n)){this.rl.line=n,this.rl.cursor=r,process.stdout.write(n);const e=n.length-r;if(e>0)for(let t=0;t<e;t++)process.stdout.write("[D")}}}}});function detectRuntime(){const e=globalThis;return"undefined"!=typeof globalThis&&e.Deno?"deno":"undefined"!=typeof globalThis&&e.Bun?"bun":"undefined"!=typeof process&&process.versions&&process.versions.node?"node":"unknown"}var init_runtime=__esm({"src/utils/runtime.ts"(){}});import{openSync}from"node:fs";import{Readable as Readable2}from"node:stream";function createBunTTYStream(e){e&&console.error("[Bun] createBunTTYStream called");try{const t=process.binding("tty_wrap");if(!t||!t.TTY)return e&&console.error("[Bun] tty_wrap not available"),null;let n;try{n=openSync("/dev/tty","r+")}catch(t){return e&&(console.error("[Bun] Failed to open /dev/tty:",t instanceof Error?t.message:String(t)),console.error("[Bun] This is expected when running with piped input")),null}e&&console.error(`[Bun] TTY file descriptor: ${n}`);const r=new(0,t.TTY)(n);r.isTTY=!0;class s extends Readable2{constructor(e){super(),this.reading=!1,this.tty=e,this.isTTY=!0,this.setRawMode=e=>this.tty.setRawMode?this.tty.setRawMode(e):this,this.isRaw=!1}_read(e){if(!this.reading){this.reading=!0;try{this.tty.readStart&&this.tty.readStart(),this.tty.onread=(e,t)=>{if(e>0){const n=t.slice(0,e);this.push(n)}else 0===e||this.push(null)}}catch(e){this.destroy(e)}}}_destroy(e,t){try{this.tty.readStop&&this.tty.readStop(),this.tty.close&&this.tty.close()}catch(e){}t(e)}}const i=new s(r);return e&&console.error("[Bun] TTY stream created successfully"),i}catch(t){return e&&console.error("[Bun] Failed to create TTY stream:",t),null}}var init_bun_tty_handler=__esm({"src/utils/bun-tty-handler.ts"(){}}),tty_helper_exports={};__export(tty_helper_exports,{createTTYInputStream:()=>createTTYInputStream,getInteractiveInputStream:()=>getInteractiveInputStream});import{openSync as openSync2}from"node:fs";import{ReadStream}from"node:tty";async function createTTYInputStream(e){const t=detectRuntime();try{if("bun"===t){const t=createBunTTYStream(e);return t||(process.stdin&&"function"==typeof process.stdin.setRawMode?process.stdin:null)}{const e="win32"===process.platform?"CON":"/dev/tty",t=openSync2(e,"r+");(t<0||t>1024)&&console.warn(`Warning: Unexpected file descriptor value: ${t}`);const n=new ReadStream(t);return n.isTTY=!0,n}}catch(e){return null}}async function getInteractiveInputStream(e,t){if(process.stdin.isTTY)return process.stdin;if(!process.stdin.isTTY&&e){const e=detectRuntime();if("bun"===e){const e=await createTTYInputStream(t);return e?(t&&console.error("[Bun] Successfully opened TTY device using tty_wrap"),process.stdin.pause(),e):(t&&console.error("[Bun] Failed to open TTY, using standard input"),process.stdin)}const n=await createTTYInputStream(t);return n?(t&&console.error(`[${e}] Successfully opened TTY device`),process.stdin.pause(),n):(t&&console.error(`[${e}] Failed to open TTY, using standard input`),process.stdin)}return process.stdin}var init_tty_helper=__esm({"src/utils/tty-helper.ts"(){init_bun_tty_handler(),init_runtime()}});import{readFileSync}from"node:fs";import{cpus as cpus3}from"node:os";import{dirname as dirname3,join as join4}from"node:path";import{fileURLToPath as fileURLToPath3}from"node:url";import{Command}from"commander";var LRUCache=class{constructor(e=52428800,t=1e4){this.cache=new Map,this.currentSize=0,this.maxSize=e,this.maxEntries=t}get(e){const t=this.cache.get(e);if(t)return t.lastAccessed=Date.now(),this.cache.delete(e),this.cache.set(e,t),t.value}set(e,t,n){const r=this.cache.get(e);for(r&&(this.currentSize-=r.size,this.cache.delete(e));(this.currentSize+n>this.maxSize||this.cache.size>=this.maxEntries)&&this.cache.size>0;){const e=this.cache.keys().next().value,t=this.cache.get(e);t&&(this.currentSize-=t.size,this.cache.delete(e))}n<=this.maxSize&&(this.cache.set(e,{value:t,size:n,lastAccessed:Date.now()}),this.currentSize+=n)}clear(){this.cache.clear(),this.currentSize=0}get size(){return this.cache.size}get sizeInBytes(){return this.currentSize}getStats(){return{entries:this.cache.size,sizeInBytes:this.currentSize,maxEntries:this.maxEntries,maxSizeInBytes:this.maxSize}}};function getStringSizeInBytes(e){return 2*e.length}var ApplicationContext=class{constructor(){this.quickjsModule=null,this.quickjsInitialized=!1,this.quickjsInitError=null,this.expressionCache=new LRUCache,this.compiledFunctionCache=new LRUCache}async getQuickJSModule(){if(this.quickjsInitError)throw this.quickjsInitError;if(!this.quickjsModule||!this.quickjsInitialized)try{const{getQuickJS:e,getQuickJSSync:t}=await import("quickjs-emscripten");if(this.quickjsModule=await e(),this.quickjsInitialized=!0,"function"==typeof t)try{const e=t();e&&(this.quickjsModule=e)}catch{}}catch(e){throw e instanceof Error?e.message.includes("dynamic import callback")||e.message.includes("experimental-vm-modules")||"ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING_FLAG"===e.code?this.quickjsInitError=new Error("QuickJS cannot be initialized in the current environment. Jest tests require --experimental-vm-modules flag. Run with NODE_OPTIONS=--experimental-vm-modules"):this.quickjsInitError=e:this.quickjsInitError=new Error(String(e)),this.quickjsInitError}return this.quickjsModule}async dispose(){this.expressionCache.clear(),this.compiledFunctionCache.clear(),this.quickjsModule=null,this.quickjsInitialized=!1,this.quickjsInitError=null}getCacheStats(){return{expressionCache:this.expressionCache.getStats(),compiledFunctionCache:this.compiledFunctionCache.getStats()}}};function createApplicationContext(){return new ApplicationContext}init_output_formatter();import{cpus as cpus2}from"node:os";import{Transform}from"node:stream";import pc2 from"picocolors";var ErrorFormatter=class e{static formatError(t,n){const r=e.getTypeLabel(t.type),s=t.detail?` (${t.detail})`:"",i=t.position?` at line ${t.position.line}:${t.position.column}`:"";return pc2.bold(pc2.red(`${r}: ${t.message}${s}${i}`))}static getTypeLabel(e){switch(e){case"syntax":return"SYNTAX ERROR";case"security":return"SECURITY ERROR";case"runtime":return"RUNTIME ERROR"}}static parseJSONError(t,n){const r=t.message,s=r.match(/at position (\d+)/),i=r.match(/Unexpected token (.) in JSON at position (\d+)/),a=r.match(/Unexpected end of JSON input/);let o,l;if(s||i){const t=i?i[2]:null==s?void 0:s[1];if(t){const r=parseInt(t,10);if(o=e.calculatePosition(n,r),i){const t=i[1];t&&(l=e.getJSONSuggestion(t,n,r))}}}else a&&(o=e.calculatePosition(n,n.length),l="JSON input ended unexpectedly. Check for missing closing brackets or quotes.");return{type:"syntax",message:"Invalid JSON syntax",detail:r,position:o,suggestion:l}}static parseSecurityError(t,n){let r,s,i=null;for(const e of t){const t=n.indexOf(e);-1!==t&&(!i||t<i.index)&&(i={pattern:e,index:t})}return i&&(r=e.calculatePosition(n,i.index),r.length=i.pattern.length,s=e.getSecuritySuggestion(i.pattern)),{type:"security",message:"Expression contains potentially dangerous patterns",detail:`Found dangerous patterns: ${t.join(", ")}`,position:r,suggestion:s}}static parseExpressionError(t,n){const r=t.message,s=r.match(/Unexpected token '?(.+?)'?/);r.match(/Missing (.+?) after/);let i,a;if(s){const t=s[1];if(t){const r=n.indexOf(t);-1!==r&&(i=e.calculatePosition(n,r),i.length=t.length)}a=e.getExpressionSuggestion(r)}return{type:"syntax",message:"Invalid expression syntax",detail:r,position:i,suggestion:a}}static calculatePosition(e,t){let n=1,r=1;for(let s=0;s<Math.min(t,e.length);s++)"\n"===e[s]?(n++,r=1):r++;return{line:n,column:r}}static getJSONSuggestion(e,t,n){switch(e){case"'":return"Single quotes are not valid in JSON. Use double quotes instead.";case",":return n===t.length-1||"}"===t[n+1]||"]"===t[n+1]?"Trailing commas are not allowed in JSON.":"Check for missing values or extra commas.";case"}":case"]":return"Unexpected closing bracket. Check for matching opening brackets.";default:return"Check JSON syntax near this position."}}static getSecuritySuggestion(e){return{eval:"Use a safer alternative like JSON.parse() or a sandboxed evaluator.",Function:"Dynamic function creation is dangerous. Consider using predefined functions.",require:"Dynamic imports are not allowed. Use static imports or predefined modules.",import:"Dynamic imports are not allowed. Use static imports or predefined modules.",process:"Access to process object is restricted for security reasons.",global:"Access to global scope is restricted. Use the provided context.",__dirname:"File system access is not allowed in expressions.",__filename:"File system access is not allowed in expressions.","while(true)":"Infinite loops are not allowed. Use finite iterations.","for(;;)":"Infinite loops are not allowed. Use finite iterations.",readFile:"File system operations are not allowed in expressions.",writeFile:"File system operations are not allowed in expressions.",exec:"Shell command execution is not allowed for security reasons.",spawn:"Process spawning is not allowed for security reasons.",fetch:"Network requests are not allowed in expressions.",setTimeout:"Asynchronous operations are restricted. Use synchronous alternatives.",setInterval:"Asynchronous operations are restricted. Use synchronous alternatives.",Buffer:"Buffer operations are restricted for security reasons."}[e]||"This pattern is restricted for security reasons."}static getExpressionSuggestion(e){return e.includes("Unexpected token")?"Check for syntax errors like missing operators, brackets, or quotes.":e.includes("is not defined")?"The variable or function is not available in the expression context.":e.includes("Cannot read property")?"Trying to access a property of null or undefined. Add null checks.":"Review the expression syntax and ensure all variables are properly defined."}};init_lodash_shared_methods();var methodsMatch=LODASH_METHODS.match(/globalThis\.lodashMethods = ({[\s\S]*});/);if(!methodsMatch||!methodsMatch[1])throw new Error("Failed to extract methods from LODASH_METHODS");var methodsCode=methodsMatch[1],createMethods=new Function(`return ${methodsCode}`),methods=createMethods(),Lodash=class{constructor(e){this._value=e,this.__isLodash=!0}get length(){return Array.isArray(this._value)||"string"==typeof this._value?this._value.length:this._value&&"object"==typeof this._value?Object.keys(this._value).length:0}[Symbol.iterator](){return null===this._value||void 0===this._value?[][Symbol.iterator]():Array.isArray(this._value)||"string"==typeof this._value?this._value[Symbol.iterator]():this._value&&"object"==typeof this._value?Object.entries(this._value)[Symbol.iterator]():[][Symbol.iterator]()}toJSON(){return this._value}valueOf(){return this._value}toString(){return null===this._value?"null":void 0===this._value?"undefined":String(this._value)}[Symbol.toPrimitive](e){return"string"===e?this.toString():this._value}};function createLodashInstance(e){if(null==e)return;const t=new Lodash(e);return new Proxy(t,{get(e,t){if(t in e){const n=e[t];return"function"==typeof n?n.bind(e):n}if("string"==typeof t&&!Number.isNaN(Number(t))){const n=Number(t);if(Array.isArray(e._value)&&n>=0&&n<e._value.length)return e._value[n]}if(null!==e._value&&void 0!==e._value&&"object"==typeof e._value){const n=e._value;if(t in n){const e=n[t];return null!=e&&"object"==typeof e?createLodashInstance(e):e}}},set:(e,t,n)=>null!==e._value&&void 0!==e._value&&"object"==typeof e._value&&(e._value[t]=n,!0),has:(e,t)=>t in e||null!==e._value&&void 0!==e._value&&"object"==typeof e._value&&t in e._value})}function _(...e){if(0!==e.length)return createLodashInstance(e[0])}Object.entries(methods).forEach((([e,t])=>{const n=function(...e){return t.apply(this,e)};n.toString=()=>`function bound ${e}() {[native code]}`,Lodash.prototype[e]=n})),_.toString=()=>"function() {[native code]}",Object.entries(methods).forEach((([e,t])=>{const n=(...n)=>{if("isArray"===e||"isObject"===e||"isString"===e||"isNumber"===e||"isFunction"===e||"isNull"===e||"isUndefined"===e){if(0===n.length)return!1;let t=n[0];if(t&&"object"==typeof t){const e=t;(e.__isSmartDollar||e.__isChainableWrapper)&&(t="function"==typeof e.valueOf?e.valueOf():t)}const r=new Lodash(t);return r[e].call(r)}if(n.length>0){const t=n[0],r=new Lodash(t),s=r[e].call(r,...n.slice(1));return"chain"===e?s:s&&"object"==typeof s&&"__isLodash"in s&&!0===s.__isLodash?s._value:s}return t.call({_value:void 0,constructor:Lodash})};n.toString=()=>`function bound ${e}() {[native code]}`,_[e]=n}));var _typed=_,SecurityManager=class{constructor(e){this.context=this.createSecurityContext(e)}getSecurityContext(){return this.context}createEvaluationContext(e){const t={...e},{level:n}=this.context;if(n.allowedGlobals.length>0){const e={};for(const r of n.allowedGlobals)r in t&&(e[r]=t[r]);return e}return t}validateExpression(e){const t=[];let n;if(this.context.options.unsafe)return{valid:!0,errors:[]};if(this.shouldUseVM()){const r=[{pattern:/eval\s*\(/,name:"eval"},{pattern:/Function\s*\(/,name:"Function"},{pattern:/setTimeout/,name:"setTimeout"},{pattern:/setInterval/,name:"setInterval"},{pattern:/global\./,name:"global"},{pattern:/globalThis\./,name:"globalThis"},{pattern:/process\./,name:"process"},{pattern:/__dirname/,name:"__dirname"},{pattern:/__filename/,name:"__filename"},{pattern:/this\.constructor/,name:"this.constructor"},{pattern:/constructor\.constructor/,name:"constructor.constructor"},{pattern:/arguments\.callee/,name:"arguments.callee"},{pattern:/Buffer\./,name:"Buffer"},{pattern:/while\s*\(\s*true\s*\)/,name:"while(true)"},{pattern:/for\s*\(\s*;;\s*\)/,name:"for(;;)"},{pattern:/performance\.now/,name:"performance.now"},{pattern:/process\.hrtime/,name:"process.hrtime"},{pattern:/\[\s*['"`]constructor['"`]\s*\]/,name:'["constructor"]'},{pattern:/window\./,name:"window"},{pattern:/document\./,name:"document"},{pattern:/\[\s*['"`]eval['"`]\s*\]/,name:'["eval"]'},{pattern:/\(\s*\d+\s*,\s*eval\s*\)/,name:"(1, eval)"},{pattern:/\[\s*['"`]Function['"`]\s*\]/,name:'["Function"]'},{pattern:/require\s*\(/,name:"require"},{pattern:/import\s*\(/,name:"import"},{pattern:/execSync/,name:"execSync"},{pattern:/exec/,name:"exec"},{pattern:/spawn/,name:"spawn"},{pattern:/fork/,name:"fork"},{pattern:/readFile/,name:"readFile"},{pattern:/writeFile/,name:"writeFile"},{pattern:/readFileSync/,name:"readFileSync"},{pattern:/writeFileSync/,name:"writeFileSync"},{pattern:/createReadStream/,name:"createReadStream"},{pattern:/createWriteStream/,name:"createWriteStream"}],s=[];for(const{pattern:t,name:n}of r)t.test(e)&&s.push(n);s.length>0&&(t.push(`Expression contains dangerous patterns: ${s.join(", ")}`),n=`Security error: Expression contains dangerous patterns: ${s.join(", ")}`)}return{valid:0===t.length,errors:t,...void 0!==n&&{formattedError:n}}}shouldUseVM(){return this.context.level.useVM}getTimeout(){return this.context.level.timeout}getMemoryLimit(){return this.context.level.memoryLimit}getCpuLimit(){return this.context.level.cpuLimit}getVMConfig(){return this.context.vmConfig}getCapabilities(){return this.context.capabilities}getWarnings(){return this.context.warnings}createSecurityContext(e){let t,n,r;return e.unsafe?t=this.createUnsafeLevel(e):(t=this.createSandboxLevel(e),n=this.createSandboxVMConfig(e),r=this.createSandboxCapabilities()),{level:t,options:e,warnings:[],...void 0!==n&&{vmConfig:n},...void 0!==r&&{capabilities:r}}}createSandboxLevel(e){return{allowNetwork:!1,allowShell:!1,allowFileSystem:!1,allowDynamicImports:!1,allowedGlobals:[],timeout:Number(e.cpuLimit)||3e4,memoryLimit:Number(e.memoryLimit)||128,...e.cpuLimit&&{cpuLimit:Number(e.cpuLimit)},maxContextSize:10485760,useVM:!0}}createUnsafeLevel(e){return{allowNetwork:!0,allowShell:!0,allowFileSystem:!0,allowDynamicImports:!0,allowedGlobals:[],useVM:!1}}createSandboxVMConfig(e){return{memoryLimit:Number(e.memoryLimit)||128,timeout:Number(e.cpuLimit)||3e4,...e.cpuLimit&&{cpuLimit:Number(e.cpuLimit)},enableAsync:!0,enableGenerators:!0,enableProxies:!1,enableSymbols:!0,maxContextSize:10485760,recycleIsolates:!0,isolatePoolSize:3}}createSandboxCapabilities(){return{console:!0,timers:!1,promises:!0,json:!0,math:!0,date:!0,array:!0,object:!0,string:!0,number:!0,boolean:!0,regexp:!0,error:!0,map:!0,set:!0,weakmap:!0,weakset:!0,proxy:!1,reflect:!0,symbol:!0,bigint:!0,intl:!1,buffer:!1,url:!1,crypto:!1}}};function transformExpression(e,t){const n=e.trim();if(t){const n=t.get(e);if(void 0!==n)return n}let r;return r=n.includes("\n")&&/\b(while|for|if|switch|do)\s*[({]/.test(n)||n.includes("\n")&&/^\s*(const|let|var)\s+/.test(n)&&!isUsingSemicolonAsSeparator(n)&&!hasVariablePipelineDeclaration(n)?e:hasSemicolonOperator(n)?transformSemicolonExpression(n):hasVariablePipelineDeclaration(n)?transformVariablePipelineDeclaration(n):hasPipeOperator(n)?transformPipeExpression(n):isArrayLiteralWithMethods(n)?transformArrayLiteralExpression(n):hasAsyncGeneratorMethods(n)?transformAsyncGeneratorExpression(n):"."===n?"data":n.startsWith(".")&&n.length>1?`data${n}`:"$"===n?"$":"_"===n?"_":e,r=transformHyphenatedProperties(r),t&&t.set(e,r,getStringSizeInBytes(e)+getStringSizeInBytes(r)),r}function hasAsyncGeneratorMethods(e){return["interval","timer"].some((t=>e.includes(`.${t}(`)||e.match(new RegExp(`\\$\\.${t}\\(`))))}function isArrayLiteralWithMethods(e){const t=e.trim();return t.startsWith("[")&&t.includes("].")&&!t.startsWith("$.")}function findArrayEndIndex(e){let t,n=0,r=!1;for(let s=0;s<e.length;s++){const i=e.charAt(s),a=s>0?e.charAt(s-1):void 0;if(shouldUpdateStringState(i,a,r,t)){const e=getStringState(i,a,r,t);r=e.inString,t=e.stringChar}else if(!r)if("["===i)n++;else if("]"===i&&(n--,0===n))return s}return-1}function shouldUpdateStringState(e,t,n,r){return!n&&isQuoteChar(e)||n&&e===r&&"\\"!==t}function getStringState(e,t,n,r){return!n&&isQuoteChar(e)?{inString:!0,stringChar:e}:n&&e===r&&"\\"!==t?{inString:!1,stringChar:void 0}:{inString:n,stringChar:r}}function isQuoteChar(e){return'"'===e||"'"===e||"`"===e}function transformArrayLiteralExpression(e){const t=e.trim(),n=findArrayEndIndex(t);if(-1===n)return e;return`createSmartDollar(${t.substring(0,n+1)})${t.substring(n+1)}`}function transformAsyncGeneratorExpression(e){return e}function createInitialParseState(){return{inString:!1,stringChar:void 0,parenDepth:0,braceDepth:0,bracketDepth:0}}function updateStringState(e,t,n){if(!e.inString&&('"'===t||"'"===t||"`"===t))return e.inString=!0,void(e.stringChar=t);e.inString&&t===e.stringChar&&"\\\\"!==n&&(e.inString=!1,e.stringChar=void 0)}function updateBracketDepth(e,t){"("===t&&e.parenDepth++,")"===t&&e.parenDepth--,"{"===t&&e.braceDepth++,"}"===t&&e.braceDepth--,"["===t&&e.bracketDepth++,"]"===t&&e.bracketDepth--}function isPipeOperatorAt(e,t,n){const r=e.charAt(t),s=e.charAt(t+1),i=e.charAt(t+2);return" "===r&&"|"===s&&" "===i&&0===n.parenDepth&&0===n.braceDepth&&0===n.bracketDepth}function hasPipeOperator(e){const t=createInitialParseState();for(let n=0;n<e.length-2;n++){const r=e.charAt(n);if(updateStringState(t,r,n>0?e.charAt(n-1):""),!t.inString&&(updateBracketDepth(t,r),isPipeOperatorAt(e,n,t)))return!0}return!1}function transformPipeExpression(e){var t,n;const r=splitByPipe(e);if(r.length<=1)return e;let s=(null==(t=r[0])?void 0:t.trim())||"";for(let e=1;e<r.length;e++){const t=(null==(n=r[e])?void 0:n.trim())||"";s=t.startsWith("$")?t.replace(/^\$/,`(${s})`):t.startsWith("_.")||t.startsWith("lodash.")||t.match(/^(Math|Date|Object|Array|String|Number|Boolean|console)\.[a-zA-Z_$][a-zA-Z0-9_$]*\(/)?t:`(${s}).${t}`}return s}function handleStringChar(e,t,n){return updateStringState(e,t,n||""),t}function shouldSplitAtPipe(e,t,n,r){return"|"===e&&" "===t&&" "===n&&0===r.parenDepth&&0===r.braceDepth&&0===r.bracketDepth}function processSplit(e,t){return e.push(t.trim()),""}function addFinalPart(e,t){t.trim()&&e.push(t.trim())}function splitByPipe(e){const t=[];let n="";const r=createInitialParseState();for(let s=0;s<e.length;s++){const i=e.charAt(s),a=e.charAt(s+1),o=s>0?e.charAt(s-1):void 0;n+=handleStringChar(r,i,o),r.inString||(updateBracketDepth(r,i),shouldSplitAtPipe(i,o,a,r)&&(n=n.slice(0,-1),n=processSplit(t,n),s++))}return addFinalPart(t,n),t}function hasVariablePipelineDeclaration(e){const t=e.trim();return/^(const|let)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*([^|]+)\s*\|\s*(.+)$/s.test(t)}function transformVariablePipelineDeclaration(e){const t=e.trim();return hasMultipleVariableDeclarations(t)?transformMultipleVariableDeclarations(t):transformSingleVariableDeclaration(t)}function hasMultipleVariableDeclarations(e){return/\|\s*(const|let)\s+[a-zA-Z_$][a-zA-Z0-9_$]*\s*=/.test(e)}function transformMultipleVariableDeclarations(e){const t=[];let n=e.trim(),r="";for(;;){const e=n.match(/^(const|let)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*([^|]+)\s*\|\s*(.*)$/s);if(!e){r=n.trim();break}const[,s,i,a,o]=e;if(!(s&&i&&a&&void 0!==o))break;t.push(`${s} ${i} = ${a.trim()};`),n=o.trim()}return/\bawait\b/.test(e)?`(async () => {\n      ${t.join("\n      ")}\n      return ${r};\n    })()`:`(() => {\n      ${t.join("\n      ")}\n      return ${r};\n    })()`}function transformSingleVariableDeclaration(e){const t=e.match(/^(const|let)\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\s*=\s*([^|]+)\s*\|\s*(.+)$/s);if(!t)return e;const[,n,r,s,i]=t;if(!r||!s||!i)return e;return/\bawait\b/.test(s)||/\bawait\b/.test(i)?`(async () => { \n      let ${r} = ${s.trim()}; \n      // Only unwrap ChainableWrapper if it's not a SmartDollar instance\n      if (${r} && typeof ${r} === 'object' && !${r}.__isSmartDollar && ('value' in ${r} || 'valueOf' in ${r})) {\n        ${r} = ${r}.value !== undefined ? ${r}.value : ${r}.valueOf();\n      }\n      return ${i.trim()}; \n    })()`:`(() => { \n      let ${r} = ${s.trim()}; \n      // Only unwrap ChainableWrapper if it's not a SmartDollar instance\n      if (${r} && typeof ${r} === 'object' && !${r}.__isSmartDollar && ('value' in ${r} || 'valueOf' in ${r})) {\n        ${r} = ${r}.value !== undefined ? ${r}.value : ${r}.valueOf();\n      }\n      return ${i.trim()}; \n    })()`}function isUsingSemicolonAsSeparator(e){if(e.includes("\n")){const t=e.split("\n").map((e=>e.trim())).filter((e=>e)),n=t.some((e=>e.endsWith(";")));return t.some((e=>{const t=(e.match(/;/g)||[]).length;return t>1||1===t&&!e.endsWith(";")}))&&!n}return hasSemicolonOperator(e)}function hasSemicolonOperator(e){const t=createInitialParseState();for(let n=0;n<e.length;n++){const r=e.charAt(n);if(updateStringState(t,r,n>0?e.charAt(n-1):""),!t.inString&&(updateBracketDepth(t,r),";"===r&&0===t.parenDepth&&0===t.braceDepth&&0===t.bracketDepth))return!0}return!1}function transformSemicolonExpression(e){const t=splitBySemicolon(e);if(t.length<=1)return e;const n=/\bawait\b/.test(e),r=t.slice(0,-1),s=t[t.length-1];return s?n?`(async () => {\n      ${r.map((e=>`${e.trim()};`)).join("\n      ")}\n      return ${s.trim()};\n    })()`:`(() => {\n      ${r.map((e=>`${e.trim()};`)).join("\n      ")}\n      return ${s.trim()};\n    })()`:e}function splitBySemicolon(e){const t=[];let n="";const r=createInitialParseState();for(let s=0;s<e.length;s++){const i=e.charAt(s);updateStringState(r,i,s>0?e.charAt(s-1):""),n+=i,r.inString||(updateBracketDepth(r,i),";"===i&&0===r.parenDepth&&0===r.braceDepth&&0===r.bracketDepth&&(n=n.slice(0,-1),n.trim()&&t.push(n.trim()),n=""))}return n.trim()&&t.push(n.trim()),t}function transformHyphenatedProperties(e){return e.replace(/\.([a-zA-Z0-9_$][\w$]*(?:-[\w$]+)+)(?=\.|[^\w$-]|$)/g,((e,t)=>`["${t}"]`))}var ExpressionTransformer={transform:transformExpression,hasPipeOperator:hasPipeOperator,transformPipeExpression:transformPipeExpression,splitByPipe:splitByPipe,hasVariablePipelineDeclaration:hasVariablePipelineDeclaration,transformVariablePipelineDeclaration:transformVariablePipelineDeclaration,hasSemicolonOperator:hasSemicolonOperator,transformSemicolonExpression:transformSemicolonExpression,splitBySemicolon:splitBySemicolon},asyncMethods={mapAsync:async(e,t)=>Promise.all(e.map(((n,r)=>t(n,r,e)))),mapAsyncSeq:async(e,t)=>{const n=[];for(let r=0;r<e.length;r++)n.push(await t(e[r],r,e));return n},forEachAsync:async(e,t)=>{await Promise.all(e.map(((n,r)=>t(n,r,e))))},forEachAsyncSeq:async(e,t)=>{for(let n=0;n<e.length;n++)await t(e[n],n,e)}},_ChainableWrapper=class e{constructor(t){return this.data=t,new Proxy(this,{get(t,n,r){if(n in t){const s=Reflect.get(t,n,r);if("function"==typeof s){let r=e.methodCache.get(t);r||(r=new Map,e.methodCache.set(t,r));const i=String(n);let a=r.get(i);return!a&&s&&(a=s.bind(t)),a&&r.set(i,a),a}return s}if("string"==typeof n){if(t.isObject(t.data)&&n in t.data)return new e(t.data[n]);if(Array.isArray(t.data))return new e(void 0)}return new e(void 0)}})}get value(){return this.data}get(t){return this.isObject(this.data)&&t in this.data?new e(this.data[t]):new e(void 0)}filter(t){return Array.isArray(this.data)?new e(this.data.filter(t)):new e([])}map(t){return Array.isArray(this.data)?new e(this.data.map(t)):new e([])}find(t){return Array.isArray(this.data)?new e(this.data.find(t)):new e(void 0)}where(t,n){if(Array.isArray(this.data)){const r=this.data.filter((e=>!(!this.isObject(e)||!(t in e))&&e[t]===n));return new e(r)}return new e([])}pluck(t){if(Array.isArray(this.data)){const n=this.data.map((e=>{if(this.isObject(e)&&t in e)return e[t]})).filter((e=>void 0!==e));return new e(n)}return new e([])}sortBy(t){if(Array.isArray(this.data)){const n=[...this.data].sort(((e,n)=>{let r,s;if("function"==typeof t)r=t(e),s=t(n);else{if(!this.isObject(e)||!this.isObject(n))return 0;r=e[t],s=n[t]}return"string"==typeof r&&"string"==typeof s?r.localeCompare(s):"number"==typeof r&&"number"==typeof s?r-s:0}));return new e(n)}return new e([])}take(t){return Array.isArray(this.data)?new e(this.data.slice(0,t)):new e([])}skip(t){return Array.isArray(this.data)?new e(this.data.slice(t)):new e([])}uniqBy(t){if(Array.isArray(this.data)){const n=new Set,r=this.data.filter((e=>{const r=t(e);return!n.has(r)&&(n.add(r),!0)}));return new e(r)}return new e([])}flatten(){return Array.isArray(this.data)?new e(this.data.flat()):new e([])}flattenDeep(){if(Array.isArray(this.data)){const t=e=>e.reduce(((e,n)=>Array.isArray(n)?e.concat(t(n)):e.concat(n)),[]);return new e(t(this.data))}return new e([])}compact(){return Array.isArray(this.data)?new e(this.data.filter(Boolean)):new e([])}chunk(t){if(Array.isArray(this.data)){const n=[];for(let e=0;e<this.data.length;e+=t)n.push(this.data.slice(e,e+t));return new e(n)}return new e([])}takeWhile(t){if(Array.isArray(this.data)){const n=[];for(const e of this.data){if(!t(e))break;n.push(e)}return new e(n)}return new e([])}drop(t){return Array.isArray(this.data)?new e(this.data.slice(t)):new e([])}dropWhile(t){if(Array.isArray(this.data)){let n=0;for(;n<this.data.length&&t(this.data[n]);)n++;return new e(this.data.slice(n))}return new e([])}reverse(){return Array.isArray(this.data)?new e([...this.data].reverse()):new e(this.data)}shuffle(){if(Array.isArray(this.data)){const t=[...this.data];for(let e=t.length-1;e>0;e--){const n=Math.floor(Math.random()*(e+1));[t[e],t[n]]=[t[n],t[e]]}return new e(t)}return new e(this.data)}sample(){if(Array.isArray(this.data)&&this.data.length>0){const t=Math.floor(Math.random()*this.data.length);return new e(this.data[t])}return new e(void 0)}sampleSize(t){if(Array.isArray(this.data)){const n=[...this.data].sort((()=>.5-Math.random()));return new e(n.slice(0,t))}return new e([])}orderBy(t,n=[]){if(Array.isArray(this.data)){const r=[...this.data].sort(this.createOrderByComparator(t,n));return new e(r)}return new e([])}createOrderByComparator(e,t){return(n,r)=>{for(let s=0;s<e.length;s++){const i=e[s];if(!i)continue;const a=t[s]||"asc";let o,l;if("function"==typeof i)o=i(n),l=i(r);else{if(!this.isObject(n)||!this.isObject(r))continue;o=n[i],l=r[i]}let u=0;if(null!==o&&null!==l&&void 0!==o&&void 0!==l&&(o<l?u=-1:o>l&&(u=1)),0!==u)return"desc"===a?-u:u}return 0}}groupBy(t){if(Array.isArray(this.data)){const n={};for(const e of this.data){const r=t(e);n[r]||(n[r]=[]),n[r].push(e)}return new e(n)}return new e({})}countBy(t){if(Array.isArray(this.data)){const n={};for(const e of this.data){const r=t(e);n[r]=(n[r]||0)+1}return new e(n)}return new e({})}keyBy(t){if(Array.isArray(this.data)){const n={};for(const e of this.data)n[t(e)]=e;return new e(n)}return new e({})}pick(t){if(this.isObject(this.data)){const n=this.data,r={};for(const e of t)e in n&&(r[e]=n[e]);return new e(r)}return new e({})}omit(t){if(this.isObject(this.data)){const n={...this.data};for(const e of t)delete n[e];return new e(n)}return new e({})}invert(){if(this.isObject(this.data)){const t=this.data,n={};for(const[e,r]of Object.entries(t))n[String(r)]=e;return new e(n)}return new e({})}mean(){if(Array.isArray(this.data)){const t=this.data.filter((e=>"number"==typeof e));if(0===t.length)return new e(0);const n=t.reduce(((e,t)=>e+t),0);return new e(n/t.length)}return new e(0)}min(){if(Array.isArray(this.data)){const t=this.data.filter((e=>"number"==typeof e));return new e(t.length>0?Math.min(...t):void 0)}return new e(void 0)}max(){if(Array.isArray(this.data)){const t=this.data.filter((e=>"number"==typeof e));return new e(t.length>0?Math.max(...t):void 0)}return new e(void 0)}minBy(t){if(Array.isArray(this.data)&&this.data.length>0){const n=this.data.reduce(((e,n)=>t(n)<t(e)?n:e));return new e(n)}return new e(void 0)}maxBy(t){if(Array.isArray(this.data)&&this.data.length>0){const n=this.data.reduce(((e,n)=>t(n)>t(e)?n:e));return new e(n)}return new e(void 0)}size(){return Array.isArray(this.data)?new e(this.data.length):this.isObject(this.data)?new e(Object.keys(this.data).length):new e(0)}isEmpty(){return null==this.data?new e(!0):Array.isArray(this.data)||"string"==typeof this.data?new e(0===this.data.length):this.isObject(this.data)?new e(0===Object.keys(this.data).length):new e(!1)}includes(t){return Array.isArray(this.data)?new e(this.data.includes(t)):this.isObject(this.data)?new e(Object.values(this.data).includes(t)):new e(!1)}length(){return Array.isArray(this.data)?new e(this.data.length):this.isObject(this.data)?new e(Object.keys(this.data).length):new e(0)}sum(t){if(Array.isArray(this.data)){const n=(t?this.data.map((e=>this.isObject(e)?e[t]:0)):this.data).reduce(((e,t)=>e+("number"==typeof t?t:0)),0);return new e(n)}return new e(0)}keys(){return this.isObject(this.data)?new e(Object.keys(this.data)):new e([])}values(){return this.isObject(this.data)?new e(Object.values(this.data)):new e([])}entries(){return this.isObject(this.data)?new e(Object.entries(this.data)):new e([])}flatMap(t){if(Array.isArray(this.data)){const n=[];for(let e=0;e<this.data.length;e++){const r=t(this.data[e],e);Array.isArray(r)?n.push(...r):n.push(r)}return new e(n)}return new e([])}mapValues(t){if(this.isObject(this.data)){const n=this.data,r={};for(const[e,s]of Object.entries(n))r[e]=t(s,e);return new e(r)}return new e({})}isObject(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}valueOf(){return this.data}toString(){return JSON.stringify(this.data,null,2)}toJSON(){return this.data}[Symbol.toPrimitive](e){return"default"===e||"string"===e?this.data:"number"===e?"number"==typeof this.data?this.data:Number(this.data):this.data}partition(t){if(Array.isArray(this.data)){const n=[],r=[];for(let e=0;e<this.data.length;e++)t(this.data[e],e)?n.push(this.data[e]):r.push(this.data[e]);return new e([n,r])}return new e([[],[]])}windowed(t,n=1){if(Array.isArray(this.data)){if(t<=0)return new e([]);const r=[];for(let e=0;e<=this.data.length-t;e+=n)r.push(this.data.slice(e,e+t));return new e(r)}return new e([])}chunked(e){return this.chunk(e)}span(t){if(Array.isArray(this.data)){let n=this.data.length;for(let e=0;e<this.data.length;e++)if(!t(this.data[e],e)){n=e;break}const r=this.data.slice(0,n),s=this.data.slice(n);return new e([r,s])}return new e([[],[]])}breakAt(e){return this.span(((t,n)=>!e(t,n)))}takeUntil(t){if(Array.isArray(this.data)){const n=[];for(let e=0;e<this.data.length&&!t(this.data[e],e);e++)n.push(this.data[e]);return new e(n)}return new e([])}dropUntil(t){if(Array.isArray(this.data)){let n=0;for(;n<this.data.length&&!t(this.data[n],n);)n++;return new e(this.data.slice(n))}return new e([])}frequencies(){if(Array.isArray(this.data)){const t={};for(const e of this.data){const n=String(e);t[n]=(t[n]||0)+1}return new e(t)}return new e({})}groupWith(t,n){if(Array.isArray(this.data)){const r={};for(const e of this.data){const s=t(e),i=n(e);r[s]||(r[s]=[]),r[s].push(i)}return new e(r)}return new e({})}reduceBy(t,n,r){if(Array.isArray(this.data)){const s={};for(const e of this.data){const i=t(e);s[i]=s[i]?n(s[i],e):n(r,e)}return new e(s)}return new e({})}scanLeft(t,n){if(Array.isArray(this.data)){const r=[n];let s=n;for(let e=0;e<this.data.length;e++)s=t(s,this.data[e],e),r.push(s);return new e(r)}return new e([n])}scan(e,t){return this.scanLeft(e,t)}scanRight(t,n){if(Array.isArray(this.data)){const r=[n];let s=n;for(let e=this.data.length-1;e>=0;e--)s=t(this.data[e],s,e),r.unshift(s);return new e(r)}return new e([n])}distinctBy(t){if(Array.isArray(this.data)){const n=[],r=[];for(const e of this.data){const s=t(e);n.includes(s)||(n.push(s),r.push(e))}return new e(r)}return new e([])}intersectBy(t,n){if(Array.isArray(this.data)){const r=t.map(n),s=this.data.filter((e=>r.includes(n(e))));return new e(s)}return new e([])}spy(t){if(Array.isArray(this.data))for(let e=0;e<this.data.length;e++)t(this.data[e],e);return new e(this.data)}filterMap(t){if(Array.isArray(this.data)){const n=[];for(let e=0;e<this.data.length;e++){const r=t(this.data[e],e);null!=r&&n.push(r)}return new e(n)}return new e([])}findLast(t){if(Array.isArray(this.data))for(let n=this.data.length-1;n>=0;n--)if(t(this.data[n],n))return new e(this.data[n]);return new e(void 0)}quantify(t){if(Array.isArray(this.data)){let n=0;for(let e=0;e<this.data.length;e++)t(this.data[e],e)&&n++;return new e(n)}return new e(0)}pairwise(){if(Array.isArray(this.data)&&this.data.length>=2){const t=[];for(let e=0;e<this.data.length-1;e++)t.push([this.data[e],this.data[e+1]]);return new e(t)}return new e([])}intersperse(t){if(Array.isArray(this.data)){if(this.data.length<=1)return new e(this.data);const n=[this.data[0]];for(let e=1;e<this.data.length;e++)n.push(t,this.data[e]);return new e(n)}return new e([])}peekable(){if(Array.isArray(this.data)){const t=this.data;let n=0;return new e({hasNext:()=>n<t.length,next:()=>n<t.length?t[n++]:void 0,peek:()=>n<t.length?t[n]:void 0,remaining:()=>t.slice(n)})}return new e({hasNext:()=>!1,next:()=>{},peek:()=>{},remaining:()=>[]})}batched(t,n){if(Array.isArray(this.data)){if(t<=0)return new e([]);const r=[];for(let e=0;e<this.data.length;e+=t){const s=this.data.slice(e,e+t);if(void 0!==n&&s.length<t&&e+t>this.data.length)for(;s.length<t;)s.push(n);r.push(s)}return new e(r)}return new e([])}reduce(e,t){return Array.isArray(this.data)?this.data.reduce(((t,n,r)=>e(t,n,r)),t):t}fold(e,t){return this.reduce(e,t)}foldLeft(t,n){if(Array.isArray(this.data)){let r=t;for(let e=0;e<this.data.length;e++)r=n(r,this.data[e],e);return new e(r)}return new e(t)}foldRight(t,n){if(Array.isArray(this.data)){let r=t;for(let e=this.data.length-1;e>=0;e--)r=n(this.data[e],r,e);return new e(r)}return new e(t)}traverse(t,n){if(Array.isArray(this.data)){const r=[];let s=t;for(let e=0;e<this.data.length;e++){const{value:t,state:i}=n(s,this.data[e],e);r.push(t),s=i}return new e({values:r,finalState:s})}return new e({values:[],finalState:t})}delay(t){return new Promise((n=>{setTimeout((()=>n(new e(this.data))),t)}))}debounceTime(t){return new Promise((n=>{if(!Array.isArray(this.data))return void setTimeout((()=>n(new e(this.data))),t);const r=this.data;0!==r.length?setTimeout((()=>{n(new e(r[r.length-1]))}),t):n(new e([]))}))}throttleTime(t){return new Promise((n=>{if(!Array.isArray(this.data))return void n(new e(this.data));const r=this.data;0!==r.length?setTimeout((()=>{n(new e(r[0]))}),t):n(new e([]))}))}timeout(t){return Promise.race([new Promise((t=>{t(new e(this.data))})),new Promise(((e,n)=>{setTimeout((()=>n(new Error(`Operation timed out after ${t}ms`))),t)}))])}async*interval(t){if(!Array.isArray(this.data))return void(yield new e(this.data));const n=this.data;for(const r of n)yield new e(r),await new Promise((e=>setTimeout(e,t)))}async*timer(t,n){if(await new Promise((e=>setTimeout(e,t))),!Array.isArray(this.data))return void(yield new e(this.data));const r=this.data;let s=0;for(;s<r.length;)yield new e(r[s++]),n&&s<r.length&&await new Promise((e=>setTimeout(e,n)))}async concatMap(t){if(!Array.isArray(this.data)){const n=await Promise.resolve(t(this.data,0));return new e(n)}const n=this.data,r=[];for(let e=0;e<n.length;e++){const s=await Promise.resolve(t(n[e],e));Array.isArray(s)?r.push(...s):r.push(s)}return new e(r)}async mergeMap(t){if(!Array.isArray(this.data)){const n=await Promise.resolve(t(this.data,0));return new e(n)}const n=this.data.map(((e,n)=>Promise.resolve(t(e,n)))),r=await Promise.all(n),s=[];for(const e of r)Array.isArray(e)?s.push(...e):s.push(e);return new e(s)}async switchMap(t){if(!Array.isArray(this.data)){const n=await Promise.resolve(t(this.data,0));return new e(n)}const n=this.data;if(0===n.length)return new e([]);const r=n[n.length-1],s=await Promise.resolve(t(r,n.length-1));return new e(Array.isArray(s)?s:[s])}async exhaustMap(t){if(!Array.isArray(this.data)){const n=await Promise.resolve(t(this.data,0));return new e(n)}const n=this.data;if(0===n.length)return new e([]);const r=n[0],s=await Promise.resolve(t(r,0));return new e(Array.isArray(s)?s:[s])}distinctUntilChanged(t){if(!Array.isArray(this.data))return new e(this.data);const n=this.data;if(0===n.length)return new e([]);const r=[n[0]];let s=t?t(n[0]):n[0];for(let e=1;e<n.length;e++){const i=t?t(n[e]):n[e];i!==s&&(r.push(n[e]),s=i)}return new e(r)}skipLast(t){if(!Array.isArray(this.data))return new e(t>0?void 0:this.data);const n=this.data;if(t<=0)return new e(n);const r=n.slice(0,Math.max(0,n.length-t));return new e(r)}takeLast(t){if(!Array.isArray(this.data))return new e(t>0?this.data:void 0);const n=this.data;if(t<=0)return new e([]);const r=n.slice(Math.max(0,n.length-t));return new e(r)}combineLatest(t){if(!Array.isArray(this.data))return new e([this.data,...t.map((e=>e[e.length-1]||null))]);const n=this.data,r=Math.max(n.length,...t.map((e=>e.length))),s=[];for(let e=0;e<r;e++){const r=[e<n.length?n[e]:n[n.length-1]||null];for(const n of t)r.push(e<n.length?n[e]:n[n.length-1]||null);s.push(r)}return new e(s)}zip(t){const n=Array.isArray(t)&&t.length>0&&!Array.isArray(t[0])?[t]:t;if(!Array.isArray(this.data))return new e([this.data,...n.map((e=>e[0]||null))]);const r=this.data,s=Math.min(r.length,...n.map((e=>e.length))),i=[];for(let e=0;e<s;e++){const t=[r[e]];for(const r of n)t.push(r[e]);i.push(t)}return new e(i)}zipWith(t,n){if(!Array.isArray(this.data))return new e([]);const r=this.data,s=Array.isArray(t)?t:[],i=Math.min(r.length,s.length),a=[];for(let e=0;e<i;e++)a.push(n(r[e],s[e],e));return new e(a)}unzip(){if(!Array.isArray(this.data))return new e([[],[]]);const t=[],n=[];for(const e of this.data)Array.isArray(e)&&e.length>=2&&(t.push(e[0]),n.push(e[1]));return new e([t,n])}merge(t){if(!Array.isArray(this.data)){const n=[this.data];for(const e of t)n.push(...e);return new e(n)}const n=[...this.data];for(const e of t)n.push(...e);return new e(n)}async retry(t,n){let r=0;const s=t+1;for(;r<s;)try{if(n){const t=await n();return new e(t)}return new e(this.data)}catch(e){if(r++,r>=s)throw e;await new Promise((e=>setTimeout(e,1e3*2**(r-1))))}return new e(this.data)}async catchError(t){try{return new e(this.data)}catch(n){const r=await Promise.resolve(t(n));return new e(r)}}forEach(t){if(Array.isArray(this.data)){const e=this.data;e.forEach(((n,r)=>{t(n,r,e)}))}else t(this.data,0,[this.data]);return new e(this.data)}each(e){return this.forEach(e)}async forEachAsync(t){return Array.isArray(this.data)?await asyncMethods.forEachAsync(this.data,t):await t(this.data,0,[this.data]),new e(this.data)}async forEachAsyncSeq(t){return Array.isArray(this.data)?await asyncMethods.forEachAsyncSeq(this.data,t):await t(this.data,0,[this.data]),new e(this.data)}async mapAsync(t){if(Array.isArray(this.data)){const n=await asyncMethods.mapAsync(this.data,t);return new e(n)}const n=await t(this.data,0);return new e([n])}async mapAsyncSeq(t){if(Array.isArray(this.data)){const n=await asyncMethods.mapAsyncSeq(this.data,t);return new e(n)}const n=await t(this.data,0);return new e([n])}tap(t){if(Array.isArray(this.data)){this.data.forEach(((e,n)=>{t(e,n)}))}else t(this.data,0);return new e(this.data)}startWith(t){return Array.isArray(this.data)?new e([t,...this.data]):new e([t,this.data])}iterate(t,n){const r=[];let s=this.data;for(let e=0;e<n;e++)r.push(s),s=t(s,e);return new e(r)}unfold(t,n){const r=[];let s=void 0!==n?n:this.data,i=t(s);for(;null!=i&&Array.isArray(i)&&2===i.length;)r.push(i[0]),s=i[1],i=t(s);return new e(r)}cycle(t=1){if(!Array.isArray(this.data)||0===this.data.length)return new e([]);const n=[];for(let e=0;e<t;e++)n.push(...this.data);return new e(n)}intercalate(t){if(!Array.isArray(this.data))return new e([]);const n=[];for(let e=0;e<this.data.length;e++)e>0&&void 0!==t&&(Array.isArray(t)?n.push(...t):n.push(t)),Array.isArray(this.data[e])?n.push(...this.data[e]):n.push(this.data[e]);return new e(n)}transpose(){if(!Array.isArray(this.data)||0===this.data.length)return new e([]);const t=this.data,n=Math.max(...t.map((e=>Array.isArray(e)?e.length:0))),r=[];for(let e=0;e<n;e++){const n=[];for(let r=0;r<t.length;r++)Array.isArray(t[r])&&e<t[r].length&&n.push(t[r][e]);r.push(n)}return new e(r)}tee(...t){const n=t.map((e=>e(this.data)));return new e(n)}debug(e){const t=e?`[${e}] `:"";return console.log(`${t}Debug:`,this.data),this}benchmark(t,n){const r=performance.now(),s=t(this.data),i=performance.now()-r,a=n?`[${n}] `:"";return console.log(`${a}Benchmark: ${i}ms`),new e(s)}memoize(t,n){const r=new Map,s=n?n(this.data):JSON.stringify(this.data);if(r.has(s))return new e(r.get(s));const i=t(this.data);return r.set(s,i),new e(i)}partitionBy(...t){if(!Array.isArray(this.data))return new e(Array(t.length+1).fill([]));const n=Array(t.length+1).fill(null).map((()=>[]));for(let e=0;e<this.data.length;e++){let r=!1;for(let s=0;s<t.length;s++)if(t[s](this.data[e],e)){n[s].push(this.data[e]),r=!0;break}r||n[t.length].push(this.data[e])}return new e(n)}head(){if(Array.isArray(this.data))return this.data[0]}tail(){return Array.isArray(this.data)?new e(this.data.slice(1)):new e([])}init(){return Array.isArray(this.data)?new e(this.data.slice(0,-1)):new e([])}last(){if(Array.isArray(this.data))return this.data[this.data.length-1]}cons(t){return Array.isArray(this.data)?new e([t,...this.data]):new e([t])}snoc(t){return Array.isArray(this.data)?new e([...this.data,t]):new e([t])}sliding(e,t=1){return this.windowed(e,t)}enumerate(){if(!Array.isArray(this.data))return new e([]);const t=[];for(let e=0;e<this.data.length;e++)t.push([e,this.data[e]]);return new e(t)}groupByMultiple(...t){if(!Array.isArray(this.data))return new e({});const n={};for(let e=0;e<this.data.length;e++){const r=t.map((t=>t(this.data[e],e))),s=JSON.stringify(r);n[s]||(n[s]={keys:r,items:[]}),n[s].items.push(this.data[e])}return new e(Object.values(n))}[Symbol.iterator](){return Array.isArray(this.data)?this.data[Symbol.iterator]():[][Symbol.iterator]()}};_ChainableWrapper.methodCache=new WeakMap;var VMSandboxSimple2,VMSandboxQuickJS2,getVMEngineType2,ChainableWrapper=_ChainableWrapper,CHAINABLE_METHODS=["map","filter","find","reduce","groupBy","sortBy","orderBy","slice","flatten","flattenDeep","flatMap","uniq","uniqBy","compact","chunk","pluck","where","findWhere","first","last","take","takeWhile","drop","dropWhile","skip","sample","sampleSize","shuffle","reverse","keys","values","entries","pick","omit","invert","defaults","merge","assignIn","assignWith","extend","mapValues","clone","has","includes","get","set","sum","mean","min","minBy","max","maxBy","count","countBy","keyBy","size","isEmpty","isArray","isObject","isString","isNumber","toArray","partition","windowed","chunked","span","takeUntil","dropUntil","frequencies","groupWith","reduceBy","scanLeft","distinctBy","intersectBy","spy","filterMap","findLast","quantify","pairwise","intersperse","peekable","batched","fold","foldLeft","foldRight","traverse","scan","scanRight","delay","debounceTime","throttleTime","timeout","interval","timer","concatMap","mergeMap","switchMap","exhaustMap","distinctUntilChanged","skipLast","takeLast","combineLatest","zip","zipWith","unzip","merge","retry","catchError","tap","startWith","forEach","each","forEachAsync","forEachAsyncSeq","mapAsync","mapAsyncSeq","head","tail","init","last","cons","snoc","breakAt","iterate","unfold","cycle","intercalate","transpose","tee","debug","benchmark","memoize","partitionBy","sliding","enumerate","groupByMultiple"];function createSmartDollar(e){if(null==e){const t=(...t)=>0===t.length?e:new ChainableWrapper(t[0]);return Object.defineProperty(t,"valueOf",{value:()=>e}),Object.defineProperty(t,"toString",{value:()=>String(e)}),Object.defineProperty(t,"toJSON",{value:()=>e}),Object.defineProperty(t,Symbol.toPrimitive,{value:t=>"default"===t||"string"===t?e:"number"===t?"number"==typeof e?e:Number(e):e}),t}if(Array.isArray(e)){const t=[...e];return Object.defineProperty(t,"data",{value:e,enumerable:!1,configurable:!0,writable:!1}),Object.defineProperty(t,"value",{value:e,enumerable:!1,configurable:!0,writable:!1}),Object.defineProperty(t,"constructor",{value:Array,enumerable:!1,configurable:!0,writable:!0}),attachChainableMethods(t,e),Object.defineProperty(t,"chain",{value:()=>new ChainableWrapper(e),enumerable:!1,configurable:!0,writable:!1}),Object.defineProperty(t,"toJSON",{value:()=>e,enumerable:!1,configurable:!0}),Object.defineProperty(t,"valueOf",{value:()=>e,enumerable:!1,configurable:!0}),Object.defineProperty(t,"toString",{value:()=>JSON.stringify(e),enumerable:!1,configurable:!0}),t}const t=(...t)=>0===t.length?new ChainableWrapper(e):new ChainableWrapper(t[0]);if("object"==typeof e&&!Array.isArray(e)){const n=e;for(const[e,r]of Object.entries(n))CHAINABLE_METHODS.includes(e)||Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!1});return new Proxy(t,{get(e,t,r){if("hasOwnProperty"===t)return e=>Object.hasOwn(n,e);if("propertyIsEnumerable"===t)return e=>Object.prototype.propertyIsEnumerable.call(n,e);if("toJSON"===t)return()=>n;if("valueOf"===t)return()=>n;if("toString"===t)return()=>JSON.stringify(n);if("string"==typeof t&&Object.hasOwn(n,t)){const e=n[t];return CHAINABLE_METHODS.includes(t),new ChainableWrapper(e)}const s=Reflect.get(e,t,r);return void 0!==s?s:void 0},getOwnPropertyDescriptor:(e,t)=>"string"==typeof t&&t in n?{configurable:!0,enumerable:!0,value:n[t],writable:!1}:Reflect.getOwnPropertyDescriptor(e,t),has:(e,t)=>t in n||Reflect.has(e,t),ownKeys:()=>Object.keys(n)})}return Object.defineProperty(t,"hasOwnProperty",{value:Object.prototype.hasOwnProperty,enumerable:!1,configurable:!0}),Object.defineProperty(t,"propertyIsEnumerable",{value:Object.prototype.propertyIsEnumerable,enumerable:!1,configurable:!0}),attachChainableMethods(t,e),Object.defineProperty(t,"toJSON",{value:()=>e,enumerable:!1,configurable:!0}),Object.defineProperty(t,"valueOf",{value:()=>e,enumerable:!1,configurable:!0}),Object.defineProperty(t,"toString",{value:()=>"string"==typeof e?e:"number"==typeof e||"boolean"==typeof e?String(e):JSON.stringify(e),enumerable:!1,configurable:!0}),Object.defineProperty(t,Symbol.for("nodejs.util.inspect.custom"),{value:()=>e,enumerable:!1,configurable:!0}),Object.defineProperty(t,"__isSmartDollar",{value:!0,enumerable:!1,configurable:!1,writable:!1}),Object.defineProperty(t,"_value",{value:e,enumerable:!1,configurable:!1,writable:!1}),t}function attachChainableMethods(e,t){const n=new ChainableWrapper(t);for(const r of CHAINABLE_METHODS)if(r in n&&"function"==typeof n[r]){if("object"==typeof t&&!Array.isArray(t)&&null!==t&&r in t)continue;Object.defineProperty(e,r,{value:(...e)=>{const s=n[r];if("function"!=typeof s)throw new Error(`${r} is not a function`);const i=s(...e);if(Array.isArray(t))return i;if(i&&"object"==typeof i&&"value"in i){const e=i.value;return Array.isArray(e)?createSmartDollar(e):e}return i},enumerable:!1,configurable:!0,writable:!1})}Object.defineProperty(e,"chain",{value:()=>new ChainableWrapper(t),enumerable:!1,configurable:!0,writable:!1})}var vmModulesLoaded=!1;async function loadVMModules(){if(!vmModulesLoaded){try{const e=await Promise.resolve().then((()=>(init_vm_sandbox_simple(),vm_sandbox_simple_exports)));VMSandboxSimple2=e.VMSandboxSimple}catch(e){"test"!==process.env.NODE_ENV&&console.error("Failed to load vm-sandbox-simple module:",e)}try{const e=await Promise.resolve().then((()=>(init_vm_sandbox_quickjs(),vm_sandbox_quickjs_exports)));VMSandboxQuickJS2=e.VMSandboxQuickJS}catch(e){"test"!==process.env.NODE_ENV&&console.error("Failed to load vm-sandbox-quickjs module:",e)}try{const e=await Promise.resolve().then((()=>(init_VMEngineFactory(),VMEngineFactory_exports)));getVMEngineType2=e.getVMEngineType}catch(e){"test"!==process.env.NODE_ENV&&console.error("Failed to load VMEngineFactory module:",e)}vmModulesLoaded=!0}}var ExpressionEvaluator=class{constructor(e,t){this.vmSandbox=null,this.options=e,this.appContext=t,this.securityManager=new SecurityManager(e)}async dispose(){this.vmSandbox&&(await this.vmSandbox.dispose(),this.vmSandbox=null)}showSecurityWarnings(){const e=this.securityManager.getWarnings();if("test"!==process.env.NODE_ENV||"true"===process.env.SHOW_SECURITY_WARNINGS)for(const t of e)console.error(t)}async evaluate(e,t,n){await loadVMModules();try{this.showSecurityWarnings();const r=this.transformExpression(e),s=this.securityManager.validateExpression(r);if(!s.valid){if(s.formattedError)throw new Error(s.formattedError);throw new Error(`Security validation failed: ${s.errors.join(", ")}`)}if("$"===r.trim())return t;if("_"===r.trim()&&!this.securityManager.shouldUseVM()){return(await this.loadUtilities())(t)}const i=this.securityManager.shouldUseVM()?t:createSmartDollar(t),a=await this.createEvaluationContext(i,t,n),o=this.securityManager.createEvaluationContext(a),l=await this.executeExpression(r,o);return this.unwrapResult(l)}catch(e){if(e instanceof Error&&e.message.includes("Security validation failed"))throw e;if(e instanceof Error&&"code"in e&&"CPU_LIMIT"===e.code)throw new Error("CPU time limit exceeded");throw new Error(`Expression evaluation failed: ${e instanceof Error?e.message:"Unknown error"}`)}}transformExpression(e){var t;const n=transformExpression(e,null==(t=this.appContext)?void 0:t.expressionCache);return this.options.verbose&&n!==e&&console.error("Transformed expression:",n),n}async createEvaluationContext(e,t,n){if(this.securityManager.shouldUseVM()){return{console:this.createConsoleObject(),data:t,$:e,_:null,$_:n}}return{$:e,console:this.createConsoleObject(),JSON:JSON,Math:Math,Date:Date,Array:Array,Object:Object,String:String,Number:Number,Boolean:Boolean,Set:Set,Map:Map,Reflect:Reflect,Symbol:Symbol,_:await this.loadUtilities(),$_:n,data:t}}createConsoleObject(){return{log:console.log,error:console.error,warn:console.warn,info:console.info,debug:this.options.verbose?console.debug:()=>{},trace:this.options.verbose?console.trace:()=>{},table:console.table,time:console.time,timeEnd:console.timeEnd,group:console.group,groupEnd:console.groupEnd,clear:console.clear,count:console.count,assert:console.assert,dir:console.dir}}async executeExpression(e,t){return this.securityManager.shouldUseVM()?(this.options.verbose&&console.error("🔒 Running in secure VM isolation mode"),await this.executeInVMSandbox(e,t)):(this.options.verbose&&console.error("⚡ Running in non-VM mode (should not happen)"),await this.safeEval(e,t))}async unwrapResult(e){if(this.debugResult(e),e instanceof Promise){const t=await e;return this.unwrapResult(t)}return this.isAsyncGenerator(e)?this.handleAsyncGenerator(e):this.isChainableWrapper(e)?this.unwrapChainableWrapper(e):this.isSmartDollar(e)?this.unwrapSmartDollar(e):e}debugResult(e){var t;this.options.verbose&&(console.error("Debug: Result type:",typeof e,"isArray:",Array.isArray(e)),e&&"object"==typeof e&&(console.error("Debug: Result has value:","value"in e),console.error("Debug: Result constructor:",null==(t=e.constructor)?void 0:t.name)))}isChainableWrapper(e){return null!==e&&"object"==typeof e&&!Array.isArray(e)&&"value"in e&&(e.constructor.name.includes("ChainableWrapper")||e.constructor.name.includes("_ChainableWrapper"))}isAsyncGenerator(e){return null!==e&&"object"==typeof e&&"next"in e&&"function"==typeof e.next&&Symbol.asyncIterator in e&&"function"==typeof e[Symbol.asyncIterator]}async handleAsyncGenerator(e){const t=[];for await(const n of e){const e=this.isChainableWrapper(n)?this.unwrapChainableWrapper(n):n;t.push(e)}return t}unwrapChainableWrapper(e){this.options.verbose&&console.error("Debug: Unwrapping result with .value");const t=e.value;return this.options.verbose&&console.error("Debug: Unwrapped value type:",typeof t),t}isSmartDollar(e){return null!==e&&"object"==typeof e&&"__isSmartDollar"in e&&!0===e.__isSmartDollar}unwrapSmartDollar(e){this.options.verbose&&console.error("Debug: Unwrapping SmartDollar object");const t=e,n=void 0!==t._value?t._value:t.value;return this.options.verbose&&console.error("Debug: Unwrapped SmartDollar value type:",typeof n),n}async safeEval(e,t){const n=Object.keys(t),r=Object.values(t);try{const t=new(0,Object.getPrototypeOf((async()=>{})).constructor)(...n,`\n        "use strict";\n        return (${e});\n      `);return await t(...r)}catch(t){if(t instanceof Error){const n=ErrorFormatter.parseExpressionError(t,e),r=ErrorFormatter.formatError(n,e);throw new Error(r)}throw new Error("Invalid expression: Syntax error")}}async loadUtilities(){return _typed}async executeInVMSandbox(e,t){if(await loadVMModules(),!this.vmSandbox){const e=this.securityManager.getVMConfig();if(!e)throw new Error("VM configuration not available");if("quickjs"===(getVMEngineType2?getVMEngineType2():"quickjs")&&VMSandboxQuickJS2)this.vmSandbox=new VMSandboxQuickJS2(this.appContext,e),this.options.verbose&&console.error("Using QuickJS VM engine (on-demand)");else{if(!VMSandboxSimple2)throw new Error("No VM sandbox available");this.vmSandbox=new VMSandboxSimple2(this.appContext,e),this.options.verbose&&console.error("Using VM engine (on-demand)")}}try{const n=this.securityManager.getTimeout(),r=this.securityManager.getMemoryLimit(),s=this.securityManager.getCpuLimit(),i={...void 0!==n&&{timeout:n},...void 0!==r&&{memoryLimit:r},...void 0!==s&&{cpuLimit:s},allowedGlobals:this.securityManager.getSecurityContext().level.allowedGlobals,allowNetwork:this.securityManager.getSecurityContext().level.allowNetwork};if(this.options.verbose){console.error("VM Context keys:",Object.keys(t));for(const[e,n]of Object.entries(t))console.error(`  ${e}: ${typeof n}${"function"==typeof n?` (${n.name||"anonymous"})`:""}`)}const a={};for(const[e,n]of Object.entries(t))a[e]=n;return(await this.vmSandbox.execute(e,a,i)).value}catch(t){if(t instanceof Error){if(this.options.verbose&&(console.error("VM execution error:",t.message),console.error("Expression:",e),console.error("Stack:",t.stack)),t.message.includes("Cannot find module"))throw new Error("VM module not found. Please ensure all dependencies are properly installed.");if(t.message.includes("QuickJS initialization failed"))throw t;if("code"in t&&"CPU_LIMIT"===t.code)throw t;let n=t.message;const r=n.match(/"message":"([^"]+)"/);throw r&&(n=r[1]),new Error(n)}throw t}}},JsonParser=class{constructor(e){this.options=e}parse(e){try{if(!e.trim())throw new Error("Empty input");const t=JSON.parse(e);return this.options.schema&&this.validateSchema(t,this.options.schema),t}catch(t){if(t instanceof SyntaxError){const n=this.preprocessJson(e);try{return JSON.parse(n)}catch(n){const r=ErrorFormatter.parseJSONError(t,e),s=ErrorFormatter.formatError(r,e);throw new Error(s)}}throw t}}preprocessJson(e){let t=e.trim();return t=t.replace(/,(\s*[}\]])/g,"$1"),t=t.replace(/(\w+):/g,'"$1":'),t}parseStream(e){throw new Error("Stream parsing not yet implemented")}validateSchema(e,t){if(!t)return!0;throw new Error("Schema validation not yet implemented")}};import{cpus}from"node:os";import{dirname,join}from"node:path";import{fileURLToPath}from"node:url";import{Worker}from"node:worker_threads";var WorkerPool=class{constructor(e){this.workers=[],this.taskQueue=[],this.nextTaskId=0,this.isShuttingDown=!1,this.maxWorkers=e||Math.max(1,cpus().length-1);const t=fileURLToPath(import.meta.url),n=dirname(t);n.includes("/src/")?this.workerScript=join(n,"parallel-worker.ts"):this.workerScript=join(n,"parallel-worker.js")}async initialize(){if(this.workers.length>0)return;const e=[];for(let t=0;t<this.maxWorkers;t++){const n=new Worker(this.workerScript),r={worker:n,busy:!1,id:t,currentTask:void 0};n.on("message",(e=>{"type"in e&&"ready"===e.type||this.handleWorkerResult(r,e)})),n.on("error",(e=>{console.error(`Worker ${t} error:`,e),this.handleWorkerError(r,e)})),n.on("exit",(e=>{0===e||this.isShuttingDown||console.error(`Worker ${t} exited with code ${e}`)})),this.workers.push(r),e.push(new Promise((e=>{const t=r=>{"ready"===r.type&&(n.off("message",t),e())};n.on("message",t)})))}await Promise.all(e)}async processTask(e,t,n){if(this.isShuttingDown)throw new Error("Worker pool is shutting down");await this.initialize();const r={id:this.nextTaskId++,data:e,expression:t,options:n};return new Promise(((e,t)=>{this.taskQueue.push({task:r,resolve:e,reject:t}),this.processQueue()}))}processQueue(){if(0===this.taskQueue.length)return;const e=this.workers.find((e=>!e.busy));if(!e)return;const t=this.taskQueue.shift();t&&(e.busy=!0,e.currentTask=t,e.worker.postMessage(t.task))}handleWorkerResult(e,t){const n=e.currentTask;n?(e.busy=!1,e.currentTask=void 0,t.error?n.reject(new Error(`Worker error: ${t.error}`)):n.resolve(t.results),this.processQueue()):console.error("Received result from worker without corresponding task")}handleWorkerError(e,t){const n=e.currentTask;e.busy=!1,n&&(e.currentTask=void 0,n.reject(t)),this.processQueue()}async shutdown(){if(this.isShuttingDown)return;this.isShuttingDown=!0;const e=this.workers.map((async e=>{try{await e.worker.terminate()}catch(t){console.error(`Error terminating worker ${e.id}:`,t)}}));await Promise.all(e),this.workers=[];for(const e of this.taskQueue)e.reject(new Error("Worker pool shutting down"));this.taskQueue=[]}getStats(){return{totalWorkers:this.workers.length,busyWorkers:this.workers.filter((e=>e.busy)).length,queueLength:this.taskQueue.length}}async processBatch(e){try{return{results:await this.processTask(e.data,e.expression,e.options)}}catch(e){return{results:[],errors:[{line:-1,message:e instanceof Error?e.message:"Unknown error"}]}}}},StreamProcessor=class{constructor(e,t){this.options=e,this.appContext=t,this.evaluator=new ExpressionEvaluator(e,t),this.parser=new JsonParser(e)}async dispose(){await this.evaluator.dispose(),this.workerPool&&await this.workerPool.shutdown()}getWorkerCount(e){if(!1===e||void 0===e)return 0;if(!0===e)return Math.max(1,cpus2().length-1);const t="string"==typeof e?parseInt(e,10):e;return Number.isNaN(t)||t<1?Math.max(1,cpus2().length-1):Math.min(t,2*cpus2().length)}async initializeWorkerPool(e){this.workerPool||(this.workerPool=new WorkerPool(e),await this.workerPool.initialize(),this.options.verbose&&console.error(`Initialized worker pool with ${e} workers`))}makeJSONSafe(e){if(null==e)return e;if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map((e=>this.makeJSONSafe(e)));if("object"==typeof e){const t={},n=e;for(const e in n)if(Object.hasOwn(n,e))try{t[e]=this.makeJSONSafe(n[e])}catch(r){t[e]=String(n[e])}return t}return String(e)}createObjectTransformStream(e,t={}){const n=ExpressionTransformer.transform(e,this.appContext.expressionCache);let r=0;return new Transform({objectMode:!0,transform:async(e,t,s)=>{r++;try{s(null,await this.processObjectChunk(e,n,r))}catch(e){this.options.verbose&&console.error(`Error processing object ${r}:`,e instanceof Error?e.message:e),s(e instanceof Error?e:new Error("Object processing error"))}}})}async processObjectChunk(e,t,n){this.options.verbose&&console.error(`Processing object ${n}`);const r=await this.evaluator.evaluate(t,e);let s;this.options.verbose&&console.error(`Processed object ${n}`);try{s=JSON.stringify(r)}catch(e){const t=this.makeJSONSafe(r);s=JSON.stringify(t)}return`${s}\n`}async processJsonLine(e,t,n){try{let r;r="object"==typeof e&&null!==e?e:this.parser.parse(e.trim());const s=await this.evaluator.evaluate(t,r);let i;this.options.verbose&&console.error(`Processed line ${n}`);try{i=JSON.stringify(s)}catch(e){const t=this.makeJSONSafe(s);i=JSON.stringify(t)}return`${i}\n`}catch(e){return this.options.verbose&&console.error(`Error processing line ${n}:`,e instanceof Error?e.message:e),null}}async processLines(e,t,n,r){const s=[];for(const i of e)if(i.trim()){if(n.value++,!r)throw new Error("Non-JSON Lines format not yet supported in streaming mode");{const e=await this.processJsonLine(i,t,n.value);e&&s.push(e)}}return s}createTransformStream(e,t={}){const{jsonLines:n=!0,delimiter:r="\n"}=t;let s="";const i={value:0},a=ExpressionTransformer.transform(e,this.appContext.expressionCache);return new Transform({objectMode:!0,transform:async(e,t,o)=>{try{s+=e.toString();const t=s.split(r);s=t.pop()||"";const l=await this.processLines(t,a,i,n);l.length>0?o(null,l.join("")):o()}catch(e){o(e instanceof Error?e:new Error("Stream processing error"))}},flush:async e=>{await this.flushBuffer(s,a,i,n,e)}})}async flushBuffer(e,t,n,r,s){if(e.trim())try{if(n.value++,r){s(null,await this.processJsonLine(e,t,n.value)||void 0)}else s()}catch(e){this.options.verbose&&console.error(`Error processing final line ${n.value}:`,e instanceof Error?e.message:e),s()}else s()}async processBatchLine(e,t,n,r,s,i){if(!e.trim())return null;try{if(i){const i=this.parser.parse(e.trim());if(t.push(i),t.length>=n){const e=await this.processBatch(r,t);s.value+=t.length,this.options.verbose&&console.error(`Processed batch of ${t.length} items (total: ${s.value})`);const n=new OutputFormatter({...this.options,oneline:!0}),i=e.map((e=>`${n.format(e)}\n`)).join("");return t.length=0,i}}}catch(e){this.options.verbose&&console.error("Error parsing line:",e instanceof Error?e.message:e)}return null}async processBatchBuffer(e,t,n,r,s,i){for(const a of e){const e=await this.processBatchLine(a,t,n,r,s,i);if(e)return e}return null}createParallelTransformStream(e,t={}){const{batchSize:n=100,jsonLines:r=!0,delimiter:s="\n",parallel:i}=t,a=this.getWorkerCount(i);if(0===a)return this.createBatchTransformStream(e,t);let o="";const l=[],u={value:0};let c=!1;const h=ExpressionTransformer.transform(e,this.appContext.expressionCache);return new Transform({objectMode:!0,transform:async(e,t,i)=>{try{c||(await this.initializeWorkerPool(a),c=!0);const t=this.processChunkToLines(e.toString(),o,s);o=t.remainingBuffer,this.addLinesToBatch(t.lines,l),this.shouldProcessBatch(l.length,n)?await this.processBatchIfReady(l,n,h,u,r,i):i()}catch(e){i(e instanceof Error?e:new Error("Parallel stream processing error"))}},flush:async e=>{try{this.addRemainingBufferToBatch(o,l),await this.processFinalBatch(l,h,u,r,e),this.workerPool&&(await this.workerPool.shutdown(),this.workerPool=void 0)}catch(t){e(t instanceof Error?t:new Error("Parallel flush error"))}}})}createWorkerParallelTransformStream(e,t={}){const{batchSize:n=1e3,delimiter:r="\n",parallel:s}=t,i=this.getWorkerCount(s);if(0===i)return this.createBatchTransformStream(e,t);let a="";const o=[];let l=!1;const u=ExpressionTransformer.transform(e,this.appContext.expressionCache);return new Transform({objectMode:!0,transform:async(e,t,s)=>{var c;try{l||(this.workerPool=new WorkerPool(i),await this.workerPool.initialize(),l=!0),a+=e.toString();const t=a.split(r);if(a=t.pop()||"",t.forEach((e=>{e.trim()&&o.push(e)})),o.length>=n){const e=o.splice(0,n),t=await(null==(c=this.workerPool)?void 0:c.processBatch({data:e,expression:u,options:this.options}));if(null!=(null==t?void 0:t.results)&&t.results.length>0){s(null,null==t?void 0:t.results.map((e=>this.formatOutput(e))).join(""))}else s()}else s()}catch(e){s(e instanceof Error?e:new Error("Worker pool processing error"))}},flush:async e=>{try{if(a.trim()&&o.push(a),o.length>0&&this.workerPool){const t=await this.workerPool.processBatch({data:o,expression:u,options:this.options});if(t.results.length>0){e(null,t.results.map((e=>this.formatOutput(e))).join(""))}else e()}else e();this.workerPool&&(await this.workerPool.shutdown(),this.workerPool=void 0)}catch(t){e(t instanceof Error?t:new Error("Worker pool flush error"))}}})}formatOutput(e){try{return`${JSON.stringify(e)}\n`}catch{return`${String(e)}\n`}}createBatchTransformStream(e,t={}){const{batchSize:n=100,jsonLines:r=!0,delimiter:s="\n"}=t;let i="";const a=[],o={value:0},l=ExpressionTransformer.transform(e,this.appContext.expressionCache);return new Transform({objectMode:!0,transform:async(e,t,u)=>{try{i+=e.toString();const t=i.split(s);i=t.pop()||"";const c=await this.processBatchBuffer(t,a,n,l,o,r);c?u(null,c):u()}catch(e){u(e instanceof Error?e:new Error("Batch stream processing error"))}},flush:async e=>{try{const t=await this.finalizeBatch(i,a,l,o,r);t?e(null,t):e()}catch(t){e(t instanceof Error?t:new Error("Batch flush error"))}}})}async finalizeBatch(e,t,n,r,s){if(e.trim())try{if(s){const n=this.parser.parse(e.trim());t.push(n)}}catch(e){this.options.verbose&&console.error("Error parsing final line:",e instanceof Error?e.message:e)}if(t.length>0){const e=await this.processBatch(n,t);r.value+=t.length,this.options.verbose&&console.error(`Processed final batch of ${t.length} items (total: ${r.value})`);const s=new OutputFormatter({...this.options,oneline:!0});return e.map((e=>`${s.format(e)}\n`)).join("")}return null}async processBatch(e,t){const n=[];for(const r of t)try{const t=await this.evaluator.evaluate(e,r);n.push(t)}catch(e){this.options.verbose&&console.error("Error processing batch item:",e instanceof Error?e.message:e)}return n}async processBatchParallel(e,t,n){try{const r=await n.processTask(t,e,this.options);return Array.isArray(r)?r:(console.error("Worker pool returned non-array result:",r),await this.fallbackSequentialProcessing(e,t))}catch(n){return this.logParallelProcessingError(n),await this.fallbackSequentialProcessing(e,t)}}logParallelProcessingError(e){this.options.verbose&&console.error("Error in parallel processing:",e instanceof Error?e.message:e)}async fallbackSequentialProcessing(e,t){const n=[];for(const r of t)try{const t=this.parser.parse(r.trim()),s=await this.evaluator.evaluate(e,t);n.push(s)}catch(e){this.logFallbackItemError(e)}return n}logFallbackItemError(e){this.options.verbose&&console.error("Error processing fallback item:",e instanceof Error?e.message:e)}async*processStreamIterable(e,t,n={}){const r=this.createTransformStream(e,n);t.pipe(r);for await(const e of r)if(e)try{yield JSON.parse(e.toString().trim())}catch(e){this.options.verbose&&console.error("Error parsing stream result:",e instanceof Error?e.message:e)}}processChunkToLines(e,t,n){const r=(t+e).split(n),s=r.pop()||"";return{lines:r,remainingBuffer:s}}addLinesToBatch(e,t){for(const n of e)n.trim()&&t.push(n.trim())}shouldProcessBatch(e,t){return e>=t&&null!==this.workerPool}async processBatchIfReady(e,t,n,r,s,i){const a=e.splice(0,t);if(s&&this.workerPool){const e=await this.processBatchParallel(n,a,this.workerPool);r.value+=a.length,this.logBatchProcessed(a.length,r.value,!1);const t=new OutputFormatter({...this.options,oneline:!0});i(null,e.map((e=>`${t.format(e)}\n`)).join(""))}else i()}addRemainingBufferToBatch(e,t){e.trim()&&t.push(e.trim())}async processFinalBatch(e,t,n,r,s){if(e.length>0&&this.workerPool&&r){const r=await this.processBatchParallel(t,e,this.workerPool);n.value+=e.length,this.logBatchProcessed(e.length,n.value,!0);const i=new OutputFormatter({...this.options,oneline:!0});s(null,r.map((e=>`${i.format(e)}\n`)).join(""))}else s()}logBatchProcessed(e,t,n){if(this.options.verbose&&this.workerPool){const r=this.workerPool.getStats(),s=n?"final":"";console.error(`Processed ${s} parallel batch of ${e} items (total: ${t}, workers: ${r.busyWorkers||r.totalWorkers}/${r.totalWorkers}`+(n?")":`, queue: ${r.queueLength})`))}}},JsqProcessor=class{constructor(e){this.appContext=createApplicationContext(),this.parser=new JsonParser(e),this.evaluator=new ExpressionEvaluator(e,this.appContext),this.streamProcessor=new StreamProcessor(e,this.appContext)}async dispose(){await this.evaluator.dispose(),await this.streamProcessor.dispose(),await this.appContext.dispose()}async process(e,t){const n=Date.now();try{let r;r=!t||null===t||"string"==typeof t&&""===t.trim()?null:this.parser.parse(t);const s=await this.evaluator.evaluate(e,r),i=Date.now()-n;return{data:s,metadata:{processingTime:i,inputSize:t?t.length:0,outputSize:void 0!==s?JSON.stringify(s).length:0}}}catch(e){throw new Error(`Processing failed: ${e instanceof Error?e.message:"Unknown error"}`)}}async processStream(e,t,n){return this.streamProcessor.processStreamIterable(e,t,n)}createTransformStream(e,t){return this.streamProcessor.createTransformStream(e,t)}createBatchTransformStream(e,t){return this.streamProcessor.createBatchTransformStream(e,t)}createObjectTransformStream(e,t){return this.streamProcessor.createObjectTransformStream(e,t)}createParallelTransformStream(e,t){return this.streamProcessor.createParallelTransformStream(e,t)}};init_default_providers();import{dirname as dirname2}from"node:path";import*as readline3 from"node:readline";import{fileURLToPath as fileURLToPath2}from"node:url";import{spawn}from"node:child_process";import{readFile,unlink,writeFile}from"node:fs/promises";import{tmpdir}from"node:os";import{join as join3}from"node:path";var ReplFileCommunicator=class{constructor(){this.pendingRequests=new Map,this.requestCounter=0,this.workerId=`${process.pid}-${Date.now()}`,this.inputFile=join3(tmpdir(),`jsq-repl-input-${this.workerId}.json`),this.outputFile=join3(tmpdir(),`jsq-repl-output-${this.workerId}.json`)}async start(){const e=join3(process.cwd(),"dist","repl-file-worker.js");console.error(`[DEBUG] Spawning worker: ${e} with ID: ${this.workerId}`),this.workerProcess=spawn("node",[e,this.workerId],{stdio:["ignore","inherit","inherit"],detached:!1}),this.workerProcess.on("error",(e=>{console.error("[DEBUG] Worker process error:",e)})),this.workerProcess.on("exit",((e,t)=>{console.error(`[DEBUG] Worker process exited with code ${e} and signal ${t}`)})),await new Promise((e=>setTimeout(e,500)));const{writeFile:t}=await import("node:fs/promises");console.error(`[DEBUG] Creating output file: ${this.outputFile}`),await t(this.outputFile,""),console.error(`[DEBUG] Starting file watcher for: ${this.outputFile}`);const{watchFile:n}=await import("node:fs");n(this.outputFile,{interval:100},(async(e,t)=>{console.error(`[DEBUG] Output file changed: size ${t.size} -> ${e.size}`),e.size>t.size&&await this.handleOutputChange()}))}async handleOutputChange(){console.error("[DEBUG] handleOutputChange() called");try{const e=await readFile(this.outputFile,"utf-8");if(console.error(`[DEBUG] Output file content length: ${e.length}`),console.error(`[DEBUG] Output file content: ${e.substring(0,200)}`),!e||""===e.trim())return void console.error("[DEBUG] Empty output file, ignoring");const t=JSON.parse(e),n=this.pendingRequests.get(t.requestId);n?(console.error(`[DEBUG] Found callback for request: ${t.requestId}`),n(t),this.pendingRequests.delete(t.requestId)):console.error(`[DEBUG] No callback found for request: ${t.requestId}`)}catch(e){console.error(`[DEBUG] Error reading output file: ${e}`)}}async evaluate(e,t,n,r){console.error(`[DEBUG] evaluate() called with expression: ${e}`);const s="req-"+this.requestCounter++,i={expression:e,data:t,options:n,requestId:s,lastResult:r};console.error(`[DEBUG] Writing request to: ${this.inputFile}`),console.error(`[DEBUG] Request content: ${JSON.stringify(i).substring(0,200)}...`),await writeFile(this.inputFile,JSON.stringify(i));const a=await readFile(this.inputFile,"utf-8");return console.error(`[DEBUG] Verified written content length: ${a.length}`),new Promise((e=>{this.pendingRequests.set(s,e),setTimeout((()=>{this.pendingRequests.has(s)&&(this.pendingRequests.delete(s),e({error:"Evaluation timeout",requestId:s}))}),3e4)}))}async dispose(){const{unwatchFile:e}=await import("node:fs");e(this.outputFile),this.workerProcess&&(this.workerProcess.kill("SIGTERM"),await new Promise((e=>{this.workerProcess?(this.workerProcess.on("exit",(()=>e())),setTimeout((()=>{this.workerProcess&&!this.workerProcess.killed&&this.workerProcess.kill("SIGKILL"),e()}),1e3)):e()})));try{await unlink(this.inputFile)}catch{}try{await unlink(this.outputFile)}catch{}}};function debounce(e,t){let n,r;const s=(...s)=>{if(r=s,n&&clearTimeout(n),0===t)return e(...r),void(r=void 0);n=setTimeout((()=>{r&&(e(...r),r=void 0),n=void 0}),t)};return s.cancel=()=>{n&&(clearTimeout(n),n=void 0),r=void 0},s.flush=()=>{n&&(clearTimeout(n),n=void 0),r&&(e(...r),r=void 0)},s}init_output_formatter(),init_pager(),init_autocomplete_engine();var StringBuffer=class{constructor(e=""){this.buffer=e.split("")}insert(e,t){const n=t.split("");this.buffer.splice(e,0,...n)}delete(e,t=1){this.buffer.splice(e,t)}toString(){return this.buffer.join("")}length(){return this.buffer.length}clear(){this.buffer=[]}set(e){this.buffer=e.split("")}substring(e,t){return this.buffer.slice(e,t).join("")}},ReplManager=class{constructor(e,t,n,r){this.isProcessingInput=!1,this.keypressQueue=[],this.maxHistorySize=1e3,this.isEvaluating=!1,this.state={data:e,history:[],historyIndex:0,currentInput:new StringBuffer,cursorPosition:0,options:t,lastDisplayedInput:"",lastDisplayedCursorPosition:0,lastResult:void 0,hasPreviewLine:!1,completions:[],completionIndex:0,isCompleting:!1,completionStart:0,completionEnd:0,originalInput:void 0,originalCursorPosition:0},this.evaluationHandler=n,this.prompt=(null==r?void 0:r.prompt)||"> ",this.realTimeEvaluation=(null==r?void 0:r.realTimeEvaluation)??!1,this.exitOnDoubleCtrlC=(null==r?void 0:r.exitOnDoubleCtrlC)??!0,this.keypressDebounceDelay=(null==r?void 0:r.keypressDebounceDelay)??10,this.boundHandleKeypress=this.handleKeypress.bind(this),this.debouncedHandleKeypress=debounce(this.processKeypressQueue.bind(this),this.keypressDebounceDelay),this.autocompleteEngine=new AutocompleteEngine,(null==r?void 0:r.io)?this.io=r.io:this.io=this.createDefaultIO()}createDefaultIO(){const e=__require("node:readline");return{input:process.stdin,output:{write:e=>process.stdout.write(e),clearLine:t=>e.clearLine(process.stdout,t),cursorTo:t=>e.cursorTo(process.stdout,t)}}}start(){this.setupKeypressHandler(),this.displayWelcomeMessage()}stop(){this.io.input.off("keypress",this.boundHandleKeypress),this.realTimeEvalTimer&&clearTimeout(this.realTimeEvalTimer),this.debouncedHandleKeypress.cancel()}displayWelcomeMessage(){this.io.output.write("jsq REPL - Interactive JSON Query Tool\n"),this.io.output.write("Type expressions to query the data. Press Ctrl+C to exit.\n"),this.io.output.write(`\n${this.prompt}`),this.state.lastDisplayedInput="",this.state.lastDisplayedCursorPosition=0}setupKeypressHandler(){this.io.input.on("keypress",this.boundHandleKeypress)}async handleKeypress(e,t){if(0===this.keypressDebounceDelay)return void await this.handleKeypressDebounced(e,t);(null==t?void 0:t.ctrl)||(null==t?void 0:t.name)&&["return","escape"].includes(t.name)?(this.debouncedHandleKeypress.cancel(),await this.processKeypressQueue(),await this.handleKeypressDebounced(e,t)):(this.keypressQueue.push({str:e,key:t}),this.debouncedHandleKeypress())}async processKeypressQueue(){const e=[...this.keypressQueue];this.keypressQueue=[];for(const{str:t,key:n}of e)await this.handleKeypressDebounced(t,n)}async handleKeypressDebounced(e,t){if(!this.isProcessingInput){this.isProcessingInput=!0;try{(null==t?void 0:t.ctrl)?await this.handleControlKey(t):(null==t?void 0:t.name)&&["return","backspace","delete","left","right","up","down","home","end","tab","escape"].includes(t.name)?await this.handleSpecialKey(t):e&&("\r"===e||"\n"===e?await this.handleEnter():await this.handleCharacterInput(e))}finally{this.isProcessingInput=!1}}}async handleControlKey(e){switch(e.name){case"c":this.handleCtrlC();break;case"d":this.handleCtrlD();break;case"l":this.handleCtrlL();break;case"a":this.moveCursorToStart();break;case"e":this.moveCursorToEnd();break;case"k":this.deleteToEnd();break;case"u":this.deleteToStart();break;case"w":this.deleteWord();break;case"r":await this.showLastResultInPager()}}async handleSpecialKey(e){if(this.state.isInCompletionMenu)switch(e.name){case"up":return void this.navigateCompletionMenuUp();case"down":return void this.navigateCompletionMenuDown();case"return":case"tab":return void this.selectCompletionFromMenu();case"escape":return void this.cancelCompletionMenu();default:this.cancelCompletionMenu()}switch(e.name){case"return":await this.handleEnter();break;case"backspace":this.handleBackspace();break;case"delete":this.handleDelete();break;case"left":this.moveCursorLeft();break;case"right":this.moveCursorRight();break;case"up":this.navigateHistoryUp();break;case"down":this.navigateHistoryDown();break;case"home":this.moveCursorToStart();break;case"end":this.moveCursorToEnd();break;case"tab":this.handleTab();break;case"escape":this.cancelCompletion()}}async handleCharacterInput(e){this.state.isCompleting&&this.cancelCompletion(),this.state.currentInput.insert(this.state.cursorPosition,e),this.state.cursorPosition+=e.length,this.updateDisplay(),this.realTimeEvaluation&&this.state.currentInput.toString().trim()&&this.scheduleRealTimeEvaluation()}handleCtrlC(){this.clearPreviewLine(),this.io.output.write("\n"),this.state.currentInput.length()>0?(this.state.currentInput.clear(),this.state.cursorPosition=0,this.io.output.write(this.prompt),this.state.lastDisplayedInput="",this.state.lastDisplayedCursorPosition=0,this.updateDisplay()):(this.stop(),this.exitOnDoubleCtrlC&&process.exit(0))}handleCtrlD(){if(0===this.state.currentInput.length())throw this.io.output.write("\n"),new Error("EOF")}handleCtrlL(){this.io.output.write("c"),this.state.lastDisplayedInput="",this.state.lastDisplayedCursorPosition=-1,this.state.hasPreviewLine=!1,this.updateDisplay()}async handleEnter(){this.clearPreviewLine();const e=this.state.currentInput.toString().trim();if(!e)return this.io.output.write(`\n${this.prompt}`),this.state.lastDisplayedInput="",void(this.state.lastDisplayedCursorPosition=0);let t;this.addToHistory(this.state.currentInput.toString());try{t=await this.evaluationHandler(e,this.state.data,this.state.options,this.state.lastResult)}catch(e){t={error:e instanceof Error?e.message:String(e)}}if(this.io.output.clearLine(0),this.io.output.cursorTo(0),this.io.output.write(`${this.prompt+this.state.currentInput.toString()}\n`),t.error)this.io.output.write(`Error: ${t.error}\n`),this.state.lastResult=void 0;else{const e=OutputFormatter.format(t.result,{...this.state.options,isReplMode:!0,oneline:!0});this.io.output.write(`${e}\n`),this.state.lastResult=t.result}this.state.currentInput.clear(),this.state.cursorPosition=0,this.state.lastDisplayedInput="",this.state.lastDisplayedCursorPosition=0,this.io.output.write(this.prompt)}addToHistory(e){this.state.history.push(e),this.state.history.length>this.maxHistorySize&&(this.state.history=this.state.history.slice(-this.maxHistorySize)),this.state.historyIndex=this.state.history.length}handleBackspace(){this.state.cursorPosition>0&&(this.state.currentInput.delete(this.state.cursorPosition-1),this.state.cursorPosition--,this.updateDisplay(),this.realTimeEvaluation&&this.scheduleRealTimeEvaluation())}handleDelete(){this.state.cursorPosition<this.state.currentInput.length()&&(this.state.currentInput.delete(this.state.cursorPosition),this.updateDisplay(),this.realTimeEvaluation&&this.scheduleRealTimeEvaluation())}moveCursorLeft(){this.state.cursorPosition>0&&(this.state.cursorPosition--,this.updateDisplay())}moveCursorRight(){this.state.cursorPosition<this.state.currentInput.length()&&(this.state.cursorPosition++,this.updateDisplay())}moveCursorToStart(){this.state.cursorPosition=0,this.updateDisplay()}moveCursorToEnd(){this.state.cursorPosition=this.state.currentInput.length(),this.updateDisplay()}deleteToEnd(){const e=this.state.currentInput.length();this.state.cursorPosition<e&&(this.state.currentInput.delete(this.state.cursorPosition,e-this.state.cursorPosition),this.updateDisplay())}deleteToStart(){if(this.state.cursorPosition>0){const e=this.state.currentInput.substring(this.state.cursorPosition);this.state.currentInput.clear(),this.state.currentInput.insert(0,e),this.state.cursorPosition=0,this.updateDisplay(),this.realTimeEvaluation&&this.scheduleRealTimeEvaluation()}}deleteWord(){const e=this.state.currentInput.toString(),t=e.substring(0,this.state.cursorPosition),n=e.substring(this.state.cursorPosition),r=t.trimEnd().lastIndexOf(" ");if(r>=0){const e=t.substring(0,r+1)+n;this.state.currentInput.set(e),this.state.cursorPosition=r+1}else this.state.currentInput.set(n),this.state.cursorPosition=0;this.updateDisplay(),this.realTimeEvaluation&&""===this.state.currentInput.toString().trim()&&this.scheduleRealTimeEvaluation()}navigateHistoryUp(){this.state.historyIndex>0&&(this.clearPreviewLine(),this.state.historyIndex--,this.state.currentInput.set(this.state.history[this.state.historyIndex]||""),this.state.cursorPosition=this.state.currentInput.length(),this.updateDisplay(),this.realTimeEvaluation&&this.state.currentInput.toString().trim()&&this.scheduleRealTimeEvaluation())}navigateHistoryDown(){this.state.historyIndex<this.state.history.length-1?(this.clearPreviewLine(),this.state.historyIndex++,this.state.currentInput.set(this.state.history[this.state.historyIndex]||""),this.state.cursorPosition=this.state.currentInput.length(),this.updateDisplay(),this.realTimeEvaluation&&this.state.currentInput.toString().trim()&&this.scheduleRealTimeEvaluation()):this.state.historyIndex===this.state.history.length-1&&(this.clearPreviewLine(),this.state.historyIndex=this.state.history.length,this.state.currentInput.clear(),this.state.cursorPosition=0,this.updateDisplay())}updateDisplay(){const e=this.state.currentInput.toString(),t=e!==this.state.lastDisplayedInput;t&&(this.io.output.clearLine(0),this.io.output.cursorTo(0),this.io.output.write(this.prompt+e),this.state.lastDisplayedInput=e),(this.state.cursorPosition!==this.state.lastDisplayedCursorPosition||t)&&(this.io.output.cursorTo(this.prompt.length+this.state.cursorPosition),this.state.lastDisplayedCursorPosition=this.state.cursorPosition)}scheduleRealTimeEvaluation(){this.realTimeEvalTimer&&clearTimeout(this.realTimeEvalTimer),this.realTimeEvalTimer=setTimeout((()=>{this.evaluateInRealTime()}),100)}clearPreviewLine(){if(this.state.hasPreviewLine){const e=this.state.cursorPosition;this.io.output.write("\n"),this.io.output.clearLine(0),this.io.output.cursorTo(0),this.io.output.write("[A"),this.io.output.cursorTo(this.prompt.length+e),this.state.hasPreviewLine=!1}}async evaluateInRealTime(){if(this.isEvaluating)return;const e=this.state.currentInput.toString().trim();if(this.clearPreviewLine(),e){this.isEvaluating=!0;try{const t=await this.evaluationHandler(e,this.state.data,this.state.options,this.state.lastResult);if(!t.error&&void 0!==t.result){const e=OutputFormatter.format(t.result,{...this.state.options,isReplMode:!0,oneline:!0}),n=this.state.cursorPosition;this.io.output.write("\n"),this.io.output.clearLine(0),this.io.output.write(`→ ${e}`),this.io.output.write("[A"),this.io.output.cursorTo(this.prompt.length+n),this.state.hasPreviewLine=!0}}finally{this.isEvaluating=!1}}}getCurrentInput(){return this.state.currentInput.toString()}getCursorPosition(){return this.state.cursorPosition}getHistory(){return[...this.state.history]}handleTab(){this.state.hasPreviewLine&&this.clearPreviewLine(),this.state.isCompleting&&this.state.completions.length>0?this.cycleCompletion():this.startCompletion()}startCompletion(){const e={input:this.state.currentInput.toString(),cursorPosition:this.state.cursorPosition,currentData:this.state.data,previousExpression:void 0!==this.state.lastResult?"$":void 0},t=this.autocompleteEngine.getSuggestions(e);0!==t.completions.length&&(this.state.completions=t.completions,this.state.completionIndex=0,this.state.isCompleting=!0,this.state.completionStart=t.replaceStart,this.state.completionEnd=t.replaceEnd,this.state.originalInput=void 0,this.applyCompletion())}cycleCompletion(){this.state.isCompleting&&0!==this.state.completions.length&&(this.state.completionIndex=(this.state.completionIndex+1)%this.state.completions.length,this.applyCompletion())}applyCompletion(){if(!this.state.isCompleting||0===this.state.completions.length)return;const e=this.state.completions[this.state.completionIndex],t=this.state.currentInput.toString();0!==this.state.completionIndex||this.state.originalInput||(this.state.originalInput=t,this.state.originalCursorPosition=this.state.cursorPosition);const n=this.state.originalInput||t,r=n.slice(0,this.state.completionStart)+e+n.slice(this.state.completionEnd);this.state.currentInput.clear(),this.state.currentInput.insert(0,r),this.state.cursorPosition=this.state.completionStart+e.length,this.updateDisplay(),this.state.completions.length>1&&this.displayCompletionInfo(),this.realTimeEvaluation&&setTimeout((()=>this.scheduleRealTimeEvaluation()),1e3)}displayCompletionInfo(){const e=`[${this.state.completionIndex+1}/${this.state.completions.length}]`,t=this.state.cursorPosition;this.io.output.write("\n"),this.io.output.clearLine(0),this.io.output.write(`${e} (Tab: next, Esc: cancel)`),this.io.output.write("[A"),this.io.output.cursorTo(this.prompt.length+t),this.state.hasPreviewLine=!0}cancelCompletion(){this.state.isCompleting&&(this.state.isCompleting=!1,this.state.completions=[],this.state.completionIndex=0,this.state.originalInput=void 0,this.state.originalCursorPosition=0,this.state.hasPreviewLine&&this.clearPreviewLine())}drawCompletionMenu(){if(!this.state.completions||0===this.state.completions.length)return;this.io.output.clearLine(0),this.io.output.cursorTo(0);const e=this.state.cursorPosition;this.io.output.write("\n"),this.io.output.write("Select completion (↑/↓ to navigate, Enter to select, Esc to cancel):\n");const t=Math.min(this.state.completions.length,10);for(let e=0;e<t;e++){const t=e===this.state.menuSelectedIndex,n=t?"→ ":"  ",r=this.state.completions[e];t?this.io.output.write(`[36m${n}${r}[0m\n`):this.io.output.write(`${n}${r}\n`)}this.state.completions.length>t&&this.io.output.write(`  ... and ${this.state.completions.length-t} more\n`);let n=Math.min(t,this.state.completions.length)+2;this.state.completions.length>t&&n++;for(let e=0;e<n;e++)this.io.output.write("[A");const r=this.state.originalInput||this.state.currentInput.toString();this.io.output.write(this.prompt+r),this.io.output.cursorTo(this.prompt.length+e)}navigateCompletionMenuUp(){this.state.isInCompletionMenu&&void 0!==this.state.menuSelectedIndex&&this.state.menuSelectedIndex>0&&(this.state.menuSelectedIndex--,this.drawCompletionMenu())}navigateCompletionMenuDown(){this.state.isInCompletionMenu&&void 0!==this.state.menuSelectedIndex&&this.state.menuSelectedIndex<this.state.completions.length-1&&(this.state.menuSelectedIndex++,this.drawCompletionMenu())}selectCompletionFromMenu(){if(!this.state.isInCompletionMenu||void 0===this.state.menuSelectedIndex)return;if(!this.state.completions||0===this.state.completions.length)return;if(this.state.menuSelectedIndex<0||this.state.menuSelectedIndex>=this.state.completions.length)return;this.state.originalInput||(this.state.originalInput=this.state.currentInput.toString());const e=this.state.completions[this.state.menuSelectedIndex];this.clearCompletionMenu();const t=this.state.originalInput.slice(0,this.state.completionStart)+e+this.state.originalInput.slice(this.state.completionEnd);this.state.currentInput.set(t),this.state.cursorPosition=this.state.completionStart+e.length,this.state.isInCompletionMenu=!1,this.state.menuSelectedIndex=void 0,this.state.isCompleting=!1,this.state.completions=[],this.updateDisplay()}cancelCompletionMenu(){this.state.isInCompletionMenu&&(this.clearCompletionMenu(),this.state.currentInput.set(this.state.originalInput||""),this.state.cursorPosition=this.state.originalCursorPosition,this.state.isInCompletionMenu=!1,this.state.menuSelectedIndex=void 0,this.state.isCompleting=!1,this.state.completions=[],this.updateDisplay())}clearCompletionMenu(){if(!this.state.completions||0===this.state.completions.length)return;const e=Math.min(this.state.completions.length,10);let t=e+2;this.state.completions.length>e&&t++;for(let e=0;e<t;e++)this.io.output.write("\n"),this.io.output.clearLine(0);for(let e=0;e<t;e++)this.io.output.write("[A")}async showLastResultInPager(){if(void 0===this.state.lastResult)return;const e=this.state.currentInput.toString(),t=this.state.cursorPosition,n=OutputFormatter.format(this.state.lastResult,{...this.state.options,isReplMode:!1,oneline:!1});this.io.output.write("[2J[H");const r=new Pager(n,this.io.input);await r.show(),this.io.output.clearLine(0),this.io.output.cursorTo(0),this.io.output.write(this.prompt+e),this.io.output.cursorTo(this.prompt.length+t),e.trim().length>0&&(this.io.output.write("\n"),await this.handleEnter())}};async function createReplEvaluationHandler(e,t){const n=fileURLToPath2(import.meta.url),r=dirname2(n);let s,i;if(e.replFileMode){i=new ReplFileCommunicator,await i.start();return{evaluator:async(e,t,n,r)=>{try{const s=await(null==i?void 0:i.evaluate(e,t,n,r));return s.error?{error:s.error}:{result:s.result}}catch(e){return{error:e instanceof Error?e.message:String(e)}}},dispose:async()=>{i&&await i.dispose()}}}{const e=t||new DefaultWorkerProvider(r);s=e.createWorker("repl-worker.js"),await new Promise(((e,t)=>{const n=t=>{"ready"===t.type&&(null==s||s.removeListener("message",n),e())},r=e=>{null==s||s.removeListener("error",r),t(e)};null==s||s.on("message",n),null==s||s.on("error",r)}));return{evaluator:async(e,t,n,r)=>{try{return await new Promise(((i,a)=>{let o;const l=e=>{var t;"result"===e.type&&(c(),(null==(t=e.errors)?void 0:t.length)>0?i({error:e.errors[0].message}):i({result:e.results[0]}))},u=e=>{c(),a(e)},c=()=>{o&&clearTimeout(o),null==s||s.removeListener("message",l),null==s||s.removeListener("error",u)};o=setTimeout((()=>{c(),i({error:"Evaluation timeout"})}),3e4),null==s||s.once("message",l),null==s||s.once("error",u),null==s||s.postMessage({type:"eval",expression:e,data:"string"==typeof t?t:JSON.stringify(t),options:n,lastResult:r})}))}catch(e){return{error:e instanceof Error?e.message:String(e)}}},dispose:async()=>{s&&await s.terminate()}}}}function createTerminalIO(e){return readline3.emitKeypressEvents(e),e.isTTY&&e.setRawMode&&e.setRawMode(!0),{input:e,output:{write:e=>process.stdout.write(e),clearLine:e=>readline3.clearLine(process.stdout,e),cursorTo:e=>readline3.cursorTo(process.stdout,e)}}}async function createAndStartRepl(e,t,n,r,s){const{evaluator:i,dispose:a}=await createReplEvaluationHandler(t,s);let o;if(t.readline)o=new ReplManager(e,t,i,{prompt:(null==r?void 0:r.prompt)||"> ",realTimeEvaluation:"true"!==process.env.JSQ_DISABLE_REALTIME_EVAL,io:createTerminalIO(n)});else{const{PromptsReplManager:t}=await Promise.resolve().then((()=>(init_prompts_repl_manager(),prompts_repl_manager_exports)));o=new t({evaluator:{evaluate:async(e,t,n)=>{const r=await i(e,t,{},n);return{value:r.result,error:r.error}}},historyFile:".jsq_history",initialData:e,inputStream:n,realTimeEvaluation:"true"!==process.env.JSQ_DISABLE_REALTIME_EVAL})}const l=async()=>{o.stop(),await a()};return process.on("SIGINT",l),process.on("SIGTERM",l),o.start(),o}init_quickjs_gc_workaround();import{createReadStream as createReadStream2,promises as fs3,constants as fsConstants}from"node:fs";import{createReadStream,promises as fs2}from"node:fs";import{Readable}from"node:stream";import*as toml from"@iarna/toml";import{parse as csvParse}from"csv-parse";import*as yaml from"js-yaml";async function parseCSVToJSON(e,t={}){const{delimiter:n=",",headers:r=!0}=t;return new Promise(((t,s)=>{const i=[],a=createReadStream(e),o=csvParse({delimiter:n,columns:r,skip_empty_lines:!0,trim:!0});a.pipe(o).on("data",(e=>{i.push(e)})).on("error",(e=>{s(new Error(`CSV parsing error: ${e.message}`))})).on("end",(()=>{t(i)}))}))}function createCSVStream(e,t={}){const{delimiter:n=",",headers:r=!0}=t,s=createReadStream(e),i=csvParse({delimiter:n,columns:r,skip_empty_lines:!0,trim:!0});return s.pipe(i)}async function parseTSVToJSON(e,t={}){return parseCSVToJSON(e,{delimiter:"\t",...t})}function createTSVStream(e,t={}){return createCSVStream(e,{delimiter:"\t",...t})}async function parseParquetToJSON(e){try{const t=await import("parquetjs-lite"),n=await t.ParquetReader.openFile(e),r=[],s=n.getCursor();let i=await s.next();for(;i;)r.push(i),i=await s.next();return await n.close(),r}catch(e){throw new Error(`Parquet parsing error: ${e instanceof Error?e.message:"Unknown error"}. Make sure the file is a valid Parquet file.`)}}async function createParquetStream(e){try{const t=await parseParquetToJSON(e),n=new Readable({objectMode:!0});let r=0;return n._read=()=>{r<t.length?n.push(t[r++]):n.push(null)},n}catch(e){throw new Error(`Failed to create Parquet stream: ${e instanceof Error?e.message:"Unknown error"}`)}}function detectFormatFromExtension(e){var t;switch(null==(t=e.split(".").pop())?void 0:t.toLowerCase()){case"json":return"json";case"jsonl":case"ndjson":return"jsonl";case"csv":return"csv";case"tsv":return"tsv";case"parquet":return"parquet";case"yaml":case"yml":return"yaml";case"toml":return"toml";default:return null}}async function parseFile(e,t,n={}){switch(t){case"json":{const t=await fs2.readFile(e,"utf8");return JSON.parse(t)}case"jsonl":return(await fs2.readFile(e,"utf8")).trim().split("\n").filter((e=>e.trim())).map((e=>JSON.parse(e)));case"csv":return parseCSVToJSON(e,n);case"tsv":return parseTSVToJSON(e,n);case"parquet":return parseParquetToJSON(e);case"yaml":case"yml":return parseYAMLToJSON(e);case"toml":return parseTOMLToJSON(e);default:throw new Error(`Unsupported format: ${t}`)}}async function parseYAMLToJSON(e){try{const t=await fs2.readFile(e,"utf8");return yaml.load(t)}catch(e){throw new Error(`YAML parsing error: ${e instanceof Error?e.message:"Unknown error"}`)}}async function parseTOMLToJSON(e){try{const t=await fs2.readFile(e,"utf8");return toml.parse(t)}catch(e){throw new Error(`TOML parsing error: ${e instanceof Error?e.message:"Unknown error"}`)}}function createFileStream(e){return createReadStream2(e,{encoding:"utf8"})}async function readFileContent(e){try{return await fs3.readFile(e,"utf8")}catch(t){throw new Error(`Failed to read file ${e}: ${t instanceof Error?t.message:"Unknown error"}`)}}async function detectFileFormat(e,t="auto"){if("auto"!==t)return t;const n=detectFormatFromExtension(e);return n||await detectFormatFromContent(e)}async function detectFormatFromContent(e){try{const t=createReadStream2(e,{encoding:"utf8"});let n="",r=0;return new Promise((e=>{t.on("data",(s=>{n+=s.toString();const i=analyzeContentLines(n.split("\n"),r);if(i.format)return t.destroy(),void e(i.format);r=i.linesChecked})),t.on("end",(()=>{e("json")})),t.on("error",(()=>{e("json")}))}))}catch{return"json"}}function analyzeContentLines(e,t){var n;let r=t;for(let s=t;s<Math.min(e.length,3);s++){const t=null==(n=e[s])?void 0:n.trim();if(t){r++;const e=detectLineFormat(t,r);if(e)return{format:e,linesChecked:r}}}return{linesChecked:r}}function detectLineFormat(e,t){try{if(JSON.parse(e),t>=2)return"jsonl"}catch{return e.includes(",")?"csv":e.includes("\t")?"tsv":"json"}return null}async function readFileByFormat(e,t){switch(t){case"json":case"jsonl":return readFileContent(e);case"csv":case"tsv":case"parquet":case"yaml":case"yml":case"toml":return await parseFile(e,t);default:throw new Error(`Unsupported file format: ${t}`)}}async function createFormatStream(e,t){switch(t){case"json":case"jsonl":case"yaml":case"yml":case"toml":return createFileStream(e);case"csv":return createCSVStream(e);case"tsv":return createTSVStream(e);case"parquet":return createParquetStream(e);default:throw new Error(`Unsupported file format for streaming: ${t}`)}}async function validateFile(e){try{await fs3.access(e,fsConstants.R_OK)}catch(t){throw new Error(`File not accessible: ${e}. ${t instanceof Error?t.message:"Unknown error"}`)}}import{stdin}from"node:process";var readStdin=async()=>new Promise(((e,t)=>{let n="",r=!1;const s=setTimeout((()=>{r||e("null")}),100);stdin.setEncoding("utf8"),stdin.on("data",(e=>{r=!0,clearTimeout(s),n+=e})),stdin.on("end",(()=>{r&&e(n.trim())})),stdin.on("error",(e=>{clearTimeout(s),t(new Error(`Failed to read from stdin: ${e.message}`))}))})),getStdinStream=()=>stdin;init_output_formatter(),init_runtime();var __filename=fileURLToPath3(import.meta.url),__dirname2=dirname3(__filename),packageJsonPath=join4(__dirname2,"..","package.json"),packageJson=JSON.parse(readFileSync(packageJsonPath,"utf8")),VERSION=packageJson.version;setupProcessExitHandlers();var program=new Command;function logRuntimeInfo(e){if(e.verbose){const e=detectRuntime();console.error(`🚀 Running on ${e} runtime`)}}program.name("jsq").description("A jQuery-like JSON query tool for the command line").version(VERSION,"-V, --version","output the version number");var commonOptions=[["-v, --verbose","Verbose output"],["-s, --stream","Enable streaming mode for large datasets"],["-b, --batch <size>","Process in batches of specified size (implies --stream)"],["-p, --parallel [workers]","Enable parallel processing (optionally specify number of workers)"],["-f, --file <path>","Read input from file instead of stdin"],["--file-format <format>","Specify input file format (json, jsonl, csv, tsv, parquet, yaml, yml, toml, auto)","auto"],["--unsafe","Run in unsafe mode without VM isolation (dangerous!)"],["--memory-limit <mb>","Memory limit in MB (default: 128)"],["--cpu-limit <ms>","CPU time limit in milliseconds (default: 30000)"],["-w, --watch","Watch input file for changes and re-execute expression"],["--oneline","Output JSON in a single line (no pretty-printing)"],["--no-color","Disable colored output"],["--indent <spaces>","Number of spaces for indentation (default: 2)"],["--compact","Compact output (no spaces after separators)"],["--repl-file-mode","Use file-based communication for REPL (experimental)"],["--readline","Use traditional readline-based REPL (legacy mode)"]];function addCommonOptions(e){return commonOptions.forEach((([t,n,r])=>{r?e.option(t,n,r):e.option(t,n)})),e}var mainCommand=program.argument("[expression]","JavaScript expression to evaluate");addCommonOptions(mainCommand).action((async(e,t)=>{try{if(!e){if(process.stdin.isTTY&&!process.env.JSQ_NO_STDIN)return void await handleReplMode(t);{const e=process.env.JSQ_STDIN_DATA||await readStdin();if("null"!==e)return t.stdinData=e,void await handleReplModeWithSubprocess(t);throw new Error("No expression provided")}}prepareOptions(t),logRuntimeInfo(t),t.watch&&!t.file&&(console.error("Error: --watch requires --file option to specify the file to watch"),process.exit(1)),await processExpression(e,t)}catch(e){handleError(e,t)}}));var YELLOW="[33m",RESET="[0m";async function loadInitialData(e){if(e.file){const t=await detectFileFormat(e.file,e.fileFormat),n=await readFileByFormat(e.file,t);if("string"==typeof n&&"json"===t)try{return JSON.parse(n)}catch{return n}return n}if(e.stdinData)try{return JSON.parse(e.stdinData)}catch{return e.stdinData}return{}}async function handleReplMode(e){const t=await loadInitialData(e);e.verbose&&console.error("[DEBUG] Loaded initial data:",JSON.stringify(t).substring(0,100));const{getInteractiveInputStream:n}=await Promise.resolve().then((()=>(init_tty_helper(),tty_helper_exports))),r=await n(e.stdinData,e.verbose);e.verbose&&(console.error(`[DEBUG] Input stream isTTY: ${r.isTTY}`),console.error(`[DEBUG] Input stream is process.stdin: ${r===process.stdin}`)),r===process.stdin&&!process.stdin.isTTY&&e.stdinData&&(e.verbose&&console.error("[DEBUG] Non-TTY mode with piped data, stdin may be at EOF"),process.stdin.resume());const s=await createAndStartRepl(t,e,r,{yellow:YELLOW,reset:RESET});process.on("SIGINT",(async()=>{e.verbose&&console.error("[DEBUG] SIGINT received, cleaning up..."),process.stdout.write("\n"),s.stop(),process.exit(0)})),await new Promise((e=>{const t=setInterval((()=>{s&&!0!==s.shouldExit||(clearInterval(t),e())}),100)})),process.exit(0)}async function handleReplModeWithSubprocess(e){if("bun"===detectRuntime()&&!process.stdin.isTTY&&e.stdinData){const{spawn:t}=await import("node:child_process");e.verbose?(console.error("[Bun] Pipe input detected. Starting REPL with Node.js for TTY support"),console.error("[Bun] This is a known limitation when using pipes in Bun")):console.error("💡 Starting REPL with Node.js for better pipe compatibility...");const n=t("node",["dist/index.js"],{stdio:"inherit",env:{...process.env,JSQ_STDIN_DATA:e.stdinData,JSQ_REPL_MODE:"1"}});await new Promise(((e,t)=>{n.on("exit",(n=>{0===n?e():t(new Error(`REPL exited with code ${n}`))})),n.on("error",t)}))}else await handleReplMode(e)}function prepareOptions(e){if(e.batch){const t="string"==typeof e.batch?parseInt(e.batch,10):e.batch;(Number.isNaN(t)||t<=0)&&(console.error("Error: Batch size must be a positive number"),process.exit(1)),e.batch=t,e.stream=!0}if(e.memoryLimit){const t="string"==typeof e.memoryLimit?parseInt(e.memoryLimit,10):e.memoryLimit;(Number.isNaN(t)||t<=0)&&(console.error("Error: Memory limit must be a positive number (in MB)"),process.exit(1)),e.memoryLimit=t}if(e.cpuLimit){const t="string"==typeof e.cpuLimit?parseInt(e.cpuLimit,10):e.cpuLimit;(Number.isNaN(t)||t<=0)&&(console.error("Error: CPU limit must be a positive number (in milliseconds)"),process.exit(1)),e.cpuLimit=t}}async function processExpression(e,t){t.watch&&t.file?await watchAndProcess(e,t):await processOnce(e,t)}async function processOnce(e,t){const{inputSource:n,detectedFormat:r}=await determineInputSource(t),s=new JsqProcessor(t);try{shouldUseStreaming(t,r)?await handleStreamingMode(e,t,n,r,s):await handleNonStreamingMode(e,t,n,r,s)}finally{await s.dispose(),await new Promise((e=>setImmediate(e)))}}async function watchAndProcess(e,t){const{watch:n}=await import("node:fs");if(!t.file)throw new Error("File path is required for watch mode");const r=t.file;let s=!1;const i=()=>{process.stdout.write("[2J[0f")},a=async()=>{if(!s){s=!0,i(),console.log(`⏱️  Watching: ${r}`),console.log(`📝 Expression: ${e}`),console.log("─".repeat(process.stdout.columns||80)),console.log();try{await processOnce(e,t),console.log(`\n${"─".repeat(process.stdout.columns||80)}`),console.log("Press Ctrl+C to exit watch mode")}catch(e){console.error("\n❌ Error occurred:"),e instanceof Error&&console.error(e.message)}s=!1}};await a();let o=null;const l=n(r,(async e=>{"change"===e&&(o&&clearTimeout(o),o=setTimeout((async()=>{await a()}),100))}));process.on("SIGINT",(()=>{i(),console.log("👋 Exiting watch mode..."),l.close(),process.exit(0)})),process.stdin.resume()}async function determineInputSource(e){if(e.file){await validateFile(e.file);const t=await detectFileFormat(e.file,e.fileFormat);return e.verbose&&(console.error(`📁 Reading from file: ${e.file}`),console.error(`📋 Detected format: ${t}`)),{inputSource:"file",detectedFormat:t}}return!0===process.stdin.isTTY||"true"===process.env.JSQ_NO_STDIN?{inputSource:"none",detectedFormat:"json"}:{inputSource:"stdin",detectedFormat:"json"}}function shouldUseStreaming(e,t){return!!e.stream||!!e.batch||["jsonl","csv","tsv","parquet"].includes(t)}async function handleStreamingMode(e,t,n,r,s){t.verbose&&(t.batch?console.error(`🚀 Starting batch processing mode (batch size: ${t.batch})`):console.error("🚀 Starting streaming mode"));const i=await getInputStream(n,t.file,r),a=createStreamOptions(t,r);if(t.parallel){const t=s.createParallelTransformStream(e,a);i.pipe(t).pipe(process.stdout)}else if(t.batch&&"number"==typeof t.batch){const t=s.createBatchTransformStream(e,a);i.pipe(t).pipe(process.stdout)}else{const t=createTransformStream(s,e,r,a);i.pipe(t).pipe(process.stdout)}await waitForStreamCompletion()}async function getInputStream(e,t,n){if("file"===e&&t)return await createFormatStream(t,n);if("none"===e){const{Readable:e}=await import("node:stream");return e.from(["null"])}return getStdinStream()}function createStreamOptions(e,t){const n={jsonLines:e.stream||!!e.batch||!!e.parallel||["jsonl","csv","tsv","parquet"].includes(t)};if("number"==typeof e.batch)n.batchSize=e.batch;else if(e.parallel){const t=cpus3().length,r="number"==typeof e.parallel?e.parallel:t;n.batchSize=Math.min(500,Math.max(100,Math.floor(1e3/r))),e.verbose&&console.error(`📦 Auto-selected batch size: ${n.batchSize} (${r} workers)`)}return e.parallel&&("string"==typeof e.parallel?n.parallel=!0:(e.parallel,n.parallel=e.parallel)),n}function createTransformStream(e,t,n,r){return["csv","tsv","parquet"].includes(n)?e.createObjectTransformStream(t,r):e.createTransformStream(t,r)}async function waitForStreamCompletion(){return new Promise(((e,t)=>{process.stdout.on("finish",e),process.stdout.on("error",t)}))}async function handleNonStreamingMode(e,t,n,r,s){const i=await getInputData(n,t.file,r,t);isStructuredFormat(r)?await processStructuredData(e,i,s,t,r):await processRegularData(e,i,s,t)}async function getInputData(e,t,n,r){return"file"===e&&t?await readFileByFormat(t,n):"none"===e?"null":(null==r?void 0:r.stdinData)?r.stdinData:await readStdin()}function isStructuredFormat(e){return["csv","tsv","parquet","yaml","yml","toml"].includes(e)}async function processStructuredData(e,t,n,r,s){const i=["yaml","yml","toml"].includes(s||"")?t:{data:t},a=await n.process(e,JSON.stringify(i));console.log(OutputFormatter.format(a.data,r)),r.verbose&&a.metadata&&(console.error(`Processing time: ${a.metadata.processingTime}ms`),console.error(`Input records: ${Array.isArray(t)?t.length:"unknown"}`),console.error(`Output size: ${a.metadata.outputSize} bytes`))}async function processRegularData(e,t,n,r){const s=await n.process(e,t);console.log(OutputFormatter.format(s.data,r)),r.verbose&&s.metadata&&(console.error(`Processing time: ${s.metadata.processingTime}ms`),console.error(`Input size: ${s.metadata.inputSize} bytes`),console.error(`Output size: ${s.metadata.outputSize} bytes`),s.metadata.steps&&console.error(`Steps: ${s.metadata.steps.join(" → ")}`))}function handleError(e,t){const n=e instanceof Error?e.message:"Unknown error occurred";n.includes("[")?console.error(n):console.error("Error:",n),process.exit(1)}process.on("exit",(()=>{})),process.on("uncaughtException",(e=>{console.error("Uncaught exception:",e),process.exit(1)})),process.on("unhandledRejection",((e,t)=>{console.error("Unhandled Rejection at:",t,"reason:",e),process.exit(1)})),program.parse();
//# sourceMappingURL=/sm/d82d0dd859e1884f0dea1d977d1faabdfdac0e1ac7fc234269e35256ef7b6337.map