Examples and recipes

Working examples: calling a tool from your own page with the SDK, and common workflows.

These examples run on a real page. The SDK is documented in API reference; the errors and their codes are listed there too. A working page that uses the SDK is at /sdk/v1/example.html(it turns the text you type into upper case, on your device).

Works with

The examples use the same tool ids and workflow blocks that the site's + Workflow control queues for you in the Workflow hub, so a chain you try in code can be rebuilt on the canvas and exported as an .html file. See Workflows, the Workflow API and the capability catalog.

Where each example runs

  • Browser SDK: your own page calls the SDK, and the work happens in a hidden frame on the visitor's device.
  • window.eeshgarg: the same operations from the console on eeshgarg.com. The runnable examples below use it.
  • Headless: the same code can run in Node without a browser. Examples marked as running in Node were executed that way in the test suite; operations that need a canvas, a worker or ffmpeg are marked browser-only.
  • Command line: CLI and scripting drives the site in a headless browser on your machine.
  • No hosted API: there is no cloud service that accepts files over HTTP. Every example processes files on the device that runs it.

Calling one operation from your page

Add the SDK import and a file input to your page. Your page's CSP must allow the SDK module and the frame (see CORS, CSP, isolation). The example below is the complete call pattern: create a client, run one operation, handle cancel and errors, and dispose the client.

import { createClient, SdkError } from "https://eeshgarg.com/sdk/v1/eeshgarg-sdk.mjs";

const controller = new AbortController(); // controller.abort() cancels the run
let client;
try {
  client = await createClient({ origin: "https://eeshgarg.com", timeoutMs: 60000 });
  // Pick a file, then run one operation on this device.
  const input = document.querySelector("input[type=file]").files[0];
  const { files } = await client.run("feature:text-transform", [input], { op: "upper" }, {
    signal: controller.signal,
    onProgress: ({ done, total, label }) => console.log(label, done, total),
  });
  const url = URL.createObjectURL(new Blob([files[0].bytes], { type: files[0].type }));
  // Use url, for example as the href of an <a download> link, then call URL.revokeObjectURL(url) when done.
} catch (e) {
  if (e instanceof SdkError && e.code === "aborted") console.log("cancelled");
  else if (e instanceof SdkError) console.log(e.code, e.message);
  else throw e;
} finally {
  client?.dispose();
}

Discover what is available with client.listCapabilities(), and check one operation's options with client.describe("feature:text-transform"). Options that the tool does not take are rejected with bad_options, not ignored.

Recipe: rotate PDFs, convert images to WebP, zip the results

This workflow takes PDFs and images, rotates the PDFs a quarter turn, converts the images to WebP, and puts all results in one archive.zip. Run it with client.runWorkflow(definition, files), or import it on the site's Workflow board. Source: docs/examples/pdfs-and-images.workflow.json.

{
  "version": 2,
  "name": "Rotate PDFs, convert images to WebP, zip everything",
  "nodes": [
    {
      "id": "pdfs",
      "type": "input",
      "x": 0,
      "y": 0,
      "config": {
        "type": "pdf"
      }
    },
    {
      "id": "images",
      "type": "input",
      "x": 0,
      "y": 200,
      "config": {
        "type": "image"
      }
    },
    {
      "id": "rotate",
      "type": "task",
      "x": 260,
      "y": 0,
      "config": {
        "tool": "rotate",
        "options": {
          "angle": 90
        }
      }
    },
    {
      "id": "webp",
      "type": "task",
      "x": 260,
      "y": 200,
      "config": {
        "tool": "feature:convert",
        "options": {
          "to": "webp",
          "quality": 0.85
        }
      }
    },
    {
      "id": "zip",
      "type": "task",
      "x": 540,
      "y": 100,
      "config": {
        "tool": "feature:zip-create",
        "options": {
          "level": 6
        }
      }
    },
    {
      "id": "out",
      "type": "output",
      "x": 800,
      "y": 100,
      "config": {}
    }
  ],
  "edges": [
    {
      "from": "pdfs",
      "fromPort": "out",
      "to": "rotate",
      "toPort": "in"
    },
    {
      "from": "images",
      "fromPort": "out",
      "to": "webp",
      "toPort": "in"
    },
    {
      "from": "rotate",
      "fromPort": "out",
      "to": "zip",
      "toPort": "in"
    },
    {
      "from": "webp",
      "fromPort": "out",
      "to": "zip",
      "toPort": "in"
    },
    {
      "from": "zip",
      "fromPort": "out",
      "to": "out",
      "toPort": "in"
    }
  ]
}

