@limai.io/cli 0.4.5 → 0.4.7

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/index.d.ts CHANGED
@@ -774,7 +774,7 @@ declare class DocumentsResource {
774
774
  processSync(extractionSchemaId: string, fileId: string, opts?: ProcessOptions): Promise<FileData>;
775
775
  processAsync(extractionSchemaId: string, fileId: string, opts?: ProcessOptions): Promise<ProcessFileAsyncResponse>;
776
776
  processFilesAsync(extractionSchemaId: string, fileIds: string[], opts?: ProcessOptions): Promise<BulkProcessResponse>;
777
- getFileData(fileId: string, extractionSchemaId?: string, include?: IncludeOption[]): Promise<FileData>;
777
+ getFileData(fileId: string, extractionSchemaId?: string, include?: IncludeOption[], jobId?: string): Promise<FileData>;
778
778
  getFilesData(fileIds: string[], include?: IncludeOption[]): Promise<BulkGetFilesDataResponse>;
779
779
  getDocumentData(deploymentId: string, fileId: string, include?: IncludeOption[]): Promise<FlatDocumentDataResponse>;
780
780
  getDocumentsData(deploymentId: string, fileIds: string[], include?: IncludeOption[]): Promise<BulkFlatDocumentDataResponse>;
@@ -1167,6 +1167,7 @@ declare class AgentsResource {
1167
1167
  type: string;
1168
1168
  title: string;
1169
1169
  description?: string;
1170
+ requirement?: string;
1170
1171
  postReviewAction?: string;
1171
1172
  data?: Record<string, unknown>;
1172
1173
  order: number;
@@ -1194,6 +1195,7 @@ declare class AgentsResource {
1194
1195
  type: string;
1195
1196
  title: string;
1196
1197
  description?: string;
1198
+ requirement?: string;
1197
1199
  postReviewAction?: string;
1198
1200
  data?: Record<string, unknown>;
1199
1201
  order: number;
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
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:()=>x,collectAll:()=>Rt,getDeploymentId:()=>ke,getFileId:()=>Ae,getJobId:()=>xe,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"}},x=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 x(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(`/deployments/${t}/configuration`)}async update(t,e){return this.http.patch(`/deployments/${t}/configuration`,e)}async getAllData(t){return this.http.get(`/deployments/${t}/all-data`)}};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 Tt=class{constructor(t){this.http=t}http;async ask(t,e){return this.http.post(`/projects/${t}/vision/ask`,e,12e4)}};var $t=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(`/deployments/${t}/validation-scripts`)).scripts}async getScript(t,e,s){return(await this.http.get(`/deployments/${t}/validation-scripts/${encodeURIComponent(e)}`,s?.includeSource?{includeSource:"true"}:void 0)).script}async pushScript(t,e){return this.http.post(`/deployments/${t}/validation-scripts`,e)}async updateScript(t,e,s){return(await this.http.patch(`/deployments/${t}/validation-scripts/${encodeURIComponent(e)}`,s)).script}async deleteScript(t,e){return this.http.del(`/deployments/${t}/validation-scripts/${encodeURIComponent(e)}`)}};var xt=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 $=await t.processFilesAsync(e,A,r.processOptions);for(let[l,o]of Object.entries($.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($){for(let l of A){let o=p.find(d=>d.fileId===l);o&&(o.status="failed",o.error=$ instanceof Error?$.message:String($),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 Tt(this.http),this.validations=new $t(this.http),this.labels=new xt(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(`
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:()=>x,collectAll:()=>Rt,getDeploymentId:()=>ke,getFileId:()=>Ae,getJobId:()=>xe,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"}},x=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 x(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,r){let i={fileId:t,extractionSchemaId:e,jobId:r,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 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(`/deployments/${t}/configuration`)}async update(t,e){return this.http.patch(`/deployments/${t}/configuration`,e)}async getAllData(t){return this.http.get(`/deployments/${t}/all-data`)}};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 Tt=class{constructor(t){this.http=t}http;async ask(t,e){return this.http.post(`/projects/${t}/vision/ask`,e,12e4)}};var $t=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(`/deployments/${t}/validation-scripts`)).scripts}async getScript(t,e,s){return(await this.http.get(`/deployments/${t}/validation-scripts/${encodeURIComponent(e)}`,s?.includeSource?{includeSource:"true"}:void 0)).script}async pushScript(t,e){return this.http.post(`/deployments/${t}/validation-scripts`,e)}async updateScript(t,e,s){return(await this.http.patch(`/deployments/${t}/validation-scripts/${encodeURIComponent(e)}`,s)).script}async deleteScript(t,e){return this.http.del(`/deployments/${t}/validation-scripts/${encodeURIComponent(e)}`)}};var xt=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 $=await t.processFilesAsync(e,A,r.processOptions);for(let[l,o]of Object.entries($.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($){for(let l of A){let o=p.find(d=>d.fileId===l);o&&(o.status="failed",o.error=$ instanceof Error?$.message:String($),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 Tt(this.http),this.validations=new $t(this.http),this.labels=new xt(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,void 0,r.jobId)}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
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
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(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@limai.io/cli",
3
- "version": "0.4.5",
3
+ "version": "0.4.7",
4
4
  "description": "CLI and SDK for the LimAI data extraction platform",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",