8000 fix(plugin-print): clear loadFont errors instead of fetch failures by hipstersmoothie · Pull Request #1475 · jimp-dev/jimp · GitHub
[go: up one dir, main page]

Skip to content

fix(plugin-print): clear loadFont errors instead of fetch failures - #1475

Merged
hipstersmoothie merged 1 commit into
mainfrom
sesh/loadfont-errors-without-fetch-1339
Nov 23, 2026
Merged

hipstersmoothie merged 1 commit into
mainfrom
sesh/loadfont-errors-without-fetch-1339

Conversation

@hipstersmoothie
Copy link
Copy Markdown
Collaborator

Fixes #1339

The problem

In Node, loadFont reads the argument from disk if it exists. Otherwise it passes the string to fetch. So these calls all ended in a fetch error:

Call Before (Node with fetch) Before (no global fetch, e.g. Raycast)
loadFont(await fs.readFile(fnt, "utf-8")) (the report) TypeError: Failed to parse URL from <font>… followed by the entire file ReferenceError: fetch is not defined
loadFont("fonts/typo.fnt") TypeError: Failed to parse URL from fonts/typo.fnt ReferenceError: fetch is not defined
loadFont("https://…/font.fnt") works ReferenceError: fetch is not defined
loadFont(SANS_16_BLACK) / a real path works works

The reporter passed the file's contents rather than its path. Their runtime also doesn't provide fetch.

The fix

