@limai.io/cli 0.4.2 → 0.4.4

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
@@ -314,17 +314,82 @@ type Deployment = {
314
314
  type DeploymentConfig = {
315
315
  id: string;
316
316
  modelName?: string;
317
+ /** @deprecated Ignored by the API; responses always echo 1. */
317
318
  temperature?: number;
319
+ thinkingBudget?: number | null;
320
+ reasoningLevel?: "LOW" | "MEDIUM" | "HIGH";
318
321
  instructions?: string;
322
+ writeMode?: string;
319
323
  bigTableExtraction?: string;
320
324
  useDynamicMapping?: boolean;
325
+ nestedExtraction?: "PER_PARENT_ROW" | "ONE_SHOT";
321
326
  bboxTier?: "OFF" | "FAST" | "BALANCED" | "PRO";
327
+ parsePdf?: boolean;
328
+ markdownConversionType?: "BASIC" | "PRO";
329
+ excelConversionMode?: "MARKDOWN_ONLY" | "PDF_ONLY" | "MARKDOWN_AND_PDF";
330
+ docxConversionMode?: "MARKDOWN_ONLY" | "PDF_ONLY" | "MARKDOWN_AND_PDF";
322
331
  enableConfidenceScore?: boolean;
323
332
  enableLLMConfidence?: boolean;
324
333
  enableLayoutConfidence?: boolean;
325
- maxPagesToProcess?: number;
334
+ llmConfidencePrompt?: string | null;
335
+ confidenceHighThreshold?: number;
336
+ extractionRunsCount?: number;
337
+ maxPagesToProcess?: number | null;
338
+ enableFilenameInExtraction?: boolean;
339
+ emailBodySplit?: boolean;
340
+ emailNestedExtraction?: "PER_PARENT_ROW" | "ONE_SHOT" | null;
326
341
  useExamples?: boolean;
327
342
  numberOfExamples?: number;
343
+ includeExampleDiff?: boolean;
344
+ exampleMatchingThreshold?: number;
345
+ disableExampleThreshold?: boolean;
346
+ setAllCorrectionsAsExamples?: boolean;
347
+ updatedAt?: string;
348
+ };
349
+ type DeploymentConfigUpdate = Partial<Omit<DeploymentConfig, "temperature">>;
350
+ type DeploymentConfigurationColumn = {
351
+ id: string;
352
+ name: string;
353
+ slug: string | null;
354
+ type: string;
355
+ index: number;
356
+ description: string | null;
357
+ defaultValue?: unknown;
358
+ defaultValueEnabled: boolean;
359
+ isKey: boolean;
360
+ isList: boolean;
361
+ measurementType: string;
362
+ dateFormat: string;
363
+ excludedFromExtraction: boolean;
364
+ autoGenerateLabels: boolean;
365
+ autoGenerateUnits: boolean;
366
+ sharedId: string | null;
367
+ labels: ColumnLabel[];
368
+ units: ColumnUnit[];
369
+ };
370
+ type DeploymentConfigurationTable = {
371
+ id: string;
372
+ name: string;
373
+ slug: string | null;
374
+ instructions: string | null;
375
+ isPrimary: boolean;
376
+ parentTableId: string | null;
377
+ wrapColumns: boolean;
378
+ columns: DeploymentConfigurationColumn[];
379
+ };
380
+ type DeploymentConfiguration = {
381
+ deployment: {
382
+ id: string;
383
+ name: string;
384
+ status: DeploymentStatus;
385
+ type: DeploymentType;
386
+ };
387
+ extractionSchema: DeploymentConfig;
388
+ tables: DeploymentConfigurationTable[];
389
+ sharedColumnIds: Array<{
390
+ id: string;
391
+ name: string;
392
+ }>;
328
393
  };
329
394
  type FileStatus = "UPLOADING" | "PARSING" | "UPLOADED" | "FAILED";
330
395
  type Document = {
@@ -426,18 +491,6 @@ type Table = {
426
491
  parentTableId?: string;
427
492
  columns: Column[];
428
493
  };
429
- type ExtractionSchema = {
430
- id: string;
431
- projectId: string;
432
- deploymentId: string;
433
- modelName?: string;
434
- instructions?: string;
435
- temperature?: number;
436
- bigTableExtraction?: string;
437
- useDynamicMapping?: boolean;
438
- bboxTier?: "OFF" | "FAST" | "BALANCED" | "PRO";
439
- enableConfidenceScore?: boolean;
440
- };
441
494
  type JobContextColumn = {
442
495
  id: string;
443
496
  name: string;
@@ -822,7 +875,7 @@ declare class DeploymentsResource {
822
875
  list(projectId: string, opts?: ListDeploymentsOpts): Promise<Deployment[]>;
823
876
  create(projectId: string, body: CreateDeploymentBody): Promise<Deployment>;
824
877
  getConfig(deploymentId: string): Promise<DeploymentConfig>;
825
- updateConfig(deploymentId: string, body: Partial<DeploymentConfig>): Promise<void>;
878
+ updateConfig(deploymentId: string, body: DeploymentConfigUpdate): Promise<void>;
826
879
  listDocuments(deploymentId: string, opts?: ListDocumentsOpts): Promise<OffsetPaginatedResponse<Document>>;
827
880
  getDocument(deploymentId: string, fileId: string): Promise<Document>;
828
881
  deleteDocument(deploymentId: string, fileId: string): Promise<void>;
@@ -976,9 +1029,9 @@ declare class SplitResource {
976
1029
  declare class SchemaResource {
977
1030
  private http;
978
1031
  constructor(http: HttpClient);
979
- get(extractionSchemaId: string): Promise<ExtractionSchema>;
980
- update(extractionSchemaId: string, body: Partial<DeploymentConfig>): Promise<DeploymentConfig>;
981
- getAllData(extractionSchemaId: string): Promise<unknown>;
1032
+ get(deploymentId: string): Promise<DeploymentConfiguration>;
1033
+ update(deploymentId: string, body: DeploymentConfigUpdate): Promise<DeploymentConfig>;
1034
+ getAllData(deploymentId: string): Promise<unknown>;
982
1035
  }
983
1036
 
984
1037
  declare class BucketsResource {
@@ -1650,4 +1703,4 @@ declare class UploadError extends LimaiError {
1650
1703
  }
1651
1704
  declare function mapHttpError(status: number, message: string, details?: unknown): LimaiError;
1652
1705
 
1653
- export { type Agent, type AgentDeploymentRoute, type AgentDetail, type AgentFile, type AgentIntegrationConfig, type AgentRole, type AgentRowData, type AgentRun, type AgentRunConversation, type AgentRunDetail, type AgentRunInferenceLog, type AgentRunInferenceLogSummary, type AgentRunInferenceLogs, type AgentRunStatus, type AgentSkill, type AgentSkillLinkedFile, type AgentStatus, type AgentStep, type AgentStepType, type AgentSubmission, type AgentTriggerType, AuthError, type Bucket, type BucketFile, type BulkFileResult, type BulkFlatDocumentDataResponse, type BulkGetFilesDataResponse, type BulkProcessResponse, type BulkProcessResult, type BulkUploadFileStatus, type BulkUploadResult, type CellBoundingBox, type CellConfidence, type CellValidation, type CellValue, type ClassificationAsyncResponse, type ClassificationResult, type ClassificationStatus, type Column, type ColumnInput, type ColumnLabel, type ColumnUnit, type ColumnUpdateInput, ConflictError, type CreateRowInput, type CreateRowsRequest, type CreateRowsResponse, type DeleteRowsRequest, type DeleteRowsResponse, type Deployment, type DeploymentConfig, type DeploymentStatus, type DeploymentType, type Document, type ExtractionRow, type ExtractionSchema, type ExtractionsResponse, type FileData, type FileStatus, type FileValidationCheck, type FileValidations, type FlatCellData, type FlatCellValidation, type FlatDocumentDataResponse, type FlatDocumentEntry, type FlatFileValidations, type FlatRow, ForbiddenError, type GetUrlResponse, HttpClient, type IncludeOption, type JobContext, type JobContextColumn, type JobContextTable, JobPoller, type JobStatus, type JobStatusValue, LimaiClient, type LimaiClientConfig, type LimaiConfig, LimaiError, NotFoundError, type OffsetPaginatedResponse, type OffsetPagination, type PagePaginatedResponse, type PagePagination, type PaginationOptions, type PollOptions, type ProcessFileAsyncResponse, type ProcessOptions, type Project, RateLimitError, type Row, SSEClient, ServerError, type SplitAsyncResponse, type SplitResult, type SplitSegment, type SplitStatus, type StageStatus, type Table, type TableData, TimeoutError, type UpdateStatusRequest, type UpdateStatusResponse, UploadError, type UploadResult, ValidationError, type ValidationResult, collectAll, getDeploymentId, getFileId, getJobId, loadConfig, loadJobContext, mapHttpError, paginateOffset, paginatePage, requireConfig, saveConfig, validateSubmission };
1706
+ export { type Agent, type AgentDeploymentRoute, type AgentDetail, type AgentFile, type AgentIntegrationConfig, type AgentRole, type AgentRowData, type AgentRun, type AgentRunConversation, type AgentRunDetail, type AgentRunInferenceLog, type AgentRunInferenceLogSummary, type AgentRunInferenceLogs, type AgentRunStatus, type AgentSkill, type AgentSkillLinkedFile, type AgentStatus, type AgentStep, type AgentStepType, type AgentSubmission, type AgentTriggerType, AuthError, type Bucket, type BucketFile, type BulkFileResult, type BulkFlatDocumentDataResponse, type BulkGetFilesDataResponse, type BulkProcessResponse, type BulkProcessResult, type BulkUploadFileStatus, type BulkUploadResult, type CellBoundingBox, type CellConfidence, type CellValidation, type CellValue, type ClassificationAsyncResponse, type ClassificationResult, type ClassificationStatus, type Column, type ColumnInput, type ColumnLabel, type ColumnUnit, type ColumnUpdateInput, ConflictError, type CreateRowInput, type CreateRowsRequest, type CreateRowsResponse, type DeleteRowsRequest, type DeleteRowsResponse, type Deployment, type DeploymentConfig, type DeploymentConfigUpdate, type DeploymentConfiguration, type DeploymentConfigurationColumn, type DeploymentConfigurationTable, type DeploymentStatus, type DeploymentType, type Document, type ExtractionRow, type ExtractionsResponse, type FileData, type FileStatus, type FileValidationCheck, type FileValidations, type FlatCellData, type FlatCellValidation, type FlatDocumentDataResponse, type FlatDocumentEntry, type FlatFileValidations, type FlatRow, ForbiddenError, type GetUrlResponse, HttpClient, type IncludeOption, type JobContext, type JobContextColumn, type JobContextTable, JobPoller, type JobStatus, type JobStatusValue, LimaiClient, type LimaiClientConfig, type LimaiConfig, LimaiError, NotFoundError, type OffsetPaginatedResponse, type OffsetPagination, type PagePaginatedResponse, type PagePagination, type PaginationOptions, type PollOptions, type ProcessFileAsyncResponse, type ProcessOptions, type Project, RateLimitError, type Row, SSEClient, ServerError, type SplitAsyncResponse, type SplitResult, type SplitSegment, type SplitStatus, type StageStatus, type Table, type TableData, TimeoutError, type UpdateStatusRequest, type UpdateStatusResponse, UploadError, type UploadResult, ValidationError, type ValidationResult, collectAll, getDeploymentId, getFileId, getJobId, loadConfig, loadJobContext, mapHttpError, paginateOffset, paginatePage, requireConfig, saveConfig, validateSubmission };
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:()=>$,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(`
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(`
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(`
@@ -7,4 +7,4 @@ ${O}`,c++}else Ee(l,o,w)?g=l.slice(l.charCodeAt(o+6)===_?o+7:o+6,d)||void 0:E(l,
7
7
  `,o)}return l.slice(o)}for(;o<l.length;){let d=l.indexOf("\r",o),w=l.indexOf(`
8
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
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});
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 $(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:$}}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 $e=n=>{throw TypeError(n)},ee=(n,t,e)=>t.has(n)||$e("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)?$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)=>(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,T,Kt,zt,Xt,Te,Yt,Qt,et,Zt,te,N=class extends EventTarget{constructor(t,e){var s,r;super(),C(this,T),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,T,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,T,et).call(this,`Non-200 status code (${c})`,c);return}if(!(g.get("content-type")||"").startsWith("text/event-stream")){D(this,T,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,T,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:$}=await E.read();$&&h(this,K).feed(m.decode($,{stream:!A})),A&&(f=!1,h(this,K).reset(),D(this,T,Zt).call(this))}while(f)}),C(this,Xt,i=>{b(this,U,void 0),!(i.name==="AbortError"||i.type==="aborted")&&D(this,T,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,T,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,T,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,T=new WeakSet,Kt=function(){b(this,I,this.CONNECTING),b(this,U,new AbortController),h(this,Nt)(h(this,L),D(this,T,Te).call(this)).then(h(this,zt)).catch(h(this,Xt))},zt=new WeakMap,Xt=new WeakMap,Te=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 x(`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 x(`JOB_CONTEXT.json (${t}) missing required fields: ${e.join(", ")}`);if(!n.schema||!Array.isArray(n.schema.tables)||n.schema.tables.length===0)throw new x(`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 x("JOB_CONTEXT.json: table missing id or name");if(!Array.isArray(s.columns)||s.columns.length===0)throw new x(`JOB_CONTEXT.json: table "${s.name}" has no columns`)}}function xe(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});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@limai.io/cli",
3
- "version": "0.4.2",
3
+ "version": "0.4.4",
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",