Recipe: clean up a list of lines

This workflow removes the final newline, removes duplicate lines, sorts the lines, and converts them to upper case. The first step is needed: sort-lines on text that ends with a newline moves the empty last line to the top. Run it with client.runWorkflow(definition, files). Source: docs/examples/text-cleanup.workflow.json.

{
  "version": 2,
  "name": "Clean up a text list: dedupe, sort, upper case",
  "nodes": [
    {
      "id": "text",
      "type": "input",
      "x": 0,
      "y": 0,
      "config": {
        "type": "text"
      }
    },
    {
      "id": "trim",
      "type": "task",
      "x": 260,
      "y": 0,
      "config": {
        "tool": "feature:text-transform",
        "options": {
          "op": "find-replace",
          "find": "\\n+$",
          "replace": "",
          "regex": true
        }
      }
    },
    {
      "id": "dedupe",
      "type": "task",
      "x": 520,
      "y": 0,
      "config": {
        "tool": "feature:text-transform",
        "options": {
          "op": "dedupe-lines"
        }
      }
    },
    {
      "id": "sort",
      "type": "task",
      "x": 780,
      "y": 0,
      "config": {
        "tool": "feature:text-transform",
        "options": {
          "op": "sort-lines"
        }
      }
    },
    {
      "id": "upper",
      "type": "task",
      "x": 1040,
      "y": 0,
      "config": {
        "tool": "feature:text-transform",
        "options": {
          "op": "upper"
        }
      }
    },
    {
      "id": "out",
      "type": "output",
      "x": 1300,
      "y": 0,
      "config": {}
    }
  ],
  "edges": [
    {
      "from": "text",
      "fromPort": "out",
      "to": "trim",
      "toPort": "in"
    },
    {
      "from": "trim",
      "fromPort": "out",
      "to": "dedupe",
      "toPort": "in"
    },
    {
      "from": "dedupe",
      "fromPort": "out",
      "to": "sort",
      "toPort": "in"
    },
    {
      "from": "sort",
      "fromPort": "out",
      "to": "upper",
      "toPort": "in"
    },
    {
      "from": "upper",
      "fromPort": "out",
      "to": "out",
      "toPort": "in"
    }
  ]
}

onNode reports each block's status while the workflow runs. How a failed step affects the blocks after it is in Workflow semantics.

Runnable examples

Each snippet calls eeshgarg.runTool or eeshgarg.runWorkflow, the methods of window.eeshgarg. Every result has files (File objects), summary and warnings. Examples that run in Node are executed by the test suite against small fixture files. The browser-only ones are checked for tool ids and option names but need a real browser to run. Options a tool does not take are rejected, not ignored.

Merge, split and convert PDFs

Runs in the browser and in Node. Inputs: pdfA and pdfB: two PDF files.

const merged = await eeshgarg.runTool("merge", [pdfA, pdfB]);
const parts = await eeshgarg.runTool("split", merged.files, { mode: "every", every: 1 });
const text = await eeshgarg.runTool("pdf-to-text", [pdfA]);
console.log(merged.files[0].name, parts.files.map((f) => f.name), text.files[0].name);

Batch: the same tool on many files

Runs in the browser and in Node. Inputs: pdfA and pdfB: PDF files.

