@graphysdk/agents-sdk 1.7.0-beta.1782310277218 → 1.7.0
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/README.md +7 -0
- package/dist/README.md +7 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +78 -12
- package/dist/index.mjs +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
TypeScript client types and helpers for Graphy agent HTTP APIs.
|
|
4
4
|
|
|
5
|
+
## Initial datasets (`datasetRef`)
|
|
6
|
+
|
|
7
|
+
Chart agent requests accept either inline **`config.data`** or a staged **`datasetRef`** (`graphy://attachments/{uuid}`).
|
|
8
|
+
Use **`uploadDataset(file)`** to stage CSV, TSV, or XLSX (presigned flow), then pass `datasetRef` on
|
|
9
|
+
`generateGraph`, `generateGraphStream`, and other `GraphGenerationRequestSchema` methods. Inline non-empty data and
|
|
10
|
+
`datasetRef` are mutually exclusive. See **`apps/agents-api/README.md`** (Initial datasets) for size limits and auth.
|
|
11
|
+
|
|
5
12
|
## Extract (`POST /api/v0/extract`)
|
|
6
13
|
|
|
7
14
|
`ExtractFromProseParams` mirrors `ExtractFromProseRequestSchema` in **agents-api**. Prefer **`attachments[]`** over deprecated **`images[]`** (do not send both).
|
package/dist/README.md
CHANGED
|
@@ -2,6 +2,13 @@
|
|
|
2
2
|
|
|
3
3
|
TypeScript client types and helpers for Graphy agent HTTP APIs.
|
|
4
4
|
|
|
5
|
+
## Initial datasets (`datasetRef`)
|
|
6
|
+
|
|
7
|
+
Chart agent requests accept either inline **`config.data`** or a staged **`datasetRef`** (`graphy://attachments/{uuid}`).
|
|
8
|
+
Use **`uploadDataset(file)`** to stage CSV, TSV, or XLSX (presigned flow), then pass `datasetRef` on
|
|
9
|
+
`generateGraph`, `generateGraphStream`, and other `GraphGenerationRequestSchema` methods. Inline non-empty data and
|
|
10
|
+
`datasetRef` are mutually exclusive. See **`apps/agents-api/README.md`** (Initial datasets) for size limits and auth.
|
|
11
|
+
|
|
5
12
|
## Extract (`POST /api/v0/extract`)
|
|
6
13
|
|
|
7
14
|
`ExtractFromProseParams` mirrors `ExtractFromProseRequestSchema` in **agents-api**. Prefer **`attachments[]`** over deprecated **`images[]`** (do not send both).
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("tslib"),t=require("zod");class n extends Error{constructor(e,t){var n;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(n=null==t?void 0:t.retryable)&&void 0!==n&&n}}const r=e=>"progress"===e.type,a=e=>"complete"===e.type,o=e=>"error"===e.type;function i(e,t){if("progress"===e){const e=t;return Object.assign({type:"progress"},e)}if("complete"===e)return{type:"complete",data:t};if("error"===e){const e=t;return Object.assign({type:"error"},e)}if("preview"===e){const e=t;return Object.assign(Object.assign({},e),{type:"preview"})}if("reasoning"===e){const e=t;return Object.assign(Object.assign({},e),{type:"reasoning"})}return"llm_step"===e||"session_budget"===e||"agent_complete"===e||"tool_call"===e||"tool_complete"===e||"tool_error"===e?t:null}class s{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return r(e)}static isCompleteEvent(e){return a(e)}static isErrorEvent(e){return o(e)}stream(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,r);return this.parseSSE(e)})}fetch(t,i,s,c){return e.__awaiter(this,void 0,void 0,function*(){var l,m,p,u,d;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const y=yield this.makeRequest(t,i,c),z=y.headers.get("content-type");if(null==z?void 0:z.includes("text/event-stream")){try{for(var h,f=!0,b=e.__asyncValues(this.parseSSE(y));!(l=(h=yield b.next()).done);f=!0){u=h.value,f=!1;const e=u;if(r(e)&&s&&s(e),a(e))return e.data;if(o(e)){const r=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${t} ${r}ms`,e.error),new n(e.error,{code:e.code,retryable:null!==(d=e.retryable)&&void 0!==d&&d})}}}catch(e){m={error:e}}finally{try{f||l||!(p=b.return)||(yield p.call(b))}finally{if(m)throw m.error}}const i=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${i}ms`),new n("Stream ended without completion")}return yield y.json()}catch(e){const r=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${r}ms`,e),e instanceof n)throw e;throw e}finally{const e=Date.now()-g;this.logger.debug(`${this.tag} Fetch completed: ${t} ${e}ms`)}})}ping(){return e.__awaiter(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}uploadMultipart(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,n,r);return yield e.json()})}get(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,void 0,n,1,"GET");return yield e.json()})}postJson(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,r,1,"POST");return yield e.json()})}sleep(t){return e.__awaiter(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(t){return e.__asyncGenerator(this,arguments,function*(){if(!t.body)throw new n("Response body is null");const r=t.body.getReader(),a=new TextDecoder;let o="",s="",c="";try{for(;;){const{done:t,value:n}=yield e.__await(r.read());if(t)break;o+=a.decode(n,{stream:!0});const l=o.split(/\r?\n/);o=l.pop()||"";for(const t of l)if(t.startsWith("event: "))s=t.slice(7).trim();else if(t.startsWith("data: "))c+=(c?"\n":"")+t.slice(6);else if(""===t.trim()&&c){try{const t=i(s,JSON.parse(c));if(null===t){s="",c="";continue}if(yield yield e.__await(t),"complete"===s||"error"===s)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",c)}s="",c=""}}}finally{r.releaseLock()}})}makeRequest(t,r,a){return e.__awaiter(this,arguments,void 0,function*(e,t,r,a=1,o="POST"){if(!e.startsWith("/"))throw new n("Invalid endpoint: must start with /");const i=new URL(e,this.baseUrl);if(i.origin!==new URL(this.baseUrl).origin)throw new n("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${a}/${this.retryConfig.attempts}: ${i}`);const s=new AbortController,c=setTimeout(()=>s.abort(),this.timeout),l=()=>s.abort();r&&r.addEventListener("abort",l);try{const c=yield fetch(i,Object.assign({method:o,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===o&&{body:JSON.stringify(t)}));if(!c.ok){let i,s=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(i=t.code)}}catch(e){}const l=!("QUOTA_EXCEEDED"===i)&&(c.status>=500||429===c.status),m=new n(s,{status:c.status,code:i,retryable:l});if(l&&a<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${n}ms (attempt ${a+1})`),yield this.sleep(n),this.makeRequest(e,t,r,a+1,o)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(i){if(i instanceof n)throw i;if(i instanceof Error&&"AbortError"===i.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),i;if(a<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${n}ms`),yield this.sleep(n),this.makeRequest(e,t,r,a+1,o)}throw this.logger.error(`${this.tag} Network error: ${e}`,i),new n("Network error",{retryable:!0})}finally{clearTimeout(c),r&&r.removeEventListener("abort",l)}})}makeMultipartRequest(t,r,a){return e.__awaiter(this,arguments,void 0,function*(e,t,r,a=1){if(!e.startsWith("/"))throw new n("Invalid endpoint: must start with /");const o=new URL(e,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new n("Endpoint resolved to unexpected origin");const i=new AbortController,s=setTimeout(()=>i.abort(),this.timeout),c=()=>i.abort();r&&r.addEventListener("abort",c);try{const s=yield fetch(o,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},body:t,signal:i.signal});if(!s.ok){let o,i=`HTTP ${s.status}`;try{const e=yield s.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?i=t.message:"string"==typeof t.error&&(i=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const c=s.status>=500||429===s.status,l=new n(i,{status:s.status,code:o,retryable:c});if(c&&a<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return yield this.sleep(n),this.makeMultipartRequest(e,t,r,a+1)}throw l}return s}catch(o){if(o instanceof n)throw o;if(o instanceof Error&&"AbortError"===o.name)throw o;if(a<this.retryConfig.attempts&&!(null==r?void 0:r.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,a-1);return yield this.sleep(n),this.makeMultipartRequest(e,t,r,a+1)}throw new n("Network error",{retryable:!0})}finally{clearTimeout(s),r&&r.removeEventListener("abort",c)}})}}const c={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".pdf":"application/pdf",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};function l(e,t){var n;const r=null===(n=null==t?void 0:t.filename)||void 0===n?void 0:n.trim();return r||("undefined"!=typeof File&&e instanceof File&&e.name.trim().length>0?e.name.trim():void 0)}function m(e,t){var n;const r=null===(n=null==t?void 0:t.mimeType)||void 0===n?void 0:n.trim();if(r)return r;const a=e.type.trim();if(a.length>0)return a;const o=l(e,t);if(o){const e=function(e){const t=e.lastIndexOf(".");if(t<0)return;const n=e.slice(t).toLowerCase();return c[n]}(o);if(e)return e}throw new Error("uploadAttachment requires a MIME type: set `file.type`, pass `options.mimeType`, or use a filename with a supported extension (.png, .jpg, .pdf, .xlsx, …)")}const p=t.z.object({inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional(),wallClockMs:t.z.number()}),u=t.z.object({wallClockMs:t.z.number(),inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional()}),d=t.z.object({limits:t.z.object({maxWallClockMs:t.z.number().optional(),maxTotalTokens:t.z.number().optional(),maxCostUsd:t.z.number().optional(),trackUsage:t.z.boolean().optional()}),consumed:u,exceeded:t.z.boolean(),exceededDimensions:t.z.array(t.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:t.z.string().optional()});t.z.object({inputTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),modelName:t.z.string(),inputCachedTokens:t.z.number().optional(),inputUncachedTokens:t.z.number().optional(),cost:t.z.number().optional(),latencyMs:t.z.number().optional(),effort:t.z.string().optional(),providerReasoning:t.z.string().optional()});const g={usage:p.optional(),budget:d.optional()},h=t.z.enum(["EN_GB","EN_US"]),f=t.z.custom(e=>null!=e&&"object"==typeof e),b=t.z.enum(["low","medium","high"]),y=t.z.enum(["none","low","medium","high"]),z=t.z.enum(["agentic","fast"]),x=3e5,v=5e5,_=t.z.object({maxWallClockMs:t.z.number().positive().max(x).optional(),maxTotalTokens:t.z.number().int().positive().max(v).optional(),maxCostUsd:t.z.number().positive().max(10).optional(),trackUsage:t.z.boolean().optional()}),w=t.z.object({wallClockMs:t.z.number(),inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional()});t.z.object({limits:_,consumed:w,exceeded:t.z.boolean(),exceededDimensions:t.z.array(t.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:t.z.string().optional()});const S=t.z.object({callId:t.z.string().max(256).optional(),locale:h.optional(),effort:b.optional(),storytellingEffort:y.optional().default("low"),budget:_.optional(),executionMode:z.optional(),enforceTableRowCap:t.z.boolean().optional()}),T=t.z.object({steps:t.z.array(t.z.string()),postProcess:t.z.object({measureRelevance:t.z.enum(["prompt-named","derived","magnitude"]).optional(),grain:t.z.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:t.z.string().optional(),comparison:t.z.string().optional()}).optional(),droppedMeasures:t.z.array(t.z.string()).optional(),rowCount:t.z.number().int().nonnegative(),totalRowCountBeforeSlice:t.z.number().int().positive().optional(),displayedRowCount:t.z.number().int().nonnegative().optional(),columnKeys:t.z.array(t.z.string()),activeFilters:t.z.array(t.z.string()).optional(),grainSummary:t.z.string().optional()}),E=t.z.object({runId:t.z.string(),trackingId:t.z.string(),callId:t.z.string().optional()}),C=1e4,j=t.z.enum(["comparison","relationship","distribution","composition"]),A=t.z.object({config:f,userPrompt:t.z.string().max(C).optional().default(""),metadata:S.optional(),chartFamily:j.optional()}),k=A.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}),R=t.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),$=t.z.object({dataPrepPrompt:t.z.string(),chartType:R,summary:t.z.string()}),M=A.extend({userPrompt:t.z.string().max(C),mutationReceipt:T.optional(),exploreFindingSummary:t.z.string().max(500).optional()}),O=t.z.object({response:t.z.object({message:t.z.string()}),config:f,run:E.optional()}).extend(g),U=t.z.object({suggestions:t.z.array($),run:E.optional()}).extend(g),P=t.z.object({finding:t.z.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:t.z.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:t.z.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:t.z.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:t.z.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:j.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:t.z.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),D=t.z.object({topic:t.z.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:t.z.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:t.z.number().int().min(1).describe("Number of findings in this story."),findings:t.z.array(P).describe("Child findings, sorted by quadrant score desc.")}),I=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(D),run:E.optional()}).extend(g);A.extend({mutationReceipt:T.optional()});const B=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:f,run:E.optional()}).extend(g),G=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:f,mutationReceipt:T.optional(),warnings:t.z.array(t.z.string()).optional(),run:E.optional()}).extend(g),F=t.z.enum(["explore","mutate","narrate","annotate"]),X=t.z.object({agent:F,summary:t.z.string(),steps:t.z.array(t.z.string()).optional()}),q=A.extend({userPrompt:t.z.string().max(C),stages:t.z.array(F).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:t.z.string().max(500).optional()}),N=G.extend({reasoning:t.z.array(X),stories:t.z.array(D).optional()}),L=t.z.enum(["high","medium","low"]),K=t.z.object({confidence:L,needsUserInput:t.z.boolean(),warnings:t.z.array(t.z.string()),cellConfidence:t.z.array(t.z.object({rowIndex:t.z.number().int().nonnegative(),columnKey:t.z.string(),confidence:L,quote:t.z.string().optional()})).optional()}),H=t.z.object({score:t.z.number().min(0).max(1),issues:t.z.array(t.z.string()),sufficient:t.z.boolean(),summary:t.z.string()}),W=5e5,Y=2097152,J=7340032,V=6291456,Q=8388608,Z=V,ee=Q,te=12582912,ne=12,re=52428800;function ae(e){return 4*Math.ceil(e/3)}const oe=ae(Y),ie=ae(J),se=ae(V),ce=ae(Q),le=ae(Z),me=ae(ee),pe=ae(te);function ue(e){return e.replace(/\s+/g,"")}function de(e){const t=ue(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const ge=/^image\/(png|jpeg|jpg|webp|gif)$/i,he=t.z.object({mimeType:t.z.string().min(1).refine(e=>ge.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:t.z.string().min(1).max(oe).refine(de,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),fe=t.z.enum(["image","document","spreadsheet"]),be=he.extend({kind:t.z.literal("image")}),ye=t.z.object({kind:t.z.literal("document"),mimeType:t.z.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:t.z.string().min(1).max(se).refine(de,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),ze=t.z.object({kind:t.z.literal("spreadsheet"),mimeType:t.z.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:t.z.string().min(1).max(le).refine(de,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:t.z.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),xe=t.z.discriminatedUnion("kind",[be,ye,ze]),ve=t.z.string().regex(/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),_e=t.z.enum(["pending","ready","failed"]),we=t.z.object({id:t.z.string().uuid(),uri:t.z.string(),status:_e,kind:fe.optional(),mimeType:t.z.string(),filename:t.z.string().optional(),sizeBytes:t.z.number().int().nonnegative(),uploadExpiresAt:t.z.string().datetime().optional(),completedAt:t.z.string().datetime().optional(),expiresAt:t.z.string().datetime()}),Se=we.extend({status:t.z.literal("ready"),kind:fe,sizeBytes:t.z.number().int().positive()}),Te=t.z.object({mimeType:t.z.string().min(1),filename:t.z.string().max(512).optional(),sizeBytes:t.z.number().int().positive().max(re).optional()}),Ee=t.z.object({files:t.z.array(Te).min(1).max(ne)}),Ce=we.extend({status:t.z.literal("pending"),uploadUrl:t.z.string().url()}),je=t.z.object({uploads:t.z.array(Ce)}),Ae=t.z.object({sourceText:t.z.string().max(W).default(""),images:t.z.array(he).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(xe).max(ne).optional(),attachmentRefs:t.z.array(ve).max(ne).optional(),metadata:S.optional()}).superRefine((e,t)=>{var n,r,a;const o=e.sourceText.trim(),i=null!==(n=e.images)&&void 0!==n?n:[],s=null!==(r=e.attachments)&&void 0!==r?r:[],c=null!==(a=e.attachmentRefs)&&void 0!==a?a:[];if(i.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===o.length&&0===i.length&&0===s.length&&0===c.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(i.length+s.length+c.length>ne)return void t.addIssue({code:"custom",message:"Too many attachments (max 12 across inline payloads and attachmentRefs)",path:["attachmentRefs"]});if(c.length>0&&0===s.length&&0===i.length)return;if(i.length>0){i.reduce((e,t)=>e+ue(t.dataBase64).length,0)>ie&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let l=0,m=0,p=0,u=0,d=0,g=0,h=0;for(const e of s){const t=ue(e.dataBase64).length;switch(h+=t,e.kind){case"image":l+=1,u+=t;break;case"document":m+=1,d+=t;break;case"spreadsheet":p+=1,g+=t}}l>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),p>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=l<=8&&m<=2&&p<=2;s.length>0&&f&&(u>ie&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>ce&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>me&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>pe&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const ke=t.z.object({response:t.z.object({message:t.z.string()}),config:f,extractMeta:K.nullable(),lastAccuracyEvaluation:H.optional(),run:E.optional()}).extend(g),Re=t.z.object({config:f,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),run:E.optional()}).extend(g),$e=U,Me=t.z.enum(["deal-breaker","pro","con","family","continuity"]),Oe=t.z.object({kind:Me,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),Ue=t.z.enum(["ok","disqualified"]),Pe=t.z.object({rank:t.z.number().int().positive(),type:R,score:t.z.number(),verdict:Ue,factors:t.z.array(Oe)}),De=t.z.object({config:f,chartFamily:j.optional(),metadata:S.optional()}),Ie=t.z.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),Be=t.z.object({kind:Ie,message:t.z.string()}),Ge=t.z.enum(["sum","avg","count","min","max"]),Fe=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:Ge,chartType:R,score:t.z.number(),message:t.z.string()}),Xe=t.z.object({ranking:t.z.array(Pe),observations:t.z.array(Be).optional().default([]),suggestions:t.z.array(Fe).optional().default([]),run:E.optional()}),qe=t.z.object({prompt:t.z.string(),datasetSummary:t.z.string().optional(),mustShow:t.z.array(t.z.string()).optional(),unacceptable:t.z.array(t.z.string()).optional(),acceptableChartFamilies:t.z.array(t.z.string()).optional()}),Ne=t.z.object({config:f.optional(),chartImage:t.z.string().optional(),data:t.z.unknown().optional(),rubric:qe.optional(),userPrompt:t.z.string().optional(),metadata:S.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),Le=t.z.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),Ke=t.z.enum(["info","low","medium","high"]),He=t.z.object({category:Le,severity:Ke,observation:t.z.string(),rationale:t.z.string().optional(),suggestedChange:t.z.string().optional(),configPaths:t.z.array(t.z.string()).optional()}),We=t.z.object({overallSummary:t.z.string(),overallSeverity:t.z.enum(["none","low","medium","high"]).optional(),issues:t.z.array(He)}),Ye=t.z.object({dataFidelity:t.z.number().min(0).max(1),promptRelevance:t.z.number().min(0).max(1),chartTypeAppropriateness:t.z.number().min(0).max(1),readability:t.z.number().min(0).max(1),honesty:t.z.number().min(0).max(1),composite:t.z.number().min(0).max(1),rationale:t.z.string().optional()}),Je=t.z.object({capturedAt:t.z.string(),chartId:t.z.string()}),Ve=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string()),critiqueCommitted:t.z.boolean()}),critiqueReport:We.nullable(),chartVisionAudit:Je.nullable().optional().default(null),rubricScores:Ye.nullable().optional().default(null),run:E.optional()}).extend(g),Qe="/api/v0";exports.AggregationFunctionSchema=Ge,exports.AggregationSuggestionSchema=Fe,exports.AiChartTypeEnum=R,exports.AttachmentResponseSchema=we,exports.AttachmentUploadResponseSchema=Se,exports.AttachmentUploadSlotResponseSchema=Ce,exports.ChartCritiqueIssueCategorySchema=Le,exports.ChartCritiqueIssueSchema=He,exports.ChartCritiqueIssueSeveritySchema=Ke,exports.ChartCritiqueReportSchema=We,exports.ChartFamilySchema=j,exports.ChartFitEntrySchema=Pe,exports.ChartFitFactorKindSchema=Me,exports.ChartFitFactorSchema=Oe,exports.ChartFitVerdictSchema=Ue,exports.ChartJudgeRubricSchema=qe,exports.CreateAttachmentUploadsParamsSchema=Ee,exports.CreateAttachmentUploadsResponseSchema=je,exports.DataObservationKindSchema=Ie,exports.DataObservationSchema=Be,exports.EvaluateParamsSchema=De,exports.EvaluateResponseSchema=Xe,exports.ExecutionModeSchema=z,exports.ExploreFindingSchema=P,exports.ExploreStorySchema=D,exports.ExtractAccuracyEvaluationSchema=H,exports.ExtractAttachmentInputSchema=xe,exports.ExtractAttachmentKindSchema=fe,exports.ExtractConfidenceSchema=L,exports.ExtractFromProseParamsSchema=Ae,exports.ExtractFromProseResponseSchema=ke,exports.ExtractMetaSchema=K,exports.GenerateAnnotationsResponseSchema=B,exports.GenerateExplorationResponseSchema=I,exports.GenerateGraphResponseSchema=Re,exports.GenerateGraphSuggestionsResponseSchema=$e,exports.GenerateMutationResponseSchema=G,exports.GenerateNarrativeParamsSchema=M,exports.GenerateNarrativeResponseSchema=O,exports.GeneratePipelineParamsSchema=q,exports.GeneratePipelineResponseSchema=N,exports.GenerateSuggestionsParamsSchema=k,exports.GenerateSuggestionsResponseSchema=U,exports.GraphGenerationRequestSchema=A,exports.GraphyAiSdk=class{constructor(e){this.client=new s(e)}generateGraph(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:a}=t,o=e.__rest(t,["storytellingOptions"]),i=yield this.client.fetch(`${Qe}/generate`,o,n,r),s=Re.parse(i);return this.stripStorytelling(s,a)})}generateGraphStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:r}=t,a=e.__rest(t,["storytellingOptions"]),o=yield this.client.stream(`${Qe}/generate`,a,n);return this.wrapStreamWithStorytellingStripping(o,r)})}generateNarrative(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/narrate`,t,n,r);return O.parse(e)})}generateNarrativeStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/narrate`,t,n)})}generateSuggestions(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/suggestions`,t,n,r);return U.parse(e)})}generateSuggestionsStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/suggestions`,t,n)})}generateExploration(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/explore`,t,n,r);return I.parse(e)})}generateExplorationStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/explore`,t,n)})}generateAnnotations(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/annotate`,t,n,r);return B.parse(e)})}generateAnnotationsStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/annotate`,t,n)})}generateMutation(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/mutate`,t,n,r);return G.parse(e)})}generateMutationStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/mutate`,t,n)})}generatePipeline(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/pipeline`,t,n,r);return N.parse(e)})}generatePipelineStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/pipeline`,t,n)})}evaluate(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/evaluate`,t,void 0,n);return Xe.parse(e)})}judge(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/judge`,t,void 0,n);return Ve.parse(e)})}judgeStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/judge`,t,n)})}extractFromProse(t,n,r){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Qe}/extract`,t,n,r);return ke.parse(e)})}extractFromProseStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${Qe}/extract`,t,n)})}uploadAttachment(t,r,a){return e.__awaiter(this,void 0,void 0,function*(){const e=m(t,r),o=l(t,r),{uploads:i}=yield this.createAttachmentUploads({files:[Object.assign(Object.assign({mimeType:e},o?{filename:o}:{}),t.size>0?{sizeBytes:t.size}:{})]},a),s=i[0];if(!s)throw new n("Attachment upload slot was not returned");const c=yield fetch(s.uploadUrl,{method:"PUT",headers:{"Content-Type":e},body:t,signal:a});if(!c.ok)throw new n(`Attachment upload failed (HTTP ${c.status})`,{status:c.status,retryable:c.status>=500});const p=yield this.completeAttachmentUpload(s.id,a);return Se.parse(p)})}createAttachmentUploads(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${Qe}/attachment-uploads`,t,n);return je.parse(e)})}completeAttachmentUpload(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${Qe}/attachments/${t}/complete`,{},n);return we.parse(e)})}getAttachment(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.get(`${Qe}/attachments/${t}`,n);return we.parse(e)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(t,n){return e.__asyncGenerator(this,arguments,function*(){var r,o,i,s;try{for(var c,l=!0,m=e.__asyncValues(t);!(r=(c=yield e.__await(m.next())).done);l=!0){s=c.value,l=!1;const t=s;if(a(t)){const r=this.stripStorytelling(t.data,n);yield yield e.__await(Object.assign(Object.assign({},t),{data:r}))}else yield yield e.__await(t)}}catch(e){o={error:e}}finally{try{l||r||!(i=m.return)||(yield e.__await(i.call(m)))}finally{if(o)throw o.error}}})}},exports.GraphyApiError=n,exports.InvocationBudgetSchema=_,exports.InvocationEffortSchema=b,exports.JudgeParamsSchema=Ne,exports.JudgeResponseSchema=Ve,exports.MAX_BUDGET_COST_USD=10,exports.MAX_BUDGET_TOTAL_TOKENS=v,exports.MAX_BUDGET_WALL_CLOCK_MS=x,exports.MAX_EXTRACT_ATTACHMENTS=ne,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=te,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=Q,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=V,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=J,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=Y,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=ee,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=Z,exports.MAX_SOURCE_TEXT_LENGTH=W,exports.MAX_STAGED_FILE_BYTES=re,exports.MAX_USER_PROMPT_LENGTH=C,exports.MetadataSchema=S,exports.MutateNarrationReceiptSchema=T,exports.PipelineAgentNameSchema=F,exports.PipelineStageReasoningSchema=X,exports.RubricScoresSchema=Ye,exports.RunContextSchema=E,exports.StorytellingEffortSchema=y,exports.SuggestionSchema=$,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ue(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ue(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ue(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isAgentCompleteEvent=e=>"agent_complete"===e.type,exports.isCompleteEvent=a,exports.isErrorEvent=o,exports.isGraphyApiError=e=>e instanceof n,exports.isLlmStepEvent=e=>"llm_step"===e.type,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=r,exports.isReasoningEvent=e=>"reasoning"===e.type,exports.isSessionBudgetEvent=e=>"session_budget"===e.type,exports.isToolCallEvent=e=>"tool_call"===e.type,exports.isToolCompleteEvent=e=>"tool_complete"===e.type,exports.isToolErrorEvent=e=>"tool_error"===e.type;
|
|
1
|
+
"use strict";var e=require("tslib"),t=require("zod");class n extends Error{constructor(e,t){var n;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(n=null==t?void 0:t.retryable)&&void 0!==n&&n}}const a=e=>"progress"===e.type,r=e=>"complete"===e.type,o=e=>"error"===e.type;function i(e,t){if("progress"===e){const e=t;return Object.assign({type:"progress"},e)}if("complete"===e)return{type:"complete",data:t};if("error"===e){const e=t;return Object.assign({type:"error"},e)}if("preview"===e){const e=t;return Object.assign(Object.assign({},e),{type:"preview"})}if("reasoning"===e){const e=t;return Object.assign(Object.assign({},e),{type:"reasoning"})}return"llm_step"===e||"session_budget"===e||"agent_complete"===e||"tool_call"===e||"tool_complete"===e||"tool_error"===e?t:null}class s{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return a(e)}static isCompleteEvent(e){return r(e)}static isErrorEvent(e){return o(e)}stream(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,a);return this.parseSSE(e)})}fetch(t,i,s,c){return e.__awaiter(this,void 0,void 0,function*(){var l,m,p,u,d;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${t}`);try{const y=yield this.makeRequest(t,i,c),z=y.headers.get("content-type");if(null==z?void 0:z.includes("text/event-stream")){try{for(var h,f=!0,b=e.__asyncValues(this.parseSSE(y));!(l=(h=yield b.next()).done);f=!0){u=h.value,f=!1;const e=u;if(a(e)&&s&&s(e),r(e))return e.data;if(o(e)){const a=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${t} ${a}ms`,e.error),new n(e.error,{code:e.code,retryable:null!==(d=e.retryable)&&void 0!==d&&d})}}}catch(e){m={error:e}}finally{try{f||l||!(p=b.return)||(yield p.call(b))}finally{if(m)throw m.error}}const i=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${t} ${i}ms`),new n("Stream ended without completion")}return yield y.json()}catch(e){const a=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${t} ${a}ms`,e),e instanceof n)throw e;throw e}finally{const e=Date.now()-g;this.logger.debug(`${this.tag} Fetch completed: ${t} ${e}ms`)}})}ping(){return e.__awaiter(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}uploadMultipart(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,n,a);return yield e.json()})}get(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,void 0,n,1,"GET");return yield e.json()})}postJson(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,a,1,"POST");return yield e.json()})}sleep(t){return e.__awaiter(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(t){return e.__asyncGenerator(this,arguments,function*(){if(!t.body)throw new n("Response body is null");const a=t.body.getReader(),r=new TextDecoder;let o="",s="",c="";try{for(;;){const{done:t,value:n}=yield e.__await(a.read());if(t)break;o+=r.decode(n,{stream:!0});const l=o.split(/\r?\n/);o=l.pop()||"";for(const t of l)if(t.startsWith("event: "))s=t.slice(7).trim();else if(t.startsWith("data: "))c+=(c?"\n":"")+t.slice(6);else if(""===t.trim()&&c){try{const t=i(s,JSON.parse(c));if(null===t){s="",c="";continue}if(yield yield e.__await(t),"complete"===s||"error"===s)return yield e.__await(void 0)}catch(e){this.logger.warn("Invalid SSE data format",c)}s="",c=""}}}finally{a.releaseLock()}})}makeRequest(t,a,r){return e.__awaiter(this,arguments,void 0,function*(e,t,a,r=1,o="POST"){if(!e.startsWith("/"))throw new n("Invalid endpoint: must start with /");const i=new URL(e,this.baseUrl);if(i.origin!==new URL(this.baseUrl).origin)throw new n("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${r}/${this.retryConfig.attempts}: ${i}`);const s=new AbortController,c=setTimeout(()=>s.abort(),this.timeout),l=()=>s.abort();a&&a.addEventListener("abort",l);try{const c=yield fetch(i,Object.assign({method:o,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===o&&{body:JSON.stringify(t)}));if(!c.ok){let i,s=`HTTP ${c.status}`;try{const e=yield c.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(i=t.code)}}catch(e){}const l=!("QUOTA_EXCEEDED"===i)&&(c.status>=500||429===c.status),m=new n(s,{status:c.status,code:i,retryable:l});if(l&&r<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${n}ms (attempt ${r+1})`),yield this.sleep(n),this.makeRequest(e,t,a,r+1,o)}throw this.logger.error(`${this.tag} Request failed: ${e} (${c.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),c}catch(i){if(i instanceof n)throw i;if(i instanceof Error&&"AbortError"===i.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),i;if(r<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${n}ms`),yield this.sleep(n),this.makeRequest(e,t,a,r+1,o)}throw this.logger.error(`${this.tag} Network error: ${e}`,i),new n("Network error",{retryable:!0})}finally{clearTimeout(c),a&&a.removeEventListener("abort",l)}})}makeMultipartRequest(t,a,r){return e.__awaiter(this,arguments,void 0,function*(e,t,a,r=1){if(!e.startsWith("/"))throw new n("Invalid endpoint: must start with /");const o=new URL(e,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new n("Endpoint resolved to unexpected origin");const i=new AbortController,s=setTimeout(()=>i.abort(),this.timeout),c=()=>i.abort();a&&a.addEventListener("abort",c);try{const s=yield fetch(o,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},body:t,signal:i.signal});if(!s.ok){let o,i=`HTTP ${s.status}`;try{const e=yield s.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?i=t.message:"string"==typeof t.error&&(i=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const c=s.status>=500||429===s.status,l=new n(i,{status:s.status,code:o,retryable:c});if(c&&r<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return yield this.sleep(n),this.makeMultipartRequest(e,t,a,r+1)}throw l}return s}catch(o){if(o instanceof n)throw o;if(o instanceof Error&&"AbortError"===o.name)throw o;if(r<this.retryConfig.attempts&&!(null==a?void 0:a.aborted)){const n=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,r-1);return yield this.sleep(n),this.makeMultipartRequest(e,t,a,r+1)}throw new n("Network error",{retryable:!0})}finally{clearTimeout(s),a&&a.removeEventListener("abort",c)}})}}const c={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".pdf":"application/pdf",".csv":"text/csv",".tsv":"text/tab-separated-values",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};function l(e,t){var n;const a=null===(n=null==t?void 0:t.filename)||void 0===n?void 0:n.trim();return a||("undefined"!=typeof File&&e instanceof File&&e.name.trim().length>0?e.name.trim():void 0)}function m(e,t){var n;const a=null===(n=null==t?void 0:t.mimeType)||void 0===n?void 0:n.trim();if(a)return a;const r=e.type.trim();if(r.length>0)return r;const o=l(e,t);if(o){const e=function(e){const t=e.lastIndexOf(".");if(t<0)return;const n=e.slice(t).toLowerCase();return c[n]}(o);if(e)return e}throw new Error("uploadAttachment requires a MIME type: set `file.type`, pass `options.mimeType`, or use a filename with a supported extension (.png, .jpg, .pdf, .csv, .tsv, .xlsx, …)")}const p=new Set(["text/csv","text/tab-separated-values","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]);function u(e,t){const n=m(e,t);if(a=n,!p.has(a.trim()))throw new Error("uploadDataset requires a dataset MIME type (text/csv, text/tab-separated-values, or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)");var a;return n}const d=t.z.object({inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional(),wallClockMs:t.z.number()}),g=t.z.object({wallClockMs:t.z.number(),inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional()}),h=t.z.object({limits:t.z.object({maxWallClockMs:t.z.number().optional(),maxTotalTokens:t.z.number().optional(),maxCostUsd:t.z.number().optional(),trackUsage:t.z.boolean().optional()}),consumed:g,exceeded:t.z.boolean(),exceededDimensions:t.z.array(t.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:t.z.string().optional()});t.z.object({inputTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),modelName:t.z.string(),inputCachedTokens:t.z.number().optional(),inputUncachedTokens:t.z.number().optional(),cost:t.z.number().optional(),latencyMs:t.z.number().optional(),effort:t.z.string().optional(),providerReasoning:t.z.string().optional()});const f={usage:d.optional(),budget:h.optional()};function b(e,t){const n=void 0!==e.config.data,a=function(e){const{data:t}=e;return void 0!==t&&(t.columns.length>0||t.rows.length>0)}(e.config),r=void 0!==e.datasetRef&&e.datasetRef.trim().length>0;a&&r&&t.addIssue({code:"custom",message:"Provide either config.data or datasetRef, not both",path:["datasetRef"]}),n||r||t.addIssue({code:"custom",message:"Provide config.data or datasetRef",path:["datasetRef"]})}const y=t.z.enum(["EN_GB","EN_US"]),z=t.z.custom(e=>null!=e&&"object"==typeof e),x=t.z.enum(["low","medium","high"]),v=t.z.enum(["none","low","medium","high"]),_=t.z.enum(["agentic","fast"]),w=3e5,S=5e5,T=t.z.object({maxWallClockMs:t.z.number().positive().max(w).optional(),maxTotalTokens:t.z.number().int().positive().max(S).optional(),maxCostUsd:t.z.number().positive().max(10).optional(),trackUsage:t.z.boolean().optional()}),E=t.z.object({wallClockMs:t.z.number(),inputTokens:t.z.number(),inputCachedTokens:t.z.number(),inputUncachedTokens:t.z.number(),outputTokens:t.z.number(),totalTokens:t.z.number(),costUsd:t.z.number().nullable(),costEnforcementSkipped:t.z.boolean().optional()});t.z.object({limits:T,consumed:E,exceeded:t.z.boolean(),exceededDimensions:t.z.array(t.z.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:t.z.string().optional()});const C=t.z.object({callId:t.z.string().max(256).optional(),locale:y.optional(),effort:x.optional(),storytellingEffort:v.optional().default("low"),budget:T.optional(),executionMode:_.optional(),enforceTableRowCap:t.z.boolean().optional()}),j=t.z.object({steps:t.z.array(t.z.string()),postProcess:t.z.object({measureRelevance:t.z.enum(["prompt-named","derived","magnitude"]).optional(),grain:t.z.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:t.z.string().optional(),comparison:t.z.string().optional()}).optional(),droppedMeasures:t.z.array(t.z.string()).optional(),rowCount:t.z.number().int().nonnegative(),totalRowCountBeforeSlice:t.z.number().int().positive().optional(),displayedRowCount:t.z.number().int().nonnegative().optional(),columnKeys:t.z.array(t.z.string()),activeFilters:t.z.array(t.z.string()).optional(),grainSummary:t.z.string().optional()}),A=t.z.object({runId:t.z.string(),trackingId:t.z.string(),callId:t.z.string().optional()}),R=1e4,k=t.z.enum(["comparison","relationship","distribution","composition"]),$=/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,M=t.z.string().regex($,"datasetRef must be graphy://attachments/{uuid}"),O=t.z.object({config:z,userPrompt:t.z.string().max(R).optional().default(""),metadata:C.optional(),chartFamily:k.optional(),datasetRef:M.optional()}),P=O.superRefine(b),D=O.extend({maxSuggestionCount:t.z.number().int().min(1).max(4).optional()}).superRefine(b),U=t.z.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),I=t.z.object({dataPrepPrompt:t.z.string(),chartType:U,summary:t.z.string()}),B=O.extend({userPrompt:t.z.string().max(R),mutationReceipt:j.optional(),exploreFindingSummary:t.z.string().max(500).optional()}).superRefine(b),G=t.z.object({response:t.z.object({message:t.z.string()}),config:z,run:A.optional()}).extend(f),X=t.z.object({suggestions:t.z.array(I),run:A.optional()}).extend(f),q=t.z.object({finding:t.z.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:t.z.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:t.z.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:t.z.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:t.z.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:k.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:t.z.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),F=t.z.object({topic:t.z.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:t.z.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:t.z.number().int().min(1).describe("Number of findings in this story."),findings:t.z.array(q).describe("Child findings, sorted by quadrant score desc.")}),N=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),stories:t.z.array(F),run:A.optional()}).extend(f);O.extend({mutationReceipt:j.optional()}).superRefine(b);const L=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:z,run:A.optional()}).extend(f),K=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),config:z,mutationReceipt:j.optional(),warnings:t.z.array(t.z.string()).optional(),run:A.optional()}).extend(f),H=t.z.enum(["explore","mutate","narrate","annotate"]),W=t.z.object({agent:H,summary:t.z.string(),steps:t.z.array(t.z.string()).optional()}),Y=O.extend({userPrompt:t.z.string().max(R),stages:t.z.array(H).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:t.z.string().max(500).optional()}).superRefine(b),J=K.extend({reasoning:t.z.array(W),stories:t.z.array(F).optional()}),V=t.z.enum(["high","medium","low"]),Q=t.z.object({confidence:V,needsUserInput:t.z.boolean(),warnings:t.z.array(t.z.string()),cellConfidence:t.z.array(t.z.object({rowIndex:t.z.number().int().nonnegative(),columnKey:t.z.string(),confidence:V,quote:t.z.string().optional()})).optional()}),Z=t.z.object({score:t.z.number().min(0).max(1),issues:t.z.array(t.z.string()),sufficient:t.z.boolean(),summary:t.z.string()}),ee=5e5,te=2097152,ne=7340032,ae=6291456,re=8388608,oe=ae,ie=re,se=12582912,ce=12,le=52428800;function me(e){return 4*Math.ceil(e/3)}const pe=me(te),ue=me(ne),de=me(ae),ge=me(re),he=me(oe),fe=me(ie),be=me(se);function ye(e){return e.replace(/\s+/g,"")}function ze(e){const t=ye(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const xe=/^image\/(png|jpeg|jpg|webp|gif)$/i,ve=t.z.object({mimeType:t.z.string().min(1).refine(e=>xe.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:t.z.string().min(1).max(pe).refine(ze,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),_e=t.z.enum(["image","document","spreadsheet","tabular"]),we=ve.extend({kind:t.z.literal("image")}),Se=t.z.object({kind:t.z.literal("document"),mimeType:t.z.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:t.z.string().min(1).max(de).refine(ze,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Te=t.z.object({kind:t.z.literal("spreadsheet"),mimeType:t.z.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:t.z.string().min(1).max(he).refine(ze,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:t.z.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),Ee=t.z.discriminatedUnion("kind",[we,Se,Te]),Ce=t.z.string().regex($,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),je=t.z.enum(["pending","ready","failed"]),Ae=t.z.object({id:t.z.string().uuid(),uri:t.z.string(),status:je,kind:_e.optional(),mimeType:t.z.string(),filename:t.z.string().optional(),sizeBytes:t.z.number().int().nonnegative(),uploadExpiresAt:t.z.string().datetime().optional(),completedAt:t.z.string().datetime().optional(),expiresAt:t.z.string().datetime()}),Re=Ae.extend({status:t.z.literal("ready"),kind:_e,sizeBytes:t.z.number().int().positive()}),ke=t.z.object({mimeType:t.z.string().min(1),filename:t.z.string().max(512).optional(),sizeBytes:t.z.number().int().positive().max(le).optional()}),$e=t.z.object({files:t.z.array(ke).min(1).max(ce)}),Me=Ae.extend({status:t.z.literal("pending"),uploadUrl:t.z.string().url()}),Oe=t.z.object({uploads:t.z.array(Me)}),Pe=t.z.object({sourceText:t.z.string().max(ee).default(""),images:t.z.array(ve).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:t.z.array(Ee).max(ce).optional(),attachmentRefs:t.z.array(Ce).max(ce).optional(),metadata:C.optional()}).superRefine((e,t)=>{var n,a,r;const o=e.sourceText.trim(),i=null!==(n=e.images)&&void 0!==n?n:[],s=null!==(a=e.attachments)&&void 0!==a?a:[],c=null!==(r=e.attachmentRefs)&&void 0!==r?r:[];if(i.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===o.length&&0===i.length&&0===s.length&&0===c.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(i.length+s.length+c.length>ce)return void t.addIssue({code:"custom",message:"Too many attachments (max 12 across inline payloads and attachmentRefs)",path:["attachmentRefs"]});if(c.length>0&&0===s.length&&0===i.length)return;if(i.length>0){i.reduce((e,t)=>e+ye(t.dataBase64).length,0)>ue&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let l=0,m=0,p=0,u=0,d=0,g=0,h=0;for(const e of s){const t=ye(e.dataBase64).length;switch(h+=t,e.kind){case"image":l+=1,u+=t;break;case"document":m+=1,d+=t;break;case"spreadsheet":p+=1,g+=t}}l>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),p>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=l<=8&&m<=2&&p<=2;s.length>0&&f&&(u>ue&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),d>ge&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>fe&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>be&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});const De=t.z.object({response:t.z.object({message:t.z.string()}),config:z,extractMeta:Q.nullable(),lastAccuracyEvaluation:Z.optional(),run:A.optional()}).extend(f),Ue=t.z.object({config:z,response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string())}),run:A.optional()}).extend(f),Ie=X,Be=t.z.enum(["deal-breaker","pro","con","family","continuity"]),Ge=t.z.object({kind:Be,label:t.z.string(),weight:t.z.number(),reason:t.z.string()}),Xe=t.z.enum(["ok","disqualified"]),qe=t.z.object({rank:t.z.number().int().positive(),type:U,score:t.z.number(),verdict:Xe,factors:t.z.array(Ge)}),Fe=P,Ne=t.z.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),Le=t.z.object({kind:Ne,message:t.z.string()}),Ke=t.z.enum(["sum","avg","count","min","max"]),He=t.z.object({dimensionName:t.z.string(),dimensionLabel:t.z.string(),measureName:t.z.string().nullable(),measureLabel:t.z.string().nullable(),fn:Ke,chartType:U,score:t.z.number(),message:t.z.string()}),We=t.z.object({ranking:t.z.array(qe),observations:t.z.array(Le).optional().default([]),suggestions:t.z.array(He).optional().default([]),run:A.optional()}),Ye=t.z.object({prompt:t.z.string(),datasetSummary:t.z.string().optional(),mustShow:t.z.array(t.z.string()).optional(),unacceptable:t.z.array(t.z.string()).optional(),acceptableChartFamilies:t.z.array(t.z.string()).optional()}),Je=t.z.object({config:z.optional(),chartImage:t.z.string().optional(),data:t.z.unknown().optional(),rubric:Ye.optional(),userPrompt:t.z.string().optional(),metadata:C.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),Ve=t.z.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),Qe=t.z.enum(["info","low","medium","high"]),Ze=t.z.object({category:Ve,severity:Qe,observation:t.z.string(),rationale:t.z.string().optional(),suggestedChange:t.z.string().optional(),configPaths:t.z.array(t.z.string()).optional()}),et=t.z.object({overallSummary:t.z.string(),overallSeverity:t.z.enum(["none","low","medium","high"]).optional(),issues:t.z.array(Ze)}),tt=t.z.object({dataFidelity:t.z.number().min(0).max(1),promptRelevance:t.z.number().min(0).max(1),chartTypeAppropriateness:t.z.number().min(0).max(1),readability:t.z.number().min(0).max(1),honesty:t.z.number().min(0).max(1),composite:t.z.number().min(0).max(1),rationale:t.z.string().optional()}),nt=t.z.object({capturedAt:t.z.string(),chartId:t.z.string()}),at=t.z.object({response:t.z.object({message:t.z.string(),steps:t.z.array(t.z.string()),critiqueCommitted:t.z.boolean()}),critiqueReport:et.nullable(),chartVisionAudit:nt.nullable().optional().default(null),rubricScores:tt.nullable().optional().default(null),run:A.optional()}).extend(f),rt="/api/v0";exports.AggregationFunctionSchema=Ke,exports.AggregationSuggestionSchema=He,exports.AiChartTypeEnum=U,exports.AttachmentResponseSchema=Ae,exports.AttachmentUploadResponseSchema=Re,exports.AttachmentUploadSlotResponseSchema=Me,exports.ChartCritiqueIssueCategorySchema=Ve,exports.ChartCritiqueIssueSchema=Ze,exports.ChartCritiqueIssueSeveritySchema=Qe,exports.ChartCritiqueReportSchema=et,exports.ChartFamilySchema=k,exports.ChartFitEntrySchema=qe,exports.ChartFitFactorKindSchema=Be,exports.ChartFitFactorSchema=Ge,exports.ChartFitVerdictSchema=Xe,exports.ChartJudgeRubricSchema=Ye,exports.CreateAttachmentUploadsParamsSchema=$e,exports.CreateAttachmentUploadsResponseSchema=Oe,exports.DataObservationKindSchema=Ne,exports.DataObservationSchema=Le,exports.EvaluateParamsSchema=Fe,exports.EvaluateResponseSchema=We,exports.ExecutionModeSchema=_,exports.ExploreFindingSchema=q,exports.ExploreStorySchema=F,exports.ExtractAccuracyEvaluationSchema=Z,exports.ExtractAttachmentInputSchema=Ee,exports.ExtractAttachmentKindSchema=_e,exports.ExtractConfidenceSchema=V,exports.ExtractFromProseParamsSchema=Pe,exports.ExtractFromProseResponseSchema=De,exports.ExtractMetaSchema=Q,exports.GenerateAnnotationsResponseSchema=L,exports.GenerateExplorationResponseSchema=N,exports.GenerateGraphResponseSchema=Ue,exports.GenerateGraphSuggestionsResponseSchema=Ie,exports.GenerateMutationResponseSchema=K,exports.GenerateNarrativeParamsSchema=B,exports.GenerateNarrativeResponseSchema=G,exports.GeneratePipelineParamsSchema=Y,exports.GeneratePipelineResponseSchema=J,exports.GenerateSuggestionsParamsSchema=D,exports.GenerateSuggestionsResponseSchema=X,exports.GraphGenerationRequestSchema=P,exports.GraphyAiSdk=class{constructor(e){this.client=new s(e)}generateGraph(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:r}=t,o=e.__rest(t,["storytellingOptions"]),i=yield this.client.fetch(`${rt}/generate`,o,n,a),s=Ue.parse(i);return this.stripStorytelling(s,r)})}generateGraphStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){const{storytellingOptions:a}=t,r=e.__rest(t,["storytellingOptions"]),o=yield this.client.stream(`${rt}/generate`,r,n);return this.wrapStreamWithStorytellingStripping(o,a)})}generateNarrative(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/narrate`,t,n,a);return G.parse(e)})}generateNarrativeStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/narrate`,t,n)})}generateSuggestions(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/suggestions`,t,n,a);return X.parse(e)})}generateSuggestionsStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/suggestions`,t,n)})}generateExploration(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/explore`,t,n,a);return N.parse(e)})}generateExplorationStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/explore`,t,n)})}generateAnnotations(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/annotate`,t,n,a);return L.parse(e)})}generateAnnotationsStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/annotate`,t,n)})}generateMutation(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/mutate`,t,n,a);return K.parse(e)})}generateMutationStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/mutate`,t,n)})}generatePipeline(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/pipeline`,t,n,a);return J.parse(e)})}generatePipelineStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/pipeline`,t,n)})}evaluate(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/evaluate`,t,void 0,n);return We.parse(e)})}judge(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/judge`,t,void 0,n);return at.parse(e)})}judgeStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/judge`,t,n)})}extractFromProse(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${rt}/extract`,t,n,a);return De.parse(e)})}extractFromProseStream(t,n){return e.__awaiter(this,void 0,void 0,function*(){return this.client.stream(`${rt}/extract`,t,n)})}uploadAttachment(t,a,r){return e.__awaiter(this,void 0,void 0,function*(){const e=m(t,a),o=l(t,a),{uploads:i}=yield this.createAttachmentUploads({files:[Object.assign(Object.assign({mimeType:e},o?{filename:o}:{}),t.size>0?{sizeBytes:t.size}:{})]},r),s=i[0];if(!s)throw new n("Attachment upload slot was not returned");const c=yield fetch(s.uploadUrl,{method:"PUT",headers:{"Content-Type":e},body:t,signal:r});if(!c.ok)throw new n(`Attachment upload failed (HTTP ${c.status})`,{status:c.status,retryable:c.status>=500});const p=yield this.completeAttachmentUpload(s.id,r);return Re.parse(p)})}uploadDataset(t,n,a){return e.__awaiter(this,void 0,void 0,function*(){const e=u(t,n);return this.uploadAttachment(t,Object.assign(Object.assign({},n),{mimeType:e}),a)})}createAttachmentUploads(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${rt}/attachment-uploads`,t,n);return Oe.parse(e)})}completeAttachmentUpload(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${rt}/attachments/${t}/complete`,{},n);return Ae.parse(e)})}getAttachment(t,n){return e.__awaiter(this,void 0,void 0,function*(){const e=yield this.client.get(`${rt}/attachments/${t}`,n);return Ae.parse(e)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(t,n){return e.__asyncGenerator(this,arguments,function*(){var a,o,i,s;try{for(var c,l=!0,m=e.__asyncValues(t);!(a=(c=yield e.__await(m.next())).done);l=!0){s=c.value,l=!1;const t=s;if(r(t)){const a=this.stripStorytelling(t.data,n);yield yield e.__await(Object.assign(Object.assign({},t),{data:a}))}else yield yield e.__await(t)}}catch(e){o={error:e}}finally{try{l||a||!(i=m.return)||(yield e.__await(i.call(m)))}finally{if(o)throw o.error}}})}},exports.GraphyApiError=n,exports.InvocationBudgetSchema=T,exports.InvocationEffortSchema=x,exports.JudgeParamsSchema=Je,exports.JudgeResponseSchema=at,exports.MAX_BUDGET_COST_USD=10,exports.MAX_BUDGET_TOTAL_TOKENS=S,exports.MAX_BUDGET_WALL_CLOCK_MS=w,exports.MAX_EXTRACT_ATTACHMENTS=ce,exports.MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES=se,exports.MAX_EXTRACT_DOCUMENTS=2,exports.MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES=re,exports.MAX_EXTRACT_DOCUMENT_DECODED_BYTES=ae,exports.MAX_EXTRACT_IMAGES=8,exports.MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES=ne,exports.MAX_EXTRACT_IMAGE_DECODED_BYTES=te,exports.MAX_EXTRACT_SPREADSHEETS=2,exports.MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES=ie,exports.MAX_EXTRACT_SPREADSHEET_DECODED_BYTES=oe,exports.MAX_SOURCE_TEXT_LENGTH=ee,exports.MAX_STAGED_FILE_BYTES=le,exports.MAX_USER_PROMPT_LENGTH=R,exports.MetadataSchema=C,exports.MutateNarrationReceiptSchema=j,exports.PipelineAgentNameSchema=H,exports.PipelineStageReasoningSchema=W,exports.RubricScoresSchema=tt,exports.RunContextSchema=A,exports.StorytellingEffortSchema=v,exports.SuggestionSchema=I,exports.buildImageAttachment=function(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:ye(e.dataBase64)}},exports.buildPdfAttachment=function(e){return{kind:"document",mimeType:"application/pdf",dataBase64:ye(e.dataBase64)}},exports.buildSpreadsheetAttachment=function(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:ye(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})},exports.isAgentCompleteEvent=e=>"agent_complete"===e.type,exports.isCompleteEvent=r,exports.isErrorEvent=o,exports.isGraphyApiError=e=>e instanceof n,exports.isLlmStepEvent=e=>"llm_step"===e.type,exports.isPreviewEvent=e=>"preview"===e.type,exports.isProgressEvent=a,exports.isReasoningEvent=e=>"reasoning"===e.type,exports.isSessionBudgetEvent=e=>"session_budget"===e.type,exports.isToolCallEvent=e=>"tool_call"===e.type,exports.isToolCompleteEvent=e=>"tool_complete"===e.type,exports.isToolErrorEvent=e=>"tool_error"===e.type;
|
package/dist/index.d.ts
CHANGED
|
@@ -405,6 +405,8 @@ type UploadAttachmentOptions = {
|
|
|
405
405
|
mimeType?: string;
|
|
406
406
|
};
|
|
407
407
|
|
|
408
|
+
type UploadDatasetOptions = UploadAttachmentOptions;
|
|
409
|
+
|
|
408
410
|
declare const InvocationEffortSchema: z.ZodEnum<{
|
|
409
411
|
low: "low";
|
|
410
412
|
medium: "medium";
|
|
@@ -522,6 +524,47 @@ declare const ChartFamilySchema: z.ZodEnum<{
|
|
|
522
524
|
composition: "composition";
|
|
523
525
|
}>;
|
|
524
526
|
type ChartFamily = z.infer<typeof ChartFamilySchema>;
|
|
527
|
+
/** Object shape shared by chart agent request bodies (before dataset-source refinement). */
|
|
528
|
+
declare const GraphGenerationRequestBodySchema: z.ZodObject<{
|
|
529
|
+
config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
|
|
530
|
+
userPrompt: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
|
531
|
+
metadata: z.ZodOptional<z.ZodObject<{
|
|
532
|
+
callId: z.ZodOptional<z.ZodString>;
|
|
533
|
+
locale: z.ZodOptional<z.ZodEnum<{
|
|
534
|
+
EN_GB: "EN_GB";
|
|
535
|
+
EN_US: "EN_US";
|
|
536
|
+
}>>;
|
|
537
|
+
effort: z.ZodOptional<z.ZodEnum<{
|
|
538
|
+
low: "low";
|
|
539
|
+
medium: "medium";
|
|
540
|
+
high: "high";
|
|
541
|
+
}>>;
|
|
542
|
+
storytellingEffort: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
|
|
543
|
+
low: "low";
|
|
544
|
+
medium: "medium";
|
|
545
|
+
high: "high";
|
|
546
|
+
none: "none";
|
|
547
|
+
}>>>;
|
|
548
|
+
budget: z.ZodOptional<z.ZodObject<{
|
|
549
|
+
maxWallClockMs: z.ZodOptional<z.ZodNumber>;
|
|
550
|
+
maxTotalTokens: z.ZodOptional<z.ZodNumber>;
|
|
551
|
+
maxCostUsd: z.ZodOptional<z.ZodNumber>;
|
|
552
|
+
trackUsage: z.ZodOptional<z.ZodBoolean>;
|
|
553
|
+
}, z.core.$strip>>;
|
|
554
|
+
executionMode: z.ZodOptional<z.ZodEnum<{
|
|
555
|
+
agentic: "agentic";
|
|
556
|
+
fast: "fast";
|
|
557
|
+
}>>;
|
|
558
|
+
enforceTableRowCap: z.ZodOptional<z.ZodBoolean>;
|
|
559
|
+
}, z.core.$strip>>;
|
|
560
|
+
chartFamily: z.ZodOptional<z.ZodEnum<{
|
|
561
|
+
comparison: "comparison";
|
|
562
|
+
relationship: "relationship";
|
|
563
|
+
distribution: "distribution";
|
|
564
|
+
composition: "composition";
|
|
565
|
+
}>>;
|
|
566
|
+
datasetRef: z.ZodOptional<z.ZodString>;
|
|
567
|
+
}, z.core.$strip>;
|
|
525
568
|
/**
|
|
526
569
|
* Shared request body for every agent endpoint (`/v0/generate`, `/v0/narrate`,
|
|
527
570
|
* `/v0/explore`, `/v0/annotate`, etc.). Mirrors `GraphGenerationRequestSchema`
|
|
@@ -565,8 +608,9 @@ declare const GraphGenerationRequestSchema: z.ZodObject<{
|
|
|
565
608
|
distribution: "distribution";
|
|
566
609
|
composition: "composition";
|
|
567
610
|
}>>;
|
|
611
|
+
datasetRef: z.ZodOptional<z.ZodString>;
|
|
568
612
|
}, z.core.$strip>;
|
|
569
|
-
type GraphGenerationRequest = z.input<typeof
|
|
613
|
+
type GraphGenerationRequest = z.input<typeof GraphGenerationRequestBodySchema>;
|
|
570
614
|
/** Request body for `POST /v0/suggestions` only. `maxSuggestionCount` max must match agents-api `PROMPT_SUGGESTIONS_UPPER_BOUND`. */
|
|
571
615
|
declare const GenerateSuggestionsParamsSchema: z.ZodObject<{
|
|
572
616
|
config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
|
|
@@ -606,6 +650,7 @@ declare const GenerateSuggestionsParamsSchema: z.ZodObject<{
|
|
|
606
650
|
distribution: "distribution";
|
|
607
651
|
composition: "composition";
|
|
608
652
|
}>>;
|
|
653
|
+
datasetRef: z.ZodOptional<z.ZodString>;
|
|
609
654
|
maxSuggestionCount: z.ZodOptional<z.ZodNumber>;
|
|
610
655
|
}, z.core.$strip>;
|
|
611
656
|
type GenerateSuggestionsParams = z.input<typeof GenerateSuggestionsParamsSchema>;
|
|
@@ -700,6 +745,7 @@ declare const GenerateNarrativeParamsSchema: z.ZodObject<{
|
|
|
700
745
|
distribution: "distribution";
|
|
701
746
|
composition: "composition";
|
|
702
747
|
}>>;
|
|
748
|
+
datasetRef: z.ZodOptional<z.ZodString>;
|
|
703
749
|
userPrompt: z.ZodString;
|
|
704
750
|
mutationReceipt: z.ZodOptional<z.ZodObject<{
|
|
705
751
|
steps: z.ZodArray<z.ZodString>;
|
|
@@ -992,6 +1038,7 @@ declare const GenerateAnnotationsParamsSchema: z.ZodObject<{
|
|
|
992
1038
|
distribution: "distribution";
|
|
993
1039
|
composition: "composition";
|
|
994
1040
|
}>>;
|
|
1041
|
+
datasetRef: z.ZodOptional<z.ZodString>;
|
|
995
1042
|
mutationReceipt: z.ZodOptional<z.ZodObject<{
|
|
996
1043
|
steps: z.ZodArray<z.ZodString>;
|
|
997
1044
|
postProcess: z.ZodOptional<z.ZodObject<{
|
|
@@ -1200,6 +1247,7 @@ declare const GeneratePipelineParamsSchema: z.ZodObject<{
|
|
|
1200
1247
|
distribution: "distribution";
|
|
1201
1248
|
composition: "composition";
|
|
1202
1249
|
}>>;
|
|
1250
|
+
datasetRef: z.ZodOptional<z.ZodString>;
|
|
1203
1251
|
userPrompt: z.ZodString;
|
|
1204
1252
|
stages: z.ZodArray<z.ZodEnum<{
|
|
1205
1253
|
explore: "explore";
|
|
@@ -1378,6 +1426,7 @@ declare const ExtractAttachmentKindSchema: z.ZodEnum<{
|
|
|
1378
1426
|
image: "image";
|
|
1379
1427
|
document: "document";
|
|
1380
1428
|
spreadsheet: "spreadsheet";
|
|
1429
|
+
tabular: "tabular";
|
|
1381
1430
|
}>;
|
|
1382
1431
|
type ExtractAttachmentKind = z.infer<typeof ExtractAttachmentKindSchema>;
|
|
1383
1432
|
declare const ExtractAttachmentInputSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
@@ -1407,6 +1456,7 @@ declare const AttachmentResponseSchema: z.ZodObject<{
|
|
|
1407
1456
|
image: "image";
|
|
1408
1457
|
document: "document";
|
|
1409
1458
|
spreadsheet: "spreadsheet";
|
|
1459
|
+
tabular: "tabular";
|
|
1410
1460
|
}>>;
|
|
1411
1461
|
mimeType: z.ZodString;
|
|
1412
1462
|
filename: z.ZodOptional<z.ZodString>;
|
|
@@ -1430,6 +1480,7 @@ declare const AttachmentUploadResponseSchema: z.ZodObject<{
|
|
|
1430
1480
|
image: "image";
|
|
1431
1481
|
document: "document";
|
|
1432
1482
|
spreadsheet: "spreadsheet";
|
|
1483
|
+
tabular: "tabular";
|
|
1433
1484
|
}>;
|
|
1434
1485
|
sizeBytes: z.ZodNumber;
|
|
1435
1486
|
}, z.core.$strip>;
|
|
@@ -1449,6 +1500,7 @@ declare const AttachmentUploadSlotResponseSchema: z.ZodObject<{
|
|
|
1449
1500
|
image: "image";
|
|
1450
1501
|
document: "document";
|
|
1451
1502
|
spreadsheet: "spreadsheet";
|
|
1503
|
+
tabular: "tabular";
|
|
1452
1504
|
}>>;
|
|
1453
1505
|
mimeType: z.ZodString;
|
|
1454
1506
|
filename: z.ZodOptional<z.ZodString>;
|
|
@@ -1468,6 +1520,7 @@ declare const CreateAttachmentUploadsResponseSchema: z.ZodObject<{
|
|
|
1468
1520
|
image: "image";
|
|
1469
1521
|
document: "document";
|
|
1470
1522
|
spreadsheet: "spreadsheet";
|
|
1523
|
+
tabular: "tabular";
|
|
1471
1524
|
}>>;
|
|
1472
1525
|
mimeType: z.ZodString;
|
|
1473
1526
|
filename: z.ZodOptional<z.ZodString>;
|
|
@@ -1841,19 +1894,14 @@ declare const ChartFitEntrySchema: z.ZodObject<{
|
|
|
1841
1894
|
}, z.core.$strip>;
|
|
1842
1895
|
type ChartFitEntry = z.infer<typeof ChartFitEntrySchema>;
|
|
1843
1896
|
/**
|
|
1844
|
-
* Request body for `POST /v0/evaluate`.
|
|
1845
|
-
*
|
|
1846
|
-
*
|
|
1847
|
-
* `config.type
|
|
1897
|
+
* Request body for `POST /v0/evaluate`. Reuses `GraphGenerationRequestSchema` for shape
|
|
1898
|
+
* symmetry with other chart routes (including `datasetRef`). The handler only reads
|
|
1899
|
+
* `config.data` (and `chartFamily` if present); other fields including `userPrompt` and
|
|
1900
|
+
* `config.type` are accepted-and-ignored.
|
|
1848
1901
|
*/
|
|
1849
1902
|
declare const EvaluateParamsSchema: z.ZodObject<{
|
|
1850
1903
|
config: z.ZodType<GraphConfig, unknown, z.core.$ZodTypeInternals<GraphConfig, unknown>>;
|
|
1851
|
-
|
|
1852
|
-
comparison: "comparison";
|
|
1853
|
-
relationship: "relationship";
|
|
1854
|
-
distribution: "distribution";
|
|
1855
|
-
composition: "composition";
|
|
1856
|
-
}>>;
|
|
1904
|
+
userPrompt: z.ZodDefault<z.ZodOptional<z.ZodString>>;
|
|
1857
1905
|
metadata: z.ZodOptional<z.ZodObject<{
|
|
1858
1906
|
callId: z.ZodOptional<z.ZodString>;
|
|
1859
1907
|
locale: z.ZodOptional<z.ZodEnum<{
|
|
@@ -1883,8 +1931,15 @@ declare const EvaluateParamsSchema: z.ZodObject<{
|
|
|
1883
1931
|
}>>;
|
|
1884
1932
|
enforceTableRowCap: z.ZodOptional<z.ZodBoolean>;
|
|
1885
1933
|
}, z.core.$strip>>;
|
|
1934
|
+
chartFamily: z.ZodOptional<z.ZodEnum<{
|
|
1935
|
+
comparison: "comparison";
|
|
1936
|
+
relationship: "relationship";
|
|
1937
|
+
distribution: "distribution";
|
|
1938
|
+
composition: "composition";
|
|
1939
|
+
}>>;
|
|
1940
|
+
datasetRef: z.ZodOptional<z.ZodString>;
|
|
1886
1941
|
}, z.core.$strip>;
|
|
1887
|
-
type EvaluateParams =
|
|
1942
|
+
type EvaluateParams = GraphGenerationRequest;
|
|
1888
1943
|
/**
|
|
1889
1944
|
* Actionable observation returned alongside the ranking. Each `kind` describes a data-shape
|
|
1890
1945
|
* or data-quality concern (not a chart-specific suggestion — those live in `suggestions`).
|
|
@@ -3568,6 +3623,17 @@ declare class GraphyAiSdk {
|
|
|
3568
3623
|
* @returns Staged attachment metadata including `graphy://attachments/{id}` URI.
|
|
3569
3624
|
*/
|
|
3570
3625
|
uploadAttachment(file: Blob, options?: UploadAttachmentOptions, signal?: AbortSignal): Promise<AttachmentUploadResponse>;
|
|
3626
|
+
/**
|
|
3627
|
+
* Uploads a dataset file (CSV, TSV, or XLSX) via the presigned attachment flow.
|
|
3628
|
+
* Returns a `graphy://attachments/{id}` URI for `datasetRef` on chart agent routes.
|
|
3629
|
+
*
|
|
3630
|
+
* @param file - File or Blob to upload (browser `File` or Node `Blob`).
|
|
3631
|
+
* @param options - Optional filename and mimeType overrides when `file` lacks metadata.
|
|
3632
|
+
* @param signal - Optional `AbortSignal` to cancel the request.
|
|
3633
|
+
* @returns Staged attachment metadata including `graphy://attachments/{id}` URI.
|
|
3634
|
+
* @throws {Error} When the MIME type is not dataset-eligible (e.g. PDF or image).
|
|
3635
|
+
*/
|
|
3636
|
+
uploadDataset(file: Blob, options?: UploadDatasetOptions, signal?: AbortSignal): Promise<AttachmentUploadResponse>;
|
|
3571
3637
|
/**
|
|
3572
3638
|
* Mints presigned upload slots (`POST /v0/attachment-uploads`).
|
|
3573
3639
|
*
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{__awaiter as e,__asyncValues as t,__asyncGenerator as n,__await as i,__rest as o}from"tslib";import{z as r}from"zod";class a extends Error{constructor(e,t){var n;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(n=null==t?void 0:t.retryable)&&void 0!==n&&n}}const s=e=>e instanceof a,l=e=>"progress"===e.type,c=e=>"complete"===e.type,m=e=>"error"===e.type,d=e=>"preview"===e.type,u=e=>"reasoning"===e.type,p=e=>"llm_step"===e.type,g=e=>"session_budget"===e.type,h=e=>"agent_complete"===e.type,f=e=>"tool_call"===e.type,b=e=>"tool_complete"===e.type,y=e=>"tool_error"===e.type;function v(e,t){if("progress"===e){const e=t;return Object.assign({type:"progress"},e)}if("complete"===e)return{type:"complete",data:t};if("error"===e){const e=t;return Object.assign({type:"error"},e)}if("preview"===e){const e=t;return Object.assign(Object.assign({},e),{type:"preview"})}if("reasoning"===e){const e=t;return Object.assign(Object.assign({},e),{type:"reasoning"})}return"llm_step"===e||"session_budget"===e||"agent_complete"===e||"tool_call"===e||"tool_complete"===e||"tool_error"===e?t:null}class x{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return l(e)}static isCompleteEvent(e){return c(e)}static isErrorEvent(e){return m(e)}stream(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,i);return this.parseSSE(e)})}fetch(n,i,o,r){return e(this,void 0,void 0,function*(){var e,s,d,u,p;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${n}`);try{const y=yield this.makeRequest(n,i,r),v=y.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var h,f=!0,b=t(this.parseSSE(y));!(e=(h=yield b.next()).done);f=!0){u=h.value,f=!1;const e=u;if(l(e)&&o&&o(e),c(e))return e.data;if(m(e)){const t=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${n} ${t}ms`,e.error),new a(e.error,{code:e.code,retryable:null!==(p=e.retryable)&&void 0!==p&&p})}}}catch(e){s={error:e}}finally{try{f||e||!(d=b.return)||(yield d.call(b))}finally{if(s)throw s.error}}const i=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${n} ${i}ms`),new a("Stream ended without completion")}return yield y.json()}catch(e){const t=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${n} ${t}ms`,e),e instanceof a)throw e;throw e}finally{const e=Date.now()-g;this.logger.debug(`${this.tag} Fetch completed: ${n} ${e}ms`)}})}ping(){return e(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}uploadMultipart(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,n,i);return yield e.json()})}get(t,n){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,void 0,n,1,"GET");return yield e.json()})}postJson(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,i,1,"POST");return yield e.json()})}sleep(t){return e(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(e){return n(this,arguments,function*(){if(!e.body)throw new a("Response body is null");const t=e.body.getReader(),n=new TextDecoder;let o="",r="",s="";try{for(;;){const{done:e,value:a}=yield i(t.read());if(e)break;o+=n.decode(a,{stream:!0});const l=o.split(/\r?\n/);o=l.pop()||"";for(const e of l)if(e.startsWith("event: "))r=e.slice(7).trim();else if(e.startsWith("data: "))s+=(s?"\n":"")+e.slice(6);else if(""===e.trim()&&s){try{const e=v(r,JSON.parse(s));if(null===e){r="",s="";continue}if(yield yield i(e),"complete"===r||"error"===r)return yield i(void 0)}catch(e){this.logger.warn("Invalid SSE data format",s)}r="",s=""}}}finally{t.releaseLock()}})}makeRequest(t,n,i){return e(this,arguments,void 0,function*(e,t,n,i=1,o="POST"){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const r=new URL(e,this.baseUrl);if(r.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${r}`);const s=new AbortController,l=setTimeout(()=>s.abort(),this.timeout),c=()=>s.abort();n&&n.addEventListener("abort",c);try{const l=yield fetch(r,Object.assign({method:o,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===o&&{body:JSON.stringify(t)}));if(!l.ok){let r,s=`HTTP ${l.status}`;try{const e=yield l.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(r=t.code)}}catch(e){}const c=!("QUOTA_EXCEEDED"===r)&&(l.status>=500||429===l.status),m=new a(s,{status:l.status,code:r,retryable:c});if(c&&i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${r}ms (attempt ${i+1})`),yield this.sleep(r),this.makeRequest(e,t,n,i+1,o)}throw this.logger.error(`${this.tag} Request failed: ${e} (${l.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),l}catch(r){if(r instanceof a)throw r;if(r instanceof Error&&"AbortError"===r.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),r;if(i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${r}ms`),yield this.sleep(r),this.makeRequest(e,t,n,i+1,o)}throw this.logger.error(`${this.tag} Network error: ${e}`,r),new a("Network error",{retryable:!0})}finally{clearTimeout(l),n&&n.removeEventListener("abort",c)}})}makeMultipartRequest(t,n,i){return e(this,arguments,void 0,function*(e,t,n,i=1){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const o=new URL(e,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");const r=new AbortController,s=setTimeout(()=>r.abort(),this.timeout),l=()=>r.abort();n&&n.addEventListener("abort",l);try{const s=yield fetch(o,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},body:t,signal:r.signal});if(!s.ok){let o,r=`HTTP ${s.status}`;try{const e=yield s.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?r=t.message:"string"==typeof t.error&&(r=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const l=s.status>=500||429===s.status,c=new a(r,{status:s.status,code:o,retryable:l});if(l&&i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return yield this.sleep(o),this.makeMultipartRequest(e,t,n,i+1)}throw c}return s}catch(o){if(o instanceof a)throw o;if(o instanceof Error&&"AbortError"===o.name)throw o;if(i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return yield this.sleep(o),this.makeMultipartRequest(e,t,n,i+1)}throw new a("Network error",{retryable:!0})}finally{clearTimeout(s),n&&n.removeEventListener("abort",l)}})}}const w={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".pdf":"application/pdf",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};function j(e,t){var n;const i=null===(n=null==t?void 0:t.filename)||void 0===n?void 0:n.trim();return i||("undefined"!=typeof File&&e instanceof File&&e.name.trim().length>0?e.name.trim():void 0)}function k(e,t){var n;const i=null===(n=null==t?void 0:t.mimeType)||void 0===n?void 0:n.trim();if(i)return i;const o=e.type.trim();if(o.length>0)return o;const r=j(e,t);if(r){const e=function(e){const t=e.lastIndexOf(".");if(t<0)return;const n=e.slice(t).toLowerCase();return w[n]}(r);if(e)return e}throw new Error("uploadAttachment requires a MIME type: set `file.type`, pass `options.mimeType`, or use a filename with a supported extension (.png, .jpg, .pdf, .xlsx, …)")}const T=r.object({inputTokens:r.number(),inputCachedTokens:r.number(),inputUncachedTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),costUsd:r.number().nullable(),costEnforcementSkipped:r.boolean().optional(),wallClockMs:r.number()}),$=r.object({wallClockMs:r.number(),inputTokens:r.number(),inputCachedTokens:r.number(),inputUncachedTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),costUsd:r.number().nullable(),costEnforcementSkipped:r.boolean().optional()}),S=r.object({limits:r.object({maxWallClockMs:r.number().optional(),maxTotalTokens:r.number().optional(),maxCostUsd:r.number().optional(),trackUsage:r.boolean().optional()}),consumed:$,exceeded:r.boolean(),exceededDimensions:r.array(r.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:r.string().optional()});r.object({inputTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),modelName:r.string(),inputCachedTokens:r.number().optional(),inputUncachedTokens:r.number().optional(),cost:r.number().optional(),latencyMs:r.number().optional(),effort:r.string().optional(),providerReasoning:r.string().optional()});const C={usage:T.optional(),budget:S.optional()},R=r.enum(["EN_GB","EN_US"]),E=r.custom(e=>null!=e&&"object"==typeof e),U=r.enum(["low","medium","high"]),A=r.enum(["none","low","medium","high"]),O=r.enum(["agentic","fast"]),I=3e5,P=5e5,M=10,B=r.object({maxWallClockMs:r.number().positive().max(I).optional(),maxTotalTokens:r.number().int().positive().max(P).optional(),maxCostUsd:r.number().positive().max(10).optional(),trackUsage:r.boolean().optional()}),q=r.object({wallClockMs:r.number(),inputTokens:r.number(),inputCachedTokens:r.number(),inputUncachedTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),costUsd:r.number().nullable(),costEnforcementSkipped:r.boolean().optional()});r.object({limits:B,consumed:q,exceeded:r.boolean(),exceededDimensions:r.array(r.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:r.string().optional()});const F=r.object({callId:r.string().max(256).optional(),locale:R.optional(),effort:U.optional(),storytellingEffort:A.optional().default("low"),budget:B.optional(),executionMode:O.optional(),enforceTableRowCap:r.boolean().optional()}),_=r.object({steps:r.array(r.string()),postProcess:r.object({measureRelevance:r.enum(["prompt-named","derived","magnitude"]).optional(),grain:r.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:r.string().optional(),comparison:r.string().optional()}).optional(),droppedMeasures:r.array(r.string()).optional(),rowCount:r.number().int().nonnegative(),totalRowCountBeforeSlice:r.number().int().positive().optional(),displayedRowCount:r.number().int().nonnegative().optional(),columnKeys:r.array(r.string()),activeFilters:r.array(r.string()).optional(),grainSummary:r.string().optional()}),D=r.object({runId:r.string(),trackingId:r.string(),callId:r.string().optional()}),N=1e4,K=r.enum(["comparison","relationship","distribution","composition"]),L=r.object({config:E,userPrompt:r.string().max(N).optional().default(""),metadata:F.optional(),chartFamily:K.optional()}),z=L.extend({maxSuggestionCount:r.number().int().min(1).max(4).optional()}),G=r.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),W=r.object({dataPrepPrompt:r.string(),chartType:G,summary:r.string()}),H=L.extend({userPrompt:r.string().max(N),mutationReceipt:_.optional(),exploreFindingSummary:r.string().max(500).optional()}),J=r.object({response:r.object({message:r.string()}),config:E,run:D.optional()}).extend(C),X=r.object({suggestions:r.array(W),run:D.optional()}).extend(C),Q=r.object({finding:r.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:r.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:r.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:r.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:r.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:K.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:r.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),V=r.object({topic:r.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:r.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:r.number().int().min(1).describe("Number of findings in this story."),findings:r.array(Q).describe("Child findings, sorted by quadrant score desc.")}),Y=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),stories:r.array(V),run:D.optional()}).extend(C);L.extend({mutationReceipt:_.optional()});const Z=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),config:E,run:D.optional()}).extend(C),ee=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),config:E,mutationReceipt:_.optional(),warnings:r.array(r.string()).optional(),run:D.optional()}).extend(C),te=r.enum(["explore","mutate","narrate","annotate"]),ne=r.object({agent:te,summary:r.string(),steps:r.array(r.string()).optional()}),ie=L.extend({userPrompt:r.string().max(N),stages:r.array(te).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:r.string().max(500).optional()}),oe=ee.extend({reasoning:r.array(ne),stories:r.array(V).optional()}),re=r.enum(["high","medium","low"]),ae=r.object({confidence:re,needsUserInput:r.boolean(),warnings:r.array(r.string()),cellConfidence:r.array(r.object({rowIndex:r.number().int().nonnegative(),columnKey:r.string(),confidence:re,quote:r.string().optional()})).optional()}),se=r.object({score:r.number().min(0).max(1),issues:r.array(r.string()),sufficient:r.boolean(),summary:r.string()}),le=5e5,ce=8,me=2097152,de=7340032,ue=2,pe=6291456,ge=8388608,he=2,fe=pe,be=ge,ye=12582912,ve=12,xe=52428800;function we(e){return 4*Math.ceil(e/3)}const je=we(me),ke=we(de),Te=we(pe),$e=we(ge),Se=we(fe),Ce=we(be),Re=we(ye);function Ee(e){return e.replace(/\s+/g,"")}function Ue(e){const t=Ee(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const Ae=/^image\/(png|jpeg|jpg|webp|gif)$/i,Oe=r.object({mimeType:r.string().min(1).refine(e=>Ae.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:r.string().min(1).max(je).refine(Ue,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Ie=r.enum(["image","document","spreadsheet"]),Pe=Oe.extend({kind:r.literal("image")}),Me=r.object({kind:r.literal("document"),mimeType:r.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:r.string().min(1).max(Te).refine(Ue,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Be=r.object({kind:r.literal("spreadsheet"),mimeType:r.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:r.string().min(1).max(Se).refine(Ue,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:r.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),qe=r.discriminatedUnion("kind",[Pe,Me,Be]),Fe=r.string().regex(/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),_e=r.enum(["pending","ready","failed"]),De=r.object({id:r.string().uuid(),uri:r.string(),status:_e,kind:Ie.optional(),mimeType:r.string(),filename:r.string().optional(),sizeBytes:r.number().int().nonnegative(),uploadExpiresAt:r.string().datetime().optional(),completedAt:r.string().datetime().optional(),expiresAt:r.string().datetime()}),Ne=De.extend({status:r.literal("ready"),kind:Ie,sizeBytes:r.number().int().positive()}),Ke=r.object({mimeType:r.string().min(1),filename:r.string().max(512).optional(),sizeBytes:r.number().int().positive().max(xe).optional()}),Le=r.object({files:r.array(Ke).min(1).max(ve)}),ze=De.extend({status:r.literal("pending"),uploadUrl:r.string().url()}),Ge=r.object({uploads:r.array(ze)}),We=r.object({sourceText:r.string().max(le).default(""),images:r.array(Oe).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:r.array(qe).max(ve).optional(),attachmentRefs:r.array(Fe).max(ve).optional(),metadata:F.optional()}).superRefine((e,t)=>{var n,i,o;const r=e.sourceText.trim(),a=null!==(n=e.images)&&void 0!==n?n:[],s=null!==(i=e.attachments)&&void 0!==i?i:[],l=null!==(o=e.attachmentRefs)&&void 0!==o?o:[];if(a.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===r.length&&0===a.length&&0===s.length&&0===l.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(a.length+s.length+l.length>ve)return void t.addIssue({code:"custom",message:"Too many attachments (max 12 across inline payloads and attachmentRefs)",path:["attachmentRefs"]});if(l.length>0&&0===s.length&&0===a.length)return;if(a.length>0){a.reduce((e,t)=>e+Ee(t.dataBase64).length,0)>ke&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let c=0,m=0,d=0,u=0,p=0,g=0,h=0;for(const e of s){const t=Ee(e.dataBase64).length;switch(h+=t,e.kind){case"image":c+=1,u+=t;break;case"document":m+=1,p+=t;break;case"spreadsheet":d+=1,g+=t}}c>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),d>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=c<=8&&m<=2&&d<=2;s.length>0&&f&&(u>ke&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>$e&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>Ce&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>Re&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function He(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:Ee(e.dataBase64)}}function Je(e){return{kind:"document",mimeType:"application/pdf",dataBase64:Ee(e.dataBase64)}}function Xe(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:Ee(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const Qe=r.object({response:r.object({message:r.string()}),config:E,extractMeta:ae.nullable(),lastAccuracyEvaluation:se.optional(),run:D.optional()}).extend(C),Ve=r.object({config:E,response:r.object({message:r.string(),steps:r.array(r.string())}),run:D.optional()}).extend(C),Ye=X,Ze=r.enum(["deal-breaker","pro","con","family","continuity"]),et=r.object({kind:Ze,label:r.string(),weight:r.number(),reason:r.string()}),tt=r.enum(["ok","disqualified"]),nt=r.object({rank:r.number().int().positive(),type:G,score:r.number(),verdict:tt,factors:r.array(et)}),it=r.object({config:E,chartFamily:K.optional(),metadata:F.optional()}),ot=r.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),rt=r.object({kind:ot,message:r.string()}),at=r.enum(["sum","avg","count","min","max"]),st=r.object({dimensionName:r.string(),dimensionLabel:r.string(),measureName:r.string().nullable(),measureLabel:r.string().nullable(),fn:at,chartType:G,score:r.number(),message:r.string()}),lt=r.object({ranking:r.array(nt),observations:r.array(rt).optional().default([]),suggestions:r.array(st).optional().default([]),run:D.optional()}),ct=r.object({prompt:r.string(),datasetSummary:r.string().optional(),mustShow:r.array(r.string()).optional(),unacceptable:r.array(r.string()).optional(),acceptableChartFamilies:r.array(r.string()).optional()}),mt=r.object({config:E.optional(),chartImage:r.string().optional(),data:r.unknown().optional(),rubric:ct.optional(),userPrompt:r.string().optional(),metadata:F.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),dt=r.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),ut=r.enum(["info","low","medium","high"]),pt=r.object({category:dt,severity:ut,observation:r.string(),rationale:r.string().optional(),suggestedChange:r.string().optional(),configPaths:r.array(r.string()).optional()}),gt=r.object({overallSummary:r.string(),overallSeverity:r.enum(["none","low","medium","high"]).optional(),issues:r.array(pt)}),ht=r.object({dataFidelity:r.number().min(0).max(1),promptRelevance:r.number().min(0).max(1),chartTypeAppropriateness:r.number().min(0).max(1),readability:r.number().min(0).max(1),honesty:r.number().min(0).max(1),composite:r.number().min(0).max(1),rationale:r.string().optional()}),ft=r.object({capturedAt:r.string(),chartId:r.string()}),bt=r.object({response:r.object({message:r.string(),steps:r.array(r.string()),critiqueCommitted:r.boolean()}),critiqueReport:gt.nullable(),chartVisionAudit:ft.nullable().optional().default(null),rubricScores:ht.nullable().optional().default(null),run:D.optional()}).extend(C),yt="/api/v0";class vt{constructor(e){this.client=new x(e)}generateGraph(t,n,i){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,r=o(t,["storytellingOptions"]),a=yield this.client.fetch(`${yt}/generate`,r,n,i),s=Ve.parse(a);return this.stripStorytelling(s,e)})}generateGraphStream(t,n){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,i=o(t,["storytellingOptions"]),r=yield this.client.stream(`${yt}/generate`,i,n);return this.wrapStreamWithStorytellingStripping(r,e)})}generateNarrative(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/narrate`,t,n,i);return J.parse(e)})}generateNarrativeStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${yt}/narrate`,t,n)})}generateSuggestions(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/suggestions`,t,n,i);return X.parse(e)})}generateSuggestionsStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${yt}/suggestions`,t,n)})}generateExploration(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/explore`,t,n,i);return Y.parse(e)})}generateExplorationStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${yt}/explore`,t,n)})}generateAnnotations(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/annotate`,t,n,i);return Z.parse(e)})}generateAnnotationsStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${yt}/annotate`,t,n)})}generateMutation(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/mutate`,t,n,i);return ee.parse(e)})}generateMutationStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${yt}/mutate`,t,n)})}generatePipeline(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/pipeline`,t,n,i);return oe.parse(e)})}generatePipelineStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${yt}/pipeline`,t,n)})}evaluate(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/evaluate`,t,void 0,n);return lt.parse(e)})}judge(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/judge`,t,void 0,n);return bt.parse(e)})}judgeStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${yt}/judge`,t,n)})}extractFromProse(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${yt}/extract`,t,n,i);return Qe.parse(e)})}extractFromProseStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${yt}/extract`,t,n)})}uploadAttachment(t,n,i){return e(this,void 0,void 0,function*(){const e=k(t,n),o=j(t,n),{uploads:r}=yield this.createAttachmentUploads({files:[Object.assign(Object.assign({mimeType:e},o?{filename:o}:{}),t.size>0?{sizeBytes:t.size}:{})]},i),s=r[0];if(!s)throw new a("Attachment upload slot was not returned");const l=yield fetch(s.uploadUrl,{method:"PUT",headers:{"Content-Type":e},body:t,signal:i});if(!l.ok)throw new a(`Attachment upload failed (HTTP ${l.status})`,{status:l.status,retryable:l.status>=500});const c=yield this.completeAttachmentUpload(s.id,i);return Ne.parse(c)})}createAttachmentUploads(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${yt}/attachment-uploads`,t,n);return Ge.parse(e)})}completeAttachmentUpload(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${yt}/attachments/${t}/complete`,{},n);return De.parse(e)})}getAttachment(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.get(`${yt}/attachments/${t}`,n);return De.parse(e)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(e,o){return n(this,arguments,function*(){var n,r,a,s;try{for(var l,m=!0,d=t(e);!(n=(l=yield i(d.next())).done);m=!0){s=l.value,m=!1;const e=s;if(c(e)){const t=this.stripStorytelling(e.data,o);yield yield i(Object.assign(Object.assign({},e),{data:t}))}else yield yield i(e)}}catch(e){r={error:e}}finally{try{m||n||!(a=d.return)||(yield i(a.call(d)))}finally{if(r)throw r.error}}})}}export{at as AggregationFunctionSchema,st as AggregationSuggestionSchema,G as AiChartTypeEnum,De as AttachmentResponseSchema,Ne as AttachmentUploadResponseSchema,ze as AttachmentUploadSlotResponseSchema,dt as ChartCritiqueIssueCategorySchema,pt as ChartCritiqueIssueSchema,ut as ChartCritiqueIssueSeveritySchema,gt as ChartCritiqueReportSchema,K as ChartFamilySchema,nt as ChartFitEntrySchema,Ze as ChartFitFactorKindSchema,et as ChartFitFactorSchema,tt as ChartFitVerdictSchema,ct as ChartJudgeRubricSchema,Le as CreateAttachmentUploadsParamsSchema,Ge as CreateAttachmentUploadsResponseSchema,ot as DataObservationKindSchema,rt as DataObservationSchema,it as EvaluateParamsSchema,lt as EvaluateResponseSchema,O as ExecutionModeSchema,Q as ExploreFindingSchema,V as ExploreStorySchema,se as ExtractAccuracyEvaluationSchema,qe as ExtractAttachmentInputSchema,Ie as ExtractAttachmentKindSchema,re as ExtractConfidenceSchema,We as ExtractFromProseParamsSchema,Qe as ExtractFromProseResponseSchema,ae as ExtractMetaSchema,Z as GenerateAnnotationsResponseSchema,Y as GenerateExplorationResponseSchema,Ve as GenerateGraphResponseSchema,Ye as GenerateGraphSuggestionsResponseSchema,ee as GenerateMutationResponseSchema,H as GenerateNarrativeParamsSchema,J as GenerateNarrativeResponseSchema,ie as GeneratePipelineParamsSchema,oe as GeneratePipelineResponseSchema,z as GenerateSuggestionsParamsSchema,X as GenerateSuggestionsResponseSchema,L as GraphGenerationRequestSchema,vt as GraphyAiSdk,a as GraphyApiError,B as InvocationBudgetSchema,U as InvocationEffortSchema,mt as JudgeParamsSchema,bt as JudgeResponseSchema,M as MAX_BUDGET_COST_USD,P as MAX_BUDGET_TOTAL_TOKENS,I as MAX_BUDGET_WALL_CLOCK_MS,ve as MAX_EXTRACT_ATTACHMENTS,ye as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,ue as MAX_EXTRACT_DOCUMENTS,ge as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,pe as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,ce as MAX_EXTRACT_IMAGES,de as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,me as MAX_EXTRACT_IMAGE_DECODED_BYTES,he as MAX_EXTRACT_SPREADSHEETS,be as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,fe as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,le as MAX_SOURCE_TEXT_LENGTH,xe as MAX_STAGED_FILE_BYTES,N as MAX_USER_PROMPT_LENGTH,F as MetadataSchema,_ as MutateNarrationReceiptSchema,te as PipelineAgentNameSchema,ne as PipelineStageReasoningSchema,ht as RubricScoresSchema,D as RunContextSchema,A as StorytellingEffortSchema,W as SuggestionSchema,He as buildImageAttachment,Je as buildPdfAttachment,Xe as buildSpreadsheetAttachment,h as isAgentCompleteEvent,c as isCompleteEvent,m as isErrorEvent,s as isGraphyApiError,p as isLlmStepEvent,d as isPreviewEvent,l as isProgressEvent,u as isReasoningEvent,g as isSessionBudgetEvent,f as isToolCallEvent,b as isToolCompleteEvent,y as isToolErrorEvent};
|
|
1
|
+
import{__awaiter as e,__asyncValues as t,__asyncGenerator as n,__await as i,__rest as o}from"tslib";import{z as r}from"zod";class a extends Error{constructor(e,t){var n;super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="GraphyApiError",this.status=null==t?void 0:t.status,this.code=null==t?void 0:t.code,this.retryable=null!==(n=null==t?void 0:t.retryable)&&void 0!==n&&n}}const s=e=>e instanceof a,l=e=>"progress"===e.type,c=e=>"complete"===e.type,m=e=>"error"===e.type,d=e=>"preview"===e.type,u=e=>"reasoning"===e.type,p=e=>"llm_step"===e.type,g=e=>"session_budget"===e.type,h=e=>"agent_complete"===e.type,f=e=>"tool_call"===e.type,b=e=>"tool_complete"===e.type,y=e=>"tool_error"===e.type;function v(e,t){if("progress"===e){const e=t;return Object.assign({type:"progress"},e)}if("complete"===e)return{type:"complete",data:t};if("error"===e){const e=t;return Object.assign({type:"error"},e)}if("preview"===e){const e=t;return Object.assign(Object.assign({},e),{type:"preview"})}if("reasoning"===e){const e=t;return Object.assign(Object.assign({},e),{type:"reasoning"})}return"llm_step"===e||"session_budget"===e||"agent_complete"===e||"tool_call"===e||"tool_complete"===e||"tool_error"===e?t:null}class x{constructor(e){if(this.tag="[GRAPHY]",!e.apiKey||0===e.apiKey.trim().length)throw new Error("apiKey is required and must not be empty");const t=new URL(e.baseUrl);if(!["http:","https:"].includes(t.protocol))throw new Error(`Invalid baseUrl protocol: ${t.protocol}. Only http(s) is allowed.`);this.apiKey=e.apiKey,this.baseUrl=t.origin+t.pathname.replace(/\/$/,""),this.timeout=e.timeout||6e4,this.retryConfig=e.retryConfig||{attempts:3,delay:1e3,backoff:2},this.logger=e.logger||{log:console.log,warn:console.warn,error:console.error,debug:console.debug}}static isProgressEvent(e){return l(e)}static isCompleteEvent(e){return c(e)}static isErrorEvent(e){return m(e)}stream(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,i);return this.parseSSE(e)})}fetch(n,i,o,r){return e(this,void 0,void 0,function*(){var e,s,d,u,p;const g=Date.now();this.logger.debug(`${this.tag} Fetch: ${n}`);try{const y=yield this.makeRequest(n,i,r),v=y.headers.get("content-type");if(null==v?void 0:v.includes("text/event-stream")){try{for(var h,f=!0,b=t(this.parseSSE(y));!(e=(h=yield b.next()).done);f=!0){u=h.value,f=!1;const e=u;if(l(e)&&o&&o(e),c(e))return e.data;if(m(e)){const t=Date.now()-g;throw this.logger.error(`${this.tag} Server error: ${n} ${t}ms`,e.error),new a(e.error,{code:e.code,retryable:null!==(p=e.retryable)&&void 0!==p&&p})}}}catch(e){s={error:e}}finally{try{f||e||!(d=b.return)||(yield d.call(b))}finally{if(s)throw s.error}}const i=Date.now()-g;throw this.logger.error(`${this.tag} Stream incomplete: ${n} ${i}ms`),new a("Stream ended without completion")}return yield y.json()}catch(e){const t=Date.now()-g;if(this.logger.error(`${this.tag} Fetch failed: ${n} ${t}ms`,e),e instanceof a)throw e;throw e}finally{const e=Date.now()-g;this.logger.debug(`${this.tag} Fetch completed: ${n} ${e}ms`)}})}ping(){return e(this,void 0,void 0,function*(){const e=Date.now();try{return yield this.makeRequest("/health",void 0,void 0,this.retryConfig.attempts,"GET"),{ok:!0,latency:Date.now()-e}}catch(t){return{ok:!1,latency:Date.now()-e}}})}uploadMultipart(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeMultipartRequest(t,n,i);return yield e.json()})}get(t,n){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,void 0,n,1,"GET");return yield e.json()})}postJson(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.makeRequest(t,n,i,1,"POST");return yield e.json()})}sleep(t){return e(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}parseSSE(e){return n(this,arguments,function*(){if(!e.body)throw new a("Response body is null");const t=e.body.getReader(),n=new TextDecoder;let o="",r="",s="";try{for(;;){const{done:e,value:a}=yield i(t.read());if(e)break;o+=n.decode(a,{stream:!0});const l=o.split(/\r?\n/);o=l.pop()||"";for(const e of l)if(e.startsWith("event: "))r=e.slice(7).trim();else if(e.startsWith("data: "))s+=(s?"\n":"")+e.slice(6);else if(""===e.trim()&&s){try{const e=v(r,JSON.parse(s));if(null===e){r="",s="";continue}if(yield yield i(e),"complete"===r||"error"===r)return yield i(void 0)}catch(e){this.logger.warn("Invalid SSE data format",s)}r="",s=""}}}finally{t.releaseLock()}})}makeRequest(t,n,i){return e(this,arguments,void 0,function*(e,t,n,i=1,o="POST"){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const r=new URL(e,this.baseUrl);if(r.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");this.logger.debug(`${this.tag} Request ${i}/${this.retryConfig.attempts}: ${r}`);const s=new AbortController,l=setTimeout(()=>s.abort(),this.timeout),c=()=>s.abort();n&&n.addEventListener("abort",c);try{const l=yield fetch(r,Object.assign({method:o,headers:{"Content-Type":"application/json",Accept:"application/json, text/event-stream","Cache-Control":"no-cache",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},signal:s.signal},"POST"===o&&{body:JSON.stringify(t)}));if(!l.ok){let r,s=`HTTP ${l.status}`;try{const e=yield l.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?s=t.message:"string"==typeof t.error&&(s=t.error),"string"==typeof t.code&&(r=t.code)}}catch(e){}const c=!("QUOTA_EXCEEDED"===r)&&(l.status>=500||429===l.status),m=new a(s,{status:l.status,code:r,retryable:c});if(c&&i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Retrying ${e} in ${r}ms (attempt ${i+1})`),yield this.sleep(r),this.makeRequest(e,t,n,i+1,o)}throw this.logger.error(`${this.tag} Request failed: ${e} (${l.status}) - ${s}`),m}return this.logger.debug(`${this.tag} Connected: ${e}`),l}catch(r){if(r instanceof a)throw r;if(r instanceof Error&&"AbortError"===r.name)throw this.logger.debug(`${this.tag} Aborted: ${e}`),r;if(i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const r=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return this.logger.warn(`${this.tag} Network error, retrying ${e} in ${r}ms`),yield this.sleep(r),this.makeRequest(e,t,n,i+1,o)}throw this.logger.error(`${this.tag} Network error: ${e}`,r),new a("Network error",{retryable:!0})}finally{clearTimeout(l),n&&n.removeEventListener("abort",c)}})}makeMultipartRequest(t,n,i){return e(this,arguments,void 0,function*(e,t,n,i=1){if(!e.startsWith("/"))throw new a("Invalid endpoint: must start with /");const o=new URL(e,this.baseUrl);if(o.origin!==new URL(this.baseUrl).origin)throw new a("Endpoint resolved to unexpected origin");const r=new AbortController,s=setTimeout(()=>r.abort(),this.timeout),l=()=>r.abort();n&&n.addEventListener("abort",l);try{const s=yield fetch(o,{method:"POST",headers:{Accept:"application/json",Authorization:`Bearer ${this.apiKey}`,"User-Agent":"Graphy-SDK/1.0"},body:t,signal:r.signal});if(!s.ok){let o,r=`HTTP ${s.status}`;try{const e=yield s.json();if("object"==typeof e&&null!==e){const t=e;"string"==typeof t.message?r=t.message:"string"==typeof t.error&&(r=t.error),"string"==typeof t.code&&(o=t.code)}}catch(e){}const l=s.status>=500||429===s.status,c=new a(r,{status:s.status,code:o,retryable:l});if(l&&i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return yield this.sleep(o),this.makeMultipartRequest(e,t,n,i+1)}throw c}return s}catch(o){if(o instanceof a)throw o;if(o instanceof Error&&"AbortError"===o.name)throw o;if(i<this.retryConfig.attempts&&!(null==n?void 0:n.aborted)){const o=this.retryConfig.delay*Math.pow(this.retryConfig.backoff,i-1);return yield this.sleep(o),this.makeMultipartRequest(e,t,n,i+1)}throw new a("Network error",{retryable:!0})}finally{clearTimeout(s),n&&n.removeEventListener("abort",l)}})}}const w={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif",".pdf":"application/pdf",".csv":"text/csv",".tsv":"text/tab-separated-values",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"};function j(e,t){var n;const i=null===(n=null==t?void 0:t.filename)||void 0===n?void 0:n.trim();return i||("undefined"!=typeof File&&e instanceof File&&e.name.trim().length>0?e.name.trim():void 0)}function k(e,t){var n;const i=null===(n=null==t?void 0:t.mimeType)||void 0===n?void 0:n.trim();if(i)return i;const o=e.type.trim();if(o.length>0)return o;const r=j(e,t);if(r){const e=function(e){const t=e.lastIndexOf(".");if(t<0)return;const n=e.slice(t).toLowerCase();return w[n]}(r);if(e)return e}throw new Error("uploadAttachment requires a MIME type: set `file.type`, pass `options.mimeType`, or use a filename with a supported extension (.png, .jpg, .pdf, .csv, .tsv, .xlsx, …)")}const T=new Set(["text/csv","text/tab-separated-values","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"]);function $(e,t){const n=k(e,t);if(i=n,!T.has(i.trim()))throw new Error("uploadDataset requires a dataset MIME type (text/csv, text/tab-separated-values, or application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)");var i;return n}const S=r.object({inputTokens:r.number(),inputCachedTokens:r.number(),inputUncachedTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),costUsd:r.number().nullable(),costEnforcementSkipped:r.boolean().optional(),wallClockMs:r.number()}),C=r.object({wallClockMs:r.number(),inputTokens:r.number(),inputCachedTokens:r.number(),inputUncachedTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),costUsd:r.number().nullable(),costEnforcementSkipped:r.boolean().optional()}),R=r.object({limits:r.object({maxWallClockMs:r.number().optional(),maxTotalTokens:r.number().optional(),maxCostUsd:r.number().optional(),trackUsage:r.boolean().optional()}),consumed:C,exceeded:r.boolean(),exceededDimensions:r.array(r.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:r.string().optional()});r.object({inputTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),modelName:r.string(),inputCachedTokens:r.number().optional(),inputUncachedTokens:r.number().optional(),cost:r.number().optional(),latencyMs:r.number().optional(),effort:r.string().optional(),providerReasoning:r.string().optional()});const E={usage:S.optional(),budget:R.optional()};function U(e,t){const n=void 0!==e.config.data,i=function(e){const{data:t}=e;return void 0!==t&&(t.columns.length>0||t.rows.length>0)}(e.config),o=void 0!==e.datasetRef&&e.datasetRef.trim().length>0;i&&o&&t.addIssue({code:"custom",message:"Provide either config.data or datasetRef, not both",path:["datasetRef"]}),n||o||t.addIssue({code:"custom",message:"Provide config.data or datasetRef",path:["datasetRef"]})}const A=r.enum(["EN_GB","EN_US"]),I=r.custom(e=>null!=e&&"object"==typeof e),O=r.enum(["low","medium","high"]),P=r.enum(["none","low","medium","high"]),M=r.enum(["agentic","fast"]),B=3e5,q=5e5,D=10,F=r.object({maxWallClockMs:r.number().positive().max(B).optional(),maxTotalTokens:r.number().int().positive().max(q).optional(),maxCostUsd:r.number().positive().max(10).optional(),trackUsage:r.boolean().optional()}),_=r.object({wallClockMs:r.number(),inputTokens:r.number(),inputCachedTokens:r.number(),inputUncachedTokens:r.number(),outputTokens:r.number(),totalTokens:r.number(),costUsd:r.number().nullable(),costEnforcementSkipped:r.boolean().optional()});r.object({limits:F,consumed:_,exceeded:r.boolean(),exceededDimensions:r.array(r.enum(["wallClockMs","totalTokens","costUsd"])),exceededSummary:r.string().optional()});const N=r.object({callId:r.string().max(256).optional(),locale:A.optional(),effort:O.optional(),storytellingEffort:P.optional().default("low"),budget:F.optional(),executionMode:M.optional(),enforceTableRowCap:r.boolean().optional()}),K=r.object({steps:r.array(r.string()),postProcess:r.object({measureRelevance:r.enum(["prompt-named","derived","magnitude"]).optional(),grain:r.enum(["remap-x","groupBy","reshape","compositeX"]).optional(),chartType:r.string().optional(),comparison:r.string().optional()}).optional(),droppedMeasures:r.array(r.string()).optional(),rowCount:r.number().int().nonnegative(),totalRowCountBeforeSlice:r.number().int().positive().optional(),displayedRowCount:r.number().int().nonnegative().optional(),columnKeys:r.array(r.string()),activeFilters:r.array(r.string()).optional(),grainSummary:r.string().optional()}),L=r.object({runId:r.string(),trackingId:r.string(),callId:r.string().optional()}),z=1e4,G=r.enum(["comparison","relationship","distribution","composition"]),W=/^graphy:\/\/attachments\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,H=r.string().regex(W,"datasetRef must be graphy://attachments/{uuid}"),J=r.object({config:I,userPrompt:r.string().max(z).optional().default(""),metadata:N.optional(),chartFamily:G.optional(),datasetRef:H.optional()}),X=J.superRefine(U),Q=J.extend({maxSuggestionCount:r.number().int().min(1).max(4).optional()}).superRefine(U),V=r.enum(["line","areaStacked","bar","groupedBar","stackedBar","100StackedBar","column","groupedColumn","stackedColumn","100StackedColumn","combo","pie","donut","funnel","heatmap","scatter","bubble","waterfall","table","mekko"]),Y=r.object({dataPrepPrompt:r.string(),chartType:V,summary:r.string()}),Z=J.extend({userPrompt:r.string().max(z),mutationReceipt:K.optional(),exploreFindingSummary:r.string().max(500).optional()}).superRefine(U),ee=r.object({response:r.object({message:r.string()}),config:I,run:L.optional()}).extend(E),te=r.object({suggestions:r.array(Y),run:L.optional()}).extend(E),ne=r.object({finding:r.string().describe("Plain-English summary of the finding (no stats jargon)."),confidence:r.number().min(0).max(1).describe("Statistical strength of the finding (0..1). Independent of topicality."),relevance:r.number().min(0).max(1).describe("Topical fit with the user prompt and chart narrative (0..1). Independent of statistical strength."),topic:r.string().min(1).describe("Kebab-case label grouping this finding with related ones; consumers can render findings as threads."),chartHint:r.string().min(1).max(240).describe('Natural-language data-prep recipe for a downstream mutate agent: filter → group → aggregate → sort, naming real dataset columns. No chart type or "render as" clause — that is set via chartFamily.'),chartFamily:G.describe("Abela family (comparison | relationship | distribution | composition). Downstream chart-generator picks the concrete chart type from this family + the data shape."),evidenceSummary:r.string().max(300).describe("Rigorous statistical back-up with exact numbers.")}),ie=r.object({topic:r.string().min(1).describe("Kebab-case story headline shared by all child findings."),score:r.number().min(0).max(1).describe("Max quadrant score (relevance × confidence) across child findings."),count:r.number().int().min(1).describe("Number of findings in this story."),findings:r.array(ne).describe("Child findings, sorted by quadrant score desc.")}),oe=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),stories:r.array(ie),run:L.optional()}).extend(E);J.extend({mutationReceipt:K.optional()}).superRefine(U);const re=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),config:I,run:L.optional()}).extend(E),ae=r.object({response:r.object({message:r.string(),steps:r.array(r.string())}),config:I,mutationReceipt:K.optional(),warnings:r.array(r.string()).optional(),run:L.optional()}).extend(E),se=r.enum(["explore","mutate","narrate","annotate"]),le=r.object({agent:se,summary:r.string(),steps:r.array(r.string()).optional()}),ce=J.extend({userPrompt:r.string().max(z),stages:r.array(se).min(1).refine(e=>new Set(e).size===e.length,{message:"Duplicate pipeline stages are not allowed"}),exploreFindingSummary:r.string().max(500).optional()}).superRefine(U),me=ae.extend({reasoning:r.array(le),stories:r.array(ie).optional()}),de=r.enum(["high","medium","low"]),ue=r.object({confidence:de,needsUserInput:r.boolean(),warnings:r.array(r.string()),cellConfidence:r.array(r.object({rowIndex:r.number().int().nonnegative(),columnKey:r.string(),confidence:de,quote:r.string().optional()})).optional()}),pe=r.object({score:r.number().min(0).max(1),issues:r.array(r.string()),sufficient:r.boolean(),summary:r.string()}),ge=5e5,he=8,fe=2097152,be=7340032,ye=2,ve=6291456,xe=8388608,we=2,je=ve,ke=xe,Te=12582912,$e=12,Se=52428800;function Ce(e){return 4*Math.ceil(e/3)}const Re=Ce(fe),Ee=Ce(be),Ue=Ce(ve),Ae=Ce(xe),Ie=Ce(je),Oe=Ce(ke),Pe=Ce(Te);function Me(e){return e.replace(/\s+/g,"")}function Be(e){const t=Me(e);return 0!==t.length&&t.length%4==0&&/^[A-Za-z0-9+/]+={0,2}$/.test(t)}const qe=/^image\/(png|jpeg|jpg|webp|gif)$/i,De=r.object({mimeType:r.string().min(1).refine(e=>qe.test(e.trim()),{message:"mimeType must be image/png, image/jpeg, image/jpg, image/webp, or image/gif"}),dataBase64:r.string().min(1).max(Re).refine(Be,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Fe=r.enum(["image","document","spreadsheet","tabular"]),_e=De.extend({kind:r.literal("image")}),Ne=r.object({kind:r.literal("document"),mimeType:r.string().min(1).refine(e=>/^application\/pdf$/i.test(e.trim()),{message:"document mimeType must be application/pdf"}),dataBase64:r.string().min(1).max(Ue).refine(Be,{message:"dataBase64 must be standard base64 (RFC 4648)"})}),Ke=r.object({kind:r.literal("spreadsheet"),mimeType:r.string().min(1).refine(e=>/^application\/vnd\.openxmlformats-officedocument\.spreadsheetml\.sheet$/i.test(e.trim()),{message:"spreadsheet mimeType must be application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}),dataBase64:r.string().min(1).max(Ie).refine(Be,{message:"dataBase64 must be standard base64 (RFC 4648)"}),filename:r.string().max(512).optional()}).refine(e=>void 0===e.filename||e.filename.trim().length>0,{message:"spreadsheet filename must not be empty or whitespace-only",path:["filename"]}),Le=r.discriminatedUnion("kind",[_e,Ne,Ke]),ze=r.string().regex(W,"attachmentRefs items must be graphy://attachments/{uuid} URIs"),Ge=r.enum(["pending","ready","failed"]),We=r.object({id:r.string().uuid(),uri:r.string(),status:Ge,kind:Fe.optional(),mimeType:r.string(),filename:r.string().optional(),sizeBytes:r.number().int().nonnegative(),uploadExpiresAt:r.string().datetime().optional(),completedAt:r.string().datetime().optional(),expiresAt:r.string().datetime()}),He=We.extend({status:r.literal("ready"),kind:Fe,sizeBytes:r.number().int().positive()}),Je=r.object({mimeType:r.string().min(1),filename:r.string().max(512).optional(),sizeBytes:r.number().int().positive().max(Se).optional()}),Xe=r.object({files:r.array(Je).min(1).max($e)}),Qe=We.extend({status:r.literal("pending"),uploadUrl:r.string().url()}),Ve=r.object({uploads:r.array(Qe)}),Ye=r.object({sourceText:r.string().max(ge).default(""),images:r.array(De).max(8).optional().describe('@deprecated Use attachments[] with kind: "image" instead. Will be removed in a future major release.'),attachments:r.array(Le).max($e).optional(),attachmentRefs:r.array(ze).max($e).optional(),metadata:N.optional()}).superRefine((e,t)=>{var n,i,o;const r=e.sourceText.trim(),a=null!==(n=e.images)&&void 0!==n?n:[],s=null!==(i=e.attachments)&&void 0!==i?i:[],l=null!==(o=e.attachmentRefs)&&void 0!==o?o:[];if(a.length>0&&s.length>0)return void t.addIssue({code:"custom",message:'Use either `images` (deprecated) or `attachments`, not both. Migrate to `attachments` with `kind: "image"`.',path:["attachments"]});if(0===r.length&&0===a.length&&0===s.length&&0===l.length)return void t.addIssue({code:"custom",message:"Provide non-empty sourceText and/or at least one attachment",path:["sourceText"]});if(a.length+s.length+l.length>$e)return void t.addIssue({code:"custom",message:"Too many attachments (max 12 across inline payloads and attachmentRefs)",path:["attachmentRefs"]});if(l.length>0&&0===s.length&&0===a.length)return;if(a.length>0){a.reduce((e,t)=>e+Me(t.dataBase64).length,0)>Ee&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["images"]})}let c=0,m=0,d=0,u=0,p=0,g=0,h=0;for(const e of s){const t=Me(e.dataBase64).length;switch(h+=t,e.kind){case"image":c+=1,u+=t;break;case"document":m+=1,p+=t;break;case"spreadsheet":d+=1,g+=t}}c>8&&t.addIssue({code:"custom",message:"Too many images (max 8)",path:["attachments"]}),m>2&&t.addIssue({code:"custom",message:"Too many documents (max 2)",path:["attachments"]}),d>2&&t.addIssue({code:"custom",message:"Too many spreadsheets (max 2)",path:["attachments"]});const f=c<=8&&m<=2&&d<=2;s.length>0&&f&&(u>Ee&&t.addIssue({code:"custom",message:"Combined image base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),p>Ae&&t.addIssue({code:"custom",message:"Combined document base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),g>Oe&&t.addIssue({code:"custom",message:"Combined spreadsheet base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}),h>Pe&&t.addIssue({code:"custom",message:"Combined attachment base64 exceeds maximum length for this API (must fit server decode limits)",path:["attachments"]}))});function Ze(e){return{kind:"image",mimeType:e.mimeType.trim(),dataBase64:Me(e.dataBase64)}}function et(e){return{kind:"document",mimeType:"application/pdf",dataBase64:Me(e.dataBase64)}}function tt(e){return Object.assign({kind:"spreadsheet",mimeType:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",dataBase64:Me(e.dataBase64)},void 0!==e.filename?{filename:e.filename.trim()}:{})}const nt=r.object({response:r.object({message:r.string()}),config:I,extractMeta:ue.nullable(),lastAccuracyEvaluation:pe.optional(),run:L.optional()}).extend(E),it=r.object({config:I,response:r.object({message:r.string(),steps:r.array(r.string())}),run:L.optional()}).extend(E),ot=te,rt=r.enum(["deal-breaker","pro","con","family","continuity"]),at=r.object({kind:rt,label:r.string(),weight:r.number(),reason:r.string()}),st=r.enum(["ok","disqualified"]),lt=r.object({rank:r.number().int().positive(),type:V,score:r.number(),verdict:st,factors:r.array(at)}),ct=X,mt=r.enum(["drop-noisy-dimensions","reshape-for-heatmap","unpivot-wide-format","needs-row-reduction","high-null-columns","constant-columns","outlier-heavy-measures","mixed-scale-measures","needs-metric-filter"]),dt=r.object({kind:mt,message:r.string()}),ut=r.enum(["sum","avg","count","min","max"]),pt=r.object({dimensionName:r.string(),dimensionLabel:r.string(),measureName:r.string().nullable(),measureLabel:r.string().nullable(),fn:ut,chartType:V,score:r.number(),message:r.string()}),gt=r.object({ranking:r.array(lt),observations:r.array(dt).optional().default([]),suggestions:r.array(pt).optional().default([]),run:L.optional()}),ht=r.object({prompt:r.string(),datasetSummary:r.string().optional(),mustShow:r.array(r.string()).optional(),unacceptable:r.array(r.string()).optional(),acceptableChartFamilies:r.array(r.string()).optional()}),ft=r.object({config:I.optional(),chartImage:r.string().optional(),data:r.unknown().optional(),rubric:ht.optional(),userPrompt:r.string().optional(),metadata:N.optional()}).refine(e=>void 0!==e.config||void 0!==e.chartImage,{message:"Provide a chart config or a chart image to judge."}),bt=r.enum(["layout","color_contrast","typography","clutter","encoding","labels_legends","title_caption","other"]),yt=r.enum(["info","low","medium","high"]),vt=r.object({category:bt,severity:yt,observation:r.string(),rationale:r.string().optional(),suggestedChange:r.string().optional(),configPaths:r.array(r.string()).optional()}),xt=r.object({overallSummary:r.string(),overallSeverity:r.enum(["none","low","medium","high"]).optional(),issues:r.array(vt)}),wt=r.object({dataFidelity:r.number().min(0).max(1),promptRelevance:r.number().min(0).max(1),chartTypeAppropriateness:r.number().min(0).max(1),readability:r.number().min(0).max(1),honesty:r.number().min(0).max(1),composite:r.number().min(0).max(1),rationale:r.string().optional()}),jt=r.object({capturedAt:r.string(),chartId:r.string()}),kt=r.object({response:r.object({message:r.string(),steps:r.array(r.string()),critiqueCommitted:r.boolean()}),critiqueReport:xt.nullable(),chartVisionAudit:jt.nullable().optional().default(null),rubricScores:wt.nullable().optional().default(null),run:L.optional()}).extend(E),Tt="/api/v0";class $t{constructor(e){this.client=new x(e)}generateGraph(t,n,i){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,r=o(t,["storytellingOptions"]),a=yield this.client.fetch(`${Tt}/generate`,r,n,i),s=it.parse(a);return this.stripStorytelling(s,e)})}generateGraphStream(t,n){return e(this,void 0,void 0,function*(){const{storytellingOptions:e}=t,i=o(t,["storytellingOptions"]),r=yield this.client.stream(`${Tt}/generate`,i,n);return this.wrapStreamWithStorytellingStripping(r,e)})}generateNarrative(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/narrate`,t,n,i);return ee.parse(e)})}generateNarrativeStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/narrate`,t,n)})}generateSuggestions(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/suggestions`,t,n,i);return te.parse(e)})}generateSuggestionsStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/suggestions`,t,n)})}generateExploration(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/explore`,t,n,i);return oe.parse(e)})}generateExplorationStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/explore`,t,n)})}generateAnnotations(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/annotate`,t,n,i);return re.parse(e)})}generateAnnotationsStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/annotate`,t,n)})}generateMutation(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/mutate`,t,n,i);return ae.parse(e)})}generateMutationStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/mutate`,t,n)})}generatePipeline(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/pipeline`,t,n,i);return me.parse(e)})}generatePipelineStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/pipeline`,t,n)})}evaluate(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/evaluate`,t,void 0,n);return gt.parse(e)})}judge(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/judge`,t,void 0,n);return kt.parse(e)})}judgeStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/judge`,t,n)})}extractFromProse(t,n,i){return e(this,void 0,void 0,function*(){const e=yield this.client.fetch(`${Tt}/extract`,t,n,i);return nt.parse(e)})}extractFromProseStream(t,n){return e(this,void 0,void 0,function*(){return this.client.stream(`${Tt}/extract`,t,n)})}uploadAttachment(t,n,i){return e(this,void 0,void 0,function*(){const e=k(t,n),o=j(t,n),{uploads:r}=yield this.createAttachmentUploads({files:[Object.assign(Object.assign({mimeType:e},o?{filename:o}:{}),t.size>0?{sizeBytes:t.size}:{})]},i),s=r[0];if(!s)throw new a("Attachment upload slot was not returned");const l=yield fetch(s.uploadUrl,{method:"PUT",headers:{"Content-Type":e},body:t,signal:i});if(!l.ok)throw new a(`Attachment upload failed (HTTP ${l.status})`,{status:l.status,retryable:l.status>=500});const c=yield this.completeAttachmentUpload(s.id,i);return He.parse(c)})}uploadDataset(t,n,i){return e(this,void 0,void 0,function*(){const e=$(t,n);return this.uploadAttachment(t,Object.assign(Object.assign({},n),{mimeType:e}),i)})}createAttachmentUploads(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${Tt}/attachment-uploads`,t,n);return Ve.parse(e)})}completeAttachmentUpload(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.postJson(`${Tt}/attachments/${t}/complete`,{},n);return We.parse(e)})}getAttachment(t,n){return e(this,void 0,void 0,function*(){const e=yield this.client.get(`${Tt}/attachments/${t}`,n);return We.parse(e)})}stripStorytelling(e,t){return t&&e.config.content?Object.assign(Object.assign({},e),{config:Object.assign(Object.assign({},e.config),{content:Object.assign(Object.assign(Object.assign(Object.assign({},e.config.content),t.excludeTitle&&{title:void 0}),t.excludeSubtitle&&{subtitle:void 0}),t.excludeCaption&&{caption:void 0})})}):e}wrapStreamWithStorytellingStripping(e,o){return n(this,arguments,function*(){var n,r,a,s;try{for(var l,m=!0,d=t(e);!(n=(l=yield i(d.next())).done);m=!0){s=l.value,m=!1;const e=s;if(c(e)){const t=this.stripStorytelling(e.data,o);yield yield i(Object.assign(Object.assign({},e),{data:t}))}else yield yield i(e)}}catch(e){r={error:e}}finally{try{m||n||!(a=d.return)||(yield i(a.call(d)))}finally{if(r)throw r.error}}})}}export{ut as AggregationFunctionSchema,pt as AggregationSuggestionSchema,V as AiChartTypeEnum,We as AttachmentResponseSchema,He as AttachmentUploadResponseSchema,Qe as AttachmentUploadSlotResponseSchema,bt as ChartCritiqueIssueCategorySchema,vt as ChartCritiqueIssueSchema,yt as ChartCritiqueIssueSeveritySchema,xt as ChartCritiqueReportSchema,G as ChartFamilySchema,lt as ChartFitEntrySchema,rt as ChartFitFactorKindSchema,at as ChartFitFactorSchema,st as ChartFitVerdictSchema,ht as ChartJudgeRubricSchema,Xe as CreateAttachmentUploadsParamsSchema,Ve as CreateAttachmentUploadsResponseSchema,mt as DataObservationKindSchema,dt as DataObservationSchema,ct as EvaluateParamsSchema,gt as EvaluateResponseSchema,M as ExecutionModeSchema,ne as ExploreFindingSchema,ie as ExploreStorySchema,pe as ExtractAccuracyEvaluationSchema,Le as ExtractAttachmentInputSchema,Fe as ExtractAttachmentKindSchema,de as ExtractConfidenceSchema,Ye as ExtractFromProseParamsSchema,nt as ExtractFromProseResponseSchema,ue as ExtractMetaSchema,re as GenerateAnnotationsResponseSchema,oe as GenerateExplorationResponseSchema,it as GenerateGraphResponseSchema,ot as GenerateGraphSuggestionsResponseSchema,ae as GenerateMutationResponseSchema,Z as GenerateNarrativeParamsSchema,ee as GenerateNarrativeResponseSchema,ce as GeneratePipelineParamsSchema,me as GeneratePipelineResponseSchema,Q as GenerateSuggestionsParamsSchema,te as GenerateSuggestionsResponseSchema,X as GraphGenerationRequestSchema,$t as GraphyAiSdk,a as GraphyApiError,F as InvocationBudgetSchema,O as InvocationEffortSchema,ft as JudgeParamsSchema,kt as JudgeResponseSchema,D as MAX_BUDGET_COST_USD,q as MAX_BUDGET_TOTAL_TOKENS,B as MAX_BUDGET_WALL_CLOCK_MS,$e as MAX_EXTRACT_ATTACHMENTS,Te as MAX_EXTRACT_ATTACHMENTS_COMBINED_DECODED_BYTES,ye as MAX_EXTRACT_DOCUMENTS,xe as MAX_EXTRACT_DOCUMENTS_TOTAL_DECODED_BYTES,ve as MAX_EXTRACT_DOCUMENT_DECODED_BYTES,he as MAX_EXTRACT_IMAGES,be as MAX_EXTRACT_IMAGES_TOTAL_DECODED_BYTES,fe as MAX_EXTRACT_IMAGE_DECODED_BYTES,we as MAX_EXTRACT_SPREADSHEETS,ke as MAX_EXTRACT_SPREADSHEETS_TOTAL_DECODED_BYTES,je as MAX_EXTRACT_SPREADSHEET_DECODED_BYTES,ge as MAX_SOURCE_TEXT_LENGTH,Se as MAX_STAGED_FILE_BYTES,z as MAX_USER_PROMPT_LENGTH,N as MetadataSchema,K as MutateNarrationReceiptSchema,se as PipelineAgentNameSchema,le as PipelineStageReasoningSchema,wt as RubricScoresSchema,L as RunContextSchema,P as StorytellingEffortSchema,Y as SuggestionSchema,Ze as buildImageAttachment,et as buildPdfAttachment,tt as buildSpreadsheetAttachment,h as isAgentCompleteEvent,c as isCompleteEvent,m as isErrorEvent,s as isGraphyApiError,p as isLlmStepEvent,d as isPreviewEvent,l as isProgressEvent,u as isReasoningEvent,g as isSessionBudgetEvent,f as isToolCallEvent,b as isToolCompleteEvent,y as isToolErrorEvent};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@graphysdk/agents-sdk",
|
|
3
3
|
"author": "Graphy",
|
|
4
|
-
"version": "1.7.0
|
|
4
|
+
"version": "1.7.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
7
7
|
"files": [
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
},
|
|
19
19
|
"dependencies": {
|
|
20
20
|
"zod": "^4.3.6",
|
|
21
|
-
"@graphysdk/core": "1.7.0
|
|
21
|
+
"@graphysdk/core": "1.7.0"
|
|
22
22
|
},
|
|
23
23
|
"devDependencies": {
|
|
24
24
|
"@rollup/plugin-commonjs": "^28.0.6",
|