coze-coding-dev-sdk 0.7.19-beta.6 → 0.7.19-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/esm/131.mjs CHANGED
@@ -1,4 +1,4 @@
1
- let e,i,n,t,a,r,o,u,s,l,h,g,c,d;import*as p from"buffer";import*as f from"child_process";import*as m from"crypto";import*as y from"events";import*as S from"fs";import*as b from"node:fs";import*as C from"node:fs/promises";import*as T from"node:stream";import*as w from"os";import*as x from"path";import*as E from"stream";import*as L from"zlib";import{__webpack_require__ as _}from"./rslib-runtime.mjs";import Y from"axios";import{ChatOpenAI as D}from"@langchain/openai";import{AIMessage as v,HumanMessage as A,SystemMessage as N}from"@langchain/core/messages";import P from"pg";import{env as Z,versions as R}from"process";import{Agent as M,request as J}from"http";import{Agent as k,request as B}from"https";_.add({"./node_modules/dotenv/lib/main.js"(e,i,n){let t=n("fs"),a=n("path"),r=n("os"),o=n("crypto"),u=n("./node_modules/dotenv/package.json").version,s=["\uD83D\uDD10 encrypt with Dotenvx: https://dotenvx.com","\uD83D\uDD10 prevent committing .env to code: https://dotenvx.com/precommit","\uD83D\uDD10 prevent building .env in docker: https://dotenvx.com/prebuild","\uD83D\uDCE1 add observability to secrets: https://dotenvx.com/ops","\uD83D\uDC65 sync secrets across teammates & machines: https://dotenvx.com/ops","\uD83D\uDDC2️ backup and recover secrets: https://dotenvx.com/ops","✅ audit secrets and track compliance: https://dotenvx.com/ops","\uD83D\uDD04 add secrets lifecycle management: https://dotenvx.com/ops","\uD83D\uDD11 add access controls to secrets: https://dotenvx.com/ops","\uD83D\uDEE0️ run anywhere with `dotenvx run -- yourcommand`","⚙️ specify custom .env file path with { path: '/custom/path/.env' }","⚙️ enable debug logging with { debug: true }","⚙️ override existing env vars with { override: true }","⚙️ suppress all logs with { quiet: true }","⚙️ write to custom object with { processEnv: myObject }","⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"];function _getRandomTip(){return s[Math.floor(Math.random()*s.length)]}function parseBoolean(e){return"string"==typeof e?!["false","0","no","off",""].includes(e.toLowerCase()):!!e}function supportsAnsi(){return process.stdout.isTTY}function dim(e){return supportsAnsi()?`\x1b[2m${e}\x1b[0m`:e}let l=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function _warn(e){console.error(`[dotenv@${u}][WARN] ${e}`)}function _debug(e){console.log(`[dotenv@${u}][DEBUG] ${e}`)}function _log(e){console.log(`[dotenv@${u}] ${e}`)}function _dotenvKey(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function _instructions(e,i){let n;try{n=new URL(i)}catch(e){if("ERR_INVALID_URL"===e.code){let e=Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw e.code="INVALID_DOTENV_KEY",e}throw e}let t=n.password;if(!t){let e=Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}let a=n.searchParams.get("environment");if(!a){let e=Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}let r=`DOTENV_VAULT_${a.toUpperCase()}`,o=e.parsed[r];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${r} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:o,key:t}}function _vaultPath(e){let i=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let n of e.path)t.existsSync(n)&&(i=n.endsWith(".vault")?n:`${n}.vault`);else i=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else i=a.resolve(process.cwd(),".env.vault");return t.existsSync(i)?i:null}function _resolveHome(e){return"~"===e[0]?a.join(r.homedir(),e.slice(1)):e}let h={configDotenv:function(e){let i,n=a.resolve(process.cwd(),".env"),r="utf8",o=process.env;e&&null!=e.processEnv&&(o=e.processEnv);let u=parseBoolean(o.DOTENV_CONFIG_DEBUG||e&&e.debug),s=parseBoolean(o.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?r=e.encoding:u&&_debug("No encoding is specified. UTF-8 is used by default");let l=[n];if(e&&e.path)if(Array.isArray(e.path))for(let i of(l=[],e.path))l.push(_resolveHome(i));else l=[_resolveHome(e.path)];let g={};for(let n of l)try{let i=h.parse(t.readFileSync(n,{encoding:r}));h.populate(g,i,e)}catch(e){u&&_debug(`Failed to load ${n} ${e.message}`),i=e}let c=h.populate(o,g,e);if(u=parseBoolean(o.DOTENV_CONFIG_DEBUG||u),s=parseBoolean(o.DOTENV_CONFIG_QUIET||s),u||!s){let e=Object.keys(c).length,n=[];for(let e of l)try{let i=a.relative(process.cwd(),e);n.push(i)}catch(n){u&&_debug(`Failed to load ${e} ${n.message}`),i=n}_log(`injecting env (${e}) from ${n.join(",")} ${dim(`-- tip: ${_getRandomTip()}`)}`)}return i?{parsed:g,error:i}:{parsed:g}},_configVault:function(e){let i=parseBoolean(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=parseBoolean(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(i||!n)&&_log("Loading env from encrypted .env.vault");let t=h._parseVault(e),a=process.env;return e&&null!=e.processEnv&&(a=e.processEnv),h.populate(a,t,e),{parsed:t}},_parseVault:function(e){let i,n=_vaultPath(e=e||{});e.path=n;let t=h.configDotenv(e);if(!t.parsed){let e=Error(`MISSING_DATA: Cannot parse ${n} for an unknown reason`);throw e.code="MISSING_DATA",e}let a=_dotenvKey(e).split(","),r=a.length;for(let e=0;e<r;e++)try{let n=a[e].trim(),r=_instructions(t,n);i=h.decrypt(r.ciphertext,r.key);break}catch(i){if(e+1>=r)throw i}return h.parse(i)},config:function(e){if(0===_dotenvKey(e).length)return h.configDotenv(e);let i=_vaultPath(e);return i?h._configVault(e):(_warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${i}. Did you forget to build it?`),h.configDotenv(e))},decrypt:function(e,i){let n=Buffer.from(i.slice(-64),"hex"),t=Buffer.from(e,"base64"),a=t.subarray(0,12),r=t.subarray(-16);t=t.subarray(12,-16);try{let e=o.createDecipheriv("aes-256-gcm",n,a);return e.setAuthTag(r),`${e.update(t)}${e.final()}`}catch(t){let e=t instanceof RangeError,i="Invalid key length"===t.message,n="Unsupported state or unable to authenticate data"===t.message;if(e||i){let e=Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(n){let e=Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw e.code="DECRYPTION_FAILED",e}throw t}},parse:function(e){let i,n={},t=e.toString();for(t=t.replace(/\r\n?/mg,"\n");null!=(i=l.exec(t));){let e=i[1],t=i[2]||"",a=(t=t.trim())[0];t=t.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),'"'===a&&(t=(t=t.replace(/\\n/g,"\n")).replace(/\\r/g,"\r")),n[e]=t}return n},populate:function(e,i,n={}){let t=!!(n&&n.debug),a=!!(n&&n.override),r={};if("object"!=typeof i){let e=Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw e.code="OBJECT_REQUIRED",e}for(let n of Object.keys(i))Object.prototype.hasOwnProperty.call(e,n)?(!0===a&&(e[n]=i[n],r[n]=i[n]),t&&(!0===a?_debug(`"${n}" is already defined and WAS overwritten`):_debug(`"${n}" is already defined and was NOT overwritten`))):(e[n]=i[n],r[n]=i[n]);return r}};e.exports.configDotenv=h.configDotenv,e.exports._configVault=h._configVault,e.exports._parseVault=h._parseVault,e.exports.config=h.config,e.exports.decrypt=h.decrypt,e.exports.parse=h.parse,e.exports.populate=h.populate,e.exports=h},"./src/report/buffer.ts"(e,i,n){n.d(i,{R:()=>t});class t{buffer=[];timer=null;projectId;env;client;destroyed=!1;flushing=!1;pendingFlush=!1;onExitHandler;constructor(e){this.client=e,this.projectId=process.env.COZELOOP_WORKSPACE_ID||null,this.env=process.env.COZE_PROJECT_ENV||null,this.timer=setInterval(()=>this.flush(),6e4),this.timer.unref&&this.timer.unref(),this.onExitHandler=()=>{this.destroyAndExit()},process.on("beforeExit",()=>this.destroy()),process.on("SIGTERM",this.onExitHandler),process.on("SIGINT",this.onExitHandler)}add(e){if(!this.destroyed)try{e.project_id=this.projectId,e.env=this.env,this.buffer.push(e),this.buffer.length>=100&&this.flush().catch(()=>{})}catch(e){console.error("[report] buffer.add failed:",e)}}async flush(){if(this.flushing){this.pendingFlush=!0;return}if(!this.buffer.length)return;this.flushing=!0;let e=this.buffer.splice(0,100);try{await this.client.batchReport(e)}catch(i){console.error("[report] flush failed, re-queuing entries:",i),this.buffer=e.concat(this.buffer)}finally{this.flushing=!1,(this.pendingFlush||this.buffer.length>=100)&&(this.pendingFlush=!1,this.flush().catch(()=>{}))}}destroy(){this.destroyed||(this.destroyed=!0,this.timer&&(clearInterval(this.timer),this.timer=null),process.removeListener("SIGTERM",this.onExitHandler),process.removeListener("SIGINT",this.onExitHandler),this.flush().catch(()=>{}))}destroyAndExit(){if(this.destroyed)return;this.destroyed=!0,this.timer&&(clearInterval(this.timer),this.timer=null),process.removeListener("SIGTERM",this.onExitHandler),process.removeListener("SIGINT",this.onExitHandler);let e=setTimeout(()=>process.exit(0),5e3);e.unref&&e.unref(),this.flush().catch(()=>{}).finally(()=>{clearTimeout(e),process.exit(0)})}}},"./src/report/client.ts"(e,i,n){n.d(i,{W:()=>o});var t=n("child_process");let a=!1,r={baseUrl:"",apiKey:""};function loadReportEnv(){if(a)return r;let e=process.env.COZE_INTEGRATION_BASE_URL||"",i=process.env.COZE_WORKLOAD_IDENTITY_API_KEY||"";if(e&&i)return a=!0,r={baseUrl:e,apiKey:i};try{if(n("./node_modules/dotenv/lib/main.js").config(),e=process.env.COZE_INTEGRATION_BASE_URL||"",i=process.env.COZE_WORKLOAD_IDENTITY_API_KEY||"",e&&i)return a=!0,r={baseUrl:e,apiKey:i}}catch{}try{let n=`
1
+ let e,i,n,t,a,r,o,u,s,l,h,g,c,d;import*as p from"buffer";import*as f from"child_process";import*as m from"crypto";import*as y from"events";import*as S from"fs";import*as b from"node:fs";import*as C from"node:fs/promises";import*as T from"node:stream";import*as w from"os";import*as x from"path";import*as E from"stream";import*as L from"zlib";import{__webpack_require__ as _}from"./rslib-runtime.mjs";import Y from"axios";import{ChatOpenAI as D}from"@langchain/openai";import{AIMessage as v,HumanMessage as A,SystemMessage as N}from"@langchain/core/messages";import P from"pg";import{env as Z,versions as R}from"process";import{Agent as M,request as J}from"http";import{Agent as k,request as B}from"https";_.add({"./node_modules/dotenv/lib/main.js"(e,i,n){let t=n("fs"),a=n("path"),r=n("os"),o=n("crypto"),u=n("./node_modules/dotenv/package.json").version,s=["\uD83D\uDD10 encrypt with Dotenvx: https://dotenvx.com","\uD83D\uDD10 prevent committing .env to code: https://dotenvx.com/precommit","\uD83D\uDD10 prevent building .env in docker: https://dotenvx.com/prebuild","\uD83D\uDCE1 add observability to secrets: https://dotenvx.com/ops","\uD83D\uDC65 sync secrets across teammates & machines: https://dotenvx.com/ops","\uD83D\uDDC2️ backup and recover secrets: https://dotenvx.com/ops","✅ audit secrets and track compliance: https://dotenvx.com/ops","\uD83D\uDD04 add secrets lifecycle management: https://dotenvx.com/ops","\uD83D\uDD11 add access controls to secrets: https://dotenvx.com/ops","\uD83D\uDEE0️ run anywhere with `dotenvx run -- yourcommand`","⚙️ specify custom .env file path with { path: '/custom/path/.env' }","⚙️ enable debug logging with { debug: true }","⚙️ override existing env vars with { override: true }","⚙️ suppress all logs with { quiet: true }","⚙️ write to custom object with { processEnv: myObject }","⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"];function _getRandomTip(){return s[Math.floor(Math.random()*s.length)]}function parseBoolean(e){return"string"==typeof e?!["false","0","no","off",""].includes(e.toLowerCase()):!!e}function supportsAnsi(){return process.stdout.isTTY}function dim(e){return supportsAnsi()?`\x1b[2m${e}\x1b[0m`:e}let l=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function _warn(e){console.error(`[dotenv@${u}][WARN] ${e}`)}function _debug(e){console.log(`[dotenv@${u}][DEBUG] ${e}`)}function _log(e){console.log(`[dotenv@${u}] ${e}`)}function _dotenvKey(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function _instructions(e,i){let n;try{n=new URL(i)}catch(e){if("ERR_INVALID_URL"===e.code){let e=Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw e.code="INVALID_DOTENV_KEY",e}throw e}let t=n.password;if(!t){let e=Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}let a=n.searchParams.get("environment");if(!a){let e=Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}let r=`DOTENV_VAULT_${a.toUpperCase()}`,o=e.parsed[r];if(!o){let e=Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${r} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:o,key:t}}function _vaultPath(e){let i=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(let n of e.path)t.existsSync(n)&&(i=n.endsWith(".vault")?n:`${n}.vault`);else i=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else i=a.resolve(process.cwd(),".env.vault");return t.existsSync(i)?i:null}function _resolveHome(e){return"~"===e[0]?a.join(r.homedir(),e.slice(1)):e}let h={configDotenv:function(e){let i,n=a.resolve(process.cwd(),".env"),r="utf8",o=process.env;e&&null!=e.processEnv&&(o=e.processEnv);let u=parseBoolean(o.DOTENV_CONFIG_DEBUG||e&&e.debug),s=parseBoolean(o.DOTENV_CONFIG_QUIET||e&&e.quiet);e&&e.encoding?r=e.encoding:u&&_debug("No encoding is specified. UTF-8 is used by default");let l=[n];if(e&&e.path)if(Array.isArray(e.path))for(let i of(l=[],e.path))l.push(_resolveHome(i));else l=[_resolveHome(e.path)];let g={};for(let n of l)try{let i=h.parse(t.readFileSync(n,{encoding:r}));h.populate(g,i,e)}catch(e){u&&_debug(`Failed to load ${n} ${e.message}`),i=e}let c=h.populate(o,g,e);if(u=parseBoolean(o.DOTENV_CONFIG_DEBUG||u),s=parseBoolean(o.DOTENV_CONFIG_QUIET||s),u||!s){let e=Object.keys(c).length,n=[];for(let e of l)try{let i=a.relative(process.cwd(),e);n.push(i)}catch(n){u&&_debug(`Failed to load ${e} ${n.message}`),i=n}_log(`injecting env (${e}) from ${n.join(",")} ${dim(`-- tip: ${_getRandomTip()}`)}`)}return i?{parsed:g,error:i}:{parsed:g}},_configVault:function(e){let i=parseBoolean(process.env.DOTENV_CONFIG_DEBUG||e&&e.debug),n=parseBoolean(process.env.DOTENV_CONFIG_QUIET||e&&e.quiet);(i||!n)&&_log("Loading env from encrypted .env.vault");let t=h._parseVault(e),a=process.env;return e&&null!=e.processEnv&&(a=e.processEnv),h.populate(a,t,e),{parsed:t}},_parseVault:function(e){let i,n=_vaultPath(e=e||{});e.path=n;let t=h.configDotenv(e);if(!t.parsed){let e=Error(`MISSING_DATA: Cannot parse ${n} for an unknown reason`);throw e.code="MISSING_DATA",e}let a=_dotenvKey(e).split(","),r=a.length;for(let e=0;e<r;e++)try{let n=a[e].trim(),r=_instructions(t,n);i=h.decrypt(r.ciphertext,r.key);break}catch(i){if(e+1>=r)throw i}return h.parse(i)},config:function(e){if(0===_dotenvKey(e).length)return h.configDotenv(e);let i=_vaultPath(e);return i?h._configVault(e):(_warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${i}. Did you forget to build it?`),h.configDotenv(e))},decrypt:function(e,i){let n=Buffer.from(i.slice(-64),"hex"),t=Buffer.from(e,"base64"),a=t.subarray(0,12),r=t.subarray(-16);t=t.subarray(12,-16);try{let e=o.createDecipheriv("aes-256-gcm",n,a);return e.setAuthTag(r),`${e.update(t)}${e.final()}`}catch(t){let e=t instanceof RangeError,i="Invalid key length"===t.message,n="Unsupported state or unable to authenticate data"===t.message;if(e||i){let e=Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(n){let e=Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw e.code="DECRYPTION_FAILED",e}throw t}},parse:function(e){let i,n={},t=e.toString();for(t=t.replace(/\r\n?/mg,"\n");null!=(i=l.exec(t));){let e=i[1],t=i[2]||"",a=(t=t.trim())[0];t=t.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),'"'===a&&(t=(t=t.replace(/\\n/g,"\n")).replace(/\\r/g,"\r")),n[e]=t}return n},populate:function(e,i,n={}){let t=!!(n&&n.debug),a=!!(n&&n.override),r={};if("object"!=typeof i){let e=Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw e.code="OBJECT_REQUIRED",e}for(let n of Object.keys(i))Object.prototype.hasOwnProperty.call(e,n)?(!0===a&&(e[n]=i[n],r[n]=i[n]),t&&(!0===a?_debug(`"${n}" is already defined and WAS overwritten`):_debug(`"${n}" is already defined and was NOT overwritten`))):(e[n]=i[n],r[n]=i[n]);return r}};e.exports.configDotenv=h.configDotenv,e.exports._configVault=h._configVault,e.exports._parseVault=h._parseVault,e.exports.config=h.config,e.exports.decrypt=h.decrypt,e.exports.parse=h.parse,e.exports.populate=h.populate,e.exports=h},"./src/report/buffer.ts"(e,i,n){n.d(i,{R:()=>t});class t{buffer=[];timer=null;projectId;env;client;destroyed=!1;flushing=!1;pendingFlush=!1;onExitHandler;constructor(e){this.client=e,this.projectId=process.env.COZELOOP_WORKSPACE_ID||null,this.env=process.env.COZE_PROJECT_ENV||null,this.timer=setInterval(()=>this.flush(),6e4),this.timer.unref&&this.timer.unref(),this.onExitHandler=()=>{this.destroyAndExit()},process.on("beforeExit",()=>this.destroy()),process.on("SIGTERM",this.onExitHandler),process.on("SIGINT",this.onExitHandler)}add(e){if(!this.destroyed)try{this.buffer.length>=6e4&&this.buffer.shift(),e.project_id=this.projectId,e.env=this.env,this.buffer.push(e),this.buffer.length>=100&&this.flush().catch(()=>{})}catch(e){console.error("[report] buffer.add failed:",e)}}async flush(){if(this.flushing){this.pendingFlush=!0;return}if(!this.buffer.length)return;this.flushing=!0;let e=this.buffer.splice(0,100);try{await this.client.batchReport(e)}catch(i){console.error("[report] flush failed, re-queuing entries:",i),this.buffer=e.concat(this.buffer)}finally{this.flushing=!1,(this.pendingFlush||this.buffer.length>=100)&&(this.pendingFlush=!1,this.flush().catch(()=>{}))}}destroy(){this.destroyed||(this.destroyed=!0,this.timer&&(clearInterval(this.timer),this.timer=null),process.removeListener("SIGTERM",this.onExitHandler),process.removeListener("SIGINT",this.onExitHandler),this.flush().catch(()=>{}))}destroyAndExit(){if(this.destroyed)return;this.destroyed=!0,this.timer&&(clearInterval(this.timer),this.timer=null),process.removeListener("SIGTERM",this.onExitHandler),process.removeListener("SIGINT",this.onExitHandler);let e=setTimeout(()=>process.exit(0),5e3);e.unref&&e.unref(),this.flush().catch(()=>{}).finally(()=>{clearTimeout(e),process.exit(0)})}}},"./src/report/client.ts"(e,i,n){n.d(i,{W:()=>o});var t=n("child_process");let a=!1,r={baseUrl:"",apiKey:""};function loadReportEnv(){if(a)return r;let e=process.env.COZE_INTEGRATION_BASE_URL||"",i=process.env.COZE_WORKLOAD_IDENTITY_API_KEY||"";if(e&&i)return a=!0,r={baseUrl:e,apiKey:i};try{if(n("./node_modules/dotenv/lib/main.js").config(),e=process.env.COZE_INTEGRATION_BASE_URL||"",i=process.env.COZE_WORKLOAD_IDENTITY_API_KEY||"",e&&i)return a=!0,r={baseUrl:e,apiKey:i}}catch{}try{let n=`
2
2
  import sys
3
3
  try:
4
4
  from coze_workload_identity import Client
@@ -10,7 +10,7 @@ try:
10
10
  print(f"{env_var.key}={env_var.value}")
11
11
  except Exception as e:
12
12
  print(f"# Error: {e}", file=sys.stderr)
13
- `;for(let a of(0,t.execSync)(`python3 -c '${n.replace(/'/g,"'\"'\"'")}'`,{encoding:"utf-8",timeout:1e4,stdio:["pipe","pipe","pipe"]}).trim().split("\n")){if(a.startsWith("#"))continue;let n=a.indexOf("=");if(n>0){let t=a.substring(0,n),r=a.substring(n+1);(r.startsWith("'")&&r.endsWith("'")||r.startsWith('"')&&r.endsWith('"'))&&(r=r.slice(1,-1)),"COZE_INTEGRATION_BASE_URL"===t?e=r:"COZE_WORKLOAD_IDENTITY_API_KEY"===t&&(i=r)}}}catch{}return a=!0,r={baseUrl:e,apiKey:i}}class o{baseUrl;apiKey;configured;constructor(){try{let e=loadReportEnv();if(this.baseUrl=e.baseUrl,this.apiKey=e.apiKey,this.configured=!!(this.baseUrl&&this.apiKey),!this.configured){let e=[];this.baseUrl||e.push("COZE_INTEGRATION_BASE_URL"),this.apiKey||e.push("COZE_WORKLOAD_IDENTITY_API_KEY"),console.error(`[report] ReportClient not configured: ${e.join(", ")} is missing`)}}catch(e){this.baseUrl="",this.apiKey="",this.configured=!1,console.error("[report] ReportClient config failed:",e)}}async batchReport(e){if(e.length){if(!this.configured)return void console.error(`[report] batchReport skipped: ReportClient is not configured. Set COZE_INTEGRATION_BASE_URL and COZE_WORKLOAD_IDENTITY_API_KEY environment variables. Dropping ${e.length} entries.`);try{let i=`${this.baseUrl}/v1/memory_report/batch_report`;console.log(`[report] batchReport sending ${e.length} entries to ${i}`);let n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json","x-coze-token":this.apiKey},body:JSON.stringify({entries:e}),signal:ma.timeout(1e4)});console.log(`[report] batchReport response: ${n.status} ${n.statusText}`)}catch(e){console.error("[report] batchReport failed:",e)}}}}},"./src/report/index.ts"(e,i,n){n.r(i),n.d(i,{ReportBuffer:()=>a.R,ReportClient:()=>t.W,createS3ReportMiddleware:()=>s.L,createWrappedFetch:()=>u.E,getReportBuffer:()=>r.T,redactUrl:()=>o.B,truncate:()=>o.x});var t=n("./src/report/client.ts"),a=n("./src/report/buffer.ts"),r=n("./src/report/singleton.ts"),o=n("./src/report/utils.ts"),u=n("./src/report/interceptors/fetch-wrapper.ts"),s=n("./src/report/interceptors/s3-middleware.ts")},"./src/report/interceptors/fetch-wrapper.ts"(e,i,n){n.d(i,{E:()=>createWrappedFetch});var t=n("./src/report/utils.ts");function createWrappedFetch(e,i="supabase"){return console.log(`[report] createWrappedFetch called, source=${i}`),async(n,t)=>{let a=Date.now();try{let r=await fetch(n,t);return safeRecordLog(e,i,n,t,r,null,a),r}catch(r){throw safeRecordLog(e,i,n,t,null,r,a),r}}}function safeRecordLog(e,i,n,a,r,o,u){try{let s=Date.now()-u,l="string"==typeof n?n:n instanceof URL?n.toString():n.url||"",h=a?.method||(n instanceof Request?n.method:"GET"),g=r?.status??null,c=null;if(a?.body)try{c=(0,t.x)("string"==typeof a.body?a.body:JSON.stringify(a.body))}catch{c=null}let d={source:i,project_id:null,env:null,method:h.toUpperCase(),url:(0,t.B)(l),request_body:c,response_body:null,status_code:g,error:o?.message??null,duration_ms:s,timestamp:new Date(u).toISOString(),success:null!==g&&g>=200&&g<300};if(r){let i=r.clone().body?.getReader();i?i.read().then(({value:n})=>{if(n){let e=new TextDecoder().decode(n.slice(0,2048));d.response_body=(0,t.x)(e)}i.cancel().catch(()=>{}),e.add(d)}).catch(()=>{e.add(d)}):e.add(d)}else e.add(d)}catch(e){console.error("[report] safeRecordLog error:",e)}}},"./src/report/interceptors/s3-middleware.ts"(e,i,n){n.d(i,{L:()=>createS3ReportMiddleware});var t=n("./src/report/utils.ts");function createS3ReportMiddleware(e){return e?{middleware:(i,n)=>async n=>{let t=Date.now(),{request:a}=n;try{let r=await i(n);return safeRecordS3Log(e,a,r,null,t),r}catch(i){throw safeRecordS3Log(e,a,null,i,t),i}},options:{step:"deserialize",name:"reportLogger",override:!0}}:null}function safeRecordS3Log(e,i,n,a,r){try{let o=Date.now()-r,u=i?.method||"UNKNOWN",s=i?.hostname?`${i.protocol||"https:"}//${i.hostname}${i.path||""}`:"",l=n?.response?.statusCode??null,h=null;if(i?.body)try{let e=i.body;"string"==typeof e?h=(0,t.x)(e):Buffer.isBuffer(e)&&(h=(0,t.x)(`[Binary ${e.length} bytes]`))}catch{h=null}let g={source:"s3",project_id:null,env:null,method:u.toUpperCase(),url:(0,t.B)(s),request_body:h,response_body:null,status_code:l,error:a?.message??null,duration_ms:o,timestamp:new Date(r).toISOString(),success:null!==l&&l>=200&&l<300};if(n?.output)try{let{Body:e,...i}=n.output;Object.keys(i).length>0&&(g.response_body=(0,t.x)(JSON.stringify(i)))}catch{}e.add(g)}catch{}}},"./src/report/singleton.ts"(e,i,n){n.d(i,{T:()=>getReportBuffer});var t=n("./src/report/client.ts"),a=n("./src/report/buffer.ts");let r=null;function getReportBuffer(){if(r)return r;try{let e=new t.W;return r=new a.R(e),console.log("[report] singleton buffer created successfully"),r}catch(e){return console.error("[report] failed to create singleton buffer:",e),null}}},"./src/report/utils.ts"(e,i,n){n.d(i,{B:()=>redactUrl,x:()=>truncate});let t=/((?:apikey|api_key|access_key|secret_key|access_token|token|secret|password|authorization|credential|X-Amz-Signature|X-Amz-Credential|X-Amz-Security-Token)=)[^&]*/gi;function truncate(e,i=1024){return null==e?null:e.length<=i?e:e.substring(0,i)+"...[truncated]"}function redactUrl(e){return e.replace(t,"$1***")}},buffer(e){e.exports=p},child_process(e){e.exports=f},crypto(e){e.exports=m},events(e){e.exports=y},fs(e){e.exports=S},"node:fs"(e){e.exports=b},"node:fs/promises"(e){e.exports=C},"node:stream"(e){e.exports=T},os(e){e.exports=w},path(e){e.exports=x},stream(e){e.exports=E},zlib(e){e.exports=L},"./node_modules/dotenv/package.json"(e){e.exports=JSON.parse('{"name":"dotenv","version":"17.2.3","description":"Loads environment variables from .env file","main":"lib/main.js","types":"lib/main.d.ts","exports":{".":{"types":"./lib/main.d.ts","require":"./lib/main.js","default":"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},"scripts":{"dts-check":"tsc --project tests/types/tsconfig.json","lint":"standard","pretest":"npm run lint && npm run dts-check","test":"tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov","prerelease":"npm test","release":"standard-version"},"repository":{"type":"git","url":"git://github.com/motdotla/dotenv.git"},"homepage":"https://github.com/motdotla/dotenv#readme","funding":"https://dotenvx.com","keywords":["dotenv","env",".env","environment","variables","config","settings"],"readmeFilename":"README.md","license":"BSD-2-Clause","devDependencies":{"@types/node":"^18.11.3","decache":"^4.6.2","sinon":"^14.0.1","standard":"^17.0.0","standard-version":"^9.5.0","tap":"^19.2.0","typescript":"^4.8.4"},"engines":{"node":">=12"},"browser":{"fs":false}}')}});var H,F,X,I,O,Q,G,U,q,K,$,z,W,j,V,ee,ei,en,et,ea,er,eo,eu,es,el,eh,eg,ec,ed={};_.r(ed),_.d(ed,{T:()=>ey});var ep={};_.r(ep),_.d(ep,{n:()=>ex,p:()=>eE});var ef={};_.r(ef),_.d(ef,{F:()=>mZ});var em={};_.r(em),_.d(em,{c:()=>ek});class ey{apiKey;baseUrl;modelBaseUrl;retryTimes;retryDelay;timeout;constructor(e){this.apiKey=e?.apiKey||process.env.COZE_WORKLOAD_IDENTITY_API_KEY||"",this.baseUrl=e?.baseUrl||process.env.COZE_INTEGRATION_BASE_URL||"",this.modelBaseUrl=e?.modelBaseUrl||process.env.COZE_INTEGRATION_MODEL_BASE_URL||"",this.retryTimes=e?.retryTimes??3,this.retryDelay=e?.retryDelay??1,this.timeout=e?.timeout??9e5}validate(){if(!this.apiKey)throw Error("API key is required. Set COZE_WORKLOAD_IDENTITY_API_KEY or provide apiKey in config.")}getHeaders(){if(!this.apiKey)throw Error("API key is required. Set COZE_WORKLOAD_IDENTITY_API_KEY or provide apiKey in config.");return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}}class eS extends Error{constructor(e){super(e),this.name="ConfigurationError"}}class eb extends Error{statusCode;response;constructor(e,i,n){super(e),this.name="APIError",this.statusCode=i,this.response=n}}class eC extends Error{originalError;constructor(e,i){super(e),this.originalError=i,this.name="NetworkError"}}class eT extends Error{constructor(e){super(e),this.name="ValidationError"}}class ew{config;axiosInstance;verbose;constructor(e,i,n=!1){this.config=e||new ey,this.verbose=n,this.axiosInstance=Y.create({timeout:this.config.timeout,headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json","X-Client-Sdk":"coze-coding-dev-sdk-typescript/0.3.0",...i}})}async request(e,i,n,t){let a=null;for(let r=0;r<=this.config.retryTimes;r++)try{0===r&&this.verbose&&this.logRequest(e,i,n,t);let a=await this.axiosInstance.request({method:e,url:i,data:n,...t});return 0===r&&this.verbose&&this.logResponse(a),a.data}catch(e){if(a=e,e.response){let i=e.response.status;if(i>=400&&i<500&&429!==i)throw new eb(e.response.data?.message||e.message,i,e.response.data)}r<this.config.retryTimes&&await this.sleep(1e3*this.config.retryDelay*(r+1))}if(a)if(Y.isAxiosError(a)&&a.response)throw new eb(a.response.data?.message||a.message,a.response.status,a.response.data);else throw new eC(a.message);throw new eC("Request failed after retries")}async requestWithResponse(e,i,n,t){let a=null;for(let r=0;r<=this.config.retryTimes;r++)try{0===r&&this.verbose&&this.logRequest(e,i,n,t);let a=await this.axiosInstance.request({method:e,url:i,data:n,...t});return 0===r&&this.verbose&&this.logResponse(a),a}catch(e){if(a=e,e.response){let i=e.response.status;if(i>=400&&i<500&&429!==i)throw new eb(e.response.data?.message||e.message,i,e.response.data)}r<this.config.retryTimes&&await this.sleep(1e3*this.config.retryDelay*(r+1))}if(a)if(Y.isAxiosError(a)&&a.response)throw new eb(a.response.data?.message||a.message,a.response.status,a.response.data);else throw new eC(a.message);throw new eC("Request failed after retries")}sanitizeHeaders(e){let i=["authorization","auth","api-key","apikey","api_key","x-api-key","x-auth-token","token","secret","password","passwd","pwd"],n={};for(let[t,a]of Object.entries(e)){let e=t.toLowerCase();i.some(i=>e.includes(i))?n[t]="***":n[t]=a}return n}logRequest(e,i,n,t){console.log("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log("\uD83D\uDCE4 HTTP Request"),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log(`Method: ${e}`),console.log(`URL: ${i}`);let a={};Object.assign(a,this.axiosInstance.defaults.headers.common||{},this.axiosInstance.defaults.headers[e.toLowerCase()]||{},t?.headers||{});let r=this.sanitizeHeaders(a);for(let[e,i]of(console.log("\nHeaders:"),Object.entries(r)))console.log(` ${e}: ${i}`);n&&(console.log("\nBody:"),console.log(JSON.stringify(n,null,2))),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")}logResponse(e){if(console.log("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log("\uD83D\uDCE5 HTTP Response"),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log(`Status: ${e.status} ${e.statusText}`),e.headers)for(let[i,n]of(console.log("\nHeaders:"),Object.entries(e.headers)))console.log(` ${i}: ${n}`);if(e.data){console.log("\nBody:");let i="string"==typeof e.data?e.data:JSON.stringify(e.data,null,2);console.log(i.length>1e3?i.substring(0,1e3)+"\n... (truncated)":i)}console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")}sleep(e){return new Promise(i=>setTimeout(i,e))}}let ex=["x-tt-logid","x-tt-env","x-use-ppe","x-tt-env-fe","x-run-mode","rpc-persist-res-rec-biz-scene","rpc-persist-coze-record-root-id","rpc-persist-res-rec-root-entity-type","rpc-persist-res-rec-root-entity-id","rpc-persist-res-rec-ext-info"];class eE{static extractForwardHeaders(e){let i={};return e instanceof Headers?ex.forEach(n=>{let t=e.get(n);t&&(i[n]=t)}):ex.forEach(n=>{let t=e[n]||e[n.toLowerCase()];t&&(i[n]=t)}),i}}class eL{static DEFAULT_MODEL="doubao-seedream-5-0-260128";static DEFAULT_SIZE="2K";static DEFAULT_CUSTOM_SIZE="2048x2048";static DEFAULT_WATERMARK=!0;static DEFAULT_RESPONSE_FORMAT="url";static DEFAULT_OPTIMIZE_PROMPT_MODE="standard";static DEFAULT_SEQUENTIAL_IMAGE_GENERATION="disabled";static DEFAULT_SEQUENTIAL_IMAGE_GENERATION_MAX_IMAGES=15;static MIN_TOTAL_PIXELS=3686400;static MAX_TOTAL_PIXELS=0x1000000;static MIN_ASPECT_RATIO=1/16;static MAX_ASPECT_RATIO=16;static PRESET_SIZES=["2K","4K"]}function validateImageSize(e){if(eL.PRESET_SIZES.includes(e))return e;let i=e.match(/^(\d+)x(\d+)$/);if(!i)throw Error(`Invalid size format. Must be ${JSON.stringify(eL.PRESET_SIZES)} or 'WIDTHxHEIGHT' format (e.g., 2048x2048). Got: ${e}`);let n=parseInt(i[1],10),t=parseInt(i[2],10);if(n<=0||t<=0)throw Error(`Width and height must be positive integers. Got: ${e}`);let a=n*t;if(a<eL.MIN_TOTAL_PIXELS||a>eL.MAX_TOTAL_PIXELS)throw Error(`Total pixels must be between ${eL.MIN_TOTAL_PIXELS.toLocaleString()} and ${eL.MAX_TOTAL_PIXELS.toLocaleString()}. Got: ${a.toLocaleString()} (${n}x${t})`);let r=n/t;if(r<eL.MIN_ASPECT_RATIO||r>eL.MAX_ASPECT_RATIO)throw Error(`Aspect ratio must be between 1:16 and 16:1. Got: ${n}:${t} (${r.toFixed(2)})`);return e}function validateImageSizeOrDefault(e){try{return validateImageSize(e)}catch{return eL.DEFAULT_SIZE}}class e_{response;constructor(e){this.response=e}get success(){return!this.response.error&&this.response.data.every(e=>!e.error)}get imageUrls(){return this.response.data.filter(e=>e.url).map(e=>e.url)}get imageB64List(){return this.response.data.filter(e=>e.b64_json).map(e=>e.b64_json)}get errorMessages(){let e=[];for(let i of(this.response.error&&e.push(`API Error: ${this.response.error.message||"Unknown error"}`),this.response.data))i.error&&e.push(`Image generation error: ${i.error.message||"Unknown error"}`);return e}}function buildImageGenerationApiRequest(e,i){let n=validateImageSizeOrDefault(e.size||eL.DEFAULT_SIZE);return{model:i,prompt:e.prompt,size:n,watermark:e.watermark??eL.DEFAULT_WATERMARK,image:e.image,response_format:e.responseFormat||eL.DEFAULT_RESPONSE_FORMAT,optimize_prompt_options:{mode:e.optimizePromptMode||eL.DEFAULT_OPTIMIZE_PROMPT_MODE},sequential_image_generation:e.sequentialImageGeneration||eL.DEFAULT_SEQUENTIAL_IMAGE_GENERATION,sequential_image_generation_options:{max_images:e.sequentialImageGenerationMaxImages||eL.DEFAULT_SEQUENTIAL_IMAGE_GENERATION_MAX_IMAGES}}}class eY extends ew{constructor(e,i,n=!1){super(e,i,n)}async generate(e){let i=e.model||eL.DEFAULT_MODEL,n=buildImageGenerationApiRequest(e,i),t=await this.request("POST",`${this.config.baseUrl}/api/v3/images/generations`,n);if(t.error)throw new eb(`API returned error: ${t.error.message||"Unknown error"}`,t.error.code?parseInt(t.error.code):500,t.error);for(let e of t.data)if(e.error)throw new eb(`Image generation failed: ${e.error.message||"Unknown error"}`,e.error.code?parseInt(e.error.code):500,e.error);return t}async batchGenerate(e){return Promise.all(e.map(e=>this.generate(e)))}getResponseHelper(e){return new e_(e)}}function convertToApiFormat(e){let i={};return e.query&&(i.Query=e.query),e.search_type&&(i.SearchType=e.search_type),void 0!==e.count&&(i.Count=e.count),void 0!==e.need_summary&&(i.NeedSummary=e.need_summary),e.time_range&&(i.TimeRange=e.time_range),e.filter&&(i.Filter={NeedContent:e.filter.need_content||!1,NeedUrl:e.filter.need_url||!1,Sites:e.filter.sites,BlockHosts:e.filter.block_hosts}),i}function convertFromApiFormat(e){let i={};return void 0!==e.Id&&(i.id=e.Id),void 0!==e.SortId&&(i.sort_id=e.SortId),void 0!==e.Title&&(i.title=e.Title),void 0!==e.SiteName&&(i.site_name=e.SiteName),void 0!==e.Url&&(i.url=e.Url),void 0!==e.Snippet&&(i.snippet=e.Snippet),void 0!==e.Summary&&(i.summary=e.Summary),void 0!==e.Content&&(i.content=e.Content),void 0!==e.PublishTime&&(i.publish_time=e.PublishTime),void 0!==e.LogoUrl&&(i.logo_url=e.LogoUrl),void 0!==e.RankScore&&(i.rank_score=e.RankScore),void 0!==e.AuthInfoDes&&(i.auth_info_des=e.AuthInfoDes),void 0!==e.AuthInfoLevel&&(i.auth_info_level=e.AuthInfoLevel),e.Image&&(i.image={url:e.Image.Url,width:e.Image.Width,height:e.Image.Height,shape:e.Image.Shape}),i}class eD extends ew{constructor(e,i,n=!1){super(e,i,n)}async search(e){let i,n=convertToApiFormat(e),t=await this.request("POST",`${this.config.baseUrl}/api/search_api/web_search`,n),a=t.ResponseMetadata||{};if(a.Error)throw new eb(`Search failed: ${a.Error}`,500,a.Error);let r=t.Result||{},o=[];if(r.WebResults)for(let e of r.WebResults)o.push(convertFromApiFormat(e));let u=[];if(r.ImageResults)for(let e of r.ImageResults)u.push(convertFromApiFormat(e));return r.Choices&&r.Choices.length>0&&(i=r.Choices[0].Message?.Content),{web_items:o,image_items:u,summary:i}}async webSearch(e,i=10,n=!0){return this.search({query:e,search_type:"web",count:i,need_summary:n})}async webSearchWithSummary(e,i=10){return this.search({query:e,search_type:"web_summary",count:i,need_summary:!0})}async imageSearch(e,i=10){return this.search({query:e,search_type:"image",count:i,need_summary:!1})}async advancedSearch(e,i={}){let n={need_content:i.needContent,need_url:i.needUrl,sites:i.sites,block_hosts:i.blockHosts};return this.search({query:e,search_type:i.searchType||"web",count:i.count||10,filter:n,need_summary:void 0===i.needSummary||i.needSummary,time_range:i.timeRange})}}class ev{static DEFAULT_SPEAKER="zh_female_xiaohe_uranus_bigtts";static DEFAULT_AUDIO_FORMAT="mp3";static DEFAULT_SAMPLE_RATE=24e3;static DEFAULT_SPEECH_RATE=0;static DEFAULT_LOUDNESS_RATE=0}function buildTTSApiRequest(e){let i={user:{uid:e.uid},req_params:{speaker:e.speaker||ev.DEFAULT_SPEAKER,audio_params:{format:e.audioFormat||ev.DEFAULT_AUDIO_FORMAT,sample_rate:e.sampleRate||ev.DEFAULT_SAMPLE_RATE,speech_rate:e.speechRate??ev.DEFAULT_SPEECH_RATE,loudness_rate:e.loudnessRate??ev.DEFAULT_LOUDNESS_RATE}}};return e.text?i.req_params.text=e.text:e.ssml&&(i.req_params.ssml=e.ssml),i}function buildASRApiRequest(e){let i={};return e.url?i.url=e.url:e.base64Data&&(i.data=e.base64Data),{user:{uid:e.uid},audio:i}}class eA extends ew{constructor(e,i,n=!1){super(e,i,n)}async synthesize(e){if(!e.text&&!e.ssml)throw new eT("必须提供 text 或 ssml 其中之一");let i=buildTTSApiRequest(e),n={...this.config.getHeaders(),Connection:"keep-alive"};try{let e=await Y.post(`${this.config.baseUrl}/api/v3/tts/unidirectional`,i,{headers:n,responseType:"stream",timeout:this.config.timeout});return await this.processStreamResponse(e)}catch(e){if(e.response)throw new eb(`TTS 请求失败: ${e.message}`,e.response.status,e.response.data);throw new eb(`TTS 请求异常: ${e.message}`,500)}}async processStreamResponse(e){return new Promise((i,n)=>{let t="",a=0,r="";e.data.on("data",e=>{let o=(r+=e.toString("utf-8")).split("\n");for(let e of(r=o.pop()||"",o))if(e.trim()&&e.startsWith("data:"))try{let r=e.replace("data:","").trim();if(!r)continue;let o=JSON.parse(r);if(0===o.code&&o.data){let e=Buffer.from(o.data,"base64");a+=e.length}else if(2e7===o.code){o.url&&(t=o.url),i({audioUri:t,audioSize:a});return}else if(o.code>0)return void n(new eb(`合成音频失败: ${o.message||""}`,o.code))}catch(e){n(new eb(`响应解析失败: ${e.message}`,500));return}}),e.data.on("end",()=>{t||0!==a?i({audioUri:t,audioSize:a}):n(new eb("未收到完整的音频数据",500))}),e.data.on("error",e=>{n(new eb(`流处理错误: ${e.message}`,500))})})}}class eN extends ew{constructor(e,i,n=!1){super(e,i,n)}async recognize(e){if(!e.url&&!e.base64Data)throw new eT("必须提供 url 或 base64Data 其中之一");let i=buildASRApiRequest(e);try{let e=await this.requestWithResponse("POST",`${this.config.baseUrl}/api/v3/auc/bigmodel/recognize/flash`,i),n=e.headers["x-api-status-code"]||"0",t=e.headers["x-api-message"]||"";if("20000000"!==n)throw new eb(`ASR 识别失败,状态码: ${n}, 错误信息: ${t}`,e.status,{code:n,message:t});let a=e.data.result||{};return{text:a.text||"",duration:a.duration,utterances:a.utterances,rawData:e.data}}catch(e){if(e instanceof eb)throw e;throw new eb(`ASR 请求异常: ${e.message}`,500)}}}class eP{static DEFAULT_MODEL="doubao-seedance-1-5-pro-251215";static DEFAULT_RESOLUTION="720p";static DEFAULT_RATIO="16:9";static DEFAULT_DURATION=5;static DEFAULT_WATERMARK=!0;static DEFAULT_CAMERA_FIXED=!1;static DEFAULT_GENERATE_AUDIO=!0}class eZ extends ew{baseUrl;constructor(e,i,n=!1){super(e,i,n),this.baseUrl=this.config.baseUrl}async videoGeneration(e,i){let n=(i?.maxWaitTime??900)*1e3,t={model:i?.model||eP.DEFAULT_MODEL,content:e};i?.callbackUrl&&(t.callback_url=i.callbackUrl),i?.returnLastFrame&&(t.return_last_frame=i.returnLastFrame),t.resolution=i?.resolution??eP.DEFAULT_RESOLUTION,t.ratio=i?.ratio??eP.DEFAULT_RATIO,t.duration=i?.duration??eP.DEFAULT_DURATION,t.watermark=i?.watermark??eP.DEFAULT_WATERMARK,i?.seed!==void 0&&(t.seed=i.seed),t.camerafixed=i?.camerafixed??eP.DEFAULT_CAMERA_FIXED,t.generate_audio=i?.generateAudio??eP.DEFAULT_GENERATE_AUDIO;let a=null,r=0;for(;r<3;)try{if(!(a=(await this.request("POST",`${this.baseUrl}/api/v3/contents/generations/tasks`,t)).id))throw new eb("创建视频生成任务失败:响应中缺少任务ID",500);this.verbose&&console.log(`视频生成任务创建成功,任务ID: ${a}`);break}catch(i){r++;let e=i instanceof Error?i.message:String(i);if(this.verbose&&console.error(`创建视频生成任务失败(尝试 ${r}/3): ${e}`),r>=3)throw new eb(`创建视频生成任务失败,已重试3次: ${e}`,500);if(e.toLowerCase().includes("rate limit")||e.includes("429")){let e=Math.min(2**r*1e3,1e4);this.verbose&&console.warn(`遇到速率限制,等待 ${e/1e3} 秒后重试...`),await this.sleep(e)}else if(e.toLowerCase().includes("timeout"))this.verbose&&console.warn("请求超时,等待 2 秒后重试..."),await this.sleep(2e3);else throw i}let o=Date.now(),u=0;for(;Date.now()-o<n;){u++;try{let e=await this.request("GET",`${this.baseUrl}/api/v3/contents/generations/tasks/${a}`),i=e.status;if(this.verbose&&console.log(`任务 ${a} 状态检查 #${u}: ${i}`),"succeeded"===i){let i=e.content?.video_url||null,n=e.content?.last_frame_url||"";if(!i)throw new eb(`视频生成成功但响应中缺少视频URL,任务ID: ${a}`,500);return this.verbose&&console.log(`视频生成成功,任务ID: ${a}, 视频URL: ${i}`),{videoUrl:i,response:e,lastFrameUrl:n}}if("failed"===i){let i=e.error_message||"未知错误";throw this.verbose&&console.error(`视频生成失败,任务ID: ${a}, 错误: ${i}`),new eb(`视频生成失败: ${i}`,500)}if("cancelled"===i)return this.verbose&&console.warn(`视频生成任务被取消,任务ID: ${a}`),{videoUrl:null,response:e,lastFrameUrl:""};else if("queued"===i||"running"===i){await this.sleep(5e3);continue}else{this.verbose&&console.warn(`未知的任务状态: ${i},任务ID: ${a}`),await this.sleep(5e3);continue}}catch(i){let e=i instanceof Error?i.message:String(i);if(this.verbose&&console.error(`查询任务状态失败,任务ID: ${a}, 错误: ${e}`),e.toLowerCase().includes("not found")||e.includes("404"))throw new eb(`任务不存在或已过期,任务ID: ${a}`,404);if(Date.now()-o>=n)throw i;await this.sleep(5e3);continue}}let s=Math.floor((Date.now()-o)/1e3);throw this.verbose&&console.error(`视频生成超时,任务ID: ${a}, 已等待: ${s}秒`),new eb(`视频生成超时,已等待 ${s} 秒,任务ID: ${a}`,408)}async videoGenerationAsync(e,i){return this.videoGeneration(e,i)}}class eR{static DEFAULT_URL_EXPIRE=86400;static MAX_URL_EXPIRE=2592e3;static MIN_URL_EXPIRE=1;static MIN_AUDIO_URL_EXPIRE=3600;static DEFAULT_FONT_TYPE="1525745";static DEFAULT_FONT_SIZE=36;static DEFAULT_FONT_COLOR="#FFFFFFFF";static DEFAULT_BACKGROUND_COLOR="#00000000";static DEFAULT_BACKGROUND_BORDER_WIDTH=0;static DEFAULT_FONT_POS_HEIGHT="10%";static DEFAULT_FONT_POS_X="0";static DEFAULT_FONT_POS_Y="90%";static DEFAULT_FONT_POS_WIDTH="100%";static DEFAULT_SYNC_METHOD="trim";static DEFAULT_SYNC_MODE="video";static DEFAULT_SUBTITLE_TYPE="srt";static DEFAULT_AUDIO_FORMAT="m4a"}class eM extends ew{baseUrl;constructor(e,i,n=!1){super(e,i,n),this.baseUrl=this.config.baseUrl}async extractByKeyFrame(e){let i=await this.request("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=frame_extractor_by_key_frame`,{url:e});if(0!==i.code)throw new eb(`Key frame extraction failed: ${i.msg||"Unknown error"}`,i.code);return i}async extractByInterval(e,i){let n=await this.request("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=frame_extractor_by_interval`,{url:e,interval_ms:i});if(0!==n.code)throw new eb(`Interval frame extraction failed: ${n.msg||"Unknown error"}`,n.code);return n}async extractByCount(e,i){let n=await this.request("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=frame_extractor_by_count`,{url:e,count:i});if(0!==n.code)throw new eb(`Count-based frame extraction failed: ${n.msg||"Unknown error"}`,n.code);return n}}class eJ extends ew{baseUrl;constructor(e,i,n=!1){super(e,i,n),this.baseUrl=this.config.baseUrl}validateUrlExpire(e,i=eR.MIN_URL_EXPIRE){if(void 0===e)return eR.DEFAULT_URL_EXPIRE;if(e<i||e>eR.MAX_URL_EXPIRE)throw new eb(`url_expire must be between ${i} and ${eR.MAX_URL_EXPIRE} seconds`,400);return e}async addSubtitles(e,i,n){let t=this.validateUrlExpire(n?.urlExpire),a={video:e,subtitle_config:{background_border_width:i.background_border_width??eR.DEFAULT_BACKGROUND_BORDER_WIDTH,font_type:i.font_type??eR.DEFAULT_FONT_TYPE,font_pos_config:{height:i.font_pos_config.height??eR.DEFAULT_FONT_POS_HEIGHT,pos_x:i.font_pos_config.pos_x??eR.DEFAULT_FONT_POS_X,pos_y:i.font_pos_config.pos_y??eR.DEFAULT_FONT_POS_Y,width:i.font_pos_config.width??eR.DEFAULT_FONT_POS_WIDTH}},url_expire:t};void 0!==i.border_width&&(a.subtitle_config.border_width=i.border_width),void 0!==i.font_color&&(a.subtitle_config.font_color=i.font_color),void 0!==i.font_size&&(a.subtitle_config.font_size=i.font_size),void 0!==i.background_color&&(a.subtitle_config.background_color=i.background_color),void 0!==i.border_color&&(a.subtitle_config.border_color=i.border_color),n?.subtitleUrl&&(a.subtitle_url=n.subtitleUrl),n?.textList&&n.textList.length>0&&(a.text_list=n.textList.map(e=>({end_time:e.end_time,start_time:e.start_time,text:e.text})));let r=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=add_subtitles`,a),o=r.headers["x-api-status-code"]||"0",u=r.headers["x-api-message"]||"";if("0"!==o)throw new eb(`Add subtitles failed, status code: ${o}, error: ${u}`,parseInt(o)||500);if(!r.data.url)throw new eb("Add subtitles failed: returned URL is empty",500);return r.data}async concatVideos(e,i){if(!e||0===e.length)throw new eb("videos list cannot be empty",400);let n={videos:e,url_expire:this.validateUrlExpire(i?.urlExpire)};i?.transitions&&i.transitions.length>0&&(n.transitions=i.transitions);let t=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=concat_videos`,n),a=t.headers["x-api-status-code"]||"0",r=t.headers["x-api-message"]||"";if("0"!==a)throw new eb(`Concat videos failed, status code: ${a}, error: ${r}`,parseInt(a)||500);if(!t.data.url)throw new eb("Concat videos failed: returned URL is empty",500);return t.data}async compileVideoAudio(e,i,n){let t={video:e,audio:i,url_expire:this.validateUrlExpire(n?.urlExpire)};n?.isVideoAudioSync!==void 0&&(t.is_video_audio_sync=n.isVideoAudioSync),n?.outputSync&&(t.output_sync={sync_method:n.outputSync.sync_method??eR.DEFAULT_SYNC_METHOD,sync_mode:n.outputSync.sync_mode??eR.DEFAULT_SYNC_MODE}),n?.isAudioReserve!==void 0&&(t.is_audio_reserve=n.isAudioReserve);let a=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=compile_video_audio`,t),r=a.headers["x-api-status-code"]||"0",o=a.headers["x-api-message"]||"";if("0"!==r)throw new eb(`Compile video audio failed, status code: ${r}, error: ${o}`,parseInt(r)||500);if(!a.data.url)throw new eb("Compile video audio failed: returned URL is empty",500);return a.data}async audioToSubtitle(e,i){let n={source:e,url_expire:this.validateUrlExpire(i?.urlExpire)};i?.subtitleType&&(n.subtitle_type=i.subtitleType);let t=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=audio_to_subtitle`,n),a=t.headers["x-api-status-code"]||"0",r=t.headers["x-api-message"]||"";if("0"!==a)throw new eb(`Audio to subtitle failed, status code: ${a}, error: ${r}`,parseInt(a)||500);if(!t.data.url)throw new eb("Audio to subtitle failed: returned URL is empty",500);return t.data}async extractAudio(e,i){let n={video:e,url_expire:this.validateUrlExpire(i?.urlExpire,eR.MIN_AUDIO_URL_EXPIRE)};i?.format&&(n.format=i.format);let t=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=audio_extract`,n),a=t.headers["x-api-status-code"]||"0",r=t.headers["x-api-message"]||"";if("0"!==a)throw new eb(`Extract audio failed, status code: ${a}, error: ${r}`,parseInt(a)||500);if(!t.data.url)throw new eb("Extract audio failed: returned URL is empty",500);return t.data}async videoTrim(e,i){let n=this.validateUrlExpire(i?.urlExpire);if(i?.startTime!==void 0&&i.startTime<0)throw new eb("start_time must be greater than or equal to 0",400);if(i?.endTime!==void 0&&i.endTime<0)throw new eb("end_time must be greater than or equal to 0",400);let t={video:e,url_expire:n};i?.startTime!==void 0&&(t.start_time=i.startTime),i?.endTime!==void 0&&(t.end_time=i.endTime);let a=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=video_trim`,t),r=a.headers["x-api-status-code"]||"0",o=a.headers["x-api-message"]||"";if("0"!==r)throw new eb(`Video trim failed, status code: ${r}, error: ${o}`,parseInt(r)||500);if(!a.data.url)throw new eb("Video trim failed: returned URL is empty",500);return a.data}}let ek={MODEL:"doubao-seed-1-8-251228",THINKING:"disabled",CACHING:"disabled",TEMPERATURE:1,STREAMING:!0};class eB{config;customHeaders;constructor(e,i){this.config=e||new ey,this.customHeaders=i}createLLM(e,i,n){let t={};t.thinking={type:e.thinking??ek.THINKING},e.caching&&"disabled"!==e.caching&&(t.caching={type:e.caching});let a={Authorization:`Bearer ${this.config.apiKey}`,"X-Client-Sdk":"coze-coding-dev-sdk-typescript/0.3.0",...this.customHeaders,...n};return i&&(a["X-Previous-Response-Id"]=i),new D({model:e.model||ek.MODEL,apiKey:this.config.apiKey,configuration:{baseURL:this.config.modelBaseUrl,defaultHeaders:a},streaming:void 0!==e.streaming?e.streaming:ek.STREAMING,temperature:void 0!==e.temperature?e.temperature:ek.TEMPERATURE,modelKwargs:Object.keys(t).length>0?t:void 0})}convertMessages(e){return e.map(e=>{let i=this.convertContent(e.content);switch(e.role){case"system":return new N(i);case"user":return new A(i);case"assistant":return new v(i);default:throw Error(`Unknown message role: ${e.role}`)}})}convertContent(e){return"string"==typeof e?e:e.map(e=>{if("text"===e.type)return{type:"text",text:e.text};if("image_url"===e.type){let i={url:e.image_url.url};return e.image_url.detail&&(i.detail=e.image_url.detail),{type:"image_url",image_url:i}}if("video_url"===e.type){let i={url:e.video_url.url};return void 0!==e.video_url.fps&&(i.fps=e.video_url.fps),{type:"video_url",video_url:i}}return e})}async *stream(e,i={},n,t){let a=this.createLLM(i,n,t),r=this.convertMessages(e);for await(let e of(await a.stream(r)))yield e}async invoke(e,i={},n,t){let a="";for await(let r of this.stream(e,i,n,t))r.content&&(a+=r.content.toString());return{content:a}}}var eH=((H={})[H.TEXT=0]="TEXT",H[H.URL=1]="URL",H[H.URI=2]="URI",H);class eF extends ew{baseUrl;constructor(e,i,n=!1){super(e,i,n),this.baseUrl=this.config.baseUrl}async search(e,i,n=5,t=0,a){let r={query:e,top_k:n,min_score:t};i&&(r.dataset=i);let o=`${this.baseUrl}/v1/knowledge_base/recall`,u={...a};this.config.apiKey&&(u["x-coze-token"]=`Bearer ${this.config.apiKey}`);let s=await this.request("POST",o,r,{headers:u});return{chunks:(s.data||[]).map(e=>({content:e.slice||"",score:e.score||0,chunk_id:e.chunk_id,doc_id:e.doc_id})),code:s.code||0,msg:s.msg||""}}async addDocuments(e,i,n,t){let a={dataset:i,data:e};n&&(a.chunk_config=Object.fromEntries(Object.entries(n).filter(([e,i])=>void 0!==i)));let r=`${this.baseUrl}/v1/knowledge_base/batch_import`,o={...t};this.config.apiKey&&(o["x-coze-token"]=`Bearer ${this.config.apiKey}`);let u=await this.request("POST",r,a,{headers:o}),s=u.msg||"";return 0===u.code&&(s="成功!文档正在异步导入中,请稍候。您可以查看数据库中的 'knowledge' schema 来验证导入状态。"),{doc_ids:u.doc_ids,code:u.code||0,msg:s}}}let eX=Symbol.for("drizzle:entityKind");function entity_is(e,i){if(!e||"object"!=typeof e)return!1;if(e instanceof i)return!0;if(!Object.prototype.hasOwnProperty.call(i,eX))throw Error(`Class "${i.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let n=Object.getPrototypeOf(e).constructor;if(n)for(;n;){if(eX in n&&n[eX]===i[eX])return!0;n=Object.getPrototypeOf(n)}return!1}Symbol.for("drizzle:hasOwnEntityKind");class eI{static [eX]="ConsoleLogWriter";write(e){console.log(e)}}class eO{static [eX]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new eI}logQuery(e,i){let n=i.map(e=>{try{return JSON.stringify(e)}catch{return String(e)}}),t=n.length?` -- params: [${n.join(", ")}]`:"";this.writer.write(`Query: ${e}${t}`)}}class eQ{static [eX]="NoopLogger";logQuery(){}}class eG{constructor(e,i){this.table=e,this.config=i,this.name=i.name,this.keyAsName=i.keyAsName,this.notNull=i.notNull,this.default=i.default,this.defaultFn=i.defaultFn,this.onUpdateFn=i.onUpdateFn,this.hasDefault=i.hasDefault,this.primary=i.primaryKey,this.isUnique=i.isUnique,this.uniqueName=i.uniqueName,this.uniqueType=i.uniqueType,this.dataType=i.dataType,this.columnType=i.columnType,this.generated=i.generated,this.generatedIdentity=i.generatedIdentity}static [eX]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return void 0!==this.config.generated&&"byDefault"!==this.config.generated.type}}class eU{static [eX]="ColumnBuilder";config;constructor(e,i,n){this.config={name:e,keyAsName:""===e,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:i,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){""===this.config.name&&(this.config.name=e)}}let eK=Symbol.for("drizzle:Name");class e${static [eX]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,i){this.reference=()=>{let{name:i,columns:n,foreignColumns:t}=e();return{name:i,columns:n,foreignTable:t[0].table,foreignColumns:t}},i&&(this._onUpdate=i.onUpdate,this._onDelete=i.onDelete)}onUpdate(e){return this._onUpdate=void 0===e?"no action":e,this}onDelete(e){return this._onDelete=void 0===e?"no action":e,this}build(e){return new ez(e,this)}}class ez{constructor(e,i){this.table=e,this.reference=i.reference,this.onUpdate=i._onUpdate,this.onDelete=i._onDelete}static [eX]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:i,foreignColumns:n}=this.reference(),t=i.map(e=>e.name),a=n.map(e=>e.name),r=[this.table[eK],...t,n[0].table[eK],...a];return e??`${r.join("_")}_fk`}}function iife(e,...i){return e(...i)}function uniqueKeyName(e,i){return`${e[eK]}_${i.join("_")}_unique`}class eW{constructor(e,i){this.name=i,this.columns=e}static [eX]=null;columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new eV(e,this.columns,this.nullsNotDistinctConfig,this.name)}}class ej{static [eX]=null;name;constructor(e){this.name=e}on(...e){return new eW(e,this.name)}}class eV{constructor(e,i,n,t){this.table=e,this.columns=i,this.name=t??uniqueKeyName(this.table,this.columns.map(e=>e.name)),this.nullsNotDistinct=n}static [eX]=null;columns;name;nullsNotDistinct=!1;getName(){return this.name}}function parsePgArrayValue(e,i,n){for(let t=i;t<e.length;t++){let a=e[t];if("\\"===a){t++;continue}if('"'===a)return[e.slice(i,t).replace(/\\/g,""),t+1];if(!n&&(","===a||"}"===a))return[e.slice(i,t).replace(/\\/g,""),t]}return[e.slice(i).replace(/\\/g,""),e.length]}function parsePgNestedArray(e,i=0){let n=[],t=i,a=!1;for(;t<e.length;){let r=e[t];if(","===r){(a||t===i)&&n.push(""),a=!0,t++;continue}if(a=!1,"\\"===r){t+=2;continue}if('"'===r){let[i,a]=parsePgArrayValue(e,t+1,!0);n.push(i),t=a;continue}if("}"===r)return[n,t+1];if("{"===r){let[i,a]=parsePgNestedArray(e,t+1);n.push(i),t=a;continue}let[o,u]=parsePgArrayValue(e,t,!1);n.push(o),t=u}return[n,t]}function parsePgArray(e){let[i]=parsePgNestedArray(e,1);return i}function makePgArray(e){return`{${e.map(e=>Array.isArray(e)?makePgArray(e):"string"==typeof e?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${e}`).join(",")}}`}class e0 extends eU{foreignKeyConfigs=[];static [eX]="PgColumnBuilder";array(e){return new e4(this.config.name,this,e)}references(e,i={}){return this.foreignKeyConfigs.push({ref:e,actions:i}),this}unique(e,i){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=i?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,i){return this.foreignKeyConfigs.map(({ref:n,actions:t})=>iife((n,t)=>{let a=new e$(()=>({columns:[e],foreignColumns:[n()]}));return t.onUpdate&&a.onUpdate(t.onUpdate),t.onDelete&&a.onDelete(t.onDelete),a.build(i)},n,t))}buildExtraConfigColumn(e){return new e3(e,this.config)}}class e1 extends eG{constructor(e,i){i.uniqueName||(i.uniqueName=uniqueKeyName(e,[i.name])),super(e,i),this.table=e}static [eX]="PgColumn"}class e3 extends e1{static [eX]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}}class e2{static [eX]=null;constructor(e,i,n,t){this.name=e,this.keyAsName=i,this.type=n,this.indexConfig=t}name;keyAsName;type;indexConfig}class e4 extends e0{static [eX]="PgArrayBuilder";constructor(e,i,n){super(e,"array","PgArray"),this.config.baseBuilder=i,this.config.size=n}build(e){let i=this.config.baseBuilder.build(e);return new e8(e,this.config,i)}}class e8 extends e1{constructor(e,i,n,t){super(e,i),this.baseColumn=n,this.range=t,this.size=i.size}size;static [eX]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${"number"==typeof this.size?this.size:""}]`}mapFromDriverValue(e){return"string"==typeof e&&(e=parsePgArray(e)),e.map(e=>this.baseColumn.mapFromDriverValue(e))}mapToDriverValue(e,i=!1){let n=e.map(e=>null===e?null:entity_is(this.baseColumn,e8)?this.baseColumn.mapToDriverValue(e,!0):this.baseColumn.mapToDriverValue(e));return i?n:makePgArray(n)}}class e6 extends e0{static [eX]="PgEnumObjectColumnBuilder";constructor(e,i){super(e,"string","PgEnumObjectColumn"),this.config.enum=i}build(e){return new e5(e,this.config)}}class e5 extends e1{static [eX]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,i){super(e,i),this.enum=i.enum}getSQLType(){return this.enum.enumName}}let e7=Symbol.for("drizzle:isPgEnum");function isPgEnum(e){return!!e&&"function"==typeof e&&e7 in e&&!0===e[e7]}class e9 extends e0{static [eX]="PgEnumColumnBuilder";constructor(e,i){super(e,"string","PgEnumColumn"),this.config.enum=i}build(e){return new ie(e,this.config)}}class ie extends e1{static [eX]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,i){super(e,i),this.enum=i.enum}getSQLType(){return this.enum.enumName}}class it{static [eX]="Subquery";constructor(e,i,n,t=!1,a=[]){this._={brand:"Subquery",sql:e,selectedFields:i,alias:n,isWith:t,usedTables:a}}}class ia extends it{static [eX]="WithSubquery"}let ir=(n,t)=>e?(i||(i=e.trace.getTracer("drizzle-orm","0.45.1")),iife((e,i)=>i.startActiveSpan(n,i=>{try{return t(i)}catch(n){throw i.setStatus({code:e.SpanStatusCode.ERROR,message:n instanceof Error?n.message:"Unknown error"}),n}finally{i.end()}}),e,i)):t(),io=Symbol.for("drizzle:ViewBaseConfig"),iu=Symbol.for("drizzle:Schema"),is=Symbol.for("drizzle:Columns"),il=Symbol.for("drizzle:ExtraConfigColumns"),ih=Symbol.for("drizzle:OriginalName"),ig=Symbol.for("drizzle:BaseName"),ic=Symbol.for("drizzle:IsAlias"),id=Symbol.for("drizzle:ExtraConfigBuilder"),ip=Symbol.for("drizzle:IsDrizzleTable");class im{static [eX]="Table";static Symbol={Name:eK,Schema:iu,OriginalName:ih,Columns:is,ExtraConfigColumns:il,BaseName:ig,IsAlias:ic,ExtraConfigBuilder:id};[eK];[ih];[iu];[is];[il];[ig];[ic]=!1;[ip]=!0;[id]=void 0;constructor(e,i,n){this[eK]=this[ih]=e,this[iu]=i,this[ig]=n}}function getTableUniqueName(e){return`${e[iu]??"public"}.${e[eK]}`}class iy{static [eX]=null}function isSQLWrapper(e){return null!=e&&"function"==typeof e.getSQL}function mergeQueries(e){let i={sql:"",params:[]};for(let n of e)i.sql+=n.sql,i.params.push(...n.params),n.typings?.length&&(i.typings||(i.typings=[]),i.typings.push(...n.typings));return i}class iS{static [eX]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new ib([this])}}class ib{constructor(e){for(let i of(this.queryChunks=e,e))if(entity_is(i,im)){let e=i[im.Symbol.Schema];this.usedTables.push(void 0===e?i[im.Symbol.Name]:e+"."+i[im.Symbol.Name])}}static [eX]="SQL";decoder=iT;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return ir("drizzle.buildSQL",i=>{let n=this.buildQueryFromSourceParams(this.queryChunks,e);return i?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(e,i){let n=Object.assign({},i,{inlineParams:i.inlineParams||this.shouldInlineParams,paramStartIndex:i.paramStartIndex||{value:0}}),{casing:t,escapeName:a,escapeParam:r,prepareTyping:o,inlineParams:u,paramStartIndex:s}=n;return mergeQueries(e.map(e=>{if(entity_is(e,iS))return{sql:e.value.join(""),params:[]};if(entity_is(e,iC))return{sql:a(e.value),params:[]};if(void 0===e)return{sql:"",params:[]};if(Array.isArray(e)){let i=[new iS("(")];for(let[n,t]of e.entries())i.push(t),n<e.length-1&&i.push(new iS(", "));return i.push(new iS(")")),this.buildQueryFromSourceParams(i,n)}if(entity_is(e,ib))return this.buildQueryFromSourceParams(e.queryChunks,{...n,inlineParams:u||e.shouldInlineParams});if(entity_is(e,im)){let i=e[im.Symbol.Schema],n=e[im.Symbol.Name];return{sql:void 0===i||e[ic]?a(n):a(i)+"."+a(n),params:[]}}if(entity_is(e,eG)){let n=t.getColumnCasing(e);if("indexes"===i.invokeSource)return{sql:a(n),params:[]};let r=e.table[im.Symbol.Schema];return{sql:e.table[ic]||void 0===r?a(e.table[im.Symbol.Name])+"."+a(n):a(r)+"."+a(e.table[im.Symbol.Name])+"."+a(n),params:[]}}if(entity_is(e,iD)){let i=e[io].schema,n=e[io].name;return{sql:void 0===i||e[io].isAlias?a(n):a(i)+"."+a(n),params:[]}}if(entity_is(e,ix)){if(entity_is(e.value,i_))return{sql:r(s.value++,e),params:[e],typings:["none"]};let i=null===e.value?null:e.encoder.mapToDriverValue(e.value);if(entity_is(i,ib))return this.buildQueryFromSourceParams([i],n);if(u)return{sql:this.mapInlineParam(i,n),params:[]};let t=["none"];return o&&(t=[o(e.encoder)]),{sql:r(s.value++,i),params:[i],typings:t}}return entity_is(e,i_)?{sql:r(s.value++,e),params:[e],typings:["none"]}:entity_is(e,ib.Aliased)&&void 0!==e.fieldAlias?{sql:a(e.fieldAlias),params:[]}:entity_is(e,it)?e._.isWith?{sql:a(e._.alias),params:[]}:this.buildQueryFromSourceParams([new iS("("),e._.sql,new iS(") "),new iC(e._.alias)],n):isPgEnum(e)?e.schema?{sql:a(e.schema)+"."+a(e.enumName),params:[]}:{sql:a(e.enumName),params:[]}:isSQLWrapper(e)?e.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([e.getSQL()],n):this.buildQueryFromSourceParams([new iS("("),e.getSQL(),new iS(")")],n):u?{sql:this.mapInlineParam(e,n),params:[]}:{sql:r(s.value++,e),params:[e],typings:["none"]}}))}mapInlineParam(e,{escapeString:i}){if(null===e)return"null";if("number"==typeof e||"boolean"==typeof e)return e.toString();if("string"==typeof e)return i(e);if("object"==typeof e){let n=e.toString();return"[object Object]"===n?i(JSON.stringify(e)):i(n)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return void 0===e?this:new ib.Aliased(this,e)}mapWith(e){return this.decoder="function"==typeof e?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}}class iC{constructor(e){this.value=e}static [eX]="Name";brand;getSQL(){return new ib([this])}}function isDriverValueEncoder(e){return"object"==typeof e&&null!==e&&"mapToDriverValue"in e&&"function"==typeof e.mapToDriverValue}let iT={mapFromDriverValue:e=>e},iw={mapToDriverValue:e=>e};({...iT,...iw});class ix{constructor(e,i=iw){this.value=e,this.encoder=i}static [eX]="Param";brand;getSQL(){return new ib([this])}}function sql_sql(e,...i){let n=[];for(let[t,a]of((i.length>0||e.length>0&&""!==e[0])&&n.push(new iS(e[0])),i.entries()))n.push(a,new iS(e[t+1]));return new ib(n)}(F=sql_sql||(sql_sql={})).empty=function(){return new ib([])},F.fromList=function(e){return new ib(e)},F.raw=function(e){return new ib([new iS(e)])},F.join=function(e,i){let n=[];for(let[t,a]of e.entries())t>0&&void 0!==i&&n.push(i),n.push(a);return new ib(n)},F.identifier=function(e){return new iC(e)},F.placeholder=function(e){return new i_(e)},F.param=function(e,i){return new ix(e,i)};var iE=ib||(ib={});class iL{constructor(e,i){this.sql=e,this.fieldAlias=i}static [eX]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new iL(this.sql,this.fieldAlias)}}iE.Aliased=iL;class i_{constructor(e){this.name=e}static [eX]="Placeholder";getSQL(){return new ib([this])}}function fillPlaceholders(e,i){return e.map(e=>{if(entity_is(e,i_)){if(!(e.name in i))throw Error(`No value for placeholder "${e.name}" was provided`);return i[e.name]}if(entity_is(e,ix)&&entity_is(e.value,i_)){if(!(e.value.name in i))throw Error(`No value for placeholder "${e.value.name}" was provided`);return e.encoder.mapToDriverValue(i[e.value.name])}return e})}let iY=Symbol.for("drizzle:IsDrizzleView");class iD{static [eX]="View";[io];[iY]=!0;constructor({name:e,schema:i,selectedFields:n,query:t}){this[io]={name:e,originalName:e,schema:i,selectedFields:n,query:t,isExisting:!t,isAlias:!1}}getSQL(){return new ib([this])}}eG.prototype.getSQL=function(){return new ib([this])},im.prototype.getSQL=function(){return new ib([this])},it.prototype.getSQL=function(){return new ib([this])};class iv{constructor(e){this.table=e}static [eX]="ColumnAliasProxyHandler";get(e,i){return"table"===i?this.table:e[i]}}class iA{constructor(e,i){this.alias=e,this.replaceOriginalName=i}static [eX]="TableAliasProxyHandler";get(e,i){if(i===im.Symbol.IsAlias)return!0;if(i===im.Symbol.Name||this.replaceOriginalName&&i===im.Symbol.OriginalName)return this.alias;if(i===io)return{...e[io],name:this.alias,isAlias:!0};if(i===im.Symbol.Columns){let i=e[im.Symbol.Columns];if(!i)return i;let n={};return Object.keys(i).map(t=>{n[t]=new Proxy(i[t],new iv(new Proxy(e,this)))}),n}let n=e[i];return entity_is(n,eG)?new Proxy(n,new iv(new Proxy(e,this))):n}}class iN{constructor(e){this.alias=e}static [eX]=null;get(e,i){return"sourceTable"===i?aliasedTable(e.sourceTable,this.alias):e[i]}}function aliasedTable(e,i){return new Proxy(e,new iA(i,!1))}function aliasedTableColumn(e,i){return new Proxy(e,new iv(new Proxy(e.table,new iA(i,!1))))}function mapColumnsInAliasedSQLToAlias(e,i){return new ib.Aliased(mapColumnsInSQLToAlias(e.sql,i),e.fieldAlias)}function mapColumnsInSQLToAlias(e,i){return sql_sql.join(e.queryChunks.map(e=>entity_is(e,eG)?aliasedTableColumn(e,i):entity_is(e,ib)?mapColumnsInSQLToAlias(e,i):entity_is(e,ib.Aliased)?mapColumnsInAliasedSQLToAlias(e,i):e))}function toSnakeCase(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(e=>e.toLowerCase()).join("_")}function toCamelCase(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((e,i,n)=>e+(0===n?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`),"")}function noopCase(e){return e}class iP{static [eX]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert="snake_case"===e?toSnakeCase:"camelCase"===e?toCamelCase:noopCase}getColumnCasing(e){if(!e.keyAsName)return e.name;let i=e.table[im.Symbol.Schema]??"public",n=e.table[im.Symbol.OriginalName],t=`${i}.${n}.${e.name}`;return this.cache[t]||this.cacheTable(e.table),this.cache[t]}cacheTable(e){let i=e[im.Symbol.Schema]??"public",n=e[im.Symbol.OriginalName],t=`${i}.${n}`;if(!this.cachedTables[t]){for(let i of Object.values(e[im.Symbol.Columns])){let e=`${t}.${i.name}`;this.cache[e]=this.convert(i.name)}this.cachedTables[t]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class iZ extends Error{static [eX]="DrizzleError";constructor({message:e,cause:i}){super(e),this.name="DrizzleError",this.cause=i}}class iR extends Error{constructor(e,i,n){super(`Failed query: ${e}
13
+ `;for(let a of(0,t.execSync)(`python3 -c '${n.replace(/'/g,"'\"'\"'")}'`,{encoding:"utf-8",timeout:1e4,stdio:["pipe","pipe","pipe"]}).trim().split("\n")){if(a.startsWith("#"))continue;let n=a.indexOf("=");if(n>0){let t=a.substring(0,n),r=a.substring(n+1);(r.startsWith("'")&&r.endsWith("'")||r.startsWith('"')&&r.endsWith('"'))&&(r=r.slice(1,-1)),"COZE_INTEGRATION_BASE_URL"===t?e=r:"COZE_WORKLOAD_IDENTITY_API_KEY"===t&&(i=r)}}}catch{}return a=!0,r={baseUrl:e,apiKey:i}}class o{baseUrl;apiKey;configured;constructor(){try{let e=loadReportEnv();if(this.baseUrl=e.baseUrl,this.apiKey=e.apiKey,this.configured=!!(this.baseUrl&&this.apiKey),!this.configured){let e=[];this.baseUrl||e.push("COZE_INTEGRATION_BASE_URL"),this.apiKey||e.push("COZE_WORKLOAD_IDENTITY_API_KEY"),console.error(`[report] ReportClient not configured: ${e.join(", ")} is missing`)}}catch(e){this.baseUrl="",this.apiKey="",this.configured=!1,console.error("[report] ReportClient config failed:",e)}}async batchReport(e){if(e.length){if(!this.configured)return void console.error(`[report] batchReport skipped: ReportClient is not configured. Set COZE_INTEGRATION_BASE_URL and COZE_WORKLOAD_IDENTITY_API_KEY environment variables. Dropping ${e.length} entries.`);try{let i=`${this.baseUrl}/v1/memory_report/batch_report`,n=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json","x-coze-token":this.apiKey},body:JSON.stringify({entries:e}),signal:ma.timeout(1e4)});if(!n.ok)throw Error(`batchReport failed: ${n.status} ${n.statusText}`)}catch(e){console.error("[report] batchReport failed:",e)}}}}},"./src/report/index.ts"(e,i,n){n.r(i),n.d(i,{ReportBuffer:()=>a.R,ReportClient:()=>t.W,createS3ReportMiddleware:()=>s.L,createWrappedFetch:()=>u.E,getReportBuffer:()=>r.T,redactUrl:()=>o.B,truncate:()=>o.x});var t=n("./src/report/client.ts"),a=n("./src/report/buffer.ts"),r=n("./src/report/singleton.ts"),o=n("./src/report/utils.ts"),u=n("./src/report/interceptors/fetch-wrapper.ts"),s=n("./src/report/interceptors/s3-middleware.ts")},"./src/report/interceptors/fetch-wrapper.ts"(e,i,n){n.d(i,{E:()=>createWrappedFetch});var t=n("./src/report/utils.ts");function createWrappedFetch(e,i="supabase"){return async(n,t)=>{let a=Date.now();try{let r=await fetch(n,t);return safeRecordLog(e,i,n,t,r,null,a),r}catch(r){throw safeRecordLog(e,i,n,t,null,r,a),r}}}function safeRecordLog(e,i,n,a,r,o,u){try{let s=Date.now()-u,l="string"==typeof n?n:n instanceof URL?n.toString():n.url||"",h=a?.method||(n instanceof Request?n.method:"GET"),g=r?.status??null,c=null;if(a?.body)try{c=(0,t.x)("string"==typeof a.body?a.body:JSON.stringify(a.body))}catch{c=null}let d={source:i,project_id:null,env:null,method:h.toUpperCase(),url:(0,t.B)(l),request_body:c,response_body:null,status_code:g,error:o?.message??null,duration_ms:s,timestamp:u,success:null!==g&&g>=200&&g<300};if(r){let i=r.clone().body?.getReader();i?i.read().then(({value:n})=>{if(n){let e=new TextDecoder().decode(n.slice(0,2048));d.response_body=(0,t.x)(e)}i.cancel().catch(()=>{}),e.add(d)}).catch(()=>{e.add(d)}):e.add(d)}else e.add(d)}catch(e){console.error("[report] safeRecordLog error:",e)}}},"./src/report/interceptors/s3-middleware.ts"(e,i,n){n.d(i,{L:()=>createS3ReportMiddleware});var t=n("./src/report/utils.ts");function createS3ReportMiddleware(e){return e?{middleware:(i,n)=>async n=>{let t=Date.now(),{request:a}=n;try{let r=await i(n);return safeRecordS3Log(e,a,r,null,t),r}catch(i){throw safeRecordS3Log(e,a,null,i,t),i}},options:{step:"deserialize",name:"reportLogger",override:!0}}:null}function safeRecordS3Log(e,i,n,a,r){try{let o=Date.now()-r,u=i?.method||"UNKNOWN",s=i?.hostname?`${i.protocol||"https:"}//${i.hostname}${i.path||""}`:"",l=n?.response?.statusCode??null,h=null;if(i?.body)try{let e=i.body;"string"==typeof e?h=(0,t.x)(e):Buffer.isBuffer(e)&&(h=(0,t.x)(`[Binary ${e.length} bytes]`))}catch{h=null}let g={source:"s3",project_id:null,env:null,method:u.toUpperCase(),url:(0,t.B)(s),request_body:h,response_body:null,status_code:l,error:a?.message??null,duration_ms:o,timestamp:r,success:null!==l&&l>=200&&l<300};if(n?.output)try{let{Body:e,...i}=n.output;Object.keys(i).length>0&&(g.response_body=(0,t.x)(JSON.stringify(i)))}catch{}e.add(g)}catch{}}},"./src/report/singleton.ts"(e,i,n){n.d(i,{T:()=>getReportBuffer});var t=n("./src/report/client.ts"),a=n("./src/report/buffer.ts");let r=null;function getReportBuffer(){if(r)return r;try{let e=new t.W;return r=new a.R(e)}catch(e){return console.error("[report] failed to create singleton buffer:",e),null}}},"./src/report/utils.ts"(e,i,n){n.d(i,{B:()=>redactUrl,x:()=>truncate});let t=/((?:apikey|api_key|access_key|secret_key|access_token|token|secret|password|authorization|credential|X-Amz-Signature|X-Amz-Credential|X-Amz-Security-Token)=)[^&]*/gi;function truncate(e,i=1024){return null==e?null:e.length<=i?e:e.substring(0,i)+"...[truncated]"}function redactUrl(e){return e.replace(t,"$1***")}},buffer(e){e.exports=p},child_process(e){e.exports=f},crypto(e){e.exports=m},events(e){e.exports=y},fs(e){e.exports=S},"node:fs"(e){e.exports=b},"node:fs/promises"(e){e.exports=C},"node:stream"(e){e.exports=T},os(e){e.exports=w},path(e){e.exports=x},stream(e){e.exports=E},zlib(e){e.exports=L},"./node_modules/dotenv/package.json"(e){e.exports=JSON.parse('{"name":"dotenv","version":"17.2.3","description":"Loads environment variables from .env file","main":"lib/main.js","types":"lib/main.d.ts","exports":{".":{"types":"./lib/main.d.ts","require":"./lib/main.js","default":"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},"scripts":{"dts-check":"tsc --project tests/types/tsconfig.json","lint":"standard","pretest":"npm run lint && npm run dts-check","test":"tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov","prerelease":"npm test","release":"standard-version"},"repository":{"type":"git","url":"git://github.com/motdotla/dotenv.git"},"homepage":"https://github.com/motdotla/dotenv#readme","funding":"https://dotenvx.com","keywords":["dotenv","env",".env","environment","variables","config","settings"],"readmeFilename":"README.md","license":"BSD-2-Clause","devDependencies":{"@types/node":"^18.11.3","decache":"^4.6.2","sinon":"^14.0.1","standard":"^17.0.0","standard-version":"^9.5.0","tap":"^19.2.0","typescript":"^4.8.4"},"engines":{"node":">=12"},"browser":{"fs":false}}')}});var H,F,X,I,O,Q,G,U,q,K,$,z,W,j,V,ee,ei,en,et,ea,er,eo,eu,es,el,eh,eg,ec,ed={};_.r(ed),_.d(ed,{T:()=>ey});var ep={};_.r(ep),_.d(ep,{n:()=>ex,p:()=>eE});var ef={};_.r(ef),_.d(ef,{F:()=>mZ});var em={};_.r(em),_.d(em,{c:()=>ek});class ey{apiKey;baseUrl;modelBaseUrl;retryTimes;retryDelay;timeout;constructor(e){this.apiKey=e?.apiKey||process.env.COZE_WORKLOAD_IDENTITY_API_KEY||"",this.baseUrl=e?.baseUrl||process.env.COZE_INTEGRATION_BASE_URL||"",this.modelBaseUrl=e?.modelBaseUrl||process.env.COZE_INTEGRATION_MODEL_BASE_URL||"",this.retryTimes=e?.retryTimes??3,this.retryDelay=e?.retryDelay??1,this.timeout=e?.timeout??9e5}validate(){if(!this.apiKey)throw Error("API key is required. Set COZE_WORKLOAD_IDENTITY_API_KEY or provide apiKey in config.")}getHeaders(){if(!this.apiKey)throw Error("API key is required. Set COZE_WORKLOAD_IDENTITY_API_KEY or provide apiKey in config.");return{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"}}}class eS extends Error{constructor(e){super(e),this.name="ConfigurationError"}}class eb extends Error{statusCode;response;constructor(e,i,n){super(e),this.name="APIError",this.statusCode=i,this.response=n}}class eC extends Error{originalError;constructor(e,i){super(e),this.originalError=i,this.name="NetworkError"}}class eT extends Error{constructor(e){super(e),this.name="ValidationError"}}class ew{config;axiosInstance;verbose;constructor(e,i,n=!1){this.config=e||new ey,this.verbose=n,this.axiosInstance=Y.create({timeout:this.config.timeout,headers:{Authorization:`Bearer ${this.config.apiKey}`,"Content-Type":"application/json","X-Client-Sdk":"coze-coding-dev-sdk-typescript/0.3.0",...i}})}async request(e,i,n,t){let a=null;for(let r=0;r<=this.config.retryTimes;r++)try{0===r&&this.verbose&&this.logRequest(e,i,n,t);let a=await this.axiosInstance.request({method:e,url:i,data:n,...t});return 0===r&&this.verbose&&this.logResponse(a),a.data}catch(e){if(a=e,e.response){let i=e.response.status;if(i>=400&&i<500&&429!==i)throw new eb(e.response.data?.message||e.message,i,e.response.data)}r<this.config.retryTimes&&await this.sleep(1e3*this.config.retryDelay*(r+1))}if(a)if(Y.isAxiosError(a)&&a.response)throw new eb(a.response.data?.message||a.message,a.response.status,a.response.data);else throw new eC(a.message);throw new eC("Request failed after retries")}async requestWithResponse(e,i,n,t){let a=null;for(let r=0;r<=this.config.retryTimes;r++)try{0===r&&this.verbose&&this.logRequest(e,i,n,t);let a=await this.axiosInstance.request({method:e,url:i,data:n,...t});return 0===r&&this.verbose&&this.logResponse(a),a}catch(e){if(a=e,e.response){let i=e.response.status;if(i>=400&&i<500&&429!==i)throw new eb(e.response.data?.message||e.message,i,e.response.data)}r<this.config.retryTimes&&await this.sleep(1e3*this.config.retryDelay*(r+1))}if(a)if(Y.isAxiosError(a)&&a.response)throw new eb(a.response.data?.message||a.message,a.response.status,a.response.data);else throw new eC(a.message);throw new eC("Request failed after retries")}sanitizeHeaders(e){let i=["authorization","auth","api-key","apikey","api_key","x-api-key","x-auth-token","token","secret","password","passwd","pwd"],n={};for(let[t,a]of Object.entries(e)){let e=t.toLowerCase();i.some(i=>e.includes(i))?n[t]="***":n[t]=a}return n}logRequest(e,i,n,t){console.log("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log("\uD83D\uDCE4 HTTP Request"),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log(`Method: ${e}`),console.log(`URL: ${i}`);let a={};Object.assign(a,this.axiosInstance.defaults.headers.common||{},this.axiosInstance.defaults.headers[e.toLowerCase()]||{},t?.headers||{});let r=this.sanitizeHeaders(a);for(let[e,i]of(console.log("\nHeaders:"),Object.entries(r)))console.log(` ${e}: ${i}`);n&&(console.log("\nBody:"),console.log(JSON.stringify(n,null,2))),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")}logResponse(e){if(console.log("\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log("\uD83D\uDCE5 HTTP Response"),console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"),console.log(`Status: ${e.status} ${e.statusText}`),e.headers)for(let[i,n]of(console.log("\nHeaders:"),Object.entries(e.headers)))console.log(` ${i}: ${n}`);if(e.data){console.log("\nBody:");let i="string"==typeof e.data?e.data:JSON.stringify(e.data,null,2);console.log(i.length>1e3?i.substring(0,1e3)+"\n... (truncated)":i)}console.log("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n")}sleep(e){return new Promise(i=>setTimeout(i,e))}}let ex=["x-tt-logid","x-tt-env","x-use-ppe","x-tt-env-fe","x-run-mode","rpc-persist-res-rec-biz-scene","rpc-persist-coze-record-root-id","rpc-persist-res-rec-root-entity-type","rpc-persist-res-rec-root-entity-id","rpc-persist-res-rec-ext-info"];class eE{static extractForwardHeaders(e){let i={};return e instanceof Headers?ex.forEach(n=>{let t=e.get(n);t&&(i[n]=t)}):ex.forEach(n=>{let t=e[n]||e[n.toLowerCase()];t&&(i[n]=t)}),i}}class eL{static DEFAULT_MODEL="doubao-seedream-5-0-260128";static DEFAULT_SIZE="2K";static DEFAULT_CUSTOM_SIZE="2048x2048";static DEFAULT_WATERMARK=!0;static DEFAULT_RESPONSE_FORMAT="url";static DEFAULT_OPTIMIZE_PROMPT_MODE="standard";static DEFAULT_SEQUENTIAL_IMAGE_GENERATION="disabled";static DEFAULT_SEQUENTIAL_IMAGE_GENERATION_MAX_IMAGES=15;static MIN_TOTAL_PIXELS=3686400;static MAX_TOTAL_PIXELS=0x1000000;static MIN_ASPECT_RATIO=1/16;static MAX_ASPECT_RATIO=16;static PRESET_SIZES=["2K","4K"]}function validateImageSize(e){if(eL.PRESET_SIZES.includes(e))return e;let i=e.match(/^(\d+)x(\d+)$/);if(!i)throw Error(`Invalid size format. Must be ${JSON.stringify(eL.PRESET_SIZES)} or 'WIDTHxHEIGHT' format (e.g., 2048x2048). Got: ${e}`);let n=parseInt(i[1],10),t=parseInt(i[2],10);if(n<=0||t<=0)throw Error(`Width and height must be positive integers. Got: ${e}`);let a=n*t;if(a<eL.MIN_TOTAL_PIXELS||a>eL.MAX_TOTAL_PIXELS)throw Error(`Total pixels must be between ${eL.MIN_TOTAL_PIXELS.toLocaleString()} and ${eL.MAX_TOTAL_PIXELS.toLocaleString()}. Got: ${a.toLocaleString()} (${n}x${t})`);let r=n/t;if(r<eL.MIN_ASPECT_RATIO||r>eL.MAX_ASPECT_RATIO)throw Error(`Aspect ratio must be between 1:16 and 16:1. Got: ${n}:${t} (${r.toFixed(2)})`);return e}function validateImageSizeOrDefault(e){try{return validateImageSize(e)}catch{return eL.DEFAULT_SIZE}}class e_{response;constructor(e){this.response=e}get success(){return!this.response.error&&this.response.data.every(e=>!e.error)}get imageUrls(){return this.response.data.filter(e=>e.url).map(e=>e.url)}get imageB64List(){return this.response.data.filter(e=>e.b64_json).map(e=>e.b64_json)}get errorMessages(){let e=[];for(let i of(this.response.error&&e.push(`API Error: ${this.response.error.message||"Unknown error"}`),this.response.data))i.error&&e.push(`Image generation error: ${i.error.message||"Unknown error"}`);return e}}function buildImageGenerationApiRequest(e,i){let n=validateImageSizeOrDefault(e.size||eL.DEFAULT_SIZE);return{model:i,prompt:e.prompt,size:n,watermark:e.watermark??eL.DEFAULT_WATERMARK,image:e.image,response_format:e.responseFormat||eL.DEFAULT_RESPONSE_FORMAT,optimize_prompt_options:{mode:e.optimizePromptMode||eL.DEFAULT_OPTIMIZE_PROMPT_MODE},sequential_image_generation:e.sequentialImageGeneration||eL.DEFAULT_SEQUENTIAL_IMAGE_GENERATION,sequential_image_generation_options:{max_images:e.sequentialImageGenerationMaxImages||eL.DEFAULT_SEQUENTIAL_IMAGE_GENERATION_MAX_IMAGES}}}class eY extends ew{constructor(e,i,n=!1){super(e,i,n)}async generate(e){let i=e.model||eL.DEFAULT_MODEL,n=buildImageGenerationApiRequest(e,i),t=await this.request("POST",`${this.config.baseUrl}/api/v3/images/generations`,n);if(t.error)throw new eb(`API returned error: ${t.error.message||"Unknown error"}`,t.error.code?parseInt(t.error.code):500,t.error);for(let e of t.data)if(e.error)throw new eb(`Image generation failed: ${e.error.message||"Unknown error"}`,e.error.code?parseInt(e.error.code):500,e.error);return t}async batchGenerate(e){return Promise.all(e.map(e=>this.generate(e)))}getResponseHelper(e){return new e_(e)}}function convertToApiFormat(e){let i={};return e.query&&(i.Query=e.query),e.search_type&&(i.SearchType=e.search_type),void 0!==e.count&&(i.Count=e.count),void 0!==e.need_summary&&(i.NeedSummary=e.need_summary),e.time_range&&(i.TimeRange=e.time_range),e.filter&&(i.Filter={NeedContent:e.filter.need_content||!1,NeedUrl:e.filter.need_url||!1,Sites:e.filter.sites,BlockHosts:e.filter.block_hosts}),i}function convertFromApiFormat(e){let i={};return void 0!==e.Id&&(i.id=e.Id),void 0!==e.SortId&&(i.sort_id=e.SortId),void 0!==e.Title&&(i.title=e.Title),void 0!==e.SiteName&&(i.site_name=e.SiteName),void 0!==e.Url&&(i.url=e.Url),void 0!==e.Snippet&&(i.snippet=e.Snippet),void 0!==e.Summary&&(i.summary=e.Summary),void 0!==e.Content&&(i.content=e.Content),void 0!==e.PublishTime&&(i.publish_time=e.PublishTime),void 0!==e.LogoUrl&&(i.logo_url=e.LogoUrl),void 0!==e.RankScore&&(i.rank_score=e.RankScore),void 0!==e.AuthInfoDes&&(i.auth_info_des=e.AuthInfoDes),void 0!==e.AuthInfoLevel&&(i.auth_info_level=e.AuthInfoLevel),e.Image&&(i.image={url:e.Image.Url,width:e.Image.Width,height:e.Image.Height,shape:e.Image.Shape}),i}class eD extends ew{constructor(e,i,n=!1){super(e,i,n)}async search(e){let i,n=convertToApiFormat(e),t=await this.request("POST",`${this.config.baseUrl}/api/search_api/web_search`,n),a=t.ResponseMetadata||{};if(a.Error)throw new eb(`Search failed: ${a.Error}`,500,a.Error);let r=t.Result||{},o=[];if(r.WebResults)for(let e of r.WebResults)o.push(convertFromApiFormat(e));let u=[];if(r.ImageResults)for(let e of r.ImageResults)u.push(convertFromApiFormat(e));return r.Choices&&r.Choices.length>0&&(i=r.Choices[0].Message?.Content),{web_items:o,image_items:u,summary:i}}async webSearch(e,i=10,n=!0){return this.search({query:e,search_type:"web",count:i,need_summary:n})}async webSearchWithSummary(e,i=10){return this.search({query:e,search_type:"web_summary",count:i,need_summary:!0})}async imageSearch(e,i=10){return this.search({query:e,search_type:"image",count:i,need_summary:!1})}async advancedSearch(e,i={}){let n={need_content:i.needContent,need_url:i.needUrl,sites:i.sites,block_hosts:i.blockHosts};return this.search({query:e,search_type:i.searchType||"web",count:i.count||10,filter:n,need_summary:void 0===i.needSummary||i.needSummary,time_range:i.timeRange})}}class ev{static DEFAULT_SPEAKER="zh_female_xiaohe_uranus_bigtts";static DEFAULT_AUDIO_FORMAT="mp3";static DEFAULT_SAMPLE_RATE=24e3;static DEFAULT_SPEECH_RATE=0;static DEFAULT_LOUDNESS_RATE=0}function buildTTSApiRequest(e){let i={user:{uid:e.uid},req_params:{speaker:e.speaker||ev.DEFAULT_SPEAKER,audio_params:{format:e.audioFormat||ev.DEFAULT_AUDIO_FORMAT,sample_rate:e.sampleRate||ev.DEFAULT_SAMPLE_RATE,speech_rate:e.speechRate??ev.DEFAULT_SPEECH_RATE,loudness_rate:e.loudnessRate??ev.DEFAULT_LOUDNESS_RATE}}};return e.text?i.req_params.text=e.text:e.ssml&&(i.req_params.ssml=e.ssml),i}function buildASRApiRequest(e){let i={};return e.url?i.url=e.url:e.base64Data&&(i.data=e.base64Data),{user:{uid:e.uid},audio:i}}class eA extends ew{constructor(e,i,n=!1){super(e,i,n)}async synthesize(e){if(!e.text&&!e.ssml)throw new eT("必须提供 text 或 ssml 其中之一");let i=buildTTSApiRequest(e),n={...this.config.getHeaders(),Connection:"keep-alive"};try{let e=await Y.post(`${this.config.baseUrl}/api/v3/tts/unidirectional`,i,{headers:n,responseType:"stream",timeout:this.config.timeout});return await this.processStreamResponse(e)}catch(e){if(e.response)throw new eb(`TTS 请求失败: ${e.message}`,e.response.status,e.response.data);throw new eb(`TTS 请求异常: ${e.message}`,500)}}async processStreamResponse(e){return new Promise((i,n)=>{let t="",a=0,r="";e.data.on("data",e=>{let o=(r+=e.toString("utf-8")).split("\n");for(let e of(r=o.pop()||"",o))if(e.trim()&&e.startsWith("data:"))try{let r=e.replace("data:","").trim();if(!r)continue;let o=JSON.parse(r);if(0===o.code&&o.data){let e=Buffer.from(o.data,"base64");a+=e.length}else if(2e7===o.code){o.url&&(t=o.url),i({audioUri:t,audioSize:a});return}else if(o.code>0)return void n(new eb(`合成音频失败: ${o.message||""}`,o.code))}catch(e){n(new eb(`响应解析失败: ${e.message}`,500));return}}),e.data.on("end",()=>{t||0!==a?i({audioUri:t,audioSize:a}):n(new eb("未收到完整的音频数据",500))}),e.data.on("error",e=>{n(new eb(`流处理错误: ${e.message}`,500))})})}}class eN extends ew{constructor(e,i,n=!1){super(e,i,n)}async recognize(e){if(!e.url&&!e.base64Data)throw new eT("必须提供 url 或 base64Data 其中之一");let i=buildASRApiRequest(e);try{let e=await this.requestWithResponse("POST",`${this.config.baseUrl}/api/v3/auc/bigmodel/recognize/flash`,i),n=e.headers["x-api-status-code"]||"0",t=e.headers["x-api-message"]||"";if("20000000"!==n)throw new eb(`ASR 识别失败,状态码: ${n}, 错误信息: ${t}`,e.status,{code:n,message:t});let a=e.data.result||{};return{text:a.text||"",duration:a.duration,utterances:a.utterances,rawData:e.data}}catch(e){if(e instanceof eb)throw e;throw new eb(`ASR 请求异常: ${e.message}`,500)}}}class eP{static DEFAULT_MODEL="doubao-seedance-1-5-pro-251215";static DEFAULT_RESOLUTION="720p";static DEFAULT_RATIO="16:9";static DEFAULT_DURATION=5;static DEFAULT_WATERMARK=!0;static DEFAULT_CAMERA_FIXED=!1;static DEFAULT_GENERATE_AUDIO=!0}class eZ extends ew{baseUrl;constructor(e,i,n=!1){super(e,i,n),this.baseUrl=this.config.baseUrl}async videoGeneration(e,i){let n=(i?.maxWaitTime??900)*1e3,t={model:i?.model||eP.DEFAULT_MODEL,content:e};i?.callbackUrl&&(t.callback_url=i.callbackUrl),i?.returnLastFrame&&(t.return_last_frame=i.returnLastFrame),t.resolution=i?.resolution??eP.DEFAULT_RESOLUTION,t.ratio=i?.ratio??eP.DEFAULT_RATIO,t.duration=i?.duration??eP.DEFAULT_DURATION,t.watermark=i?.watermark??eP.DEFAULT_WATERMARK,i?.seed!==void 0&&(t.seed=i.seed),t.camerafixed=i?.camerafixed??eP.DEFAULT_CAMERA_FIXED,t.generate_audio=i?.generateAudio??eP.DEFAULT_GENERATE_AUDIO;let a=null,r=0;for(;r<3;)try{if(!(a=(await this.request("POST",`${this.baseUrl}/api/v3/contents/generations/tasks`,t)).id))throw new eb("创建视频生成任务失败:响应中缺少任务ID",500);this.verbose&&console.log(`视频生成任务创建成功,任务ID: ${a}`);break}catch(i){r++;let e=i instanceof Error?i.message:String(i);if(this.verbose&&console.error(`创建视频生成任务失败(尝试 ${r}/3): ${e}`),r>=3)throw new eb(`创建视频生成任务失败,已重试3次: ${e}`,500);if(e.toLowerCase().includes("rate limit")||e.includes("429")){let e=Math.min(2**r*1e3,1e4);this.verbose&&console.warn(`遇到速率限制,等待 ${e/1e3} 秒后重试...`),await this.sleep(e)}else if(e.toLowerCase().includes("timeout"))this.verbose&&console.warn("请求超时,等待 2 秒后重试..."),await this.sleep(2e3);else throw i}let o=Date.now(),u=0;for(;Date.now()-o<n;){u++;try{let e=await this.request("GET",`${this.baseUrl}/api/v3/contents/generations/tasks/${a}`),i=e.status;if(this.verbose&&console.log(`任务 ${a} 状态检查 #${u}: ${i}`),"succeeded"===i){let i=e.content?.video_url||null,n=e.content?.last_frame_url||"";if(!i)throw new eb(`视频生成成功但响应中缺少视频URL,任务ID: ${a}`,500);return this.verbose&&console.log(`视频生成成功,任务ID: ${a}, 视频URL: ${i}`),{videoUrl:i,response:e,lastFrameUrl:n}}if("failed"===i){let i=e.error_message||"未知错误";throw this.verbose&&console.error(`视频生成失败,任务ID: ${a}, 错误: ${i}`),new eb(`视频生成失败: ${i}`,500)}if("cancelled"===i)return this.verbose&&console.warn(`视频生成任务被取消,任务ID: ${a}`),{videoUrl:null,response:e,lastFrameUrl:""};else if("queued"===i||"running"===i){await this.sleep(5e3);continue}else{this.verbose&&console.warn(`未知的任务状态: ${i},任务ID: ${a}`),await this.sleep(5e3);continue}}catch(i){let e=i instanceof Error?i.message:String(i);if(this.verbose&&console.error(`查询任务状态失败,任务ID: ${a}, 错误: ${e}`),e.toLowerCase().includes("not found")||e.includes("404"))throw new eb(`任务不存在或已过期,任务ID: ${a}`,404);if(Date.now()-o>=n)throw i;await this.sleep(5e3);continue}}let s=Math.floor((Date.now()-o)/1e3);throw this.verbose&&console.error(`视频生成超时,任务ID: ${a}, 已等待: ${s}秒`),new eb(`视频生成超时,已等待 ${s} 秒,任务ID: ${a}`,408)}async videoGenerationAsync(e,i){return this.videoGeneration(e,i)}}class eR{static DEFAULT_URL_EXPIRE=86400;static MAX_URL_EXPIRE=2592e3;static MIN_URL_EXPIRE=1;static MIN_AUDIO_URL_EXPIRE=3600;static DEFAULT_FONT_TYPE="1525745";static DEFAULT_FONT_SIZE=36;static DEFAULT_FONT_COLOR="#FFFFFFFF";static DEFAULT_BACKGROUND_COLOR="#00000000";static DEFAULT_BACKGROUND_BORDER_WIDTH=0;static DEFAULT_FONT_POS_HEIGHT="10%";static DEFAULT_FONT_POS_X="0";static DEFAULT_FONT_POS_Y="90%";static DEFAULT_FONT_POS_WIDTH="100%";static DEFAULT_SYNC_METHOD="trim";static DEFAULT_SYNC_MODE="video";static DEFAULT_SUBTITLE_TYPE="srt";static DEFAULT_AUDIO_FORMAT="m4a"}class eM extends ew{baseUrl;constructor(e,i,n=!1){super(e,i,n),this.baseUrl=this.config.baseUrl}async extractByKeyFrame(e){let i=await this.request("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=frame_extractor_by_key_frame`,{url:e});if(0!==i.code)throw new eb(`Key frame extraction failed: ${i.msg||"Unknown error"}`,i.code);return i}async extractByInterval(e,i){let n=await this.request("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=frame_extractor_by_interval`,{url:e,interval_ms:i});if(0!==n.code)throw new eb(`Interval frame extraction failed: ${n.msg||"Unknown error"}`,n.code);return n}async extractByCount(e,i){let n=await this.request("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=frame_extractor_by_count`,{url:e,count:i});if(0!==n.code)throw new eb(`Count-based frame extraction failed: ${n.msg||"Unknown error"}`,n.code);return n}}class eJ extends ew{baseUrl;constructor(e,i,n=!1){super(e,i,n),this.baseUrl=this.config.baseUrl}validateUrlExpire(e,i=eR.MIN_URL_EXPIRE){if(void 0===e)return eR.DEFAULT_URL_EXPIRE;if(e<i||e>eR.MAX_URL_EXPIRE)throw new eb(`url_expire must be between ${i} and ${eR.MAX_URL_EXPIRE} seconds`,400);return e}async addSubtitles(e,i,n){let t=this.validateUrlExpire(n?.urlExpire),a={video:e,subtitle_config:{background_border_width:i.background_border_width??eR.DEFAULT_BACKGROUND_BORDER_WIDTH,font_type:i.font_type??eR.DEFAULT_FONT_TYPE,font_pos_config:{height:i.font_pos_config.height??eR.DEFAULT_FONT_POS_HEIGHT,pos_x:i.font_pos_config.pos_x??eR.DEFAULT_FONT_POS_X,pos_y:i.font_pos_config.pos_y??eR.DEFAULT_FONT_POS_Y,width:i.font_pos_config.width??eR.DEFAULT_FONT_POS_WIDTH}},url_expire:t};void 0!==i.border_width&&(a.subtitle_config.border_width=i.border_width),void 0!==i.font_color&&(a.subtitle_config.font_color=i.font_color),void 0!==i.font_size&&(a.subtitle_config.font_size=i.font_size),void 0!==i.background_color&&(a.subtitle_config.background_color=i.background_color),void 0!==i.border_color&&(a.subtitle_config.border_color=i.border_color),n?.subtitleUrl&&(a.subtitle_url=n.subtitleUrl),n?.textList&&n.textList.length>0&&(a.text_list=n.textList.map(e=>({end_time:e.end_time,start_time:e.start_time,text:e.text})));let r=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=add_subtitles`,a),o=r.headers["x-api-status-code"]||"0",u=r.headers["x-api-message"]||"";if("0"!==o)throw new eb(`Add subtitles failed, status code: ${o}, error: ${u}`,parseInt(o)||500);if(!r.data.url)throw new eb("Add subtitles failed: returned URL is empty",500);return r.data}async concatVideos(e,i){if(!e||0===e.length)throw new eb("videos list cannot be empty",400);let n={videos:e,url_expire:this.validateUrlExpire(i?.urlExpire)};i?.transitions&&i.transitions.length>0&&(n.transitions=i.transitions);let t=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=concat_videos`,n),a=t.headers["x-api-status-code"]||"0",r=t.headers["x-api-message"]||"";if("0"!==a)throw new eb(`Concat videos failed, status code: ${a}, error: ${r}`,parseInt(a)||500);if(!t.data.url)throw new eb("Concat videos failed: returned URL is empty",500);return t.data}async compileVideoAudio(e,i,n){let t={video:e,audio:i,url_expire:this.validateUrlExpire(n?.urlExpire)};n?.isVideoAudioSync!==void 0&&(t.is_video_audio_sync=n.isVideoAudioSync),n?.outputSync&&(t.output_sync={sync_method:n.outputSync.sync_method??eR.DEFAULT_SYNC_METHOD,sync_mode:n.outputSync.sync_mode??eR.DEFAULT_SYNC_MODE}),n?.isAudioReserve!==void 0&&(t.is_audio_reserve=n.isAudioReserve);let a=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=compile_video_audio`,t),r=a.headers["x-api-status-code"]||"0",o=a.headers["x-api-message"]||"";if("0"!==r)throw new eb(`Compile video audio failed, status code: ${r}, error: ${o}`,parseInt(r)||500);if(!a.data.url)throw new eb("Compile video audio failed: returned URL is empty",500);return a.data}async audioToSubtitle(e,i){let n={source:e,url_expire:this.validateUrlExpire(i?.urlExpire)};i?.subtitleType&&(n.subtitle_type=i.subtitleType);let t=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=audio_to_subtitle`,n),a=t.headers["x-api-status-code"]||"0",r=t.headers["x-api-message"]||"";if("0"!==a)throw new eb(`Audio to subtitle failed, status code: ${a}, error: ${r}`,parseInt(a)||500);if(!t.data.url)throw new eb("Audio to subtitle failed: returned URL is empty",500);return t.data}async extractAudio(e,i){let n={video:e,url_expire:this.validateUrlExpire(i?.urlExpire,eR.MIN_AUDIO_URL_EXPIRE)};i?.format&&(n.format=i.format);let t=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=audio_extract`,n),a=t.headers["x-api-status-code"]||"0",r=t.headers["x-api-message"]||"";if("0"!==a)throw new eb(`Extract audio failed, status code: ${a}, error: ${r}`,parseInt(a)||500);if(!t.data.url)throw new eb("Extract audio failed: returned URL is empty",500);return t.data}async videoTrim(e,i){let n=this.validateUrlExpire(i?.urlExpire);if(i?.startTime!==void 0&&i.startTime<0)throw new eb("start_time must be greater than or equal to 0",400);if(i?.endTime!==void 0&&i.endTime<0)throw new eb("end_time must be greater than or equal to 0",400);let t={video:e,url_expire:n};i?.startTime!==void 0&&(t.start_time=i.startTime),i?.endTime!==void 0&&(t.end_time=i.endTime);let a=await this.requestWithResponse("POST",`${this.baseUrl}/api/v1/integration/video_editing_utils?tool_name=video_trim`,t),r=a.headers["x-api-status-code"]||"0",o=a.headers["x-api-message"]||"";if("0"!==r)throw new eb(`Video trim failed, status code: ${r}, error: ${o}`,parseInt(r)||500);if(!a.data.url)throw new eb("Video trim failed: returned URL is empty",500);return a.data}}let ek={MODEL:"doubao-seed-1-8-251228",THINKING:"disabled",CACHING:"disabled",TEMPERATURE:1,STREAMING:!0};class eB{config;customHeaders;constructor(e,i){this.config=e||new ey,this.customHeaders=i}createLLM(e,i,n){let t={};t.thinking={type:e.thinking??ek.THINKING},e.caching&&"disabled"!==e.caching&&(t.caching={type:e.caching});let a={Authorization:`Bearer ${this.config.apiKey}`,"X-Client-Sdk":"coze-coding-dev-sdk-typescript/0.3.0",...this.customHeaders,...n};return i&&(a["X-Previous-Response-Id"]=i),new D({model:e.model||ek.MODEL,apiKey:this.config.apiKey,configuration:{baseURL:this.config.modelBaseUrl,defaultHeaders:a},streaming:void 0!==e.streaming?e.streaming:ek.STREAMING,temperature:void 0!==e.temperature?e.temperature:ek.TEMPERATURE,modelKwargs:Object.keys(t).length>0?t:void 0})}convertMessages(e){return e.map(e=>{let i=this.convertContent(e.content);switch(e.role){case"system":return new N(i);case"user":return new A(i);case"assistant":return new v(i);default:throw Error(`Unknown message role: ${e.role}`)}})}convertContent(e){return"string"==typeof e?e:e.map(e=>{if("text"===e.type)return{type:"text",text:e.text};if("image_url"===e.type){let i={url:e.image_url.url};return e.image_url.detail&&(i.detail=e.image_url.detail),{type:"image_url",image_url:i}}if("video_url"===e.type){let i={url:e.video_url.url};return void 0!==e.video_url.fps&&(i.fps=e.video_url.fps),{type:"video_url",video_url:i}}return e})}async *stream(e,i={},n,t){let a=this.createLLM(i,n,t),r=this.convertMessages(e);for await(let e of(await a.stream(r)))yield e}async invoke(e,i={},n,t){let a="";for await(let r of this.stream(e,i,n,t))r.content&&(a+=r.content.toString());return{content:a}}}var eH=((H={})[H.TEXT=0]="TEXT",H[H.URL=1]="URL",H[H.URI=2]="URI",H);class eF extends ew{baseUrl;constructor(e,i,n=!1){super(e,i,n),this.baseUrl=this.config.baseUrl}async search(e,i,n=5,t=0,a){let r={query:e,top_k:n,min_score:t};i&&(r.dataset=i);let o=`${this.baseUrl}/v1/knowledge_base/recall`,u={...a};this.config.apiKey&&(u["x-coze-token"]=`Bearer ${this.config.apiKey}`);let s=await this.request("POST",o,r,{headers:u});return{chunks:(s.data||[]).map(e=>({content:e.slice||"",score:e.score||0,chunk_id:e.chunk_id,doc_id:e.doc_id})),code:s.code||0,msg:s.msg||""}}async addDocuments(e,i,n,t){let a={dataset:i,data:e};n&&(a.chunk_config=Object.fromEntries(Object.entries(n).filter(([e,i])=>void 0!==i)));let r=`${this.baseUrl}/v1/knowledge_base/batch_import`,o={...t};this.config.apiKey&&(o["x-coze-token"]=`Bearer ${this.config.apiKey}`);let u=await this.request("POST",r,a,{headers:o}),s=u.msg||"";return 0===u.code&&(s="成功!文档正在异步导入中,请稍候。您可以查看数据库中的 'knowledge' schema 来验证导入状态。"),{doc_ids:u.doc_ids,code:u.code||0,msg:s}}}let eX=Symbol.for("drizzle:entityKind");function entity_is(e,i){if(!e||"object"!=typeof e)return!1;if(e instanceof i)return!0;if(!Object.prototype.hasOwnProperty.call(i,eX))throw Error(`Class "${i.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let n=Object.getPrototypeOf(e).constructor;if(n)for(;n;){if(eX in n&&n[eX]===i[eX])return!0;n=Object.getPrototypeOf(n)}return!1}Symbol.for("drizzle:hasOwnEntityKind");class eI{static [eX]="ConsoleLogWriter";write(e){console.log(e)}}class eO{static [eX]="DefaultLogger";writer;constructor(e){this.writer=e?.writer??new eI}logQuery(e,i){let n=i.map(e=>{try{return JSON.stringify(e)}catch{return String(e)}}),t=n.length?` -- params: [${n.join(", ")}]`:"";this.writer.write(`Query: ${e}${t}`)}}class eQ{static [eX]="NoopLogger";logQuery(){}}class eG{constructor(e,i){this.table=e,this.config=i,this.name=i.name,this.keyAsName=i.keyAsName,this.notNull=i.notNull,this.default=i.default,this.defaultFn=i.defaultFn,this.onUpdateFn=i.onUpdateFn,this.hasDefault=i.hasDefault,this.primary=i.primaryKey,this.isUnique=i.isUnique,this.uniqueName=i.uniqueName,this.uniqueType=i.uniqueType,this.dataType=i.dataType,this.columnType=i.columnType,this.generated=i.generated,this.generatedIdentity=i.generatedIdentity}static [eX]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue(e){return e}mapToDriverValue(e){return e}shouldDisableInsert(){return void 0!==this.config.generated&&"byDefault"!==this.config.generated.type}}class eU{static [eX]="ColumnBuilder";config;constructor(e,i,n){this.config={name:e,keyAsName:""===e,notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:i,columnType:n,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default(e){return this.config.default=e,this.config.hasDefault=!0,this}$defaultFn(e){return this.config.defaultFn=e,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn(e){return this.config.onUpdateFn=e,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName(e){""===this.config.name&&(this.config.name=e)}}let eK=Symbol.for("drizzle:Name");class e${static [eX]="PgForeignKeyBuilder";reference;_onUpdate="no action";_onDelete="no action";constructor(e,i){this.reference=()=>{let{name:i,columns:n,foreignColumns:t}=e();return{name:i,columns:n,foreignTable:t[0].table,foreignColumns:t}},i&&(this._onUpdate=i.onUpdate,this._onDelete=i.onDelete)}onUpdate(e){return this._onUpdate=void 0===e?"no action":e,this}onDelete(e){return this._onDelete=void 0===e?"no action":e,this}build(e){return new ez(e,this)}}class ez{constructor(e,i){this.table=e,this.reference=i.reference,this.onUpdate=i._onUpdate,this.onDelete=i._onDelete}static [eX]="PgForeignKey";reference;onUpdate;onDelete;getName(){let{name:e,columns:i,foreignColumns:n}=this.reference(),t=i.map(e=>e.name),a=n.map(e=>e.name),r=[this.table[eK],...t,n[0].table[eK],...a];return e??`${r.join("_")}_fk`}}function iife(e,...i){return e(...i)}function uniqueKeyName(e,i){return`${e[eK]}_${i.join("_")}_unique`}class eW{constructor(e,i){this.name=i,this.columns=e}static [eX]=null;columns;nullsNotDistinctConfig=!1;nullsNotDistinct(){return this.nullsNotDistinctConfig=!0,this}build(e){return new eV(e,this.columns,this.nullsNotDistinctConfig,this.name)}}class ej{static [eX]=null;name;constructor(e){this.name=e}on(...e){return new eW(e,this.name)}}class eV{constructor(e,i,n,t){this.table=e,this.columns=i,this.name=t??uniqueKeyName(this.table,this.columns.map(e=>e.name)),this.nullsNotDistinct=n}static [eX]=null;columns;name;nullsNotDistinct=!1;getName(){return this.name}}function parsePgArrayValue(e,i,n){for(let t=i;t<e.length;t++){let a=e[t];if("\\"===a){t++;continue}if('"'===a)return[e.slice(i,t).replace(/\\/g,""),t+1];if(!n&&(","===a||"}"===a))return[e.slice(i,t).replace(/\\/g,""),t]}return[e.slice(i).replace(/\\/g,""),e.length]}function parsePgNestedArray(e,i=0){let n=[],t=i,a=!1;for(;t<e.length;){let r=e[t];if(","===r){(a||t===i)&&n.push(""),a=!0,t++;continue}if(a=!1,"\\"===r){t+=2;continue}if('"'===r){let[i,a]=parsePgArrayValue(e,t+1,!0);n.push(i),t=a;continue}if("}"===r)return[n,t+1];if("{"===r){let[i,a]=parsePgNestedArray(e,t+1);n.push(i),t=a;continue}let[o,u]=parsePgArrayValue(e,t,!1);n.push(o),t=u}return[n,t]}function parsePgArray(e){let[i]=parsePgNestedArray(e,1);return i}function makePgArray(e){return`{${e.map(e=>Array.isArray(e)?makePgArray(e):"string"==typeof e?`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:`${e}`).join(",")}}`}class e0 extends eU{foreignKeyConfigs=[];static [eX]="PgColumnBuilder";array(e){return new e4(this.config.name,this,e)}references(e,i={}){return this.foreignKeyConfigs.push({ref:e,actions:i}),this}unique(e,i){return this.config.isUnique=!0,this.config.uniqueName=e,this.config.uniqueType=i?.nulls,this}generatedAlwaysAs(e){return this.config.generated={as:e,type:"always",mode:"stored"},this}buildForeignKeys(e,i){return this.foreignKeyConfigs.map(({ref:n,actions:t})=>iife((n,t)=>{let a=new e$(()=>({columns:[e],foreignColumns:[n()]}));return t.onUpdate&&a.onUpdate(t.onUpdate),t.onDelete&&a.onDelete(t.onDelete),a.build(i)},n,t))}buildExtraConfigColumn(e){return new e3(e,this.config)}}class e1 extends eG{constructor(e,i){i.uniqueName||(i.uniqueName=uniqueKeyName(e,[i.name])),super(e,i),this.table=e}static [eX]="PgColumn"}class e3 extends e1{static [eX]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op(e){return this.indexConfig.opClass=e,this}}class e2{static [eX]=null;constructor(e,i,n,t){this.name=e,this.keyAsName=i,this.type=n,this.indexConfig=t}name;keyAsName;type;indexConfig}class e4 extends e0{static [eX]="PgArrayBuilder";constructor(e,i,n){super(e,"array","PgArray"),this.config.baseBuilder=i,this.config.size=n}build(e){let i=this.config.baseBuilder.build(e);return new e8(e,this.config,i)}}class e8 extends e1{constructor(e,i,n,t){super(e,i),this.baseColumn=n,this.range=t,this.size=i.size}size;static [eX]="PgArray";getSQLType(){return`${this.baseColumn.getSQLType()}[${"number"==typeof this.size?this.size:""}]`}mapFromDriverValue(e){return"string"==typeof e&&(e=parsePgArray(e)),e.map(e=>this.baseColumn.mapFromDriverValue(e))}mapToDriverValue(e,i=!1){let n=e.map(e=>null===e?null:entity_is(this.baseColumn,e8)?this.baseColumn.mapToDriverValue(e,!0):this.baseColumn.mapToDriverValue(e));return i?n:makePgArray(n)}}class e6 extends e0{static [eX]="PgEnumObjectColumnBuilder";constructor(e,i){super(e,"string","PgEnumObjectColumn"),this.config.enum=i}build(e){return new e5(e,this.config)}}class e5 extends e1{static [eX]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor(e,i){super(e,i),this.enum=i.enum}getSQLType(){return this.enum.enumName}}let e7=Symbol.for("drizzle:isPgEnum");function isPgEnum(e){return!!e&&"function"==typeof e&&e7 in e&&!0===e[e7]}class e9 extends e0{static [eX]="PgEnumColumnBuilder";constructor(e,i){super(e,"string","PgEnumColumn"),this.config.enum=i}build(e){return new ie(e,this.config)}}class ie extends e1{static [eX]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor(e,i){super(e,i),this.enum=i.enum}getSQLType(){return this.enum.enumName}}class it{static [eX]="Subquery";constructor(e,i,n,t=!1,a=[]){this._={brand:"Subquery",sql:e,selectedFields:i,alias:n,isWith:t,usedTables:a}}}class ia extends it{static [eX]="WithSubquery"}let ir=(n,t)=>e?(i||(i=e.trace.getTracer("drizzle-orm","0.45.1")),iife((e,i)=>i.startActiveSpan(n,i=>{try{return t(i)}catch(n){throw i.setStatus({code:e.SpanStatusCode.ERROR,message:n instanceof Error?n.message:"Unknown error"}),n}finally{i.end()}}),e,i)):t(),io=Symbol.for("drizzle:ViewBaseConfig"),iu=Symbol.for("drizzle:Schema"),is=Symbol.for("drizzle:Columns"),il=Symbol.for("drizzle:ExtraConfigColumns"),ih=Symbol.for("drizzle:OriginalName"),ig=Symbol.for("drizzle:BaseName"),ic=Symbol.for("drizzle:IsAlias"),id=Symbol.for("drizzle:ExtraConfigBuilder"),ip=Symbol.for("drizzle:IsDrizzleTable");class im{static [eX]="Table";static Symbol={Name:eK,Schema:iu,OriginalName:ih,Columns:is,ExtraConfigColumns:il,BaseName:ig,IsAlias:ic,ExtraConfigBuilder:id};[eK];[ih];[iu];[is];[il];[ig];[ic]=!1;[ip]=!0;[id]=void 0;constructor(e,i,n){this[eK]=this[ih]=e,this[iu]=i,this[ig]=n}}function getTableUniqueName(e){return`${e[iu]??"public"}.${e[eK]}`}class iy{static [eX]=null}function isSQLWrapper(e){return null!=e&&"function"==typeof e.getSQL}function mergeQueries(e){let i={sql:"",params:[]};for(let n of e)i.sql+=n.sql,i.params.push(...n.params),n.typings?.length&&(i.typings||(i.typings=[]),i.typings.push(...n.typings));return i}class iS{static [eX]="StringChunk";value;constructor(e){this.value=Array.isArray(e)?e:[e]}getSQL(){return new ib([this])}}class ib{constructor(e){for(let i of(this.queryChunks=e,e))if(entity_is(i,im)){let e=i[im.Symbol.Schema];this.usedTables.push(void 0===e?i[im.Symbol.Name]:e+"."+i[im.Symbol.Name])}}static [eX]="SQL";decoder=iT;shouldInlineParams=!1;usedTables=[];append(e){return this.queryChunks.push(...e.queryChunks),this}toQuery(e){return ir("drizzle.buildSQL",i=>{let n=this.buildQueryFromSourceParams(this.queryChunks,e);return i?.setAttributes({"drizzle.query.text":n.sql,"drizzle.query.params":JSON.stringify(n.params)}),n})}buildQueryFromSourceParams(e,i){let n=Object.assign({},i,{inlineParams:i.inlineParams||this.shouldInlineParams,paramStartIndex:i.paramStartIndex||{value:0}}),{casing:t,escapeName:a,escapeParam:r,prepareTyping:o,inlineParams:u,paramStartIndex:s}=n;return mergeQueries(e.map(e=>{if(entity_is(e,iS))return{sql:e.value.join(""),params:[]};if(entity_is(e,iC))return{sql:a(e.value),params:[]};if(void 0===e)return{sql:"",params:[]};if(Array.isArray(e)){let i=[new iS("(")];for(let[n,t]of e.entries())i.push(t),n<e.length-1&&i.push(new iS(", "));return i.push(new iS(")")),this.buildQueryFromSourceParams(i,n)}if(entity_is(e,ib))return this.buildQueryFromSourceParams(e.queryChunks,{...n,inlineParams:u||e.shouldInlineParams});if(entity_is(e,im)){let i=e[im.Symbol.Schema],n=e[im.Symbol.Name];return{sql:void 0===i||e[ic]?a(n):a(i)+"."+a(n),params:[]}}if(entity_is(e,eG)){let n=t.getColumnCasing(e);if("indexes"===i.invokeSource)return{sql:a(n),params:[]};let r=e.table[im.Symbol.Schema];return{sql:e.table[ic]||void 0===r?a(e.table[im.Symbol.Name])+"."+a(n):a(r)+"."+a(e.table[im.Symbol.Name])+"."+a(n),params:[]}}if(entity_is(e,iD)){let i=e[io].schema,n=e[io].name;return{sql:void 0===i||e[io].isAlias?a(n):a(i)+"."+a(n),params:[]}}if(entity_is(e,ix)){if(entity_is(e.value,i_))return{sql:r(s.value++,e),params:[e],typings:["none"]};let i=null===e.value?null:e.encoder.mapToDriverValue(e.value);if(entity_is(i,ib))return this.buildQueryFromSourceParams([i],n);if(u)return{sql:this.mapInlineParam(i,n),params:[]};let t=["none"];return o&&(t=[o(e.encoder)]),{sql:r(s.value++,i),params:[i],typings:t}}return entity_is(e,i_)?{sql:r(s.value++,e),params:[e],typings:["none"]}:entity_is(e,ib.Aliased)&&void 0!==e.fieldAlias?{sql:a(e.fieldAlias),params:[]}:entity_is(e,it)?e._.isWith?{sql:a(e._.alias),params:[]}:this.buildQueryFromSourceParams([new iS("("),e._.sql,new iS(") "),new iC(e._.alias)],n):isPgEnum(e)?e.schema?{sql:a(e.schema)+"."+a(e.enumName),params:[]}:{sql:a(e.enumName),params:[]}:isSQLWrapper(e)?e.shouldOmitSQLParens?.()?this.buildQueryFromSourceParams([e.getSQL()],n):this.buildQueryFromSourceParams([new iS("("),e.getSQL(),new iS(")")],n):u?{sql:this.mapInlineParam(e,n),params:[]}:{sql:r(s.value++,e),params:[e],typings:["none"]}}))}mapInlineParam(e,{escapeString:i}){if(null===e)return"null";if("number"==typeof e||"boolean"==typeof e)return e.toString();if("string"==typeof e)return i(e);if("object"==typeof e){let n=e.toString();return"[object Object]"===n?i(JSON.stringify(e)):i(n)}throw Error("Unexpected param value: "+e)}getSQL(){return this}as(e){return void 0===e?this:new ib.Aliased(this,e)}mapWith(e){return this.decoder="function"==typeof e?{mapFromDriverValue:e}:e,this}inlineParams(){return this.shouldInlineParams=!0,this}if(e){return e?this:void 0}}class iC{constructor(e){this.value=e}static [eX]="Name";brand;getSQL(){return new ib([this])}}function isDriverValueEncoder(e){return"object"==typeof e&&null!==e&&"mapToDriverValue"in e&&"function"==typeof e.mapToDriverValue}let iT={mapFromDriverValue:e=>e},iw={mapToDriverValue:e=>e};({...iT,...iw});class ix{constructor(e,i=iw){this.value=e,this.encoder=i}static [eX]="Param";brand;getSQL(){return new ib([this])}}function sql_sql(e,...i){let n=[];for(let[t,a]of((i.length>0||e.length>0&&""!==e[0])&&n.push(new iS(e[0])),i.entries()))n.push(a,new iS(e[t+1]));return new ib(n)}(F=sql_sql||(sql_sql={})).empty=function(){return new ib([])},F.fromList=function(e){return new ib(e)},F.raw=function(e){return new ib([new iS(e)])},F.join=function(e,i){let n=[];for(let[t,a]of e.entries())t>0&&void 0!==i&&n.push(i),n.push(a);return new ib(n)},F.identifier=function(e){return new iC(e)},F.placeholder=function(e){return new i_(e)},F.param=function(e,i){return new ix(e,i)};var iE=ib||(ib={});class iL{constructor(e,i){this.sql=e,this.fieldAlias=i}static [eX]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new iL(this.sql,this.fieldAlias)}}iE.Aliased=iL;class i_{constructor(e){this.name=e}static [eX]="Placeholder";getSQL(){return new ib([this])}}function fillPlaceholders(e,i){return e.map(e=>{if(entity_is(e,i_)){if(!(e.name in i))throw Error(`No value for placeholder "${e.name}" was provided`);return i[e.name]}if(entity_is(e,ix)&&entity_is(e.value,i_)){if(!(e.value.name in i))throw Error(`No value for placeholder "${e.value.name}" was provided`);return e.encoder.mapToDriverValue(i[e.value.name])}return e})}let iY=Symbol.for("drizzle:IsDrizzleView");class iD{static [eX]="View";[io];[iY]=!0;constructor({name:e,schema:i,selectedFields:n,query:t}){this[io]={name:e,originalName:e,schema:i,selectedFields:n,query:t,isExisting:!t,isAlias:!1}}getSQL(){return new ib([this])}}eG.prototype.getSQL=function(){return new ib([this])},im.prototype.getSQL=function(){return new ib([this])},it.prototype.getSQL=function(){return new ib([this])};class iv{constructor(e){this.table=e}static [eX]="ColumnAliasProxyHandler";get(e,i){return"table"===i?this.table:e[i]}}class iA{constructor(e,i){this.alias=e,this.replaceOriginalName=i}static [eX]="TableAliasProxyHandler";get(e,i){if(i===im.Symbol.IsAlias)return!0;if(i===im.Symbol.Name||this.replaceOriginalName&&i===im.Symbol.OriginalName)return this.alias;if(i===io)return{...e[io],name:this.alias,isAlias:!0};if(i===im.Symbol.Columns){let i=e[im.Symbol.Columns];if(!i)return i;let n={};return Object.keys(i).map(t=>{n[t]=new Proxy(i[t],new iv(new Proxy(e,this)))}),n}let n=e[i];return entity_is(n,eG)?new Proxy(n,new iv(new Proxy(e,this))):n}}class iN{constructor(e){this.alias=e}static [eX]=null;get(e,i){return"sourceTable"===i?aliasedTable(e.sourceTable,this.alias):e[i]}}function aliasedTable(e,i){return new Proxy(e,new iA(i,!1))}function aliasedTableColumn(e,i){return new Proxy(e,new iv(new Proxy(e.table,new iA(i,!1))))}function mapColumnsInAliasedSQLToAlias(e,i){return new ib.Aliased(mapColumnsInSQLToAlias(e.sql,i),e.fieldAlias)}function mapColumnsInSQLToAlias(e,i){return sql_sql.join(e.queryChunks.map(e=>entity_is(e,eG)?aliasedTableColumn(e,i):entity_is(e,ib)?mapColumnsInSQLToAlias(e,i):entity_is(e,ib.Aliased)?mapColumnsInAliasedSQLToAlias(e,i):e))}function toSnakeCase(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).map(e=>e.toLowerCase()).join("_")}function toCamelCase(e){return(e.replace(/['\u2019]/g,"").match(/[\da-z]+|[A-Z]+(?![a-z])|[A-Z][\da-z]+/g)??[]).reduce((e,i,n)=>e+(0===n?i.toLowerCase():`${i[0].toUpperCase()}${i.slice(1)}`),"")}function noopCase(e){return e}class iP{static [eX]="CasingCache";cache={};cachedTables={};convert;constructor(e){this.convert="snake_case"===e?toSnakeCase:"camelCase"===e?toCamelCase:noopCase}getColumnCasing(e){if(!e.keyAsName)return e.name;let i=e.table[im.Symbol.Schema]??"public",n=e.table[im.Symbol.OriginalName],t=`${i}.${n}.${e.name}`;return this.cache[t]||this.cacheTable(e.table),this.cache[t]}cacheTable(e){let i=e[im.Symbol.Schema]??"public",n=e[im.Symbol.OriginalName],t=`${i}.${n}`;if(!this.cachedTables[t]){for(let i of Object.values(e[im.Symbol.Columns])){let e=`${t}.${i.name}`;this.cache[e]=this.convert(i.name)}this.cachedTables[t]=!0}}clearCache(){this.cache={},this.cachedTables={}}}class iZ extends Error{static [eX]="DrizzleError";constructor({message:e,cause:i}){super(e),this.name="DrizzleError",this.cause=i}}class iR extends Error{constructor(e,i,n){super(`Failed query: ${e}
14
14
  params: ${i}`),this.query=e,this.params=i,this.cause=n,Error.captureStackTrace(this,iR),n&&(this.cause=n)}}class iM extends iZ{static [eX]="TransactionRollbackError";constructor(){super({message:"Rollback"})}}class iJ extends e0{static [eX]="PgJsonbBuilder";constructor(e){super(e,"json","PgJsonb")}build(e){return new ik(e,this.config)}}class ik extends e1{static [eX]="PgJsonb";constructor(e,i){super(e,i)}getSQLType(){return"jsonb"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if("string"==typeof e)try{return JSON.parse(e)}catch{}return e}}class iB extends e0{static [eX]="PgJsonBuilder";constructor(e){super(e,"json","PgJson")}build(e){return new iH(e,this.config)}}class iH extends e1{static [eX]="PgJson";constructor(e,i){super(e,i)}getSQLType(){return"json"}mapToDriverValue(e){return JSON.stringify(e)}mapFromDriverValue(e){if("string"==typeof e)try{return JSON.parse(e)}catch{}return e}}class iF extends e0{static [eX]="PgNumericBuilder";constructor(e,i,n){super(e,"string","PgNumeric"),this.config.precision=i,this.config.scale=n}build(e){return new iX(e,this.config)}}class iX extends e1{static [eX]="PgNumeric";precision;scale;constructor(e,i){super(e,i),this.precision=i.precision,this.scale=i.scale}mapFromDriverValue(e){return"string"==typeof e?e:String(e)}getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}}class iI extends e0{static [eX]="PgNumericNumberBuilder";constructor(e,i,n){super(e,"number","PgNumericNumber"),this.config.precision=i,this.config.scale=n}build(e){return new iO(e,this.config)}}class iO extends e1{static [eX]="PgNumericNumber";precision;scale;constructor(e,i){super(e,i),this.precision=i.precision,this.scale=i.scale}mapFromDriverValue(e){return"number"==typeof e?e:Number(e)}mapToDriverValue=String;getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}}class iQ extends e0{static [eX]="PgNumericBigIntBuilder";constructor(e,i,n){super(e,"bigint","PgNumericBigInt"),this.config.precision=i,this.config.scale=n}build(e){return new iG(e,this.config)}}class iG extends e1{static [eX]="PgNumericBigInt";precision;scale;constructor(e,i){super(e,i),this.precision=i.precision,this.scale=i.scale}mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return void 0!==this.precision&&void 0!==this.scale?`numeric(${this.precision}, ${this.scale})`:void 0===this.precision?"numeric":`numeric(${this.precision})`}}class iU extends e0{static [eX]="PgDateColumnBaseBuilder";defaultNow(){return this.default(sql_sql`now()`)}}class iq extends iU{constructor(e,i,n){super(e,"string","PgTime"),this.withTimezone=i,this.precision=n,this.config.withTimezone=i,this.config.precision=n}static [eX]="PgTimeBuilder";build(e){return new iK(e,this.config)}}class iK extends e1{static [eX]="PgTime";withTimezone;precision;constructor(e,i){super(e,i),this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){let e=void 0===this.precision?"":`(${this.precision})`;return`time${e}${this.withTimezone?" with time zone":""}`}}class i$ extends iU{static [eX]="PgTimestampBuilder";constructor(e,i,n){super(e,"date","PgTimestamp"),this.config.withTimezone=i,this.config.precision=n}build(e){return new iz(e,this.config)}}class iz extends e1{static [eX]="PgTimestamp";withTimezone;precision;constructor(e,i){super(e,i),this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){let e=void 0===this.precision?"":` (${this.precision})`;return`timestamp${e}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(e){return"string"==typeof e?new Date(this.withTimezone?e:e+"+0000"):e}mapToDriverValue=e=>e.toISOString()}class iW extends iU{static [eX]="PgTimestampStringBuilder";constructor(e,i,n){super(e,"string","PgTimestampString"),this.config.withTimezone=i,this.config.precision=n}build(e){return new ij(e,this.config)}}class ij extends e1{static [eX]="PgTimestampString";withTimezone;precision;constructor(e,i){super(e,i),this.withTimezone=i.withTimezone,this.precision=i.precision}getSQLType(){let e=void 0===this.precision?"":`(${this.precision})`;return`timestamp${e}${this.withTimezone?" with time zone":""}`}mapFromDriverValue(e){if("string"==typeof e)return e;let i=e.toISOString().slice(0,-1).replace("T"," ");if(this.withTimezone){let n=e.getTimezoneOffset();return`${i}${n<=0?"+":"-"}${Math.floor(Math.abs(n)/60).toString().padStart(2,"0")}`}return i}}class iV extends iU{static [eX]="PgDateBuilder";constructor(e){super(e,"date","PgDate")}build(e){return new i0(e,this.config)}}class i0 extends e1{static [eX]="PgDate";getSQLType(){return"date"}mapFromDriverValue(e){return"string"==typeof e?new Date(e):e}mapToDriverValue(e){return e.toISOString()}}class i1 extends iU{static [eX]="PgDateStringBuilder";constructor(e){super(e,"string","PgDateString")}build(e){return new i3(e,this.config)}}class i3 extends e1{static [eX]="PgDateString";getSQLType(){return"date"}mapFromDriverValue(e){return"string"==typeof e?e:e.toISOString().slice(0,-14)}}class i2 extends e0{static [eX]="PgUUIDBuilder";constructor(e){super(e,"string","PgUUID")}defaultRandom(){return this.default(sql_sql`gen_random_uuid()`)}build(e){return new i4(e,this.config)}}class i4 extends e1{static [eX]="PgUUID";getSQLType(){return"uuid"}}let i8=Symbol.for("drizzle:PgInlineForeignKeys"),i6=Symbol.for("drizzle:EnableRLS");class i5 extends im{static [eX]="PgTable";static Symbol=Object.assign({},im.Symbol,{InlineForeignKeys:i8,EnableRLS:i6});[i8]=[];[i6]=!1;[im.Symbol.ExtraConfigBuilder]=void 0;[im.Symbol.ExtraConfigColumns]={}}class i7{static [eX]="PgPrimaryKeyBuilder";columns;name;constructor(e,i){this.columns=e,this.name=i}build(e){return new i9(e,this.columns,this.name)}}class i9{constructor(e,i,n){this.table=e,this.columns=i,this.name=n}static [eX]="PgPrimaryKey";columns;name;getName(){return this.name??`${this.table[i5.Symbol.Name]}_${this.columns.map(e=>e.name).join("_")}_pk`}}function bindIfParam(e,i){return!isDriverValueEncoder(i)||isSQLWrapper(e)||entity_is(e,ix)||entity_is(e,i_)||entity_is(e,eG)||entity_is(e,im)||entity_is(e,iD)?e:new ix(e,i)}let eq=(e,i)=>sql_sql`${e} = ${bindIfParam(i,e)}`,ne=(e,i)=>sql_sql`${e} <> ${bindIfParam(i,e)}`;function and(...e){let i=e.filter(e=>void 0!==e);if(0!==i.length)return new ib(1===i.length?i:[new iS("("),sql_sql.join(i,new iS(" and ")),new iS(")")])}function or(...e){let i=e.filter(e=>void 0!==e);if(0!==i.length)return new ib(1===i.length?i:[new iS("("),sql_sql.join(i,new iS(" or ")),new iS(")")])}function not(e){return sql_sql`not ${e}`}let gt=(e,i)=>sql_sql`${e} > ${bindIfParam(i,e)}`,gte=(e,i)=>sql_sql`${e} >= ${bindIfParam(i,e)}`,lt=(e,i)=>sql_sql`${e} < ${bindIfParam(i,e)}`,lte=(e,i)=>sql_sql`${e} <= ${bindIfParam(i,e)}`;function inArray(e,i){return Array.isArray(i)?0===i.length?sql_sql`false`:sql_sql`${e} in ${i.map(i=>bindIfParam(i,e))}`:sql_sql`${e} in ${bindIfParam(i,e)}`}function notInArray(e,i){return Array.isArray(i)?0===i.length?sql_sql`true`:sql_sql`${e} not in ${i.map(i=>bindIfParam(i,e))}`:sql_sql`${e} not in ${bindIfParam(i,e)}`}function isNull(e){return sql_sql`${e} is null`}function isNotNull(e){return sql_sql`${e} is not null`}function exists(e){return sql_sql`exists ${e}`}function notExists(e){return sql_sql`not exists ${e}`}function between(e,i,n){return sql_sql`${e} between ${bindIfParam(i,e)} and ${bindIfParam(n,e)}`}function notBetween(e,i,n){return sql_sql`${e} not between ${bindIfParam(i,e)} and ${bindIfParam(n,e)}`}function like(e,i){return sql_sql`${e} like ${i}`}function notLike(e,i){return sql_sql`${e} not like ${i}`}function ilike(e,i){return sql_sql`${e} ilike ${i}`}function notIlike(e,i){return sql_sql`${e} not ilike ${i}`}function asc(e){return sql_sql`${e} asc`}function select_desc(e){return sql_sql`${e} desc`}class ni{constructor(e,i,n){this.sourceTable=e,this.referencedTable=i,this.relationName=n,this.referencedTableName=i[im.Symbol.Name]}static [eX]="Relation";referencedTableName;fieldName}class nn{constructor(e,i){this.table=e,this.config=i}static [eX]="Relations"}class nt extends ni{constructor(e,i,n,t){super(e,i,n?.relationName),this.config=n,this.isNullable=t}static [eX]="One";withFieldName(e){let i=new nt(this.sourceTable,this.referencedTable,this.config,this.isNullable);return i.fieldName=e,i}}class na extends ni{constructor(e,i,n){super(e,i,n?.relationName),this.config=n}static [eX]="Many";withFieldName(e){let i=new na(this.sourceTable,this.referencedTable,this.config);return i.fieldName=e,i}}function getOperators(){return{and:and,between:between,eq:eq,exists:exists,gt:gt,gte:gte,ilike:ilike,inArray:inArray,isNull:isNull,isNotNull:isNotNull,like:like,lt:lt,lte:lte,ne:ne,not:not,notBetween:notBetween,notExists:notExists,notLike:notLike,notIlike:notIlike,notInArray:notInArray,or:or,sql:sql_sql}}function getOrderByOperators(){return{sql:sql_sql,asc:asc,desc:select_desc}}function extractTablesRelationalConfig(e,i){1===Object.keys(e).length&&"default"in e&&!entity_is(e.default,im)&&(e=e.default);let n={},t={},a={};for(let[r,o]of Object.entries(e))if(entity_is(o,im)){let e=getTableUniqueName(o),i=t[e];for(let t of(n[e]=r,a[r]={tsName:r,dbName:o[im.Symbol.Name],schema:o[im.Symbol.Schema],columns:o[im.Symbol.Columns],relations:i?.relations??{},primaryKey:i?.primaryKey??[]},Object.values(o[im.Symbol.Columns])))t.primary&&a[r].primaryKey.push(t);let u=o[im.Symbol.ExtraConfigBuilder]?.(o[im.Symbol.ExtraConfigColumns]);if(u)for(let e of Object.values(u))entity_is(e,i7)&&a[r].primaryKey.push(...e.columns)}else if(entity_is(o,nn)){let e,r=getTableUniqueName(o.table),u=n[r];for(let[n,s]of Object.entries(o.config(i(o.table))))if(u){let i=a[u];i.relations[n]=s,e&&i.primaryKey.push(...e)}else r in t||(t[r]={relations:{},primaryKey:e}),t[r].relations[n]=s}return{tables:a,tableNamesMap:n}}function createOne(e){return function(i,n){return new nt(e,i,n,n?.fields.reduce((e,i)=>e&&i.notNull,!0)??!1)}}function createMany(e){return function(i,n){return new na(e,i,n)}}function normalizeRelation(e,i,n){if(entity_is(n,nt)&&n.config)return{fields:n.config.fields,references:n.config.references};let t=i[getTableUniqueName(n.referencedTable)];if(!t)throw Error(`Table "${n.referencedTable[im.Symbol.Name]}" not found in schema`);let a=e[t];if(!a)throw Error(`Table "${t}" not found in schema`);let r=n.sourceTable,o=i[getTableUniqueName(r)];if(!o)throw Error(`Table "${r[im.Symbol.Name]}" not found in schema`);let u=[];for(let e of Object.values(a.relations))(n.relationName&&n!==e&&e.relationName===n.relationName||!n.relationName&&e.referencedTable===n.sourceTable)&&u.push(e);if(u.length>1)throw n.relationName?Error(`There are multiple relations with name "${n.relationName}" in table "${t}"`):Error(`There are multiple relations between "${t}" and "${n.sourceTable[im.Symbol.Name]}". Please specify relation name`);if(u[0]&&entity_is(u[0],nt)&&u[0].config)return{fields:u[0].config.references,references:u[0].config.fields};throw Error(`There is not enough information to infer relation "${o}.${n.fieldName}"`)}function createTableRelationsHelpers(e){return{one:createOne(e),many:createMany(e)}}function mapRelationalRow(e,i,n,t,a=e=>e){let r={};for(let[o,u]of t.entries())if(u.isJson){let t=i.relations[u.tsKey],s=n[o],l="string"==typeof s?JSON.parse(s):s;r[u.tsKey]=entity_is(t,nt)?l&&mapRelationalRow(e,e[u.relationTableTsKey],l,u.selection,a):l.map(i=>mapRelationalRow(e,e[u.relationTableTsKey],i,u.selection,a))}else{let e,i=a(n[o]),t=u.field;e=entity_is(t,eG)?t:entity_is(t,ib)?t.decoder:t.sql.decoder,r[u.tsKey]=null===i?null:e.mapFromDriverValue(i)}return r}function mapResultRow(e,i,n){let t={},a=e.reduce((e,{path:a,field:r},o)=>{let u;u=entity_is(r,eG)?r:entity_is(r,ib)?r.decoder:entity_is(r,it)?r._.sql.decoder:r.sql.decoder;let s=e;for(let[e,l]of a.entries())if(e<a.length-1)l in s||(s[l]={}),s=s[l];else{let e=i[o],h=s[l]=null===e?null:u.mapFromDriverValue(e);if(n&&entity_is(r,eG)&&2===a.length){let e=a[0];e in t?"string"==typeof t[e]&&t[e]!==r.table[eK]&&(t[e]=!1):t[e]=null===h&&r.table[eK]}}return e},{});if(n&&Object.keys(t).length>0)for(let[e,i]of Object.entries(t))"string"!=typeof i||n[i]||(a[e]=null);return a}function orderSelectedFields(e,i){return Object.entries(e).reduce((e,[n,t])=>{if("string"!=typeof n)return e;let a=i?[...i,n]:[n];return entity_is(t,eG)||entity_is(t,ib)||entity_is(t,ib.Aliased)||entity_is(t,it)?e.push({path:a,field:t}):entity_is(t,im)?e.push(...orderSelectedFields(t[im.Symbol.Columns],a)):e.push(...orderSelectedFields(t,a)),e},[])}function haveSameKeys(e,i){let n=Object.keys(e),t=Object.keys(i);if(n.length!==t.length)return!1;for(let[e,i]of n.entries())if(i!==t[e])return!1;return!0}function mapUpdateSet(e,i){let n=Object.entries(i).filter(([,e])=>void 0!==e).map(([i,n])=>entity_is(n,ib)||entity_is(n,eG)?[i,n]:[i,new ix(n,e[im.Symbol.Columns][i])]);if(0===n.length)throw Error("No values to set");return Object.fromEntries(n)}function applyMixins(e,i){for(let n of i)for(let i of Object.getOwnPropertyNames(n.prototype))"constructor"!==i&&Object.defineProperty(e.prototype,i,Object.getOwnPropertyDescriptor(n.prototype,i)||Object.create(null))}function getTableColumns(e){return e[im.Symbol.Columns]}function getTableLikeName(e){return entity_is(e,it)?e._.alias:entity_is(e,iD)?e[io].name:entity_is(e,ib)?void 0:e[im.Symbol.IsAlias]?e[im.Symbol.Name]:e[im.Symbol.BaseName]}function isConfig(e){if("object"!=typeof e||null===e||"Object"!==e.constructor.name)return!1;if("logger"in e){let i=typeof e.logger;return"boolean"===i||"object"===i&&"function"==typeof e.logger.logQuery||"undefined"===i}if("schema"in e){let i=typeof e.schema;return"object"===i||"undefined"===i}if("casing"in e){let i=typeof e.casing;return"string"===i||"undefined"===i}if("mode"in e)return"default"===e.mode&&"planetscale"===e.mode&&void 0===e.mode;if("connection"in e){let i=typeof e.connection;return"string"===i||"object"===i||"undefined"===i}if("client"in e){let i=typeof e.client;return"object"===i||"function"===i||"undefined"===i}return 0===Object.keys(e).length}"u"<typeof TextDecoder||new TextDecoder;class nr extends iD{static [eX]="PgViewBase"}class no{static [eX]="PgDialect";casing;constructor(e){this.casing=new iP(e?.casing)}async migrate(e,i,n){let t="string"==typeof n?"__drizzle_migrations":n.migrationsTable??"__drizzle_migrations",a="string"==typeof n?"drizzle":n.migrationsSchema??"drizzle",r=sql_sql`
15
15
  CREATE TABLE IF NOT EXISTS ${sql_sql.identifier(a)}.${sql_sql.identifier(t)} (
16
16
  id SERIAL PRIMARY KEY,
@@ -1 +1 @@
1
- {"version":3,"file":"buffer.d.ts","sourceRoot":"","sources":["../../../src/report/buffer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAKpC,qBAAa,YAAY;IACvB,OAAO,CAAC,MAAM,CAAkB;IAChC,OAAO,CAAC,KAAK,CAA+C;IAC5D,OAAO,CAAC,SAAS,CAAgB;IACjC,OAAO,CAAC,GAAG,CAAgB;IAC3B,OAAO,CAAC,MAAM,CAAe;IAC7B,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,YAAY,CAAS;IAE7B,OAAO,CAAC,aAAa,CAAa;gBAEtB,MAAM,EAAE,YAAY;IAehC,GAAG,CAAC,KAAK,EAAE,QAAQ,GAAG,IAAI;IAcpB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAuB5B,OAAO,IAAI,IAAI;IAYf,OAAO,CAAC,cAAc;CAoBvB"}
1
+ {"version":3,"file":"buffer.d.ts","sourceRoot":"","sources":["../../../src/report/buffer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AAMpC,qBAAa,YAAY;IACvB,OAAO,CAAC,MAAM,CAAkB;IAChC,OAAO,CAAC,KAAK,CAA+C;IAC5D,OAAO,CAAC,SAAS,CAAgB;IACjC,OAAO,CAAC,GAAG,CAAgB;IAC3B,OAAO,CAAC,MAAM,CAAe;IAC7B,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,YAAY,CAAS;IAE7B,OAAO,CAAC,aAAa,CAAa;gBAEtB,MAAM,EAAE,YAAY;IAehC,GAAG,CAAC,KAAK,EAAE,QAAQ,GAAG,IAAI;IAiBpB,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAuB5B,OAAO,IAAI,IAAI;IAYf,OAAO,CAAC,cAAc;CAoBvB"}
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/report/client.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AA4EpC,qBAAa,YAAY;IACvB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,UAAU,CAAU;;IAsBtB,WAAW,CAAC,OAAO,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CA4BtD"}
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../../src/report/client.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,UAAU,CAAC;AA4EpC,qBAAa,YAAY;IACvB,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,UAAU,CAAU;;IAsBtB,WAAW,CAAC,OAAO,EAAE,QAAQ,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CA6BtD"}
@@ -1 +1 @@
1
- {"version":3,"file":"fetch-wrapper.d.ts","sourceRoot":"","sources":["../../../../src/report/interceptors/fetch-wrapper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAMzC,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,GAAE,MAAmB,IAEpE,OAAO,MAAM,GAAG,GAAG,GAAG,OAAO,EAAE,OAAO,WAAW,KAAG,OAAO,CAAC,QAAQ,CAAC,CAWpF"}
1
+ {"version":3,"file":"fetch-wrapper.d.ts","sourceRoot":"","sources":["../../../../src/report/interceptors/fetch-wrapper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAMzC,wBAAgB,kBAAkB,CAAC,MAAM,EAAE,YAAY,EAAE,MAAM,GAAE,MAAmB,IACpE,OAAO,MAAM,GAAG,GAAG,GAAG,OAAO,EAAE,OAAO,WAAW,KAAG,OAAO,CAAC,QAAQ,CAAC,CAWpF"}
@@ -9,7 +9,7 @@ export interface LogEntry {
9
9
  status_code: number | null;
10
10
  error: string | null;
11
11
  duration_ms: number;
12
- timestamp: string;
12
+ timestamp: number;
13
13
  success: boolean;
14
14
  }
15
15
  //# sourceMappingURL=models.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"singleton.d.ts","sourceRoot":"","sources":["../../../src/report/singleton.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAIxC,wBAAgB,eAAe,IAAI,YAAY,GAAG,IAAI,CAWrD"}
1
+ {"version":3,"file":"singleton.d.ts","sourceRoot":"","sources":["../../../src/report/singleton.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAIxC,wBAAgB,eAAe,IAAI,YAAY,GAAG,IAAI,CAUrD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "coze-coding-dev-sdk",
3
- "version": "0.7.19-beta.6",
3
+ "version": "0.7.19-beta.8",
4
4
  "description": "Coze Coding Dev SDK - 优雅的多功能 AI SDK,支持图片生成、视频生成、语音合成、语音识别、大语言模型和联网搜索",
5
5
  "main": "./dist/cjs/index.js",
6
6
  "module": "./dist/esm/index.mjs",