In the Node build only (typeof window === "undefined" && !isWebWorker, the same check as before), when the string isn't an existing file:

  • Contents passed instead of a path (contains a newline, or starts with <, {, BMF or a BMFont tag like info face=):
    loadFont expects a path or URL to a font file, but received the contents of one: "<font>\n <info face=…". Pass the path to the .fnt file instead, its .png pages are loaded from the same directory.
  • Not a file and not an http:/https:/data:/blob: URL:
    loadFont: font file not found: "fonts/typo.fnt". Pass a path to a .fnt file, a URL, or a SANS_* constant from jimp/fonts.
  • file: URLs are converted to paths and read from disk. Node's fetch can't load them, so they never worked before.

Other changes:

  • No global fetch: loadBitmapFontData checks typeof globalThis.fetch before fetching a URL. Without it: loadFont: can't load "https://…" because this runtime has no global fetch. Pass a path to the .fnt file instead (it and its pages are read from disk), or install a fetch polyfill.
  • Pages: when a font comes from disk, its .png pages were already read from disk (Jimp.read checks existsSync first). If a page was missing, though, Jimp.read fell back to fetch. A missing page now throws loadFont: font page not found: "<path>", so loading from a path never uses fetch.

Browser builds: unchanged. In the browser bundle window (or a worker's self) is defined, so the Node branch is skipped and every font is fetched as before, including relative URLs like /fonts/x.fnt. The only new code on that path is the fetch existence check, which browsers always pass.

Loading from in-memory contents: not added

I decided against it. A .fnt file is only an index: its glyphs are in separate .png pages, which are found relative to the font's location. Given only the contents, loadFont would have no directory to resolve page id=0 file="…" against. Supporting it would need a new API that takes the font data plus a page buffer for each page (or a base path). That's a bigger design question than this bug. The reporter's case already works if they pass the path they were reading (path.join(environment.assetsPath, "fonts/open-sans-16-black.fnt")), and that never needs fetch. The new error points them there.

Tests

Added to plugins/plugin-print/src/index.node.test.ts:

  • Contents string (XML bundled font, ASCII multi-line, a single ASCII line, <?xml), with and without fetch, gives the contents error.
  • Missing file, with and without fetch, gives the not-found error.
  • A font whose page is missing gives the page-not-found error.
  • With fetch deleted from globalThis, loading SANS_16_BLACK by path and SANS_8_BLACK by file: URL works, pages included.
  • A URL with fetch deleted gives the no-fetch error.

pnpm build, pnpm lint and pnpm test pass, and so do the jimp browser tests (pnpm test:browser). I also re-ran the repro above against the built jimp package: every row now gives the matching error, and path loads still work without fetch.

JSDoc for loadFont (which generates the API docs) and the plugin-print README explain that it takes a path rather than contents, and when fetch is used.

🤖 Generated with Claude Code

…1339)

In Node, loadFont fell through to fetch for any string that wasn't an
existing file. Passing a font's contents or a mistyped path produced
"Failed to parse URL from <whole file>", or "fetch is not defined" in
runtimes without a global fetch (like Raycast).

- Contents of a font (newlines, or starting with <, {, BMF or a BMFont
  tag): say a path is expected, not the contents.
- Anything else that isn't a file or an http(s)/data/blob URL: "font
  file not found".
- file: URLs are read from disk, since Node's fetch can't load them.
- A page missing next to a font on disk: "font page not found", instead
  of Jimp.read falling back to fetch.
- A URL with no global fetch: say the runtime has no fetch and to pass
  a path instead.

Fonts loaded from a path, pages included, never use fetch. Browser
builds are unchanged and always fetch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@hipstersmoothie
hipstersmoothie merged commit df981b7 into main Nov 23, 2026
5 checks passed
@hipstersmoothie
hipstersmoothie deleted the sesh/loadfont-errors-without-fetch-1339 branch November 23, 2026 07:20
hipstersmoothie added a commit that referenced this pull request Nov 24, 2026
* docs: Kid Studio redesign with full method reference and playgrounds (WIP)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: register sharpen, toColorSpace, otsuThreshold and the Color Spaces guide

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: register skew, affine, exposure, vibrance and the Migrate to v2 guide

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: update effects and compositing pages for 2.0

Add the sharpen page and playground op. Document dither's type and
palette options, convolute/convolution divisor, bias, preserveAlpha
and even-sized kernels, blur/gaussian radius changes, region clamping
in pixelate, convolute and blit, composite across Jimp classes with
clamped opacity and the new blend-mode error, mask luminance and alpha,
centered shadow size, and invalid boxShadow colors. Remove the cautions
for bugs fixed in 2.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: replace obsolete gotchas in WRITING.md with version-note guidance

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: update size, shape and transform pages for 2.0; add skew and affine

- New skew and affine method pages with playgrounds (#1515)
- resize/scale/scaleToFit: LANCZOS, LANCZOS2, MITCHELL (#1481),
  premultiplyAlpha (#1502), default resizer premultiplies (#1499),
  rounding fix
- cover/contain: { x, y } fractional align (#1513), missing axis centered
  and stricter flag validation (#1499), premultiplyAlpha
- crop: clamps to the image and throws for empty regions (#1501, #1511)
- autocrop/autocropRect: ignoreSides/leaveBorder with cropOnlyFrames,
  transparent pixels match (#1499)
- rotate: centered rotation and new canvas size (#1490), ResizeStrategy
  modes interpolate (#1508)
- circle radius 0, border invalid colors throw, displace alpha/stretched
  map and offset { x, y } (#1499, #1497, #1514)
- Playground: rotate interpolation modes, fractional align for
  cover/contain, displace y offset, new skew and affine ops

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: update color, pixel and constants pages for 2.0

- color(): multiply action, CSS colors in mix/multiply/xor, greyscale action
  matching greyscale(), ColorActionName exported, changed saturate/lighten maths
- new pages: exposure(), vibrance(), otsuThreshold()
- sepia(amount), threshold max "otsu" and per-channel autoGreyscale:false,
  contrast around 127.5, posterize nearest level, normalize flat channels,
  greyscale rounding, quantize colors validation
- pixels: setPixelColor ignores off-image points, NaN throws, Edge.WRAP any
  distance, Edge as a runtime export, scan/scanIterator region clamping
- concepts: color spaces section, Edge and ColorActionName, new
  ResizeStrategy members, JimpMime.ico, align rules, exported type names
- playground: exposure, vibrance and otsuThreshold ops, multiply action,
  sepia amount, threshold otsu toggle, getPixelIndex uses Edge

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: update text, comparison and errors pages for 2.0

- print: box layout from x/y, alignment without maxWidth/maxHeight,
  whole-word wrapping, kept blank lines, cb position (#1498, #1505)
- loadFont: HTTP/fetch errors, non-PNG page errors, bundled font coverage
  (#1475, #1498, #1509)
- measureText/measureTextHeight: widest line, optional maxWidth, empty lines
- hash/pHash/distance/distanceFromHash: options added in 2.0, hashes
  differ from 1.x (#1466, #1472)
- compareHashes: base argument, decodes hash() output (#1499)
- diff: options object, DiffColor, dark diff example (#1510)
- errors-and-validation: re-verified every message; colors, regions,
  ENOENT, ICO/BMP/SVG errors (#1497, #1501, #1503, #1506, #1518, #1522)
- playground: alignment without a box, blank-line preset, diffMask,
  diffColor and alpha controls

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: update loading, saving, formats and color space pages for 2.0

- read/fromBuffer: Uint8Array/Blob input, ENOENT for missing files,
  exifRotate and ReadOptions
- fromBitmap/new Jimp: data is copied and length-checked, colorSpace,
  invalid colors throw
- getBuffer/write: icc option, BMP bitPP, ICO, per-extension option
  typing; remove dead BMP/PNG options; PNG bitDepth 16 is broken
- clone copies mime, background and ICC profile
- New toColorSpace page; cssColorToHex throws and takes color()
- Formats: ICO, JPEG 2000, SVG, strict WASM options, community
  plugins (jimp-heic)
- Guides: Color Spaces restyle, exifRotate, JPEG 2000 and SVG sections
  with bundler notes, corrected JPEG memory limits, browser fonts path
  and fromBitmap copying, ICO in defaults, Node 22
- Playground encode op gains ICO; webp-example casts around the
  wasm-webp declaration bug

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: write the Migrate to v2 guide and update guides and home for 2.0

- guides/migrate-to-v2: every breaking change merged for 2.0 (Node 22,
  errors that now throw, behavior changes, removed options, types), with
  before/after code checked against 1.7.0 and the 2.0 build, plus a
  "New in 2.0" section linking the new methods, options and formats
- guides/migrate-to-v1: point to the v2 guide; note Edge is a runtime
  export only since 2.0 and that opaque PNGs drop alpha automatically
- guides/getting-started: Node.js 22, Jimp.read path vs URL rules and
  input types, ENOENT for missing files, new WASM formats
- guides/writing-plugins: the format detect() hook, color spaces in
  plugins (CSS colors, keeping iccProfile on new canvases), 2.0 versions
- home and methods index: sharpen and roundCorners in the playground,
  ICO and the new WASM formats in the feature copy, 2.0 methods in the
  section intros

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: flag stored-hash incompatibility and add #1357 and morphology to the v2 guide

- Caution near the top: pHash/hash values differ for every image in 2.0,
  so 1.x hashes can't be compared with 2.0 hashes; re-hash stored images
- Hashes section explains the degenerate 1.x hashes and cross-version
  compareHashes/distanceFromHash
- Jimp.read now passes decode options for file paths and buffers (#1357)
- New in 2.0: erode, dilate, open and close (#1523)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs: add erode, dilate, open and close method pages

Document @jimp/plugin-morphology (#1523): four method pages with
scanned-document cleanup, mask, outline and ink examples, playground
ops with radius and shape controls, and method entries under Blur &
effects. Link the new pages from the v2 migration guide, threshold and
dither.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@hipstersmoothie
Copy link
Copy Markdown
Collaborator Author

🚀 PR was released in v2.0.0 🚀

@hipstersmoothie hipstersmoothie added the released This issue/pull request has been released. label Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

released This issue/pull request has been released.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Use fetch to load fonts in load Font, but it fails in the node environment

1 participant

0