@nexterm/canvas 0.0.0-stage → 1.2.1

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.
@@ -0,0 +1,249 @@
1
+ /**
2
+ * node-canvas compatibility layer for @napi-rs/canvas.
3
+ *
4
+ * Provides a drop-in replacement API matching the `canvas` (node-canvas) npm package.
5
+ * Quality values for JPEG/WebP use the node-canvas 0-1 scale and are automatically
6
+ * converted to @napi-rs/canvas's 0-100 scale internally.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * // Drop-in replacement: change this import
11
+ * // import { createCanvas, registerFont, loadImage } from 'canvas'
12
+ * // to this:
13
+ * import { createCanvas, registerFont, loadImage } from '@napi-rs/canvas/node-canvas'
14
+ * ```
15
+ */
16
+
17
+ import { Readable } from 'node:stream'
18
+
19
+ // Re-export types from @napi-rs/canvas that are API-compatible
20
+ import {
21
+ Image as NapiImage,
22
+ ImageData as NapiImageData,
23
+ Path2D as NapiPath2D,
24
+ DOMPoint as NapiDOMPoint,
25
+ DOMMatrix as NapiDOMMatrix,
26
+ DOMRect as NapiDOMRect,
27
+ SKRSContext2D,
28
+ Canvas as NapiCanvas,
29
+ SvgCanvas,
30
+ SvgExportFlag,
31
+ IGlobalFonts,
32
+ PDFDocument,
33
+ } from './index'
34
+
35
+ // ---------------------------------------------------------------------------
36
+ // Config interfaces (node-canvas conventions)
37
+ // ---------------------------------------------------------------------------
38
+
39
+ export interface PngConfig {
40
+ /** ZLIB compression level (0-9). Default 6. Out-of-range, fractional and non-number values use the default. */
41
+ compressionLevel?: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9
42
+ /**
43
+ * libpng row filter bitmask: a non-zero OR of `0x08` (none), `0x10` (sub), `0x20` (up),
44
+ * `0x40` (average), `0x80` (Paeth). Any other value (including `0`) uses the default (`0xF8`, all filters).
45
+ */
46
+ filters?: number
47
+ /** Palette for indexed PNGs. Not supported by Skia backend. */
48
+ palette?: Uint8ClampedArray
49
+ /** Background color index for indexed PNGs. Not supported by Skia backend. */
50
+ backgroundIndex?: number
51
+ /**
52
+ * Pixels per inch, written as a PNG `pHYs` chunk with the bytes node-canvas
53
+ * writes, up to 54546055 ppi; a larger value writes 2147483647 px/m, the
54
+ * PNG maximum. The fraction is dropped. 0, a value below 1, NaN, the
55
+ * infinities and a non-number write none.
56
+ */
57
+ resolution?: number
58
+ }
59
+
60
+ export interface JpegConfig {
61
+ /** Quality between 0 and 1. Defaults to 0.75. Converted to 0-100 for Skia. */
62
+ quality?: number
63
+ /** Progressive encoding. Accepted for compatibility; not supported by Skia backend. */
64
+ progressive?: boolean
65
+ /** 2x2 chroma subsampling. Accepted for compatibility; not supported by Skia backend. */
66
+ chromaSubsampling?: boolean
67
+ }
68
+
69
+ // ---------------------------------------------------------------------------
70
+ // Canvas class (with node-canvas compatible methods)
71
+ // ---------------------------------------------------------------------------
72
+
73
+ export interface Canvas extends Omit<NapiCanvas, 'toBuffer' | 'toDataURL'> {
74
+ /**
75
+ * Encode the canvas as a PNG and return a Node.js Readable stream.
76
+ * @param config PNG encoding options (accepted for compatibility)
77
+ */
78
+ createPNGStream(config?: PngConfig): PNGStream
79
+
80
+ /**
81
+ * Encode the canvas as a JPEG and return a Node.js Readable stream.
82
+ * @param config JPEG encoding options. Quality is 0-1 (default 0.75).
83
+ */
84
+ createJPEGStream(config?: JpegConfig): JPEGStream
85
+
86
+ // --- toBuffer overloads (node-canvas conventions) ---
87
+
88
+ /** Encode as PNG (default). */
89
+ toBuffer(): Buffer
90
+ toBuffer(mimeType: 'image/png', config?: PngConfig): Buffer
91
+ /** Encode as JPEG. Quality in config is 0-1 (default 0.75). */
92
+ toBuffer(mimeType: 'image/jpeg', config?: JpegConfig): Buffer
93
+ /** Get raw unencoded pixel data. */
94
+ toBuffer(mimeType: 'raw'): Buffer
95
+
96
+ /** Async: encode as PNG (default) via callback. */
97
+ toBuffer(cb: (err: Error | null, result: Buffer) => void): void
98
+ toBuffer(cb: (err: Error | null, result: Buffer) => void, mimeType: 'image/png', config?: PngConfig): void
99
+ /** Async: encode as JPEG via callback. Quality in config is 0-1 (default 0.75). */
100
+ toBuffer(cb: (err: Error | null, result: Buffer) => void, mimeType: 'image/jpeg', config?: JpegConfig): void
101
+
102
+ // --- toDataURL overloads (node-canvas conventions) ---
103
+
104
+ /** Encode as PNG data URL (default). */
105
+ toDataURL(): string
106
+ toDataURL(mimeType: 'image/png'): string
107
+ /** Encode as JPEG data URL. Quality is 0-1. */
108
+ toDataURL(mimeType: 'image/jpeg', quality?: number): string
109
+ /** Async: encode as data URL via callback. */
110
+ toDataURL(cb: (err: Error | null, result: string) => void): void
111
+ toDataURL(mimeType: 'image/png', cb: (err: Error | null, result: string) => void): void
112
+ toDataURL(mimeType: 'image/jpeg', cb: (err: Error | null, result: string) => void): void
113
+ toDataURL(mimeType: 'image/jpeg', quality: number, cb: (err: Error | null, result: string) => void): void
114
+ }
115
+
116
+ // ---------------------------------------------------------------------------
117
+ // Stream classes
118
+ // ---------------------------------------------------------------------------
119
+
120
+ /** Readable stream that emits PNG-encoded data. */
121
+ export class PNGStream extends Readable {}
122
+
123
+ /** Readable stream that emits JPEG-encoded data. */
124
+ export class JPEGStream extends Readable {}
125
+
126
+ // ---------------------------------------------------------------------------
127
+ // Factory functions
128
+ // ---------------------------------------------------------------------------
129
+
130
+ /**
131
+ * Create a new canvas with node-canvas compatible API.
132
+ * Canvas instances created through this function have `createPNGStream()`,
133
+ * `createJPEGStream()`, and node-canvas compatible `toBuffer()` overloads.
134
+ *
135
+ * When `type` is `'svg'`, returns a `SvgCanvas` which produces vector output
136
+ * via `getContent()` instead of raster encoding methods.
137
+ *
138
+ * @param width Canvas width in pixels
139
+ * @param height Canvas height in pixels
140
+ * @param type Canvas type: 'image' (default) or 'svg'
141
+ */
142
+ export function createCanvas(width: number, height: number, type: 'svg'): SvgCanvas
143
+ export function createCanvas(width: number, height: number, type?: 'image'): Canvas
144
+
145
+ /**
146
+ * Create an ImageData instance.
147
+ * @param data Pixel data array
148
+ * @param width Width in pixels
149
+ * @param height Height in pixels (calculated from data length if omitted)
150
+ */
151
+ export function createImageData(data: Uint8ClampedArray, width: number, height?: number): NapiImageData
152
+ export function createImageData(width: number, height: number): NapiImageData
153
+
154
+ /**
155
+ * Load an image from a file path, URL, Buffer, or other source.
156
+ * Returns a Promise that resolves to an Image instance.
157
+ */
158
+ export function loadImage(
159
+ source: string | URL | Buffer | ArrayBufferLike | Uint8Array | NapiImage | import('stream').Readable,
160
+ options?: { alt?: string; maxRedirects?: number; requestOptions?: import('http').RequestOptions },
161
+ ): Promise<NapiImage>
162
+
163
+ // ---------------------------------------------------------------------------
164
+ // Font registration (node-canvas convention)
165
+ // ---------------------------------------------------------------------------
166
+
167
+ /**
168
+ * Register a font file for use in canvas text rendering.
169
+ * Compatible with node-canvas's `registerFont()`.
170
+ *
171
+ * A non-empty `family` is the face's only name, as `new FontFace(family, ...)`
172
+ * in Chrome: the family embedded in the file is not listed (Behavior change
173
+ * from 1.2.0, where it was). `family: ''` (or the embedded name) registers
174
+ * the face under its embedded name.
175
+ *
176
+ * `weight` and `style` are the face's `@font-face` descriptors: the faces of
177
+ * one family are picked by them with CSS font matching. Register one call per
178
+ * face file, e.g. `{ family: 'Lato', weight: 'bold', style: 'italic' }`.
179
+ * A field that is not given, or that the `@font-face` grammar rejects, is
180
+ * `auto`, and the other field is kept; a value the grammar accepts
181
+ * (`calc(700)` too) works exactly as in `GlobalFonts.registerFromPath`. An
182
+ * explicit weight or style (`'normal'` included) pins a variable font to it;
183
+ * use a range such as `'100 900'` to keep the axis. It throws only when the
184
+ * file cannot be registered.
185
+ *
186
+ * @param path Absolute path to the font file (.ttf, .otf, etc.)
187
+ * @param fontFace Font face properties matching CSS @font-face descriptors
188
+ */
189
+ export function registerFont(path: string, fontFace: { family: string; weight?: string | number; style?: string }): void
190
+
191
+ /**
192
+ * Deregister all previously registered fonts.
193
+ * Compatible with node-canvas's `deregisterAllFonts()`: it removes the
194
+ * registrations that `registerFont` calls made through the same loaded native
195
+ * binding (one per main thread or worker; a worker's stay when it exits, as in
196
+ * node-canvas, and only its own `deregisterAllFonts` removes them), each
197
+ * whole, as `GlobalFonts.remove(key)` removes one, with the `setAlias` entries
198
+ * made from them. `GlobalFonts` registrations and `loadFontsFromDir` fonts are
199
+ * never touched. A `registerFont` registration is its own: a file registered
200
+ * both with `registerFont` and with `GlobalFonts` has a face from each while
201
+ * both are live, and a `setAlias` made while a `registerFont` face of the
202
+ * family was the newest goes with it.
203
+ *
204
+ * A later worker never reuses an exited worker's registrations, so each
205
+ * worker that calls `registerFont` adds its faces for the life of the process
206
+ * (only `GlobalFonts.removeAll()` removes them then). A pool that recycles
207
+ * workers should call `deregisterAllFonts()` in each worker before it exits.
208
+ */
209
+ export function deregisterAllFonts(): void
210
+
211
+ // ---------------------------------------------------------------------------
212
+ // Re-exported classes & values
213
+ // ---------------------------------------------------------------------------
214
+
215
+ // Canvas is exported both as a type (the compat interface above) and as a
216
+ // value (constructor that returns compat Canvas instances at runtime).
217
+ export declare const Canvas: {
218
+ new (width: number, height: number): Canvas
219
+ new (width: number, height: number, flag: SvgExportFlag): SvgCanvas
220
+ prototype: NapiCanvas
221
+ }
222
+
223
+ export { NapiImage as Image }
224
+ export { NapiImageData as ImageData }
225
+ export { NapiPath2D as Path2D }
226
+ export { NapiDOMPoint as DOMPoint }
227
+ export { NapiDOMMatrix as DOMMatrix }
228
+ export { NapiDOMRect as DOMRect }
229
+
230
+ // SKRSContext2D is an interface in index.d.ts but a class value at runtime.
231
+ // Declare as const to export the value for instanceof checks and re-export the type.
232
+ export type CanvasRenderingContext2D = SKRSContext2D
233
+ export declare const CanvasRenderingContext2D: { prototype: SKRSContext2D }
234
+ /** Legacy alias for CanvasRenderingContext2D. */
235
+ export type Context2d = SKRSContext2D
236
+ export declare const Context2d: { prototype: SKRSContext2D }
237
+
238
+ // ---------------------------------------------------------------------------
239
+ // @napi-rs/canvas extras (not part of node-canvas, but useful)
240
+ // ---------------------------------------------------------------------------
241
+
242
+ export { IGlobalFonts }
243
+ export declare const GlobalFonts: IGlobalFonts & {
244
+ /** Reload system fonts. Available at runtime but not declared in IGlobalFonts. */
245
+ loadSystemFonts(): number
246
+ }
247
+ export { PDFDocument }
248
+ export { NapiCanvas as CanvasElement }
249
+ export { SvgCanvas as SVGCanvas }
package/node-canvas.js ADDED
@@ -0,0 +1,448 @@
1
+ 'use strict'
2
+
3
+ const { Readable } = require('node:stream')
4
+
5
+ const {
6
+ createCanvas: _createCanvas,
7
+ Canvas,
8
+ CanvasElement,
9
+ SVGCanvas,
10
+ GlobalFonts,
11
+ Image,
12
+ ImageData,
13
+ Path2D,
14
+ DOMPoint,
15
+ DOMMatrix,
16
+ DOMRect,
17
+ loadImage,
18
+ PDFDocument,
19
+ SvgExportFlag,
20
+ } = require('./index.js')
21
+
22
+ // CanvasRenderingContext2D is not re-exported by index.js, grab from native bindings
23
+ const binding = require('./js-binding')
24
+ const { CanvasRenderingContext2D } = binding
25
+
26
+ // node-canvas defaults JPEG quality to 0.75 across all paths.
27
+ // @napi-rs/canvas native default is 0.92 (matching Blink/Chrome).
28
+ const NODE_CANVAS_DEFAULT_QUALITY = 0.75
29
+
30
+ // ---------------------------------------------------------------------------
31
+ // Stream classes (node-canvas returns Node.js Readable streams)
32
+ // ---------------------------------------------------------------------------
33
+
34
+ class PNGStream extends Readable {
35
+ constructor(canvas, options) {
36
+ super()
37
+ this._canvas = canvas
38
+ this._options = options || {}
39
+ this._done = false
40
+ }
41
+
42
+ _read() {
43
+ if (this._done) return
44
+ this._done = true
45
+ this._canvas
46
+ .encode('png', _pngOptions(this._options))
47
+ .then((buf) => {
48
+ this.push(buf)
49
+ this.push(null)
50
+ })
51
+ .catch((err) => {
52
+ this.destroy(err)
53
+ })
54
+ }
55
+ }
56
+
57
+ class JPEGStream extends Readable {
58
+ constructor(canvas, options) {
59
+ super()
60
+ this._canvas = canvas
61
+ const opts = options || {}
62
+ // node-canvas quality: 0-1 (default 0.75), encode() expects 0-100
63
+ this._quality = Math.round((opts.quality != null ? opts.quality : NODE_CANVAS_DEFAULT_QUALITY) * 100)
64
+ this._done = false
65
+ }
66
+
67
+ _read() {
68
+ if (this._done) return
69
+ this._done = true
70
+ this._canvas
71
+ .encode('jpeg', this._quality)
72
+ .then((buf) => {
73
+ this.push(buf)
74
+ this.push(null)
75
+ })
76
+ .catch((err) => {
77
+ this.destroy(err)
78
+ })
79
+ }
80
+ }
81
+
82
+ // ---------------------------------------------------------------------------
83
+ // Quality normalization helpers
84
+ // ---------------------------------------------------------------------------
85
+
86
+ const MIME_FORMAT_MAP = {
87
+ 'image/png': 'png',
88
+ 'image/jpeg': 'jpeg',
89
+ 'image/webp': 'webp',
90
+ 'image/avif': 'avif',
91
+ 'image/gif': 'gif',
92
+ }
93
+
94
+ /**
95
+ * Extract quality from a node-canvas config object or number.
96
+ * Returns the raw 0-1 quality value, defaulting to NODE_CANVAS_DEFAULT_QUALITY
97
+ * for JPEG/WebP when not specified.
98
+ *
99
+ * @param {string} mime
100
+ * @param {number|object|undefined} configOrQuality
101
+ * @returns {number|undefined} 0-1 scale for JPEG/WebP, undefined for other mimes
102
+ */
103
+ function _extractQuality(mime, configOrQuality) {
104
+ if (mime !== 'image/jpeg' && mime !== 'image/webp') return undefined
105
+ if (configOrQuality == null) return NODE_CANVAS_DEFAULT_QUALITY
106
+ if (typeof configOrQuality === 'number') return configOrQuality
107
+ if (typeof configOrQuality === 'object' && configOrQuality.quality != null) {
108
+ return configOrQuality.quality
109
+ }
110
+ return NODE_CANVAS_DEFAULT_QUALITY
111
+ }
112
+
113
+ /**
114
+ * The native PNG options for a node-canvas PngConfig: `resolution` (pHYs chunk),
115
+ * `compressionLevel` (zlib 0-9) and `filters` (libpng filter bitmask); undefined
116
+ * when none of them is a number, so the native call stays a plain PNG encode.
117
+ *
118
+ * @param {object|undefined} config
119
+ * @returns {{ resolution?: number, compressionLevel?: number, filters?: number }|undefined}
120
+ */
121
+ function _pngOptions(config) {
122
+ if (config === null || typeof config !== 'object') return undefined
123
+ const resolution = config.resolution
124
+ const compressionLevel = config.compressionLevel
125
+ const filters = config.filters
126
+ const options = {}
127
+ let hasOption = false
128
+ if (typeof resolution === 'number') {
129
+ options.resolution = resolution
130
+ hasOption = true
131
+ }
132
+ if (typeof compressionLevel === 'number') {
133
+ options.compressionLevel = compressionLevel
134
+ hasOption = true
135
+ }
136
+ if (typeof filters === 'number') {
137
+ options.filters = filters
138
+ hasOption = true
139
+ }
140
+ return hasOption ? options : undefined
141
+ }
142
+
143
+ // ---------------------------------------------------------------------------
144
+ // Compat methods added to each canvas instance created via this module
145
+ // ---------------------------------------------------------------------------
146
+
147
+ // Keep references to the original prototype methods
148
+ const _origToBuffer = CanvasElement.prototype.toBuffer
149
+ const _origToDataURL = CanvasElement.prototype.toDataURL
150
+
151
+ function _compatCreatePNGStream(options) {
152
+ return new PNGStream(this, options)
153
+ }
154
+
155
+ function _compatCreateJPEGStream(options) {
156
+ return new JPEGStream(this, options)
157
+ }
158
+
159
+ /**
160
+ * node-canvas compatible toBuffer:
161
+ * - toBuffer() → PNG (sync)
162
+ * - toBuffer('image/png', config?) → PNG (sync)
163
+ * - toBuffer('image/jpeg', config?) → JPEG (sync, quality 0-1)
164
+ * - toBuffer('raw') → raw pixel data (sync)
165
+ * - toBuffer(callback) → PNG (async)
166
+ * - toBuffer(callback, mime, config?) → specified format (async)
167
+ */
168
+ function _compatToBuffer(mimeOrCallback, configOrQuality) {
169
+ // Callback form: toBuffer(callback) or toBuffer(callback, mime, config)
170
+ if (typeof mimeOrCallback === 'function') {
171
+ const callback = mimeOrCallback
172
+ const mime = typeof configOrQuality === 'string' ? configOrQuality : 'image/png'
173
+ const config = arguments[2]
174
+
175
+ if (mime === 'raw') {
176
+ let buf
177
+ try {
178
+ buf = this.data()
179
+ } catch (err) {
180
+ callback(err)
181
+ return
182
+ }
183
+ callback(null, buf)
184
+ return
185
+ }
186
+
187
+ const format = MIME_FORMAT_MAP[mime]
188
+ if (!format) {
189
+ callback(new TypeError(`Unsupported MIME type "${mime}". Supported: ${Object.keys(MIME_FORMAT_MAP).join(', ')}`))
190
+ return
191
+ }
192
+ const q = _extractQuality(mime, config)
193
+ const options = format === 'png' ? _pngOptions(config) : q != null ? Math.round(q * 100) : undefined
194
+ this.encode(format, options).then(
195
+ (buf) => callback(null, buf),
196
+ (err) => callback(err),
197
+ )
198
+ return
199
+ }
200
+
201
+ // Sync: no args → PNG
202
+ if (mimeOrCallback === undefined) {
203
+ return _origToBuffer.call(this, 'image/png')
204
+ }
205
+
206
+ // Sync: raw pixel data
207
+ if (mimeOrCallback === 'raw') {
208
+ return this.data()
209
+ }
210
+
211
+ // Sync: PNG takes the resolution; JPEG / WebP a quality (0-1) scaled to
212
+ // 0-100 for native toBuffer
213
+ if (mimeOrCallback === 'image/png') {
214
+ return _origToBuffer.call(this, mimeOrCallback, _pngOptions(configOrQuality))
215
+ }
216
+ const q = _extractQuality(mimeOrCallback, configOrQuality)
217
+ return _origToBuffer.call(this, mimeOrCallback, q != null ? Math.round(q * 100) : undefined)
218
+ }
219
+
220
+ /**
221
+ * node-canvas compatible toDataURL:
222
+ * - toDataURL() → PNG data URL (sync)
223
+ * - toDataURL('image/jpeg', quality) → JPEG data URL, quality 0-1 (sync)
224
+ * - toDataURL(callback) → PNG data URL (async)
225
+ * - toDataURL(mime, callback) → data URL (async)
226
+ * - toDataURL(mime, quality, callback) → data URL with quality (async)
227
+ */
228
+ function _compatToDataURL(mimeOrCallback, qualityOrCallback) {
229
+ // toDataURL(callback)
230
+ if (typeof mimeOrCallback === 'function') {
231
+ this.toDataURLAsync('image/png').then(
232
+ (url) => mimeOrCallback(null, url),
233
+ (err) => mimeOrCallback(err),
234
+ )
235
+ return
236
+ }
237
+ // toDataURL(mime, callback)
238
+ if (typeof qualityOrCallback === 'function') {
239
+ this.toDataURLAsync(mimeOrCallback, _extractQuality(mimeOrCallback, undefined)).then(
240
+ (url) => qualityOrCallback(null, url),
241
+ (err) => qualityOrCallback(err),
242
+ )
243
+ return
244
+ }
245
+ // toDataURL(mime, quality, callback)
246
+ const cb = arguments[2]
247
+ if (typeof cb === 'function') {
248
+ // Native toDataURLAsync expects 0-1 (f64) — pass quality through as-is
249
+ const quality = _extractQuality(mimeOrCallback, qualityOrCallback)
250
+ this.toDataURLAsync(mimeOrCallback, quality).then(
251
+ (url) => cb(null, url),
252
+ (err) => cb(err),
253
+ )
254
+ return
255
+ }
256
+
257
+ // Sync form: native toDataURL expects 0-1 (f64) — pass quality through as-is
258
+ const quality = _extractQuality(mimeOrCallback, qualityOrCallback)
259
+ return _origToDataURL.call(this, mimeOrCallback, quality)
260
+ }
261
+
262
+ /**
263
+ * Attach node-canvas compatible methods to a CanvasElement instance.
264
+ */
265
+ function _addCompatMethods(canvas) {
266
+ canvas.createPNGStream = _compatCreatePNGStream
267
+ canvas.createJPEGStream = _compatCreateJPEGStream
268
+ canvas.toBuffer = _compatToBuffer
269
+ canvas.toDataURL = _compatToDataURL
270
+ return canvas
271
+ }
272
+
273
+ // ---------------------------------------------------------------------------
274
+ // Public API: registerFont / deregisterAllFonts
275
+ // ---------------------------------------------------------------------------
276
+
277
+ /**
278
+ * Register a font file with the specified font face properties.
279
+ * Compatible with node-canvas's registerFont(path, { family, weight?, style? }).
280
+ *
281
+ * The file is registered as a registration of its own, made as
282
+ * GlobalFonts.registerFromPath makes a path it never saw, with `weight` and
283
+ * `style` as the face's @font-face descriptors, so the faces of one family
284
+ * are picked by them with CSS font matching. Register one call per face
285
+ * file. A non-empty `family` is the face's only name, as
286
+ * `new FontFace(family, ...)` in Chrome: the family embedded in the file is
287
+ * not listed (Behavior change from 1.2.0, where it was). `family: ''` (or
288
+ * the embedded name) registers it under its embedded name. Only the
289
+ * registerFont calls of this N-API env (the main thread or one worker) share
290
+ * it: the same declaration again reuses it and makes it the newest. A
291
+ * GlobalFonts call or loadFontsFromDir never reuses it, so a file registered
292
+ * both ways has a face from each.
293
+ *
294
+ * - A field that is not given is `auto`: a call with only `family` registers
295
+ * the file as GlobalFonts.registerFromPath(path, family) does, except that
296
+ * the embedded family is not listed, and a variable font keeps its axes.
297
+ * - An explicit weight or style, `'normal'` included, pins a variable font to
298
+ * it, as with @font-face. Use a range such as `'100 900'` to keep the axis.
299
+ * - Each of `weight` and `style` is read on its own: a value the @font-face
300
+ * grammar rejects (`'bolder'`, `''`) counts as not given, as node-canvas
301
+ * ignores unknown values instead of throwing, and the other field is kept.
302
+ * A value the grammar accepts (`calc(700)` too) works exactly as in
303
+ * GlobalFonts.registerFromPath. It throws only when the file cannot be
304
+ * registered.
305
+ *
306
+ * @param {string} path Absolute path to the font file (.ttf, .otf, etc.)
307
+ * @param {{ family: string, weight?: string | number, style?: string }} fontFace
308
+ */
309
+ function registerFont(path, fontFace) {
310
+ const family = fontFace ? fontFace.family : undefined
311
+ if (typeof family !== 'string') {
312
+ throw new TypeError('registerFont requires a fontFace with a "family" property')
313
+ }
314
+ // node-canvas reads `weight` as a string or a number and `style` as a
315
+ // string; any other value counts as not given. The native call reads each
316
+ // value with the @font-face grammar (src/global_fonts.rs
317
+ // register_font_face): one it rejects counts as not given too.
318
+ const w = fontFace.weight
319
+ const s = fontFace.style
320
+ const weight = typeof w === 'string' || typeof w === 'number' ? String(w) : 'auto'
321
+ const style = typeof s === 'string' ? s : 'auto'
322
+ // Read from the binding at each call, not once at load: the tests stub it.
323
+ if (!binding._registerFontFace(path, family, weight, style)) {
324
+ throw new Error(`Failed to register font from "${path}" with family "${family}"`)
325
+ }
326
+ }
327
+
328
+ /**
329
+ * Deregister all fonts previously registered via registerFont().
330
+ * Compatible with node-canvas's deregisterAllFonts() which only removes
331
+ * user-registered fonts and leaves system fonts untouched.
332
+ */
333
+ function deregisterAllFonts() {
334
+ // Removes the registerFont registrations of this N-API env whole (one per
335
+ // loaded native binding: the main thread or a worker; copies of this
336
+ // module that reuse the cached binding share it), as GlobalFonts.remove(key)
337
+ // removes a registration, the setAlias entries made from them included. A
338
+ // worker's stay when it exits, as in node-canvas (then only
339
+ // GlobalFonts.removeAll removes them; no later worker reuses them, so a
340
+ // pool that recycles workers should call this in each worker before it
341
+ // exits, or each worker adds its faces, as each adds its fonts in
342
+ // node-canvas). GlobalFonts
343
+ // registrations and loadFontsFromDir fonts are never touched, as
344
+ // node-canvas leaves other fonts untouched.
345
+ // Read at each call, as in registerFont.
346
+ binding._releaseFontFaces()
347
+ }
348
+
349
+ // ---------------------------------------------------------------------------
350
+ // Public API: createCanvas / createImageData
351
+ // ---------------------------------------------------------------------------
352
+
353
+ /**
354
+ * Create a new canvas instance with node-canvas compatible API.
355
+ *
356
+ * @param {number} width
357
+ * @param {number} height
358
+ * @param {'image'|'svg'} [type='image']
359
+ * @returns {Canvas}
360
+ */
361
+ function createCanvas(width, height, type) {
362
+ if (type === 'svg') {
363
+ // SvgExportFlag enum requires a valid variant; NoPrettyXML (0x02) is the
364
+ // least impactful on rendering behavior (only affects XML whitespace).
365
+ return _createCanvas(width, height, SvgExportFlag.NoPrettyXML)
366
+ }
367
+ if (type === 'pdf') {
368
+ throw new Error(
369
+ 'createCanvas with type "pdf" is not supported. Use the PDFDocument class from @napi-rs/canvas directly.',
370
+ )
371
+ }
372
+ if (type != null && type !== 'image') {
373
+ throw new TypeError(`createCanvas: unknown type "${type}". Supported types: "image", "svg".`)
374
+ }
375
+ return _addCompatMethods(_createCanvas(width, height))
376
+ }
377
+
378
+ /**
379
+ * Create an ImageData instance.
380
+ * Compatible with node-canvas's createImageData().
381
+ *
382
+ * @param {Uint8ClampedArray|number} dataOrWidth
383
+ * @param {number} widthOrHeight
384
+ * @param {number} [height]
385
+ * @returns {ImageData}
386
+ */
387
+ function createImageData(dataOrWidth, widthOrHeight, height) {
388
+ if (typeof dataOrWidth === 'number') {
389
+ return new ImageData(dataOrWidth, widthOrHeight)
390
+ }
391
+ if (height != null) {
392
+ return new ImageData(dataOrWidth, widthOrHeight, height)
393
+ }
394
+ return new ImageData(dataOrWidth, widthOrHeight)
395
+ }
396
+
397
+ // ---------------------------------------------------------------------------
398
+ // Canvas constructor wrapper
399
+ // ---------------------------------------------------------------------------
400
+
401
+ // In node-canvas, `new Canvas(w, h)` and `createCanvas(w, h)` produce
402
+ // equivalent canvases. Wrap the native Canvas constructor so that
403
+ // `new Canvas(w, h)` also gets compat methods, without polluting the
404
+ // prototype (which would affect @napi-rs/canvas users who don't use
405
+ // this compat layer).
406
+ const CompatCanvas = new Proxy(Canvas, {
407
+ construct(target, args) {
408
+ const canvas = new target(...args)
409
+ if (canvas instanceof CanvasElement) {
410
+ return _addCompatMethods(canvas)
411
+ }
412
+ return canvas
413
+ },
414
+ })
415
+
416
+ // ---------------------------------------------------------------------------
417
+ // Exports (matches node-canvas export shape)
418
+ // ---------------------------------------------------------------------------
419
+
420
+ module.exports = {
421
+ // Factory functions
422
+ Canvas: CompatCanvas,
423
+ createCanvas,
424
+ createImageData,
425
+ loadImage,
426
+ registerFont,
427
+ deregisterAllFonts,
428
+
429
+ // Classes
430
+ Image,
431
+ ImageData,
432
+ CanvasRenderingContext2D,
433
+ Context2d: CanvasRenderingContext2D,
434
+ PNGStream,
435
+ JPEGStream,
436
+ Path2D,
437
+
438
+ // Geometry
439
+ DOMPoint,
440
+ DOMMatrix,
441
+ DOMRect,
442
+
443
+ // @napi-rs/canvas extras (available but not part of node-canvas)
444
+ GlobalFonts,
445
+ PDFDocument,
446
+ CanvasElement,
447
+ SVGCanvas,
448
+ }