@limai.io/cli 0.4.0 → 0.4.1
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/cli.js +46 -40
- package/dist/index.d.ts +367 -7
- package/dist/index.js +9 -9
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var De=Object.create;var ot=Object.defineProperty;var Ue=Object.getOwnPropertyDescriptor;var Le=Object.getOwnPropertyNames;var _e=Object.getPrototypeOf,Fe=Object.prototype.hasOwnProperty;var Ne=(n,t)=>{for(var e in t)ot(n,e,{get:t[e],enumerable:!0})},ee=(n,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Le(t))!Fe.call(n,i)&&i!==e&&ot(n,i,{get:()=>t[i],enumerable:!(s=Ue(t,i))||s.enumerable});return n};var $=(n,t,e)=>(e=n!=null?De(_e(n)):{},ee(t||!n||!n.__esModule?ot(e,"default",{value:n,enumerable:!0}):e,n)),Me=n=>ee(ot({},"__esModule",{value:!0}),n);var cs={};Ne(cs,{AuthError:()=>at,ConflictError:()=>pt,ForbiddenError:()=>ct,HttpClient:()=>M,JobPoller:()=>G,LimaiClient:()=>kt,LimaiError:()=>R,NotFoundError:()=>lt,RateLimitError:()=>ut,SSEClient:()=>_t,ServerError:()=>dt,TimeoutError:()=>U,UploadError:()=>k,ValidationError:()=>A,collectAll:()=>bt,getDeploymentId:()=>Ae,getFileId:()=>Te,getJobId:()=>Ee,loadConfig:()=>Jt,loadJobContext:()=>rt,mapHttpError:()=>Nt,paginateOffset:()=>ae,paginatePage:()=>yt,requireConfig:()=>Re,saveConfig:()=>be,validateSubmission:()=>Ie});module.exports=Me(cs);var ie=require("fs"),re=require("fs/promises"),oe=require("stream");var R=class extends Error{code;statusCode;exitCode;details;constructor(t,e){super(t),this.name="LimaiError",this.code=e.code,this.statusCode=e.statusCode,this.exitCode=e.exitCode??1,this.details=e.details}},at=class extends R{constructor(t,e){super(t,{code:"AUTH_ERROR",statusCode:401,exitCode:2,details:e}),this.name="AuthError"}},ct=class extends R{constructor(t,e){super(t,{code:"FORBIDDEN",statusCode:403,exitCode:2,details:e}),this.name="ForbiddenError"}},lt=class extends R{constructor(t,e){super(t,{code:"NOT_FOUND",statusCode:404,exitCode:3,details:e}),this.name="NotFoundError"}},A=class extends R{constructor(t,e){super(t,{code:"VALIDATION_ERROR",statusCode:400,exitCode:4,details:e}),this.name="ValidationError"}},pt=class extends R{constructor(t,e){super(t,{code:"CONFLICT",statusCode:409,exitCode:4,details:e}),this.name="ConflictError"}},ut=class extends R{retryAfterMs;constructor(t,e){super(t,{code:"RATE_LIMITED",statusCode:429,exitCode:5}),this.name="RateLimitError",this.retryAfterMs=e}},dt=class extends R{constructor(t,e=500,s){super(t,{code:"SERVER_ERROR",statusCode:e,exitCode:6,details:s}),this.name="ServerError"}},U=class extends R{constructor(t){super(t,{code:"TIMEOUT",exitCode:7}),this.name="TimeoutError"}},k=class extends R{constructor(t,e){super(t,{code:"UPLOAD_ERROR",exitCode:8,details:e}),this.name="UploadError"}};function Nt(n,t,e){switch(n){case 400:return new A(t,e);case 401:return new at(t,e);case 403:return new ct(t,e);case 404:return new lt(t,e);case 409:return new pt(t,e);case 429:return new ut(t);default:return n>=500?new dt(t,n,e):new R(t,{code:"HTTP_ERROR",statusCode:n,details:e})}}var Be=3e4,Mt=3,se=1e3,ne=2;function He(){return process.env.LIMAI_DEBUG==="1"}function Y(...n){He()&&console.error("[limai:http]",...n)}var M=class{baseUrl;token;constructor(t){this.baseUrl=t.apiUrl.replace(/\/$/,""),this.token=t.token}buildUrl(t,e){let s=new URL(`/api/v1${t}`,this.baseUrl);if(e)for(let[i,r]of Object.entries(e))r!=null&&s.searchParams.set(i,r);return s.toString()}authHeaders(){let t={Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},e=process.env.VERCEL_BYPASS;return e&&(t["x-vercel-protection-bypass"]=e),t}async parseErrorBody(t){try{let e=await t.json();return{message:typeof e.error=="string"?e.error:`HTTP ${t.status}`,details:e.details}}catch{return{message:await t.text().catch(()=>"")||`HTTP ${t.status}`}}}shouldRetry(t){return t===429||t>=500}getRetryDelay(t,e){let s=t.headers.get("Retry-After");if(s){let i=parseInt(s,10);if(!isNaN(i))return i*1e3}return se*Math.pow(ne,e)}async request(t,e,s={}){let i=this.buildUrl(e,s.params),r=s.timeoutMs??Be;for(let a=0;a<=Mt;a++){let p=new AbortController,u=setTimeout(()=>p.abort(),r);s.signal&&s.signal.addEventListener("abort",()=>p.abort());try{Y(`${t} ${i}${a>0?` (retry ${a})`:""}`);let c=await fetch(i,{method:t,headers:this.authHeaders(),body:s.body?JSON.stringify(s.body):void 0,signal:p.signal});if(clearTimeout(u),c.ok){let m=await c.text();return m?JSON.parse(m):{}}if(this.shouldRetry(c.status)&&a<Mt){let m=this.getRetryDelay(c,a);Y(`Retrying in ${m}ms (status ${c.status})`),await new Promise(S=>setTimeout(S,m));continue}let{message:g,details:y}=await this.parseErrorBody(c);throw Nt(c.status,g,y)}catch(c){if(clearTimeout(u),c instanceof R)throw c;if(c instanceof DOMException&&c.name==="AbortError"){if(a<Mt){let g=se*Math.pow(ne,a);Y(`Timeout, retrying in ${g}ms`),await new Promise(y=>setTimeout(y,g));continue}throw new U(`Request timed out after ${r}ms: ${t} ${e}`)}throw new R(c instanceof Error?c.message:"Unknown network error",{code:"NETWORK_ERROR",exitCode:1})}}throw new R("Max retries exceeded",{code:"MAX_RETRIES",exitCode:1})}async get(t,e,s){return this.request("GET",t,{params:e,timeoutMs:s})}async post(t,e,s){return this.request("POST",t,{body:e,timeoutMs:s})}async patch(t,e){return this.request("PATCH",t,{body:e})}async del(t,e){return this.request("DELETE",t,{body:e})}async putRaw(t,e,s,i){let r=e instanceof Blob?e.size:e.length;Y(`PUT ${t} (${r} bytes)`);let a=await fetch(t,{method:"PUT",headers:{"Content-Type":s},body:e});if(i&&i(r,r),!a.ok)throw new k(`Upload failed: HTTP ${a.status}`)}async putFile(t,e,s,i){let r=(await(0,re.stat)(e)).size;Y(`PUT ${t} (${r} bytes, streamed from ${e})`);let a=(0,ie.createReadStream)(e),p=a;if(i){let c=0,g=new oe.Transform({transform(y,m,S){c+=y.byteLength,i(c,r),S(null,y)}});p=a.pipe(g)}let u=await fetch(t,{method:"PUT",headers:{"Content-Type":s,"Content-Length":String(r)},body:p,duplex:"half"});if(i&&i(r,r),!u.ok)throw new k(`Upload failed: HTTP ${u.status}`);return r}};var gt=class{constructor(t){this.http=t}http;async getUploadUrl(t,e,s){let i={filename:e,contentHash:s};return this.http.get(`/document/${t}/get-url`,i)}async processSync(t,e,s){return this.http.post(`/document/${t}/process-file/${e}`,s,18e4)}async processAsync(t,e,s){return this.http.post(`/document/${t}/process-file-async/${e}`,s)}async processFilesAsync(t,e,s){return this.http.post(`/document/${t}/process-files-async`,{fileIds:e,...s})}async getFileData(t,e,s){let i={fileId:t,extractionSchemaId:e,include:s?.length?s.join(","):void 0};return this.http.get("/document/get-file-data",i)}async getFilesData(t,e){return this.http.post("/document/get-files-data",{fileIds:t,...e?.length?{include:e}:{}})}async getDocumentData(t,e,s){let i={include:s?.length?s.join(","):void 0};return this.http.get(`/deployments/${t}/documents/${e}/data`,i)}async getDocumentsData(t,e,s){return this.http.post(`/deployments/${t}/documents/data`,{fileIds:e,...s?.length?{include:s}:{}})}async submitCorrections(t,e,s){return this.http.post(`/document/${t}/process-file/${e}/submit-corrections`,s)}};var mt=class{constructor(t){this.http=t}http;async list(){let t=await this.http.get("/projects");return Array.isArray(t)?t:t.data}async create(t){return this.http.post("/projects",t)}async getSchema(t){return this.http.get(`/projects/${t}/schema`)}async getSharedColumnIds(t){return this.http.get(`/projects/${t}/shared-column-ids`)}async listDeployments(t){return this.http.get(`/projects/${t}/deployments`)}async listBenchmarks(t){return this.http.get(`/projects/${t}/benchmarks`)}async listNotificationRoutes(t){return this.http.get(`/projects/${t}/notifications`)}async createNotificationRoute(t,e){return this.http.post(`/projects/${t}/notifications`,e)}async updateNotificationRoute(t,e,s){return this.http.patch(`/projects/${t}/notifications/${e}`,s)}async deleteNotificationRoute(t,e){return this.http.del(`/projects/${t}/notifications/${e}`)}async listNotificationIntegrations(t,e){return this.http.get(`/projects/${t}/notifications/integrations`,{provider:e})}async listNotificationSlackChannels(t,e){return this.http.get(`/projects/${t}/notifications/integrations/slack/channels`,{connectionId:e})}async listNotificationTeamsTeams(t,e){return this.http.get(`/projects/${t}/notifications/integrations/teams/teams`,{connectionId:e})}async listNotificationTeamsChannels(t,e,s){return this.http.get(`/projects/${t}/notifications/integrations/teams/channels`,{connectionId:e,teamId:s})}};var ht=class{constructor(t){this.http=t}http;async list(t,e){let s={status:e?.status,type:e?.type},i=await this.http.get(`/projects/${t}/deployments`,s);return Array.isArray(i)?i:i.data}async create(t,e){return this.http.post(`/projects/${t}/deployments`,e)}async getConfig(t){return this.http.get(`/deployments/${t}/configuration`)}async updateConfig(t,e){await this.http.patch(`/deployment/${t}/configuration`,e)}async listDocuments(t,e){let s={limit:e?.limit?.toString(),offset:e?.offset?.toString(),status:e?.status};return this.http.get(`/deployments/${t}/documents`,s)}async getDocument(t,e){return this.http.get(`/deployments/${t}/documents/${e}`)}async deleteDocument(t,e){await this.http.del(`/deployments/${t}/documents/${e}`)}async bulkDelete(t,e){await this.http.del(`/deployments/${t}/documents/bulk-delete`,{fileIds:e})}};var ft=class{constructor(t){this.http=t}http;async get(t){return this.http.get(`/tables/${t}`)}async listColumns(t){let e=await this.http.get(`/tables/${t}/columns`);return Array.isArray(e)?e:e.data}async listRows(t,e){let s={limit:e?.limit?.toString(),offset:e?.offset?.toString(),status:e?.status};return this.http.get(`/tables/${t}/rows`,s)}async createRows(t,e){return this.http.post(`/tables/${t}/rows`,e,6e4)}async deleteRows(t,e){return this.http.del(`/tables/${t}/rows`,e)}async createTable(t,e){return this.http.post(`/deployments/${t}/tables`,e)}async update(t,e){return this.http.patch(`/tables/${t}`,e)}};async function*ae(n,t={}){let e=Math.min(t.pageSize??100,500),s=0,i=0;for(;;){let r=t.maxItems?Math.min(e,t.maxItems-i):e;if(r<=0)break;let a=await n(r,s),p=a.data;if(p.length===0||(yield p,i+=p.length,s+=p.length,s>=a.pagination.total)||t.maxItems&&i>=t.maxItems)break}}async function*yt(n,t={}){let e=Math.min(t.pageSize??100,500),s=1,i=0;for(;;){let r=t.maxItems?Math.min(e,t.maxItems-i):e;if(r<=0)break;let a=await n(s,r),p=a.data;if(p.length===0||(yield p,i+=p.length,s++,s>a.pagination.totalPages)||t.maxItems&&i>=t.maxItems)break}}async function bt(n){let t=[];for await(let e of n)t.push(...e);return t}var Rt=class{constructor(t){this.http=t}http;async getRows(t,e){let s={page:e?.page?.toString(),limit:e?.limit?.toString(),order:e?.order,status:e?.status};return this.http.get(`/extractions/${t}`,s)}async*getAllRows(t,e){yield*yt(async(s,i)=>this.http.get(`/extractions/${t}`,{page:s.toString(),limit:i.toString(),order:e?.order,status:e?.status}),e)}async collectAllRows(t,e){return bt(this.getAllRows(t,e))}};var wt=class{constructor(t){this.http=t}http;async getStatus(t){return this.http.get(`/queue/${t}/status`)}async cancel(t){await this.http.post("/queue/cancel",{jobId:t})}async updateStatus(t,e){return this.http.patch(`/queue/${t}/status`,e)}};var Ct=class{constructor(t){this.http=t}http;async list(t){return this.http.get("/classify",{projectId:t})}async getUploadUrl(t,e){return this.http.get(`/classify/${t}/get-url`,{filename:e})}async classify(t,e){return this.http.post(`/classify/${t}`,{fileId:e})}async classifyAsync(t,e){return this.http.post(`/classify/${t}/async`,{fileId:e})}async getStatus(t,e){return this.http.get(`/classify/${t}`,{classificationId:e})}async createClassifier(t){return this.http.post("/classify",t)}async createRoute(t,e){return this.http.post(`/classify/${t}/routes`,e)}};var vt=class{constructor(t){this.http=t}http;async list(t){return this.http.get("/split",{projectId:t})}async getUploadUrl(t,e){return this.http.get(`/split/${t}/get-url`,{filename:e})}async split(t,e){return this.http.post(`/split/${t}`,{fileId:e})}async splitAsync(t,e){return this.http.post(`/split/${t}/async`,{fileId:e})}async getStatus(t,e){return this.http.get(`/split/${t}`,{splitId:e})}async listSplits(t){return this.http.get(`/split/${t}/splits`)}async createSplitter(t){return this.http.post("/split",t)}};var St=class{constructor(t){this.http=t}http;async get(t){return this.http.get(`/extraction-schema/${t}`)}async update(t,e){await this.http.patch(`/extraction-schema/${t}`,e)}async getAllData(t){return this.http.get("/extraction-schema/get-all-data",{extractionSchemaId:t})}};var xt=class{constructor(t){this.http=t}http;async list(t){return this.http.get(`/projects/${t}/buckets`)}async get(t){return this.http.get(`/buckets/${t}`)}async create(t,e,s){return this.http.post(`/projects/${t}/buckets`,{name:e,description:s})}async delete(t){await this.http.del(`/buckets/${t}`)}async getUploadUrl(t,e){return this.http.get(`/buckets/${t}/get-url`,{filename:e})}async confirmUpload(t,e,s){await this.http.patch(`/buckets/${t}/files/${e}/status`,{status:"UPLOADED",...s!==void 0&&{sizeBytes:s}})}async listFiles(t,e){let s={};return e&&e.length>0&&(s.labels=e.join(",")),this.http.get(`/buckets/${t}/files`,s)}async getDownloadUrl(t,e){return this.http.get(`/buckets/${t}/files/${e}/download`)}async updateLabels(t,e,s){return this.http.patch(`/buckets/${t}/files/${e}`,{labels:s})}async deleteFile(t,e){await this.http.del(`/buckets/${t}/files/${e}`)}async sendTo(t,e,s,i){return this.http.post(`/buckets/${t}/files/${e}/send-to`,{targetType:s,targetId:i})}};var Pt=class{constructor(t){this.http=t}http;async list(t,e){let s={};return e?.status&&(s.status=e.status),this.http.get(`/projects/${t}/agents`,s)}async get(t,e){return this.http.get(`/projects/${t}/agents/${e}`)}async create(t,e){return this.http.post(`/projects/${t}/agents`,e)}async update(t,e,s){return this.http.patch(`/projects/${t}/agents/${e}`,s)}async delete(t,e){await this.http.del(`/projects/${t}/agents/${e}`)}async getFileUploadUrl(t,e,s){return this.http.get(`/projects/${t}/agents/${e}/files/get-url`,{filename:s})}async deleteFile(t,e,s){await this.http.del(`/projects/${t}/agents/${e}/files/${s}`)}async updateFileMetadata(t,e,s,i){return this.http.patch(`/projects/${t}/agents/${e}/files/${s}`,i)}async getFileDownloadUrl(t,e,s){return this.http.get(`/projects/${t}/agents/${e}/files/${s}/download`)}async listSkills(t,e){return this.http.get(`/projects/${t}/agents/${e}/skills`)}async createSkill(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/skills`,s)}async updateSkill(t,e,s,i){return this.http.patch(`/projects/${t}/agents/${e}/skills/${s}`,i)}async deleteSkill(t,e,s){await this.http.del(`/projects/${t}/agents/${e}/skills/${s}`)}async linkFileToSkill(t,e,s,i){return this.http.post(`/projects/${t}/agents/${e}/skills/${s}/files`,{fileId:i})}async unlinkFileFromSkill(t,e,s,i){await this.http.del(`/projects/${t}/agents/${e}/skills/${s}/files/${i}`)}async listRuns(t,e,s){let i={};return s?.limit&&(i.limit=String(s.limit)),s?.status&&(i.status=s.status),this.http.get(`/projects/${t}/agents/${e}/runs`,i)}async getRun(t,e,s){return this.http.get(`/projects/${t}/agents/${e}/runs/${s}`)}async getRunConversation(t,e,s,i){let r={};return i?.stepId&&(r.stepId=i.stepId),this.http.get(`/projects/${t}/agents/${e}/runs/${s}/conversation`,r)}async createRun(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/runs`,s)}async createStep(t,e,s,i){return this.http.post(`/projects/${t}/agents/${e}/runs/${s}/steps`,i)}async createSteps(t,e,s,i){return this.http.post(`/projects/${t}/agents/${e}/runs/${s}/steps`,{steps:i})}async updateRun(t,e,s,i){return this.http.patch(`/projects/${t}/agents/${e}/runs/${s}`,i)}async updateStep(t,e,s,i,r){return this.http.patch(`/projects/${t}/agents/${e}/runs/${s}/steps/${i}`,r)}async updateStepConditions(t,e,s,i,r){return this.http.patch(`/projects/${t}/agents/${e}/runs/${s}/steps/${i}`,{conditions:r})}async pauseRun(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/runs/${s}/pause`,{})}async submitStepAction(t,e,s,i,r){return this.http.post(`/projects/${t}/agents/${e}/runs/${s}/steps/${i}/action`,r)}async sendEmail(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/send-email`,s)}async completeExecution(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/executions/complete`,s)}async getSharePointToken(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/sharepoint-token`,s)}async getArtifactUploadUrl(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/upload-artifact/get-url`,s)}};var $t=class{constructor(t){this.http=t}http;async ask(t,e){return this.http.post(`/projects/${t}/vision/ask`,e,12e4)}};var Et=class{constructor(t){this.http=t}http;async submit(t,e,s){return this.http.post(`/document/${t}/process-file/${e}/submit-validation`,s)}};var Tt=class{constructor(t){this.http=t}http;async list(t,e){let s={};return e?.entityType&&(s.entityType=e.entityType),this.http.get(`/projects/${t}/labels`,s)}async addRemove(t,e,s,i,r){return this.http.post(`/projects/${t}/labels`,{entityType:e,entityId:s,add:i,remove:r})}async search(t,e){let s={};return e?.entityType&&(s.entityType=e.entityType),e?.labels&&(s.labels=e.labels),e?.key&&(s.key=e.key),this.http.get(`/projects/${t}/labels/search`,s)}};var At=$(require("fs")),B=$(require("path"));var ce=$(require("fs")),le=$(require("crypto"));async function pe(n){return new Promise((t,e)=>{let s=le.createHash("sha256"),i=ce.createReadStream(n);i.on("data",r=>s.update(r)),i.on("end",()=>t(s.digest("hex"))),i.on("error",e)})}var Je={".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".tiff":"image/tiff",".tif":"image/tiff",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xls":"application/vnd.ms-excel",".csv":"text/csv",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword"};function Ge(n){let t=B.extname(n).toLowerCase();return Je[t]||"application/octet-stream"}async function It(n,t,e,s,i){let r=B.resolve(s),a=B.basename(r);if(!At.existsSync(r))throw new k(`File not found: ${r}`);if(!At.statSync(r).isFile())throw new k(`Not a file: ${r}`);let u=await pe(r),c=await t.getUploadUrl(e,a,u);if(c.isDuplicate)return{fileId:c.fileId,filename:c.fileName??a,isDuplicate:!0,bytesUploaded:0};let g=Ge(r),y=await n.putFile(c.url,r,g,i);return{fileId:c.fileId,filename:c.fileName??a,isDuplicate:!1,bytesUploaded:y}}var H=$(require("fs")),J=$(require("path"));var de=$(require("path"));var ue=250,qe=5,Bt=class{constructor(t){this.max=t}max;queue=[];current=0;async acquire(){if(this.current<this.max){this.current++;return}return new Promise(t=>{this.queue.push(t)})}release(){this.current--;let t=this.queue.shift();t&&(this.current++,t())}};async function ge(n,t,e,s,i){let r=Math.min(i?.concurrency??qe,10),a=new Bt(r),p=s.map(m=>({path:m,filename:de.basename(m),status:"pending"})),u=p.map(async(m,S)=>{await a.acquire();try{m.status="uploading",i?.onFileStatus?.(m);let f=await It(n,t,e,m.path);m.fileId=f.fileId,m.status="uploaded",i?.onFileStatus?.(m)}catch(f){m.status="failed",m.error=f instanceof Error?f.message:String(f),i?.onFileStatus?.(m)}finally{a.release()}});if(await Promise.all(u),i?.process){let S=p.filter(f=>f.status==="uploaded"&&f.fileId).map(f=>f.fileId);for(let f=0;f<S.length;f+=ue){let I=S.slice(f,f+ue);try{let T=await t.processFilesAsync(e,I,i.processOptions);for(let[l,o]of Object.entries(T.results)){let d=p.find(C=>C.fileId===l);d&&(o.status==="queued"?(d.status="queued",d.jobId=o.jobId):(d.status="failed",d.error=o.error),i?.onFileStatus?.(d))}}catch(T){for(let l of I){let o=p.find(d=>d.fileId===l);o&&(o.status="failed",o.error=T instanceof Error?T.message:String(T),i?.onFileStatus?.(o))}}}}let c=p.filter(m=>m.status==="uploaded"||m.status==="queued").length,g=p.filter(m=>m.status==="queued").length,y=p.filter(m=>m.status==="failed").length;return{total:s.length,uploaded:c,queued:g,failed:y,files:p}}var Ve=new Set([".pdf",".png",".jpg",".jpeg",".tiff",".tif",".xlsx",".xls",".csv",".docx",".doc"]);function me(n,t){let e=[],s=H.readdirSync(n,{withFileTypes:!0});for(let i of s){let r=J.join(n,i.name);if(!i.name.startsWith(".")){if(i.isDirectory())e.push(...me(r,t));else if(i.isFile()){let a=J.extname(i.name).toLowerCase();if(!Ve.has(a)||t&&!We(i.name,t))continue;e.push(r)}}}return e.sort()}function We(n,t){let e=t.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${e}$`,"i").test(n)}async function he(n,t,e,s,i){let r=J.resolve(s);if(!H.existsSync(r))throw new Error(`Directory not found: ${r}`);if(!H.statSync(r).isDirectory())throw new Error(`Not a directory: ${r}`);let p=me(r,i?.globPattern);return p.length===0?{total:0,uploaded:0,queued:0,failed:0,files:[]}:ge(n,t,e,p,{concurrency:i?.concurrency,process:i?.process,processOptions:i?.processOptions,onFileStatus:i?.onFileStatus})}var ze=1e3,Xe=1e4,Ke=1.5,Ye=3e5,Qe=["COMPLETED","FAILED","STALLED"],G=class{constructor(t){this.queue=t}queue;async*poll(t,e){let s=e?.intervalMs??ze,i=e?.maxIntervalMs??Xe,r=e?.backoffMultiplier??Ke,a=e?.timeoutMs??Ye,p=s,u=Date.now(),c;for(;;){if(Date.now()-u>a)throw new U(`Polling timed out after ${Math.round(a/1e3)}s for job ${t}`);let g=await this.queue.getStatus(t);if(g.status!==c&&(c=g.status,e?.onStatus?.(g),yield g),Qe.includes(g.status))return;await new Promise(y=>setTimeout(y,p)),p=Math.min(p*r,i)}}async waitForCompletion(t,e){let s;for await(let i of this.poll(t,e))s=i;if(!s)throw new Error(`No status received for job ${t}`);return s}};var kt=class{http;documents;projects;deployments;tables;extractions;queue;classify;split;schema;buckets;agents;vision;validations;labels;constructor(t){this.http=new M({apiUrl:t.apiUrl,token:t.token}),this.documents=new gt(this.http),this.projects=new mt(this.http),this.deployments=new ht(this.http),this.tables=new ft(this.http),this.extractions=new Rt(this.http),this.queue=new wt(this.http),this.classify=new Ct(this.http),this.split=new vt(this.http),this.schema=new St(this.http),this.buckets=new xt(this.http),this.agents=new Pt(this.http),this.vision=new $t(this.http),this.validations=new Et(this.http),this.labels=new Tt(this.http)}async uploadFile(t,e,s){return It(this.http,this.documents,t,e,s)}async uploadFolder(t,e,s){return he(this.http,this.documents,t,e,s)}async processAndWait(t,e,s){let i=await this.documents.processAsync(t,e,s?.processOptions),r=new G(this.queue),a;for await(let p of r.poll(i.jobId,s?.pollOptions))a=p;if(!a||a.status==="FAILED")throw new Error(`Extraction failed for file ${e}${a?`: ${a.status}`:""}`);return this.documents.getFileData(e,t)}async*downloadAll(t,e){yield*this.extractions.getAllRows(t,e)}};var x=$(require("fs")),Z=$(require("path")),fe=$(require("os")),Ot=require("child_process"),Ht=Z.join(fe.homedir(),".limai"),Q=Z.join(Ht,"config.json"),Ze=".limai.token",q;function ye(){if(q!==void 0)return q;try{let n=(0,Ot.execSync)("git rev-parse --show-toplevel",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim();if(!x.existsSync(Z.join(n,"packages","cli")))return q=null,null;let t=(0,Ot.execSync)("git rev-parse --git-common-dir",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim(),e="";if(t!==".git"){let s=(0,Ot.execSync)("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim();if(s){let i=s.replace(/[/\\]/g,"-").replace(/[^a-zA-Z0-9._-]/g,"").replace(/^-+|-+$/g,"");i&&(e=`${i}.`)}}return q={root:n,apiUrl:`https://${e}tables.localhost`,sseUrl:`https://${e}ws.localhost`},q}catch{return q=null,null}}function ts(){let n=ye();if(!n)return;let t=Z.join(n.root,Ze);if(x.existsSync(t))return x.readFileSync(t,"utf-8").trim()}function Jt(){let n=process.env.LIMAI_API_TOKEN,t=process.env.LIMAI_API_URL,e=process.env.LIMAI_SSE_URL,s={};if(x.existsSync(Q))try{let u=x.readFileSync(Q,"utf-8"),c=JSON.parse(u);c&&typeof c=="object"&&!Array.isArray(c)&&(s=c)}catch{s={}}let i=ye(),r=n||ts()||s.token,a=t||s.apiUrl||i?.apiUrl||process.env.LIMAI_BUILD_URL||void 0,p=e||s.sseUrl||i?.sseUrl||void 0;return!r||!a?null:{token:r,apiUrl:a,sseUrl:p,defaultProjectId:s.defaultProjectId,defaultDeploymentId:s.defaultDeploymentId}}function be(n){let t={};if(x.existsSync(Q))try{let s=x.readFileSync(Q,"utf-8");t=JSON.parse(s)}catch{t={}}let e={...t,...n};x.existsSync(Ht)||x.mkdirSync(Ht,{recursive:!0,mode:448}),x.writeFileSync(Q,JSON.stringify(e,null,2),{mode:384})}function Re(){let n=Jt();return n||(console.error("Not authenticated. Run `npm run cli:setup` or set LIMAI_API_TOKEN environment variable."),process.exit(1)),n}var jt=class extends Error{constructor(t,e){super(t),this.name="ParseError",this.type=e.type,this.field=e.field,this.value=e.value,this.line=e.line}},we=10,es=13,L=32;function Gt(n){}function Se(n){if(typeof n=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Gt,onError:e=Gt,onRetry:s=Gt,onComment:i}=n,r=[],a=!0,p,u="",c=0,g;function y(l){if(a&&(a=!1,l.charCodeAt(0)===239&&l.charCodeAt(1)===187&&l.charCodeAt(2)===191&&(l=l.slice(3))),r.length===0){let C=m(l);C!==""&&r.push(C);return}if(l.indexOf(`
|
|
2
|
-
`)===-1&&l.indexOf("\r")===-1){
|
|
1
|
+
"use strict";var _e=Object.create;var ot=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var Ne=Object.getOwnPropertyNames;var Me=Object.getPrototypeOf,Fe=Object.prototype.hasOwnProperty;var We=(n,t)=>{for(var e in t)ot(n,e,{get:t[e],enumerable:!0})},ne=(n,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of Ne(t))!Fe.call(n,r)&&r!==e&&ot(n,r,{get:()=>t[r],enumerable:!(s=Le(t,r))||s.enumerable});return n};var P=(n,t,e)=>(e=n!=null?_e(Me(n)):{},ne(t||!n||!n.__esModule?ot(e,"default",{value:n,enumerable:!0}):e,n)),Be=n=>ne(ot({},"__esModule",{value:!0}),n);var us={};We(us,{AuthError:()=>at,ConflictError:()=>pt,ForbiddenError:()=>ct,HttpClient:()=>F,JobPoller:()=>G,LimaiClient:()=>Ot,LimaiError:()=>R,NotFoundError:()=>lt,RateLimitError:()=>ut,SSEClient:()=>Mt,ServerError:()=>dt,TimeoutError:()=>j,UploadError:()=>k,ValidationError:()=>$,collectAll:()=>Rt,getDeploymentId:()=>ke,getFileId:()=>Ae,getJobId:()=>$e,loadConfig:()=>Vt,loadJobContext:()=>it,mapHttpError:()=>Wt,paginateOffset:()=>le,paginatePage:()=>bt,requireConfig:()=>we,saveConfig:()=>Ce,validateSubmission:()=>De});module.exports=Be(us);var oe=require("fs"),ae=require("fs/promises"),ce=require("stream");var R=class extends Error{code;statusCode;exitCode;details;constructor(t,e){super(t),this.name="LimaiError",this.code=e.code,this.statusCode=e.statusCode,this.exitCode=e.exitCode??1,this.details=e.details}},at=class extends R{constructor(t,e){super(t,{code:"AUTH_ERROR",statusCode:401,exitCode:2,details:e}),this.name="AuthError"}},ct=class extends R{constructor(t,e){super(t,{code:"FORBIDDEN",statusCode:403,exitCode:2,details:e}),this.name="ForbiddenError"}},lt=class extends R{constructor(t,e){super(t,{code:"NOT_FOUND",statusCode:404,exitCode:3,details:e}),this.name="NotFoundError"}},$=class extends R{constructor(t,e){super(t,{code:"VALIDATION_ERROR",statusCode:400,exitCode:4,details:e}),this.name="ValidationError"}},pt=class extends R{constructor(t,e){super(t,{code:"CONFLICT",statusCode:409,exitCode:4,details:e}),this.name="ConflictError"}},ut=class extends R{retryAfterMs;constructor(t,e){super(t,{code:"RATE_LIMITED",statusCode:429,exitCode:5}),this.name="RateLimitError",this.retryAfterMs=e}},dt=class extends R{constructor(t,e=500,s){super(t,{code:"SERVER_ERROR",statusCode:e,exitCode:6,details:s}),this.name="ServerError"}},j=class extends R{constructor(t){super(t,{code:"TIMEOUT",exitCode:7}),this.name="TimeoutError"}},k=class extends R{constructor(t,e){super(t,{code:"UPLOAD_ERROR",exitCode:8,details:e}),this.name="UploadError"}};function Wt(n,t,e){switch(n){case 400:return new $(t,e);case 401:return new at(t,e);case 403:return new ct(t,e);case 404:return new lt(t,e);case 409:return new pt(t,e);case 429:return new ut(t);default:return n>=500?new dt(t,n,e):new R(t,{code:"HTTP_ERROR",statusCode:n,details:e})}}var He=3e4,Bt=3,re=1e3,ie=2;function Ge(){return process.env.LIMAI_DEBUG==="1"}function Q(...n){Ge()&&console.error("[limai:http]",...n)}var F=class{baseUrl;token;constructor(t){this.baseUrl=t.apiUrl.replace(/\/$/,""),this.token=t.token}buildUrl(t,e){let s=new URL(`/api/v1${t}`,this.baseUrl);if(e)for(let[r,i]of Object.entries(e))i!=null&&s.searchParams.set(r,i);return s.toString()}authHeaders(){let t={Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},e=process.env.VERCEL_BYPASS;return e&&(t["x-vercel-protection-bypass"]=e),t}async parseErrorBody(t){try{let e=await t.json();return{message:typeof e.error=="string"?e.error:typeof e.message=="string"?e.message:`HTTP ${t.status}`,details:e.details}}catch{return{message:await t.text().catch(()=>"")||`HTTP ${t.status}`}}}shouldRetry(t){return t===429||t>=500}getRetryDelay(t,e){let s=t.headers.get("Retry-After");if(s){let r=parseInt(s,10);if(!isNaN(r))return r*1e3}return re*Math.pow(ie,e)}async request(t,e,s={}){let r=this.buildUrl(e,s.params),i=s.timeoutMs??He;for(let a=0;a<=Bt;a++){let p=new AbortController,u=setTimeout(()=>p.abort(),i);s.signal&&s.signal.addEventListener("abort",()=>p.abort());try{Q(`${t} ${r}${a>0?` (retry ${a})`:""}`);let c=await fetch(r,{method:t,headers:this.authHeaders(),body:s.body?JSON.stringify(s.body):void 0,signal:p.signal});if(clearTimeout(u),c.ok){let m=await c.text();return m?JSON.parse(m):{}}if(s.retry!==!1&&this.shouldRetry(c.status)&&a<Bt){let m=this.getRetryDelay(c,a);Q(`Retrying in ${m}ms (status ${c.status})`),await new Promise(E=>setTimeout(E,m));continue}let{message:g,details:y}=await this.parseErrorBody(c);throw Wt(c.status,g,y)}catch(c){if(clearTimeout(u),c instanceof R)throw c;if(c instanceof DOMException&&c.name==="AbortError"){if(s.retry!==!1&&a<Bt){let g=re*Math.pow(ie,a);Q(`Timeout, retrying in ${g}ms`),await new Promise(y=>setTimeout(y,g));continue}throw new j(`Request timed out after ${i}ms: ${t} ${e}`)}throw new R(c instanceof Error?c.message:"Unknown network error",{code:"NETWORK_ERROR",exitCode:1})}}throw new R("Max retries exceeded",{code:"MAX_RETRIES",exitCode:1})}async get(t,e,s){return this.request("GET",t,{params:e,timeoutMs:s})}async post(t,e,s,r){return this.request("POST",t,{body:e,timeoutMs:s,retry:r?.retry})}async patch(t,e,s){return this.request("PATCH",t,{body:e,retry:s?.retry})}async del(t,e){return this.request("DELETE",t,{body:e})}async putRaw(t,e,s,r){let i=e instanceof Blob?e.size:e.length;Q(`PUT ${t} (${i} bytes)`);let a=await fetch(t,{method:"PUT",headers:{"Content-Type":s},body:e});if(r&&r(i,i),!a.ok)throw new k(`Upload failed: HTTP ${a.status}`)}async putFile(t,e,s,r){let i=(await(0,ae.stat)(e)).size;Q(`PUT ${t} (${i} bytes, streamed from ${e})`);let a=(0,oe.createReadStream)(e),p=a;if(r){let c=0,g=new ce.Transform({transform(y,m,E){c+=y.byteLength,r(c,i),E(null,y)}});p=a.pipe(g)}let u=await fetch(t,{method:"PUT",headers:{"Content-Type":s,"Content-Length":String(i)},body:p,duplex:"half"});if(r&&r(i,i),!u.ok)throw new k(`Upload failed: HTTP ${u.status}`);return i}};var gt=class{constructor(t){this.http=t}http;async getUploadUrl(t,e,s){let r={filename:e,contentHash:s};return this.http.get(`/document/${t}/get-url`,r)}async processSync(t,e,s){return this.http.post(`/document/${t}/process-file/${e}`,s,18e4)}async processAsync(t,e,s){return this.http.post(`/document/${t}/process-file-async/${e}`,s)}async processFilesAsync(t,e,s){return this.http.post(`/document/${t}/process-files-async`,{fileIds:e,...s})}async getFileData(t,e,s){let r={fileId:t,extractionSchemaId:e,include:s?.length?s.join(","):void 0};return this.http.get("/document/get-file-data",r)}async getFilesData(t,e){return this.http.post("/document/get-files-data",{fileIds:t,...e?.length?{include:e}:{}})}async getDocumentData(t,e,s){let r={include:s?.length?s.join(","):void 0};return this.http.get(`/deployments/${t}/documents/${e}/data`,r)}async getDocumentsData(t,e,s){return this.http.post(`/deployments/${t}/documents/data`,{fileIds:e,...s?.length?{include:s}:{}})}async submitCorrections(t,e,s){return this.http.post(`/document/${t}/process-file/${e}/submit-corrections`,s)}};var mt=class{constructor(t){this.http=t}http;async list(){let t=await this.http.get("/projects");return Array.isArray(t)?t:t.data}async create(t){return this.http.post("/projects",t)}async delete(t){return this.http.del(`/projects/${t}`)}async getSharedColumnIds(t){return this.http.get(`/projects/${t}/shared-column-ids`)}async listDeployments(t){return this.http.get(`/projects/${t}/deployments`)}async listBenchmarks(t){return this.http.get(`/projects/${t}/benchmarks`)}async listNotificationRoutes(t){return this.http.get(`/projects/${t}/notifications`)}async createNotificationRoute(t,e){return this.http.post(`/projects/${t}/notifications`,e)}async updateNotificationRoute(t,e,s){return this.http.patch(`/projects/${t}/notifications/${e}`,s)}async deleteNotificationRoute(t,e){return this.http.del(`/projects/${t}/notifications/${e}`)}async listNotificationIntegrations(t,e){return this.http.get(`/projects/${t}/notifications/integrations`,{provider:e})}async listNotificationSlackChannels(t,e){return this.http.get(`/projects/${t}/notifications/integrations/slack/channels`,{connectionId:e})}async listNotificationTeamsTeams(t,e){return this.http.get(`/projects/${t}/notifications/integrations/teams/teams`,{connectionId:e})}async listNotificationTeamsChannels(t,e,s){return this.http.get(`/projects/${t}/notifications/integrations/teams/channels`,{connectionId:e,teamId:s})}};var ht=class{constructor(t){this.http=t}http;async list(t,e){let s={status:e?.status,type:e?.type},r=await this.http.get(`/projects/${t}/deployments`,s);return Array.isArray(r)?r:r.data}async create(t,e){return this.http.post(`/projects/${t}/deployments`,e)}async getConfig(t){return this.http.get(`/deployments/${t}/configuration`)}async updateConfig(t,e){await this.http.patch(`/deployment/${t}/configuration`,e)}async listDocuments(t,e){let s={limit:e?.limit?.toString(),offset:e?.offset?.toString(),status:e?.status};return this.http.get(`/deployments/${t}/documents`,s)}async getDocument(t,e){return this.http.get(`/deployments/${t}/documents/${e}`)}async deleteDocument(t,e){await this.http.del(`/deployments/${t}/documents/${e}`)}async bulkDelete(t,e){await this.http.del(`/deployments/${t}/documents/bulk-delete`,{fileIds:e})}};var ft=class{constructor(t){this.http=t}http;async get(t){return this.http.get(`/tables/${t}`)}async listColumns(t){let e=await this.http.get(`/tables/${t}/columns`);return Array.isArray(e)?e:e.data}async listRows(t,e){let s={limit:e?.limit?.toString(),offset:e?.offset?.toString(),status:e?.status};return this.http.get(`/tables/${t}/rows`,s)}async createRows(t,e){return this.http.post(`/tables/${t}/rows`,e,6e4)}async deleteRows(t,e){return this.http.del(`/tables/${t}/rows`,e)}async createTable(t,e){return this.http.post(`/deployments/${t}/tables`,e)}async update(t,e){return this.http.patch(`/tables/${t}`,e)}};var yt=class{constructor(t){this.http=t}http;async list(t){let e=await this.http.get(`/tables/${t}/columns`);return Array.isArray(e)?e:e.data}async get(t){return this.http.get(`/columns/${t}`)}async create(t,e){let s=await this.http.post(`/tables/${t}/columns`,e);return s&&typeof s=="object"&&"data"in s?s.data:[s]}async update(t,e){return this.http.patch(`/columns/${t}`,e)}};async function*le(n,t={}){let e=Math.min(t.pageSize??100,500),s=0,r=0;for(;;){let i=t.maxItems?Math.min(e,t.maxItems-r):e;if(i<=0)break;let a=await n(i,s),p=a.data;if(p.length===0||(yield p,r+=p.length,s+=p.length,s>=a.pagination.total)||t.maxItems&&r>=t.maxItems)break}}async function*bt(n,t={}){let e=Math.min(t.pageSize??100,500),s=1,r=0;for(;;){let i=t.maxItems?Math.min(e,t.maxItems-r):e;if(i<=0)break;let a=await n(s,i),p=a.data;if(p.length===0||(yield p,r+=p.length,s++,s>a.pagination.totalPages)||t.maxItems&&r>=t.maxItems)break}}async function Rt(n){let t=[];for await(let e of n)t.push(...e);return t}var Ct=class{constructor(t){this.http=t}http;async getRows(t,e){let s={page:e?.page?.toString(),limit:e?.limit?.toString(),order:e?.order,status:e?.status};return this.http.get(`/extractions/${t}`,s)}async*getAllRows(t,e){yield*bt(async(s,r)=>this.http.get(`/extractions/${t}`,{page:s.toString(),limit:r.toString(),order:e?.order,status:e?.status}),e)}async collectAllRows(t,e){return Rt(this.getAllRows(t,e))}};var wt=class{constructor(t){this.http=t}http;async getStatus(t){return this.http.get(`/queue/${t}/status`)}async cancel(t){await this.http.post("/queue/cancel",{jobId:t})}async updateStatus(t,e){return this.http.patch(`/queue/${t}/status`,e)}};var St=class{constructor(t){this.http=t}http;async list(t){return this.http.get("/classify",{projectId:t})}async getUploadUrl(t,e){return this.http.get(`/classify/${t}/get-url`,{filename:e})}async classify(t,e){return this.http.post(`/classify/${t}`,{fileId:e})}async classifyAsync(t,e){return this.http.post(`/classify/${t}/async`,{fileId:e})}async getStatus(t,e){return this.http.get(`/classify/${t}`,{classificationId:e})}async createClassifier(t){return this.http.post("/classify",t)}async createRoute(t,e){return this.http.post(`/classify/${t}/routes`,e)}};var vt=class{constructor(t){this.http=t}http;async list(t){return this.http.get("/split",{projectId:t})}async getUploadUrl(t,e){return this.http.get(`/split/${t}/get-url`,{filename:e})}async split(t,e){return this.http.post(`/split/${t}`,{fileId:e})}async splitAsync(t,e){return this.http.post(`/split/${t}/async`,{fileId:e})}async getStatus(t,e){return this.http.get(`/split/${t}`,{splitId:e})}async listSplits(t){return this.http.get(`/split/${t}/splits`)}async createSplitter(t){return this.http.post("/split",t)}};var Et=class{constructor(t){this.http=t}http;async get(t){return this.http.get(`/extraction-schema/${t}`)}async update(t,e){return this.http.patch(`/extraction-schema/${t}`,e)}async getAllData(t){return this.http.get("/extraction-schema/get-all-data",{extractionSchemaId:t})}};var It=class{constructor(t){this.http=t}http;async list(t){return this.http.get(`/projects/${t}/buckets`)}async get(t){return this.http.get(`/buckets/${t}`)}async create(t,e,s){return this.http.post(`/projects/${t}/buckets`,{name:e,description:s})}async delete(t){await this.http.del(`/buckets/${t}`)}async getUploadUrl(t,e){return this.http.get(`/buckets/${t}/get-url`,{filename:e})}async confirmUpload(t,e,s){await this.http.patch(`/buckets/${t}/files/${e}/status`,{status:"UPLOADED",...s!==void 0&&{sizeBytes:s}})}async listFiles(t,e){let s={};return e&&e.length>0&&(s.labels=e.join(",")),this.http.get(`/buckets/${t}/files`,s)}async getDownloadUrl(t,e){return this.http.get(`/buckets/${t}/files/${e}/download`)}async updateLabels(t,e,s){return this.http.patch(`/buckets/${t}/files/${e}`,{labels:s})}async deleteFile(t,e){await this.http.del(`/buckets/${t}/files/${e}`)}async sendTo(t,e,s,r){return this.http.post(`/buckets/${t}/files/${e}/send-to`,{targetType:s,targetId:r})}};var Pt=class{constructor(t){this.http=t}http;async list(t,e){let s={};return e?.status&&(s.status=e.status),this.http.get(`/projects/${t}/agents`,s)}async get(t,e){return this.http.get(`/projects/${t}/agents/${e}`)}async create(t,e){return this.http.post(`/projects/${t}/agents`,e)}async update(t,e,s){return this.http.patch(`/projects/${t}/agents/${e}`,s)}async delete(t,e){await this.http.del(`/projects/${t}/agents/${e}`)}async getFileUploadUrl(t,e,s){return this.http.get(`/projects/${t}/agents/${e}/files/get-url`,{filename:s})}async deleteFile(t,e,s){await this.http.del(`/projects/${t}/agents/${e}/files/${s}`)}async updateFileMetadata(t,e,s,r){return this.http.patch(`/projects/${t}/agents/${e}/files/${s}`,r)}async getFileDownloadUrl(t,e,s){return this.http.get(`/projects/${t}/agents/${e}/files/${s}/download`)}async listSkills(t,e){return this.http.get(`/projects/${t}/agents/${e}/skills`)}async createSkill(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/skills`,s)}async updateSkill(t,e,s,r){return this.http.patch(`/projects/${t}/agents/${e}/skills/${s}`,r)}async deleteSkill(t,e,s){await this.http.del(`/projects/${t}/agents/${e}/skills/${s}`)}async linkFileToSkill(t,e,s,r){return this.http.post(`/projects/${t}/agents/${e}/skills/${s}/files`,{fileId:r})}async unlinkFileFromSkill(t,e,s,r){await this.http.del(`/projects/${t}/agents/${e}/skills/${s}/files/${r}`)}async listRuns(t,e,s){let r={};return s?.limit&&(r.limit=String(s.limit)),s?.status&&(r.status=s.status),this.http.get(`/projects/${t}/agents/${e}/runs`,r)}async getRun(t,e,s){return this.http.get(`/projects/${t}/agents/${e}/runs/${s}`)}async getRunConversation(t,e,s,r){let i={};return r?.stepId&&(i.stepId=r.stepId),this.http.get(`/projects/${t}/agents/${e}/runs/${s}/conversation`,i)}async getRunInferenceLogs(t,e,s,r){let i={};return r?.limit!==void 0&&(i.limit=String(r.limit)),r?.status&&(i.status=r.status),this.http.get(`/projects/${t}/agents/${e}/runs/${s}/inference-logs`,i)}async createRun(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/runs`,s)}async createStep(t,e,s,r){return this.http.post(`/projects/${t}/agents/${e}/runs/${s}/steps`,r)}async createSteps(t,e,s,r){return this.http.post(`/projects/${t}/agents/${e}/runs/${s}/steps`,{steps:r})}async updateRun(t,e,s,r){return this.http.patch(`/projects/${t}/agents/${e}/runs/${s}`,r)}async updateStep(t,e,s,r,i){return this.http.patch(`/projects/${t}/agents/${e}/runs/${s}/steps/${r}`,i)}async updateStepConditions(t,e,s,r,i){return this.http.patch(`/projects/${t}/agents/${e}/runs/${s}/steps/${r}`,{conditions:i})}async pauseRun(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/runs/${s}/pause`,{})}async submitStepAction(t,e,s,r,i){return this.http.post(`/projects/${t}/agents/${e}/runs/${s}/steps/${r}/action`,i)}async sendEmail(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/send-email`,s)}async completeExecution(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/executions/complete`,s)}async getSharePointToken(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/sharepoint-token`,s)}async getArtifactUploadUrl(t,e,s){return this.http.post(`/projects/${t}/agents/${e}/upload-artifact/get-url`,s)}};var xt=class{constructor(t){this.http=t}http;async ask(t,e){return this.http.post(`/projects/${t}/vision/ask`,e,12e4)}};var Tt=class{constructor(t){this.http=t}http;async submit(t,e,s){return this.http.post(`/document/${t}/process-file/${e}/submit-validation`,s)}async listScripts(t){return(await this.http.get(`/extraction-schema/${t}/validation-scripts`)).scripts}async getScript(t,e,s){return(await this.http.get(`/extraction-schema/${t}/validation-scripts/${encodeURIComponent(e)}`,s?.includeSource?{includeSource:"true"}:void 0)).script}async pushScript(t,e){return this.http.post(`/extraction-schema/${t}/validation-scripts`,e)}async updateScript(t,e,s){return(await this.http.patch(`/extraction-schema/${t}/validation-scripts/${encodeURIComponent(e)}`,s)).script}async deleteScript(t,e){return this.http.del(`/extraction-schema/${t}/validation-scripts/${encodeURIComponent(e)}`)}};var $t=class{constructor(t){this.http=t}http;async list(t,e){let s={};return e?.entityType&&(s.entityType=e.entityType),this.http.get(`/projects/${t}/labels`,s)}async addRemove(t,e,s,r,i){return this.http.post(`/projects/${t}/labels`,{entityType:e,entityId:s,add:r,remove:i})}async search(t,e){let s={};return e?.entityType&&(s.entityType=e.entityType),e?.labels&&(s.labels=e.labels),e?.key&&(s.key=e.key),this.http.get(`/projects/${t}/labels/search`,s)}};var At=class{constructor(t){this.http=t}http;basePath(t){return`/projects/${t}/webhooks`}async list(t){return this.http.get(this.basePath(t))}async get(t,e){return this.http.get(`${this.basePath(t)}/${e}`)}async create(t,e){return this.http.post(this.basePath(t),e,void 0,{retry:!1})}async update(t,e,s){return this.http.patch(`${this.basePath(t)}/${e}`,s,{retry:!1})}async delete(t,e){await this.http.del(`${this.basePath(t)}/${e}`)}async pause(t,e){return this.http.post(`${this.basePath(t)}/${e}/pause`)}async resume(t,e){return this.http.post(`${this.basePath(t)}/${e}/resume`)}async verify(t,e){return this.http.post(`${this.basePath(t)}/${e}/verify`,void 0,void 0,{retry:!1})}async rotateSecret(t,e){return this.http.post(`${this.basePath(t)}/${e}/rotate-secret`,void 0,void 0,{retry:!1})}async deliveries(t,e,s){let r={};return s?.status&&(r.status=s.status),s?.eventType&&(r.eventType=s.eventType),s?.deploymentId&&(r.deploymentId=s.deploymentId),s?.agentId&&(r.agentId=s.agentId),s?.classifierId&&(r.classifierId=s.classifierId),s?.splitterId&&(r.splitterId=s.splitterId),s?.limit!==void 0&&(r.limit=String(s.limit)),s?.offset!==void 0&&(r.offset=String(s.offset)),this.http.get(`${this.basePath(t)}/${e}/deliveries`,r)}async metrics(t,e,s){let r={};return s?.window&&(r.window=s.window),s?.bucket&&(r.bucket=s.bucket),this.http.get(`${this.basePath(t)}/${e}/metrics`,r)}async retry(t,e,s){return this.http.post(`${this.basePath(t)}/${e}/retry`,{eventIds:s})}};var kt=P(require("fs")),W=P(require("path"));var pe=P(require("fs")),ue=P(require("crypto"));async function de(n){return new Promise((t,e)=>{let s=ue.createHash("sha256"),r=pe.createReadStream(n);r.on("data",i=>s.update(i)),r.on("end",()=>t(s.digest("hex"))),r.on("error",e)})}var Ve={".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".tiff":"image/tiff",".tif":"image/tiff",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".xls":"application/vnd.ms-excel",".csv":"text/csv",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".doc":"application/msword"};function Je(n){let t=W.extname(n).toLowerCase();return Ve[t]||"application/octet-stream"}async function Dt(n,t,e,s,r){let i=W.resolve(s),a=W.basename(i);if(!kt.existsSync(i))throw new k(`File not found: ${i}`);if(!kt.statSync(i).isFile())throw new k(`Not a file: ${i}`);let u=await de(i),c=await t.getUploadUrl(e,a,u);if(c.isDuplicate)return{fileId:c.fileId,filename:c.fileName??a,isDuplicate:!0,bytesUploaded:0};let g=Je(i),y=await n.putFile(c.url,i,g,r);return{fileId:c.fileId,filename:c.fileName??a,isDuplicate:!1,bytesUploaded:y}}var B=P(require("fs")),H=P(require("path"));var me=P(require("path"));var ge=250,qe=5,Ht=class{constructor(t){this.max=t}max;queue=[];current=0;async acquire(){if(this.current<this.max){this.current++;return}return new Promise(t=>{this.queue.push(t)})}release(){this.current--;let t=this.queue.shift();t&&(this.current++,t())}};async function he(n,t,e,s,r){let i=Math.min(r?.concurrency??qe,10),a=new Ht(i),p=s.map(m=>({path:m,filename:me.basename(m),status:"pending"})),u=p.map(async(m,E)=>{await a.acquire();try{m.status="uploading",r?.onFileStatus?.(m);let f=await Dt(n,t,e,m.path);m.fileId=f.fileId,m.status="uploaded",r?.onFileStatus?.(m)}catch(f){m.status="failed",m.error=f instanceof Error?f.message:String(f),r?.onFileStatus?.(m)}finally{a.release()}});if(await Promise.all(u),r?.process){let E=p.filter(f=>f.status==="uploaded"&&f.fileId).map(f=>f.fileId);for(let f=0;f<E.length;f+=ge){let A=E.slice(f,f+ge);try{let T=await t.processFilesAsync(e,A,r.processOptions);for(let[l,o]of Object.entries(T.results)){let d=p.find(w=>w.fileId===l);d&&(o.status==="queued"?(d.status="queued",d.jobId=o.jobId):(d.status="failed",d.error=o.error),r?.onFileStatus?.(d))}}catch(T){for(let l of A){let o=p.find(d=>d.fileId===l);o&&(o.status="failed",o.error=T instanceof Error?T.message:String(T),r?.onFileStatus?.(o))}}}}let c=p.filter(m=>m.status==="uploaded"||m.status==="queued").length,g=p.filter(m=>m.status==="queued").length,y=p.filter(m=>m.status==="failed").length;return{total:s.length,uploaded:c,queued:g,failed:y,files:p}}var Ke=new Set([".pdf",".png",".jpg",".jpeg",".tiff",".tif",".xlsx",".xls",".csv",".docx",".doc"]);function fe(n,t){let e=[],s=B.readdirSync(n,{withFileTypes:!0});for(let r of s){let i=H.join(n,r.name);if(!r.name.startsWith(".")){if(r.isDirectory())e.push(...fe(i,t));else if(r.isFile()){let a=H.extname(r.name).toLowerCase();if(!Ke.has(a)||t&&!ze(r.name,t))continue;e.push(i)}}}return e.sort()}function ze(n,t){let e=t.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".");return new RegExp(`^${e}$`,"i").test(n)}async function ye(n,t,e,s,r){let i=H.resolve(s);if(!B.existsSync(i))throw new Error(`Directory not found: ${i}`);if(!B.statSync(i).isDirectory())throw new Error(`Not a directory: ${i}`);let p=fe(i,r?.globPattern);return p.length===0?{total:0,uploaded:0,queued:0,failed:0,files:[]}:he(n,t,e,p,{concurrency:r?.concurrency,process:r?.process,processOptions:r?.processOptions,onFileStatus:r?.onFileStatus})}var Xe=1e3,Ye=1e4,Qe=1.5,Ze=3e5,ts=["COMPLETED","FAILED","STALLED"],G=class{constructor(t){this.queue=t}queue;async*poll(t,e){let s=e?.intervalMs??Xe,r=e?.maxIntervalMs??Ye,i=e?.backoffMultiplier??Qe,a=e?.timeoutMs??Ze,p=s,u=Date.now(),c;for(;;){if(Date.now()-u>a)throw new j(`Polling timed out after ${Math.round(a/1e3)}s for job ${t}`);let g=await this.queue.getStatus(t);if(g.status!==c&&(c=g.status,e?.onStatus?.(g),yield g),ts.includes(g.status))return;await new Promise(y=>setTimeout(y,p)),p=Math.min(p*i,r)}}async waitForCompletion(t,e){let s;for await(let r of this.poll(t,e))s=r;if(!s)throw new Error(`No status received for job ${t}`);return s}};var Ot=class{http;documents;projects;deployments;tables;columns;extractions;queue;classify;split;schema;buckets;agents;vision;validations;labels;webhooks;constructor(t){this.http=new F({apiUrl:t.apiUrl,token:t.token}),this.documents=new gt(this.http),this.projects=new mt(this.http),this.deployments=new ht(this.http),this.tables=new ft(this.http),this.columns=new yt(this.http),this.extractions=new Ct(this.http),this.queue=new wt(this.http),this.classify=new St(this.http),this.split=new vt(this.http),this.schema=new Et(this.http),this.buckets=new It(this.http),this.agents=new Pt(this.http),this.vision=new xt(this.http),this.validations=new Tt(this.http),this.labels=new $t(this.http),this.webhooks=new At(this.http)}async uploadFile(t,e,s){return Dt(this.http,this.documents,t,e,s)}async uploadFolder(t,e,s){return ye(this.http,this.documents,t,e,s)}async processAndWait(t,e,s){let r=await this.documents.processAsync(t,e,s?.processOptions),i=new G(this.queue),a;for await(let p of i.poll(r.jobId,s?.pollOptions))a=p;if(!a||a.status==="FAILED")throw new Error(`Extraction failed for file ${e}${a?`: ${a.status}`:""}`);return this.documents.getFileData(e,t)}async*downloadAll(t,e){yield*this.extractions.getAllRows(t,e)}};var v=P(require("fs")),J=P(require("path")),be=P(require("os")),Ut=require("child_process"),Gt=J.join(be.homedir(),".limai"),Z=J.join(Gt,"config.json"),es=".limai.token",V;function ss(n){if(!v.existsSync(n))return{};let t={};for(let e of v.readFileSync(n,"utf-8").split(/\r?\n/)){let s=e.match(/^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/);s&&(t[s[1]]=s[2].replace(/^(["'])(.*)\1$/,"$2"))}return t}function Re(){if(V!==void 0)return V;try{let n=(0,Ut.execSync)("git rev-parse --show-toplevel",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim();if(!v.existsSync(J.join(n,"packages","cli")))return V=null,null;let t=(0,Ut.execSync)("git rev-parse --git-common-dir",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim(),e="";if(t!==".git"){let r=(0,Ut.execSync)("git rev-parse --abbrev-ref HEAD",{encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim();if(r){let i=r.replace(/[/\\]/g,"-").replace(/[^a-zA-Z0-9._-]/g,"").replace(/^-+|-+$/g,"");i&&(e=`${i}.`)}}let s=ss(J.join(n,"tables",".env.local"));return V={root:n,apiUrl:s.NEXT_PUBLIC_BASE_URL??`https://${e}tables.localhost`,sseUrl:s.NEXT_PUBLIC_SSE_URL??`https://${e}ws.localhost`},V}catch{return V=null,null}}function ns(){let n=Re();if(!n)return;let t=J.join(n.root,es);if(v.existsSync(t))return v.readFileSync(t,"utf-8").trim()}function Vt(){let n=process.env.LIMAI_API_TOKEN,t=process.env.LIMAI_API_URL,e=process.env.LIMAI_SSE_URL,s={};if(v.existsSync(Z))try{let u=v.readFileSync(Z,"utf-8"),c=JSON.parse(u);c&&typeof c=="object"&&!Array.isArray(c)&&(s=c)}catch{s={}}let r=Re(),i=n||ns()||s.token,a=t||s.apiUrl||r?.apiUrl||process.env.LIMAI_BUILD_URL||void 0,p=e||s.sseUrl||r?.sseUrl||void 0;return!i||!a?null:{token:i,apiUrl:a,sseUrl:p,defaultProjectId:s.defaultProjectId,defaultDeploymentId:s.defaultDeploymentId}}function Ce(n){let t={};if(v.existsSync(Z))try{let s=v.readFileSync(Z,"utf-8");t=JSON.parse(s)}catch{t={}}let e={...t,...n};v.existsSync(Gt)||v.mkdirSync(Gt,{recursive:!0,mode:448}),v.writeFileSync(Z,JSON.stringify(e,null,2),{mode:384})}function we(){let n=Vt();return n||(console.error("Not authenticated. Run `npm run cli:setup` or set LIMAI_API_TOKEN environment variable."),process.exit(1)),n}var jt=class extends Error{constructor(t,e){super(t),this.name="ParseError",this.type=e.type,this.field=e.field,this.value=e.value,this.line=e.line}},Se=10,rs=13,_=32;function Jt(n){}function Ie(n){if(typeof n=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=Jt,onError:e=Jt,onRetry:s=Jt,onComment:r}=n,i=[],a=!0,p,u="",c=0,g;function y(l){if(a&&(a=!1,l.charCodeAt(0)===239&&l.charCodeAt(1)===187&&l.charCodeAt(2)===191&&(l=l.slice(3))),i.length===0){let w=m(l);w!==""&&i.push(w);return}if(l.indexOf(`
|
|
2
|
+
`)===-1&&l.indexOf("\r")===-1){i.push(l);return}i.push(l);let o=i.join("");i.length=0;let d=m(o);d!==""&&i.push(d)}function m(l){let o=0;if(l.indexOf("\r")===-1){let d=l.indexOf(`
|
|
3
3
|
`,o);for(;d!==-1;){if(o===d){c>0&&t({id:p,event:g,data:u}),p=void 0,u="",c=0,g=void 0,o=d+1,d=l.indexOf(`
|
|
4
|
-
`,o);continue}let
|
|
5
|
-
`,o);continue}u=c===0?
|
|
6
|
-
${
|
|
7
|
-
`,o)}return l.slice(o)}for(;o<l.length;){let d=l.indexOf("\r",o),
|
|
8
|
-
`,o),
|
|
9
|
-
${
|
|
10
|
-
${o}`,c++;break;case"id":p=o.includes("\0")?void 0:o;break;case"retry":/^\d+$/.test(o)?s(parseInt(o,10)):e(new jt(`Invalid \`retry\` value: "${o}"`,{type:"invalid-retry",value:o,line:d}));break;default:e(new jt(`Unknown field "${l.length>20?`${l.slice(0,20)}\u2026`:l}"`,{type:"unknown-field",field:l,value:o,line:d}));break}}function I(){c>0&&t({id:p,event:g,data:u}),p=void 0,u="",c=0,g=void 0}function T(l={}){if(l.consume&&r.length>0){let o=r.join("");S(o,0,o.length)}a=!0,p=void 0,u="",c=0,g=void 0,r.length=0}return{feed:y,reset:T}}function Ce(n,t,e){return e===100&&n.charCodeAt(t+1)===97&&n.charCodeAt(t+2)===116&&n.charCodeAt(t+3)===97&&n.charCodeAt(t+4)===58}function ve(n,t,e){return e===101&&n.charCodeAt(t+1)===118&&n.charCodeAt(t+2)===101&&n.charCodeAt(t+3)===110&&n.charCodeAt(t+4)===116&&n.charCodeAt(t+5)===58}var Ut=class extends Event{constructor(t,e){var s,i;super(t),this.code=(s=e?.code)!=null?s:void 0,this.message=(i=e?.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,e,s){return s(xe(this),e)}[Symbol.for("Deno.customInspect")](t,e){return t(xe(this),e)}};function ss(n){let t=globalThis.DOMException;return typeof t=="function"?new t(n,"SyntaxError"):new SyntaxError(n)}function qt(n){return n instanceof Error?"errors"in n&&Array.isArray(n.errors)?n.errors.map(qt).join(", "):"cause"in n&&n.cause instanceof Error?`${n}: ${qt(n.cause)}`:n.message:`${n}`}function xe(n){return{type:n.type,message:n.message,code:n.code,defaultPrevented:n.defaultPrevented,cancelable:n.cancelable,timeStamp:n.timeStamp}}var $e=n=>{throw TypeError(n)},Zt=(n,t,e)=>t.has(n)||$e("Cannot "+e),h=(n,t,e)=>(Zt(n,t,"read from private field"),e?e.call(n):t.get(n)),w=(n,t,e)=>t.has(n)?$e("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),b=(n,t,e,s)=>(Zt(n,t,"write to private field"),t.set(n,e),e),O=(n,t,e)=>(Zt(n,t,"access private method"),e),P,_,V,Dt,Lt,st,X,nt,D,W,K,z,tt,E,Vt,Wt,zt,Pe,Xt,Kt,et,Yt,Qt,F=class extends EventTarget{constructor(t,e){var s,i;super(),w(this,E),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,w(this,P),w(this,_),w(this,V),w(this,Dt),w(this,Lt),w(this,st),w(this,X),w(this,nt,null),w(this,D),w(this,W),w(this,K,null),w(this,z,null),w(this,tt,null),w(this,Wt,async r=>{var a;h(this,W).reset();let{body:p,redirected:u,status:c,headers:g}=r;if(c===204){O(this,E,et).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?b(this,V,new URL(r.url)):b(this,V,void 0),c!==200){O(this,E,et).call(this,`Non-200 status code (${c})`,c);return}if(!(g.get("content-type")||"").startsWith("text/event-stream")){O(this,E,et).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(h(this,P)===this.CLOSED)return;b(this,P,this.OPEN);let y=new Event("open");if((a=h(this,tt))==null||a.call(this,y),this.dispatchEvent(y),typeof p!="object"||!p||!("getReader"in p)){O(this,E,et).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let m=new TextDecoder,S=p.getReader(),f=!0;do{let{done:I,value:T}=await S.read();T&&h(this,W).feed(m.decode(T,{stream:!I})),I&&(f=!1,h(this,W).reset(),O(this,E,Yt).call(this))}while(f)}),w(this,zt,r=>{b(this,D,void 0),!(r.name==="AbortError"||r.type==="aborted")&&O(this,E,Yt).call(this,qt(r))}),w(this,Xt,r=>{typeof r.id=="string"&&b(this,nt,r.id);let a=new MessageEvent(r.event||"message",{data:r.data,origin:h(this,V)?h(this,V).origin:h(this,_).origin,lastEventId:r.id||""});h(this,z)&&(!r.event||r.event==="message")&&h(this,z).call(this,a),this.dispatchEvent(a)}),w(this,Kt,r=>{b(this,st,r)}),w(this,Qt,()=>{b(this,X,void 0),h(this,P)===this.CONNECTING&&O(this,E,Vt).call(this)});try{if(t instanceof URL)b(this,_,t);else if(typeof t=="string")b(this,_,new URL(t,ns()));else throw new Error("Invalid URL")}catch{throw ss("An invalid or illegal string was specified")}b(this,W,Se({onEvent:h(this,Xt),onRetry:h(this,Kt)})),b(this,P,this.CONNECTING),b(this,st,3e3),b(this,Lt,(s=e?.fetch)!=null?s:globalThis.fetch),b(this,Dt,(i=e?.withCredentials)!=null?i:!1),O(this,E,Vt).call(this)}get readyState(){return h(this,P)}get url(){return h(this,_).href}get withCredentials(){return h(this,Dt)}get onerror(){return h(this,K)}set onerror(t){b(this,K,t)}get onmessage(){return h(this,z)}set onmessage(t){b(this,z,t)}get onopen(){return h(this,tt)}set onopen(t){b(this,tt,t)}addEventListener(t,e,s){let i=e;super.addEventListener(t,i,s)}removeEventListener(t,e,s){let i=e;super.removeEventListener(t,i,s)}close(){h(this,X)&&clearTimeout(h(this,X)),h(this,P)!==this.CLOSED&&(h(this,D)&&h(this,D).abort(),b(this,P,this.CLOSED),b(this,D,void 0))}};P=new WeakMap,_=new WeakMap,V=new WeakMap,Dt=new WeakMap,Lt=new WeakMap,st=new WeakMap,X=new WeakMap,nt=new WeakMap,D=new WeakMap,W=new WeakMap,K=new WeakMap,z=new WeakMap,tt=new WeakMap,E=new WeakSet,Vt=function(){b(this,P,this.CONNECTING),b(this,D,new AbortController),h(this,Lt)(h(this,_),O(this,E,Pe).call(this)).then(h(this,Wt)).catch(h(this,zt))},Wt=new WeakMap,zt=new WeakMap,Pe=function(){var n;let t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...h(this,nt)?{"Last-Event-ID":h(this,nt)}:void 0},cache:"no-store",signal:(n=h(this,D))==null?void 0:n.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Xt=new WeakMap,Kt=new WeakMap,et=function(n,t){var e;h(this,P)!==this.CLOSED&&b(this,P,this.CLOSED);let s=new Ut("error",{code:t,message:n});(e=h(this,K))==null||e.call(this,s),this.dispatchEvent(s)},Yt=function(n,t){var e;if(h(this,P)===this.CLOSED)return;b(this,P,this.CONNECTING);let s=new Ut("error",{code:t,message:n});(e=h(this,K))==null||e.call(this,s),this.dispatchEvent(s),b(this,X,setTimeout(h(this,Qt),h(this,st)))},Qt=new WeakMap,F.CONNECTING=0,F.OPEN=1,F.CLOSED=2;function ns(){let n="document"in globalThis?globalThis.document:void 0;return n&&typeof n=="object"&&"baseURI"in n&&typeof n.baseURI=="string"?n.baseURI:void 0}var _t=class{eventSource=null;handlers=new Map;config;reconnectAttempts=0;maxReconnectAttempts=10;baseReconnectDelay=1e3;connected=!1;constructor(t){this.config={...t,sessionId:t.sessionId??crypto.randomUUID()}}async connect(){return new Promise((t,e)=>{let s=new URL("/events",this.config.sseUrl);s.searchParams.set("sessionId",this.config.sessionId),this.eventSource=new F(s.toString(),{fetch:(i,r)=>fetch(i,{...r,headers:{...r?.headers,Authorization:`Bearer ${this.config.token}`}})}),this.eventSource.onopen=()=>{this.connected=!0,this.reconnectAttempts=0,t()},this.eventSource.onerror=()=>{if(!this.connected){e(new Error("Failed to connect to SSE server"));return}this.handleReconnect()},this.eventSource.onmessage=i=>{try{let r=JSON.parse(i.data);this.dispatchEvent(r)}catch{}}})}async subscribe(t){if(!this.connected)throw new Error("Not connected to SSE server");let e=new URL("/subscribe",this.config.sseUrl),s=await fetch(e.toString(),{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:t})});if(!s.ok)throw new Error(`Failed to subscribe to project ${t}: ${s.status}`)}async unsubscribe(t){if(!this.connected)return;let e=new URL("/unsubscribe",this.config.sseUrl);await fetch(e.toString(),{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:t})})}on(t,e){let s=t;return this.handlers.has(s)||this.handlers.set(s,new Set),this.handlers.get(s).add(e),()=>{this.handlers.get(s)?.delete(e)}}disconnect(){this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.connected=!1,this.handlers.clear()}get isConnected(){return this.connected}dispatchEvent(t){let e={type:t.type,data:t.data??t,timestamp:t.timestamp??new Date().toISOString(),sequenceNumber:t.sequenceNumber},s=this.handlers.get(e.type);if(s)for(let r of s)r(e);let i=this.handlers.get("*");if(i)for(let r of i)r(e)}handleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){this.disconnect();return}this.eventSource&&(this.eventSource.close(),this.eventSource=null);let t=this.baseReconnectDelay*Math.pow(2,this.reconnectAttempts);this.reconnectAttempts++,setTimeout(()=>{this.connect().catch(()=>{this.handleReconnect()})},t)}};var Ft=$(require("fs")),it=$(require("path"));var is=["JOB_CONTEXT.json",it.join(process.env.HOME||"/home/daytona","JOB_CONTEXT.json")];function rt(n){let t=n?[it.resolve(n)]:is.map(e=>it.resolve(e));for(let e of t)if(Ft.existsSync(e)){let s=Ft.readFileSync(e,"utf-8"),i;try{i=JSON.parse(s)}catch{throw new A(`Invalid JSON in ${e}`)}return rs(i,e),i}throw new R("JOB_CONTEXT.json not found. Searched: "+t.join(", "),{code:"JOB_CONTEXT_NOT_FOUND",exitCode:1})}function rs(n,t){let e=[];if(n.jobId||e.push("jobId"),n.fileId||e.push("fileId"),n.fileName||e.push("fileName"),n.sourceFileUrl||e.push("sourceFileUrl"),n.deploymentId||e.push("deploymentId"),n.extractionSchemaId||e.push("extractionSchemaId"),e.length>0)throw new A(`JOB_CONTEXT.json (${t}) missing required fields: ${e.join(", ")}`);if(!n.schema||!Array.isArray(n.schema.tables)||n.schema.tables.length===0)throw new A(`JOB_CONTEXT.json (${t}) must have schema.tables with at least one table`);for(let s of n.schema.tables){if(!s.id||!s.name)throw new A("JOB_CONTEXT.json: table missing id or name");if(!Array.isArray(s.columns)||s.columns.length===0)throw new A(`JOB_CONTEXT.json: table "${s.name}" has no columns`)}}function Ee(n){let t=process.env.LIMAI_JOB_ID;return t||rt(n).jobId}function Te(n){let t=process.env.LIMAI_FILE_ID;return t||rt(n).fileId}function Ae(n){let t=process.env.LIMAI_DEPLOYMENT_ID;return t||rt(n).deploymentId}function Ie(n,t){let e=[],s=[],i=[],r=0;if(!n||typeof n!="object")return{valid:!1,errors:["Submission must be a JSON object"],warnings:[],summary:{tablesFound:0,totalRows:0,tableDetails:[]}};if(!n.tables||typeof n.tables!="object")return{valid:!1,errors:['Submission must have a "tables" object'],warnings:[],summary:{tablesFound:0,totalRows:0,tableDetails:[]}};let a=new Map;for(let u of t.schema.tables)a.set(u.name,u);let p=Object.keys(n.tables);for(let u of p){let c=a.get(u);if(!c){e.push(`Table "${u}" not found in schema. Available tables: ${[...a.keys()].join(", ")}`);continue}let g=n.tables[u];if(!Array.isArray(g)){e.push(`Table "${u}": rows must be an array`);continue}let y=!c.isPrimary,m=new Set(c.columns.map(f=>f.name)),S=new Map(c.columns.map(f=>[f.name,f]));for(let f=0;f<g.length;f++){let I=g[f];os(I,f,u,y,m,S,e,s)}i.push({name:u,rowCount:g.length,isChild:y}),r+=g.length}for(let u of t.schema.tables)p.includes(u.name)||s.push(`Schema table "${u.name}" has no data in submission`);return{valid:e.length===0,errors:e,warnings:s,summary:{tablesFound:p.length,totalRows:r,tableDetails:i}}}function os(n,t,e,s,i,r,a,p){let u=`Table "${e}" row ${t}`;if(typeof n!="object"||n===null){a.push(`${u}: must be an object`);return}if(typeof n.index!="number"&&a.push(`${u}: missing or invalid "index" (must be a number)`),!n.cells||typeof n.cells!="object"){a.push(`${u}: missing or invalid "cells" object`);return}s&&(n.parentIndex===void 0||n.parentIndex===null)&&a.push(`${u}: child table rows must have "parentIndex"`),s&&n.parentIndex!==void 0&&typeof n.parentIndex!="number"&&a.push(`${u}: "parentIndex" must be a number`);let c=Object.keys(n.cells);if(c.length===0){a.push(`${u}: cells object is empty`);return}let g=0;for(let y of c)if(!i.has(y))p.push(`${u}: unknown column "${y}" (will be skipped by API)`);else{g++;let m=r.get(y);m&&as(n.cells[y],y,m.type,m.isList,u,p)}g===0&&a.push(`${u}: no cell keys match any schema column`)}function as(n,t,e,s,i,r){if(n!=null){if(s&&!Array.isArray(n)){r.push(`${i}: column "${t}" is a LIST but value is not an array`);return}switch(e){case"NUMBER":typeof n!="number"&&typeof n!="string"&&r.push(`${i}: column "${t}" (NUMBER) has unexpected type ${typeof n}`);break;case"BOOLEAN":typeof n!="boolean"&&r.push(`${i}: column "${t}" (BOOLEAN) has unexpected type ${typeof n}`);break;case"DATE":typeof n!="string"&&r.push(`${i}: column "${t}" (DATE) should be an ISO date string`);break;case"LIST":Array.isArray(n)||r.push(`${i}: column "${t}" (LIST) should be an array`);break}}}0&&(module.exports={AuthError,ConflictError,ForbiddenError,HttpClient,JobPoller,LimaiClient,LimaiError,NotFoundError,RateLimitError,SSEClient,ServerError,TimeoutError,UploadError,ValidationError,collectAll,getDeploymentId,getFileId,getJobId,loadConfig,loadJobContext,mapHttpError,paginateOffset,paginatePage,requireConfig,saveConfig,validateSubmission});
|
|
4
|
+
`,o);continue}let w=l.charCodeAt(o);if(ve(l,o,w)){let S=l.charCodeAt(o+5)===_?o+6:o+5,O=l.slice(S,d);if(c===0&&l.charCodeAt(d+1)===Se){t({id:p,event:g,data:O}),p=void 0,u="",g=void 0,o=d+2,d=l.indexOf(`
|
|
5
|
+
`,o);continue}u=c===0?O:`${u}
|
|
6
|
+
${O}`,c++}else Ee(l,o,w)?g=l.slice(l.charCodeAt(o+6)===_?o+7:o+6,d)||void 0:E(l,o,d);o=d+1,d=l.indexOf(`
|
|
7
|
+
`,o)}return l.slice(o)}for(;o<l.length;){let d=l.indexOf("\r",o),w=l.indexOf(`
|
|
8
|
+
`,o),S=-1;if(d!==-1&&w!==-1?S=d<w?d:w:d!==-1?d===l.length-1?S=-1:S=d:w!==-1&&(S=w),S===-1)break;E(l,o,S),o=S+1,l.charCodeAt(o-1)===rs&&l.charCodeAt(o)===Se&&o++}return l.slice(o)}function E(l,o,d){if(o===d){A();return}let w=l.charCodeAt(o);if(ve(l,o,w)){let M=l.charCodeAt(o+5)===_?o+6:o+5,se=l.slice(M,d);u=c===0?se:`${u}
|
|
9
|
+
${se}`,c++;return}if(Ee(l,o,w)){g=l.slice(l.charCodeAt(o+6)===_?o+7:o+6,d)||void 0;return}if(w===105&&l.charCodeAt(o+1)===100&&l.charCodeAt(o+2)===58){let M=l.slice(l.charCodeAt(o+3)===_?o+4:o+3,d);p=M.includes("\0")?void 0:M;return}if(w===58){if(r){let M=l.slice(o,d);r(M.slice(l.charCodeAt(o+1)===_?2:1))}return}let S=l.slice(o,d),O=S.indexOf(":");if(O===-1){f(S,"",S);return}let Oe=S.slice(0,O),Ue=S.charCodeAt(O+1)===_?2:1,je=S.slice(O+Ue);f(Oe,je,S)}function f(l,o,d){switch(l){case"event":g=o||void 0;break;case"data":u=c===0?o:`${u}
|
|
10
|
+
${o}`,c++;break;case"id":p=o.includes("\0")?void 0:o;break;case"retry":/^\d+$/.test(o)?s(parseInt(o,10)):e(new jt(`Invalid \`retry\` value: "${o}"`,{type:"invalid-retry",value:o,line:d}));break;default:e(new jt(`Unknown field "${l.length>20?`${l.slice(0,20)}\u2026`:l}"`,{type:"unknown-field",field:l,value:o,line:d}));break}}function A(){c>0&&t({id:p,event:g,data:u}),p=void 0,u="",c=0,g=void 0}function T(l={}){if(l.consume&&i.length>0){let o=i.join("");E(o,0,o.length)}a=!0,p=void 0,u="",c=0,g=void 0,i.length=0}return{feed:y,reset:T}}function ve(n,t,e){return e===100&&n.charCodeAt(t+1)===97&&n.charCodeAt(t+2)===116&&n.charCodeAt(t+3)===97&&n.charCodeAt(t+4)===58}function Ee(n,t,e){return e===101&&n.charCodeAt(t+1)===118&&n.charCodeAt(t+2)===101&&n.charCodeAt(t+3)===110&&n.charCodeAt(t+4)===116&&n.charCodeAt(t+5)===58}var Lt=class extends Event{constructor(t,e){var s,r;super(t),this.code=(s=e?.code)!=null?s:void 0,this.message=(r=e?.message)!=null?r:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,e,s){return s(Pe(this),e)}[Symbol.for("Deno.customInspect")](t,e){return t(Pe(this),e)}};function is(n){let t=globalThis.DOMException;return typeof t=="function"?new t(n,"SyntaxError"):new SyntaxError(n)}function qt(n){return n instanceof Error?"errors"in n&&Array.isArray(n.errors)?n.errors.map(qt).join(", "):"cause"in n&&n.cause instanceof Error?`${n}: ${qt(n.cause)}`:n.message:`${n}`}function Pe(n){return{type:n.type,message:n.message,code:n.code,defaultPrevented:n.defaultPrevented,cancelable:n.cancelable,timeStamp:n.timeStamp}}var Te=n=>{throw TypeError(n)},ee=(n,t,e)=>t.has(n)||Te("Cannot "+e),h=(n,t,e)=>(ee(n,t,"read from private field"),e?e.call(n):t.get(n)),C=(n,t,e)=>t.has(n)?Te("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(n):t.set(n,e),b=(n,t,e,s)=>(ee(n,t,"write to private field"),t.set(n,e),e),D=(n,t,e)=>(ee(n,t,"access private method"),e),I,L,q,_t,Nt,st,X,nt,U,K,Y,z,tt,x,Kt,zt,Xt,xe,Yt,Qt,et,Zt,te,N=class extends EventTarget{constructor(t,e){var s,r;super(),C(this,x),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,C(this,I),C(this,L),C(this,q),C(this,_t),C(this,Nt),C(this,st),C(this,X),C(this,nt,null),C(this,U),C(this,K),C(this,Y,null),C(this,z,null),C(this,tt,null),C(this,zt,async i=>{var a;h(this,K).reset();let{body:p,redirected:u,status:c,headers:g}=i;if(c===204){D(this,x,et).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?b(this,q,new URL(i.url)):b(this,q,void 0),c!==200){D(this,x,et).call(this,`Non-200 status code (${c})`,c);return}if(!(g.get("content-type")||"").startsWith("text/event-stream")){D(this,x,et).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(h(this,I)===this.CLOSED)return;b(this,I,this.OPEN);let y=new Event("open");if((a=h(this,tt))==null||a.call(this,y),this.dispatchEvent(y),typeof p!="object"||!p||!("getReader"in p)){D(this,x,et).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}let m=new TextDecoder,E=p.getReader(),f=!0;do{let{done:A,value:T}=await E.read();T&&h(this,K).feed(m.decode(T,{stream:!A})),A&&(f=!1,h(this,K).reset(),D(this,x,Zt).call(this))}while(f)}),C(this,Xt,i=>{b(this,U,void 0),!(i.name==="AbortError"||i.type==="aborted")&&D(this,x,Zt).call(this,qt(i))}),C(this,Yt,i=>{typeof i.id=="string"&&b(this,nt,i.id);let a=new MessageEvent(i.event||"message",{data:i.data,origin:h(this,q)?h(this,q).origin:h(this,L).origin,lastEventId:i.id||""});h(this,z)&&(!i.event||i.event==="message")&&h(this,z).call(this,a),this.dispatchEvent(a)}),C(this,Qt,i=>{b(this,st,i)}),C(this,te,()=>{b(this,X,void 0),h(this,I)===this.CONNECTING&&D(this,x,Kt).call(this)});try{if(t instanceof URL)b(this,L,t);else if(typeof t=="string")b(this,L,new URL(t,os()));else throw new Error("Invalid URL")}catch{throw is("An invalid or illegal string was specified")}b(this,K,Ie({onEvent:h(this,Yt),onRetry:h(this,Qt)})),b(this,I,this.CONNECTING),b(this,st,3e3),b(this,Nt,(s=e?.fetch)!=null?s:globalThis.fetch),b(this,_t,(r=e?.withCredentials)!=null?r:!1),D(this,x,Kt).call(this)}get readyState(){return h(this,I)}get url(){return h(this,L).href}get withCredentials(){return h(this,_t)}get onerror(){return h(this,Y)}set onerror(t){b(this,Y,t)}get onmessage(){return h(this,z)}set onmessage(t){b(this,z,t)}get onopen(){return h(this,tt)}set onopen(t){b(this,tt,t)}addEventListener(t,e,s){let r=e;super.addEventListener(t,r,s)}removeEventListener(t,e,s){let r=e;super.removeEventListener(t,r,s)}close(){h(this,X)&&clearTimeout(h(this,X)),h(this,I)!==this.CLOSED&&(h(this,U)&&h(this,U).abort(),b(this,I,this.CLOSED),b(this,U,void 0))}};I=new WeakMap,L=new WeakMap,q=new WeakMap,_t=new WeakMap,Nt=new WeakMap,st=new WeakMap,X=new WeakMap,nt=new WeakMap,U=new WeakMap,K=new WeakMap,Y=new WeakMap,z=new WeakMap,tt=new WeakMap,x=new WeakSet,Kt=function(){b(this,I,this.CONNECTING),b(this,U,new AbortController),h(this,Nt)(h(this,L),D(this,x,xe).call(this)).then(h(this,zt)).catch(h(this,Xt))},zt=new WeakMap,Xt=new WeakMap,xe=function(){var n;let t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...h(this,nt)?{"Last-Event-ID":h(this,nt)}:void 0},cache:"no-store",signal:(n=h(this,U))==null?void 0:n.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Yt=new WeakMap,Qt=new WeakMap,et=function(n,t){var e;h(this,I)!==this.CLOSED&&b(this,I,this.CLOSED);let s=new Lt("error",{code:t,message:n});(e=h(this,Y))==null||e.call(this,s),this.dispatchEvent(s)},Zt=function(n,t){var e;if(h(this,I)===this.CLOSED)return;b(this,I,this.CONNECTING);let s=new Lt("error",{code:t,message:n});(e=h(this,Y))==null||e.call(this,s),this.dispatchEvent(s),b(this,X,setTimeout(h(this,te),h(this,st)))},te=new WeakMap,N.CONNECTING=0,N.OPEN=1,N.CLOSED=2;function os(){let n="document"in globalThis?globalThis.document:void 0;return n&&typeof n=="object"&&"baseURI"in n&&typeof n.baseURI=="string"?n.baseURI:void 0}var Mt=class{eventSource=null;handlers=new Map;config;reconnectAttempts=0;maxReconnectAttempts=10;baseReconnectDelay=1e3;connected=!1;constructor(t){this.config={...t,sessionId:t.sessionId??crypto.randomUUID()}}async connect(){return new Promise((t,e)=>{let s=new URL("/events",this.config.sseUrl);s.searchParams.set("sessionId",this.config.sessionId),this.eventSource=new N(s.toString(),{fetch:(r,i)=>fetch(r,{...i,headers:{...i?.headers,Authorization:`Bearer ${this.config.token}`}})}),this.eventSource.onopen=()=>{this.connected=!0,this.reconnectAttempts=0,t()},this.eventSource.onerror=()=>{if(!this.connected){e(new Error("Failed to connect to SSE server"));return}this.handleReconnect()},this.eventSource.onmessage=r=>{try{let i=JSON.parse(r.data);this.dispatchEvent(i)}catch{}}})}async subscribe(t){if(!this.connected)throw new Error("Not connected to SSE server");let e=new URL("/subscribe",this.config.sseUrl),s=await fetch(e.toString(),{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:t})});if(!s.ok)throw new Error(`Failed to subscribe to project ${t}: ${s.status}`)}async unsubscribe(t){if(!this.connected)return;let e=new URL("/unsubscribe",this.config.sseUrl);await fetch(e.toString(),{method:"POST",headers:{Authorization:`Bearer ${this.config.token}`,"Content-Type":"application/json"},body:JSON.stringify({projectId:t})})}on(t,e){let s=t;return this.handlers.has(s)||this.handlers.set(s,new Set),this.handlers.get(s).add(e),()=>{this.handlers.get(s)?.delete(e)}}disconnect(){this.eventSource&&(this.eventSource.close(),this.eventSource=null),this.connected=!1,this.handlers.clear()}get isConnected(){return this.connected}dispatchEvent(t){let e={type:t.type,data:t.data??t,timestamp:t.timestamp??new Date().toISOString(),sequenceNumber:t.sequenceNumber},s=this.handlers.get(e.type);if(s)for(let i of s)i(e);let r=this.handlers.get("*");if(r)for(let i of r)i(e)}handleReconnect(){if(this.reconnectAttempts>=this.maxReconnectAttempts){this.disconnect();return}this.eventSource&&(this.eventSource.close(),this.eventSource=null);let t=this.baseReconnectDelay*Math.pow(2,this.reconnectAttempts);this.reconnectAttempts++,setTimeout(()=>{this.connect().catch(()=>{this.handleReconnect()})},t)}};var Ft=P(require("fs")),rt=P(require("path"));var as=["JOB_CONTEXT.json",rt.join(process.env.HOME||"/home/daytona","JOB_CONTEXT.json")];function it(n){let t=n?[rt.resolve(n)]:as.map(e=>rt.resolve(e));for(let e of t)if(Ft.existsSync(e)){let s=Ft.readFileSync(e,"utf-8"),r;try{r=JSON.parse(s)}catch{throw new $(`Invalid JSON in ${e}`)}return cs(r,e),r}throw new R("JOB_CONTEXT.json not found. Searched: "+t.join(", "),{code:"JOB_CONTEXT_NOT_FOUND",exitCode:1})}function cs(n,t){let e=[];if(n.jobId||e.push("jobId"),n.fileId||e.push("fileId"),n.fileName||e.push("fileName"),n.sourceFileUrl||e.push("sourceFileUrl"),n.deploymentId||e.push("deploymentId"),n.extractionSchemaId||e.push("extractionSchemaId"),e.length>0)throw new $(`JOB_CONTEXT.json (${t}) missing required fields: ${e.join(", ")}`);if(!n.schema||!Array.isArray(n.schema.tables)||n.schema.tables.length===0)throw new $(`JOB_CONTEXT.json (${t}) must have schema.tables with at least one table`);for(let s of n.schema.tables){if(!s.id||!s.name)throw new $("JOB_CONTEXT.json: table missing id or name");if(!Array.isArray(s.columns)||s.columns.length===0)throw new $(`JOB_CONTEXT.json: table "${s.name}" has no columns`)}}function $e(n){let t=process.env.LIMAI_JOB_ID;return t||it(n).jobId}function Ae(n){let t=process.env.LIMAI_FILE_ID;return t||it(n).fileId}function ke(n){let t=process.env.LIMAI_DEPLOYMENT_ID;return t||it(n).deploymentId}function De(n,t){let e=[],s=[],r=[],i=0;if(!n||typeof n!="object")return{valid:!1,errors:["Submission must be a JSON object"],warnings:[],summary:{tablesFound:0,totalRows:0,tableDetails:[]}};if(!n.tables||typeof n.tables!="object")return{valid:!1,errors:['Submission must have a "tables" object'],warnings:[],summary:{tablesFound:0,totalRows:0,tableDetails:[]}};let a=new Map;for(let u of t.schema.tables)a.set(u.name,u);let p=Object.keys(n.tables);for(let u of p){let c=a.get(u);if(!c){e.push(`Table "${u}" not found in schema. Available tables: ${[...a.keys()].join(", ")}`);continue}let g=n.tables[u];if(!Array.isArray(g)){e.push(`Table "${u}": rows must be an array`);continue}let y=!c.isPrimary,m=new Set(c.columns.map(f=>f.name)),E=new Map(c.columns.map(f=>[f.name,f]));for(let f=0;f<g.length;f++){let A=g[f];ls(A,f,u,y,m,E,e,s)}r.push({name:u,rowCount:g.length,isChild:y}),i+=g.length}for(let u of t.schema.tables)p.includes(u.name)||s.push(`Schema table "${u.name}" has no data in submission`);return{valid:e.length===0,errors:e,warnings:s,summary:{tablesFound:p.length,totalRows:i,tableDetails:r}}}function ls(n,t,e,s,r,i,a,p){let u=`Table "${e}" row ${t}`;if(typeof n!="object"||n===null){a.push(`${u}: must be an object`);return}if(typeof n.index!="number"&&a.push(`${u}: missing or invalid "index" (must be a number)`),!n.cells||typeof n.cells!="object"){a.push(`${u}: missing or invalid "cells" object`);return}s&&(n.parentIndex===void 0||n.parentIndex===null)&&a.push(`${u}: child table rows must have "parentIndex"`),s&&n.parentIndex!==void 0&&typeof n.parentIndex!="number"&&a.push(`${u}: "parentIndex" must be a number`);let c=Object.keys(n.cells);if(c.length===0){a.push(`${u}: cells object is empty`);return}let g=0;for(let y of c)if(!r.has(y))p.push(`${u}: unknown column "${y}" (will be skipped by API)`);else{g++;let m=i.get(y);m&&ps(n.cells[y],y,m.type,m.isList,u,p)}g===0&&a.push(`${u}: no cell keys match any schema column`)}function ps(n,t,e,s,r,i){if(n!=null){if(s&&!Array.isArray(n)){i.push(`${r}: column "${t}" is a LIST but value is not an array`);return}switch(e){case"NUMBER":typeof n!="number"&&typeof n!="string"&&i.push(`${r}: column "${t}" (NUMBER) has unexpected type ${typeof n}`);break;case"BOOLEAN":typeof n!="boolean"&&i.push(`${r}: column "${t}" (BOOLEAN) has unexpected type ${typeof n}`);break;case"DATE":typeof n!="string"&&i.push(`${r}: column "${t}" (DATE) should be an ISO date string`);break;case"LIST":Array.isArray(n)||i.push(`${r}: column "${t}" (LIST) should be an array`);break}}}0&&(module.exports={AuthError,ConflictError,ForbiddenError,HttpClient,JobPoller,LimaiClient,LimaiError,NotFoundError,RateLimitError,SSEClient,ServerError,TimeoutError,UploadError,ValidationError,collectAll,getDeploymentId,getFileId,getJobId,loadConfig,loadJobContext,mapHttpError,paginateOffset,paginatePage,requireConfig,saveConfig,validateSubmission});
|