@dynjandi/sdk
v0.2.1
Published
TypeScript SDK for Dynjandi, an image CDN.
Readme
@dynjandi/sdk
TypeScript SDK for Dynjandi, an image CDN: upload an image, read a stored file's record, and build the URL of any variant of it.
Install
npm i @dynjandi/sdkReleases are published by
publish.yml with
npm provenance. ESM only.
Requirements
Node 22 or newer (engines.node) is the only runtime the tests run on. The SDK uses fetch, FormData and Blob and
nothing else, so it is intended to work in browsers and Workers too, but nothing here tests either: treat
that as untested.
Usage
import { createClient } from "@dynjandi/sdk";
const client = createClient({ projectKey: "YOUR_PROJECT_KEY" });The project key is a credential that authorises uploads and file reads for one project. Keep it on your
server and out of web pages and apps. It is sent only in the X-Project-Key header.
Migrating from publicKey
Earlier versions took createClient({ publicKey }). That option still works, but it is deprecated: it is
sent as X-Project-Key exactly like projectKey. Rename it to projectKey. Passing both options, neither,
or an empty key throws a DynjandiError with status 0.
ClientOptions is now a union of the two key options, which changes how it composes. An
interface X extends ClientOptions no longer compiles: write type X = ClientOptions & { … }. Omit and
Pick are not distributive over a union, so Omit<ClientOptions, "fetch"> loses which key is required and
the result no longer passes to createClient. Use a distributive form:
type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;
const make = (options: DistributiveOmit<ClientOptions, "fetch">) => createClient({ ...options, fetch });origin defaults to https://cdn.dynjandi.dev. Pass origin to use another one, such as the local development
server of @dynjandi/cli (dynjandi dev, not yet on npm). Run as
dynjandi dev -- <command>, it sets DYNJANDI_ORIGIN and DYNJANDI_PROJECT_KEY for the command:
const local = createClient({
projectKey: process.env.DYNJANDI_PROJECT_KEY ?? "dynjandi-local",
origin: process.env.DYNJANDI_ORIGIN ?? "http://127.0.0.1:4600",
});Started on its own, dynjandi dev listens on port 4600 and accepts the key dynjandi-local, which the
fallbacks above match.
apiOrigin defaults to origin. It is where upload and getFile send their requests, and the project
key, while every URL the SDK hands out (upload's url, url(), srcset, pictureSources,
placeholder) stays on origin. Set both when your server reaches the service under another name than
your users' browsers do, as an app in a container does with dynjandi dev on the host: origin is what
browsers load images from, apiOrigin is what the container calls. A server-side fetch of an image URL
(Next.js's default image optimiser, say) uses origin, so from inside the container it needs origin to
resolve there too. Setting apiOrigin without origin leaves the URLs on https://cdn.dynjandi.dev. Both
must be absolute http:// or https:// URLs: anything else, host.docker.internal:4600 without its scheme
included, throws a DynjandiError (status 0) from createClient.
const client = createClient({
projectKey: process.env.DYNJANDI_PROJECT_KEY ?? "dynjandi-local",
origin: process.env.DYNJANDI_ORIGIN, // browsers: http://127.0.0.1:<port>
apiOrigin: process.env.DYNJANDI_API_ORIGIN, // the container: http://host.docker.internal:<port>
});How to get the container's origin is in the CLI's From an app in a container.
upload(file, { focal? })
Uploads a Blob or File and resolves with { file, id, url, focalX, focalY }. url is absolute, on the
client's origin (not apiOrigin), the one browsers load images from. focal is { x, y }, each from 0 to 1, and both are sent together.
const { id, url } = await client.upload(file, { focal: { x: 0.42, y: 0.18 } });Uploads are server-side only. The CDN sends no CORS headers, so a browser cannot POST /upload
cross-origin. Call upload from Node or a server.
To get a focal point from a person looking at the image, see the focal point picker
(packages/focal-picker; it is in this repository and not yet on npm).
getFile(fileId)
Reads the stored record of a file and resolves with { id, contentType, bytes, originalFilename, source,
focalX, focalY, createdAt }. focalX and focalY are the stored focal point, both numbers from 0 to 1 or
both null; originalFilename is null when the upload had none.
const file = await client.getFile(id);
console.log(file.contentType, file.focalX, file.focalY);Reads are server-side only. The CDN sends no CORS headers, so a browser cannot read the response
cross-origin. Call getFile from Node or a server.
The response is Cache-Control: no-store and the SDK does not cache it. Fetch a record once and keep it;
do not call getFile per rendered image. (upload's result already carries the point it was uploaded
with.) An id the project does not have, an id that is not a UUID, and a file in another project are all
404 File not found. getFile throws a DynjandiError for a non-2xx answer (401 missing or invalid key,
404), a network failure (status 0), a 2xx body that is not a file record (status of the response), and an
empty id or ./.. (status 0, before any request). The id is percent-encoded into the path, so it
cannot change the route.
url(file, options)
Builds the URL of a variant. file is a file id, or a stored file: the result of getFile or upload.
It is synchronous, makes no request, and is safe in browsers. At least one option is required (the
original is served at the url that upload returns).
client.url(id, { width: 800, height: 600, format: "webp", quality: 80 });
client.url(id, { crop: { width: 1280, height: 400, focal: { x: 0.42, y: 0.18 } } });
client.url(id, { crop: { width: 400, height: 400, position: "face,attention" }, format: "avif" });
// With a stored file, a crop crops on the file's stored focal point.
const file = await client.getFile(id); // or the result of client.upload(...)
client.url(file, { crop: { width: 1280, height: 400 } }); // .../-/crop/1280x400/focal/0.42x0.18/A string id behaves exactly as above. A stored file is anything with id, focalX and focalY (the
StoredFile type), so a getFile result and an upload result both work as they are, with no cast.
upload already returns the point it stored, so a caller who keeps that result needs no getFile call;
a point changed later (in the dashboard, say) is only seen by a fresh getFile. For a crop with a stored
file:
- a crop that names neither
positionnorfocaluses the stored point; - an explicit
focalorpositionalways wins over the stored point; - a file with no stored point (
focalXandfocalYbothnull) crops oncenter, as a string id does.
The URL grammar itself comes from @dynjandi/transform-grammar (its ./builder entry); the SDK maps these
options onto it and never writes the grammar itself. Ranges (dimensions 1 to 10000, quality 1 to 100) are the
grammar's, and url() refuses what it would not accept.
srcset(file, options?)
Builds the value of an srcset attribute: one <url> <width>w candidate per width, smallest first. Every URL
comes from url(), so format, quality and crop pass through unchanged, and file is what url()
takes: a file id, or a stored file whose focal point a crop then uses. Like url(), it is synchronous,
makes no request, and is safe in browsers. So are pictureSources and placeholder, which take file the
same way.
import { DEFAULT_WIDTHS } from "@dynjandi/sdk";
client.srcset(id); // widths: DEFAULT_WIDTHS, [320, 640, 960, 1280, 1920]
client.srcset(id, { widths: [320, 640], format: "webp", quality: 75 });
client.srcset(id, { crop: { width: 1600, height: 900 } }); // a fixed 16:9 at every width<img src="..." srcset="<the string srcset returned>" sizes="(min-width: 800px) 800px, 100vw" alt="..." />Put alt and sizes on the <img> yourself; srcset returns the attribute value only.
options is url()'s without width and height, plus widths. A height is refused, because a fixed
height at several widths distorts the image; pass crop for a fixed aspect ratio, which resizes after it.
widths must be distinct integers from 1 to 10000, and an empty, repeated or non-integer list is refused with
a DynjandiError (status 0) before any URL is built.
A file id containing a comma, space or / cannot add a candidate: the grammar package percent-encodes it.
pictureSources(file, options?)
Builds the attributes of one <source> per format: { type, srcset, sizes? }[], in the order you give,
best format first, because the browser takes the first one it supports. formats defaults to
DEFAULT_FORMATS, ["avif", "webp"]. Each srcset is what srcset() returns for that format, so
widths, quality and crop apply to all of them. type is image/<format>; jpg is accepted as an
alias and gives image/jpeg. Like srcset(), it is synchronous, makes no request, and is safe in browsers.
It returns data, not markup, so you render it in whatever your framework calls its attributes (srcSet
in React, for one). There is no format/auto, so the fallback is not a source: it is the plain <img>,
with srcset({ format: "jpeg" }), and it must come after every <source>: a source after the <img> is
ignored.
const sizes = "(min-width: 800px) 800px, 100vw";
const sources = client.pictureSources(id, { sizes });
const fallback = client.srcset(id, { format: "jpeg" });<picture>
<source type="image/avif" srcset="<sources[0].srcset>" sizes="<sources[0].sizes>" />
<source type="image/webp" srcset="<sources[1].srcset>" sizes="<sources[1].sizes>" />
<img src="<one candidate's url>" srcset="<fallback>" sizes="(min-width: 800px) 800px, 100vw" alt="..." />
</picture>Put alt on the <img>, and sizes on it too: the <img>'s own sizes applies to its srcset, not the
sources'. sizes is passed through exactly as you give it. It is not escaped, so if it reaches markup,
escaping it is your job; the same holds for every other string you place in an attribute.
An empty formats, or one that repeats a format (jpeg and jpg are the same format), is refused with a
DynjandiError (status 0) naming formats, before any URL is built. A format option is refused too;
use formats. Everything srcset() refuses is refused here.
What it costs. Every width x format x crop is a separate variant, and each new variant counts against your project's plan cap. Variants per image = widths x formats:
| Call | Variants per image |
|---|---|
| srcset(id) with the default ladder, one format | 5 x 1 = 5 |
| srcset(id, { widths: [640, 1280] }) | 2 x 1 = 2 |
| pictureSources(id) with the defaults, avif and webp | 5 x 2 = 10 |
| the same, plus the jpeg fallback <img> | 5 x 3 = 15 |
| pictureSources(id, { widths: [640, 1280] }) plus a fallback with the same widths | 2 x 3 = 6 |
A smaller widths or formats is how you spend less. placeholder() adds one more variant per image to
any of these.
placeholder(file, options?)
Builds the URL of a small, low-quality stand-in for the image: width 24, quality 20 and format
webp, each unless you pass your own. Show it while the real image loads. Like url(), it is synchronous,
makes no request, and is safe in browsers.
client.placeholder(id); // .../-/resize/24x/-/format/webp/-/quality/20/
client.placeholder(id, { width: 32, crop: { width: 1600, height: 900 } });This is a small, low-quality image, not a blur: the grammar has no blur operation. Pass the same crop as the image it stands in for,
so it has the same aspect ratio. options is url()'s without height, which is refused with a
DynjandiError (status 0). It is one more variant per image, and counts against your project's plan cap
like any other (the table above does not include it).
Upscaling. The service upscales (observed 2026-10-04): a resize wider than the original is served at
the requested width (the live smoke test asks for 320w of a 1x1 image and gets 320px back). The SDK does
not know the original's width, because the upload response carries no dimensions, so trim widths to no
wider than the original. A wider candidate is a soft image that still costs a variant.
Using with Next.js
@dynjandi/sdk/next is a loader for next/image. It needs no next import and adds no peer dependency.
Point images.loaderFile at a file in your app that re-exports it:
// next.config.mjs
export default { images: { loader: "custom", loaderFile: "./dynjandi-loader.js" } };// dynjandi-loader.js
export { dynjandiLoader as default } from "@dynjandi/sdk/next";Tested with next.config.mjs in an app whose package.json has "type": "module"; a .js config was
not tested.
<Image src={fileId} width={800} height={600} alt="" />src is a Dynjandi file id, not a URL. An empty id, or one url() refuses, throws a DynjandiError
(status 0).
Each width Next asks for becomes one variant, resize/<width>x/, built by url(). Nothing else is added
unless you ask:
- Format. The loader sets none, and the service did not negotiate one from
Acceptwhen this was tested, so the original format is served. Passformatto the factory to encode every variant as one. - Quality. Next passes a quality only when you set
<Image quality={...}>, and only then does aquality/<q>/operation appear. A value outside 1 to 100 is refused.
For another origin, or a format, build the loader with the factory:
// dynjandi-loader.js
import { createDynjandiLoader } from "@dynjandi/sdk/next";
export default createDynjandiLoader({ origin: "https://cdn.example.com", format: "webp" });origin defaults to https://cdn.dynjandi.dev; a bad one throws when the loader is created, not on every
render. The loader takes no crop and no focal point; for a fixed aspect ratio, use fill or CSS on the
original's ratio.
What it costs. Every width Next requests is a separate variant that counts against your project's plan
cap. images.deviceSizes and images.imageSizes in next.config decide which widths Next picks, so they
decide how many variants an image costs. A fixed width={800} requested two (828w and 1920w).
An image with fill or sizes is offered up to every width in those lists rather than two, so trim both
lists to spend less.
Verified on Next.js 16.4.2, with next build and next start under both Turbopack (the default) and
webpack. A bare file id as src built and rendered under each, and the widths it requested answered 200.
next dev was not run.
Using Dynjandi from a coding agent
packages/agent-skills holds
agent skills that teach a coding agent to use this SDK and Dynjandi's other tools. They install from the GitHub repository, per
vendor: see the install guide.
Errors
Every failure is a DynjandiError with status, message and, where there is one, cause.
import { DynjandiError } from "@dynjandi/sdk";
try {
await client.upload(file);
} catch (error) {
if (error instanceof DynjandiError) {
console.error(error.status, error.message);
}
}status is the HTTP status of the response that caused the failure (401 invalid key, 400 bad request,
404 file not found, 413 over the size limit or quota). It is 0 when there was no HTTP response: the
network request failed, or the SDK refused the call before sending anything (bad focal point, bad
options, an empty or dot-segment file id). The project key is never
part of a message.
Bundle size
The browser bundle of src/index.ts, with @dynjandi/transform-grammar included, is 3,674 bytes gzipped
(10,479 bytes minified) as of 2026-11-12, with @dynjandi/transform-grammar 0.2.0. Measured from this
directory:
pnpm exec esbuild --bundle --minify --platform=browser --format=esm src/index.ts | gzip -9 -c | wc -cThe SDK's own code is 2,575 bytes gzipped (6,706 bytes minified); add
--external:@dynjandi/transform-grammar to the command to see it. The rest is the grammar package's code.
The SDK imports its zod-free ./builder entry, so zod is not in a browser bundle;
tests/bundle.test.ts bundles src/index.ts and src/next.ts the same way and fails if it ever is. The byte figure is a
baseline to compare later changes against, not a budget.
Live smoke test
tests/live/smoke.test.ts uploads a 1x1 PNG with a focal point of (0.5, 0.5) to a dedicated test project
and fetches a url() variant of it (image/*). It then reads the file back with getFile, checks the id
and the point, builds a cropped URL from that record (which must end in focal/0.5x0.5/) and fetches it.
It does not cover a later change of the point, for example in the dashboard: there is no public write
endpoint, so the point can only be set at upload. It then fetches the responsive helpers' output and
expects 200: a srcset candidate (image/*, a PNG body), an avif source from pictureSources
(content type image/avif or image/heif, as the service mislabels AVIF; the body must have an AVIF
ftyp box) and the placeholder (image/*). It also prints the width the service returns for a 320w
resize of the 1x1 original, which shows whether it upscales. It needs the project's key in
DYNJANDI_SMOKE_PROJECT_KEY and the network, so pnpm test skips it. It fails if the key is unset.
pnpm --filter @dynjandi/sdk run test:liveSee context/verify.md for loading the key locally without printing it.
.github/workflows/smoke.yml runs it daily and on demand.