const names = [];
for (const file of [pdfA, pdfB]) {
  const { files } = await eeshgarg.runTool("rotate", [file], { angle: 90 });
  names.push(files[0].name);
}
console.log(names);

Document processing: text to HTML

Runs in the browser and in Node. Inputs: none (the file is made in the snippet).

const notes = new File(["Meeting notes\nShip on Friday"], "notes.txt", { type: "text/plain" });
const { files } = await eeshgarg.runTool("feature:document", [notes], { to: "html" });
console.log(files[0].name, (await files[0].text()).includes("Ship on Friday"));

Data import and convert: CSV to JSON, sort, query

Runs in the browser and in Node. Inputs: csv: a CSV file with a name,age header.

const json = await eeshgarg.runTool("feature:convert", [csv], { to: "json" });
console.log(json.files[0].name, JSON.parse(await json.files[0].text()));

const sorted = await eeshgarg.runTool("feature:data-table", [csv], { op: "sort", columns: "age", descending: true });
console.log(await sorted.files[0].text());

const older = await eeshgarg.runTool("feature:data-query", [csv], { expression: "[?age > `40`]", to: "json" });
console.log(await older.files[0].text());

Archives: create, list and extract a ZIP

Runs in the browser and in Node. Inputs: csv: any file.

const zip = await eeshgarg.runTool("feature:zip-create", [csv]);
const extracted = await eeshgarg.runTool("feature:zip-extract", zip.files);
// The names of the extracted files are the archive's entries.
console.log(zip.files[0].name, extracted.files.map((f) => f.name));

Run an existing workflow

Runs in the browser and in Node. Inputs: recipe: the text-cleanup workflow below.

const lines = new File(["pear\napple\npear\n"], "fruit.txt", { type: "text/plain" });
const result = await eeshgarg.runWorkflow(recipe, [lines]);
console.log(result.status, await result.outputs[0].files[0].text());

A multi-step pipeline: convert, checksum, archive

Runs in the browser and in Node. Inputs: csv: a CSV file.

// Each result is a list of File objects, so it can be the next step's input.
const json = await eeshgarg.runTool("feature:convert", [csv], { to: "json" });
const sum = await eeshgarg.runTool("feature:hash", json.files, { algorithm: "sha256" });
const bundle = await eeshgarg.runTool("feature:zip-create", [...json.files, ...sum.files]);
const back = await eeshgarg.runTool("feature:zip-extract", bundle.files);
console.log(bundle.files[0].name, back.files.map((f) => f.name));

OCR a scanned PDF

Browser-only: needs a canvas, a worker or ffmpeg. Inputs: scan: a scanned PDF you picked on the page.

// Browser-only: OCR renders pages on a canvas and runs a recognition engine in a worker.
const { files, summary, warnings } = await eeshgarg.runTool("ocr", [scan], { dpi: 300, onlyMissing: true });
console.log(summary, warnings); // files: the searchable PDF, plus any extra outputs you turn on

Convert images and PDF pages

Browser-only: needs a canvas, a worker or ffmpeg. Inputs: photo: an image file; pdfA: a PDF file.

// Browser-only: these draw on a canvas.
const webp = await eeshgarg.runTool("image-convert", [photo], { format: "webp", quality: 0.8 });
const pngs = await eeshgarg.runTool("pdf-to-images", [pdfA], { format: "png", dpi: 150 });
console.log(webp.summary, pngs.summary);

Media conversion

Browser-only: needs a canvas, a worker or ffmpeg. Inputs: clip: an audio or video file.

// Browser-only: audio and video conversion runs ffmpeg compiled to WebAssembly, in a worker.
const { files } = await eeshgarg.runTool("feature:convert", [clip], { to: "mp3" });
console.log(files.length);

For the command line, see CLI and scripting. To run these from a page of your own, wrap the same calls with the SDK shown at the top of this page.