@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.
package/index.js ADDED
@@ -0,0 +1,761 @@
1
+ const { platform, homedir } = require('os')
2
+ const { join } = require('path')
3
+
4
+ const {
5
+ clearAllCache,
6
+ CanvasRenderingContext2D,
7
+ CanvasElement,
8
+ CanvasGradient,
9
+ CanvasPattern,
10
+ SVGCanvas,
11
+ Path: Path2D,
12
+ ImageData: NativeImageData,
13
+ Image,
14
+ FontKey,
15
+ GlobalFonts,
16
+ PathOp,
17
+ FillType,
18
+ StrokeJoin,
19
+ StrokeCap,
20
+ convertSVGTextToPath,
21
+ PdfDocument,
22
+ GifEncoder,
23
+ GifDisposal,
24
+ LottieAnimation,
25
+ TextMetrics,
26
+ _argumentCounts,
27
+ _imageDataConstructor,
28
+ _toNumber: toNumber,
29
+ setTextRenderer,
30
+ getTextRenderer,
31
+ } = require('./js-binding')
32
+
33
+ const { DOMPoint, DOMMatrix, DOMRect } = require('./geometry')
34
+
35
+ const loadImage = require('./load-image')
36
+
37
+ // Add Symbol.dispose support for GifEncoder (ECMAScript 2024 Explicit Resource Management)
38
+ if (GifEncoder && typeof Symbol.dispose !== 'undefined') {
39
+ GifEncoder.prototype[Symbol.dispose] = function () {
40
+ this.dispose()
41
+ }
42
+ }
43
+
44
+ // napi-rs defines a class's accessors in name order. Chrome's TextMetrics
45
+ // prototype has them in IDL order (text_metrics.idl), which for...in shows,
46
+ // then the constructor: define them again in that order.
47
+ for (const name of [
48
+ 'width',
49
+ 'actualBoundingBoxLeft',
50
+ 'actualBoundingBoxRight',
51
+ 'fontBoundingBoxAscent',
52
+ 'fontBoundingBoxDescent',
53
+ 'actualBoundingBoxAscent',
54
+ 'actualBoundingBoxDescent',
55
+ 'hangingBaseline',
56
+ 'alphabeticBaseline',
57
+ 'ideographicBaseline',
58
+ 'emHeightAscent',
59
+ 'emHeightDescent',
60
+ 'constructor',
61
+ ]) {
62
+ const descriptor = Object.getOwnPropertyDescriptor(TextMetrics.prototype, name)
63
+ delete TextMetrics.prototype[name]
64
+ Object.defineProperty(TextMetrics.prototype, name, descriptor)
65
+ }
66
+
67
+ // Chrome's Symbol.toStringTag, an own property of each prototype. The
68
+ // canvas and Image classes take their HTML element names; SVGCanvas has no
69
+ // counterpart and no tag.
70
+ for (const [Class, tag] of [
71
+ [CanvasRenderingContext2D, 'CanvasRenderingContext2D'],
72
+ [CanvasGradient, 'CanvasGradient'],
73
+ [CanvasPattern, 'CanvasPattern'],
74
+ [Path2D, 'Path2D'],
75
+ [NativeImageData, 'ImageData'],
76
+ [TextMetrics, 'TextMetrics'],
77
+ [CanvasElement, 'HTMLCanvasElement'],
78
+ [Image, 'HTMLImageElement'],
79
+ ]) {
80
+ Object.defineProperty(Class.prototype, Symbol.toStringTag, { value: tag, configurable: true })
81
+ }
82
+
83
+ const SvgExportFlag = {
84
+ ConvertTextToPaths: 0x01,
85
+ NoPrettyXML: 0x02,
86
+ RelativePathEncoding: 0x04,
87
+ }
88
+
89
+ const PngFilter = {
90
+ None: 0x08,
91
+ Sub: 0x10,
92
+ Up: 0x20,
93
+ Avg: 0x40,
94
+ Paeth: 0x80,
95
+ All: 0xf8,
96
+ }
97
+
98
+ if (!('families' in GlobalFonts)) {
99
+ Object.defineProperty(GlobalFonts, 'families', {
100
+ get: function () {
101
+ return JSON.parse(GlobalFonts.getFamilies().toString())
102
+ },
103
+ })
104
+ }
105
+
106
+ if (!('has' in GlobalFonts)) {
107
+ Object.defineProperty(GlobalFonts, 'has', {
108
+ value: function has(name) {
109
+ return !!JSON.parse(GlobalFonts.getFamilies().toString()).find(({ family }) => family === name)
110
+ },
111
+ configurable: false,
112
+ enumerable: false,
113
+ writable: false,
114
+ })
115
+ }
116
+
117
+ // Re-evaluating this module (Jest resets its module registry per test
118
+ // file; the .node binding and its prototypes stay loaded) must wrap the
119
+ // native methods again, not the previous wrappers: their argument padding
120
+ // would corrupt the argument count the native methods read.
121
+ const NATIVE_METHODS = Symbol.for('@napi-rs/canvas:native-methods')
122
+ function nativeMethods(proto) {
123
+ let stash = proto[NATIVE_METHODS]
124
+ if (stash === undefined) {
125
+ stash = {}
126
+ Object.defineProperty(proto, NATIVE_METHODS, { value: stash })
127
+ }
128
+ return stash
129
+ }
130
+
131
+ const canvasNative = nativeMethods(CanvasElement.prototype)
132
+ const _toBlob = (canvasNative.toBlob ??= CanvasElement.prototype.toBlob)
133
+ const _convertToBlob = (canvasNative.convertToBlob ??= CanvasElement.prototype.convertToBlob)
134
+ // A native method of CanvasElement for the receiver check: with no arguments
135
+ // it has no side effects.
136
+ const canvasBrand = (canvasNative.getContext ??= CanvasElement.prototype.getContext)
137
+ if ('Blob' in globalThis) {
138
+ // toBlob(callback, type, quality), as Chrome: the receiver, the argument
139
+ // count and the callback are checked first, then the native method converts
140
+ // the type and encodes. The callback gets the Blob, or null without pixels
141
+ // or when the encoder fails, from a task. A throw in it is an uncaught
142
+ // exception, as in Chrome (window.onerror).
143
+ CanvasElement.prototype.toBlob = function toBlob(callback) {
144
+ if (arguments.length < 1) {
145
+ argumentCountError(canvasBrand, this, 'toBlob', 'HTMLCanvasElement', 1, 0)
146
+ }
147
+ if (typeof callback !== 'function') {
148
+ bindingTypeError(canvasBrand, this, 'toBlob', 'HTMLCanvasElement', "parameter 1 is not of type 'Function'.")
149
+ }
150
+ // Only the arguments that were passed: past arguments.length,
151
+ // arguments[i] reads Object.prototype[i], which Chrome never reads.
152
+ const type = arguments.length > 1 ? arguments[1] : undefined
153
+ const quality = arguments.length > 2 ? arguments[2] : undefined
154
+ _toBlob.call(this, type, quality).then(
155
+ (result) => {
156
+ const blob = result === null ? null : new Blob([result.data], { type: result.type })
157
+ queueMicrotask(() => callback(blob))
158
+ },
159
+ () => queueMicrotask(() => callback(null)),
160
+ )
161
+ }
162
+ // convertToBlob(options): Chrome's OffscreenCanvas method. An options error
163
+ // rejects the promise, as a WebIDL conversion error of a promise method.
164
+ CanvasElement.prototype.convertToBlob = function convertToBlob() {
165
+ let pending
166
+ try {
167
+ pending = _convertToBlob.call(this, arguments.length > 0 ? arguments[0] : undefined)
168
+ } catch (error) {
169
+ return Promise.reject(error)
170
+ }
171
+ return pending.then((result) => new Blob([result.data], { type: result.type }))
172
+ }
173
+ } else {
174
+ // oxlint-disable-next-line no-unused-vars
175
+ CanvasElement.prototype.toBlob = function toBlob(callback, mimeType, quality) {
176
+ callback(null)
177
+ }
178
+ // oxlint-disable-next-line no-unused-vars
179
+ CanvasElement.prototype.convertToBlob = function convertToBlob(options) {
180
+ return Promise.reject(new Error('Blob is not supported in this environment'))
181
+ }
182
+ }
183
+
184
+ const ctxNative = nativeMethods(CanvasRenderingContext2D.prototype)
185
+ const _getTransform = (ctxNative.getTransform ??= CanvasRenderingContext2D.prototype.getTransform)
186
+
187
+ CanvasRenderingContext2D.prototype.getTransform = function getTransform() {
188
+ const transform = _getTransform.apply(this, arguments)
189
+ // monkey patched, skip
190
+ if (transform instanceof DOMMatrix) {
191
+ return transform
192
+ }
193
+ const { a, b, c, d, e, f } = transform
194
+ return new DOMMatrix([a, b, c, d, e, f])
195
+ }
196
+
197
+ // Chrome checks the receiver ('Illegal invocation'), then the argument count,
198
+ // before it converts any argument. `brand` is a native method of the class: a
199
+ // call on another receiver throws 'Illegal invocation'. As Blink's binding
200
+ // errors, the stack keeps the bare message and `message` gets the prefix, as
201
+ // an enumerable own property.
202
+ function argumentCountError(brand, self, method, iface, required, present) {
203
+ brand.call(self)
204
+ const message = `${required} argument${required === 1 ? '' : 's'} required, but only ${present} present.`
205
+ const error = new TypeError(message)
206
+ void error.stack
207
+ Object.defineProperty(error, 'message', {
208
+ value: `Failed to execute '${method}' on '${iface}': ${message}`,
209
+ writable: true,
210
+ enumerable: true,
211
+ configurable: true,
212
+ })
213
+ throw error
214
+ }
215
+
216
+ // A TypeError as Blink's bindings throw it after the receiver check, with the
217
+ // message formatted as argumentCountError does.
218
+ function bindingTypeError(brand, self, method, iface, message) {
219
+ brand.call(self)
220
+ const error = new TypeError(message)
221
+ void error.stack
222
+ Object.defineProperty(error, 'message', {
223
+ value: `Failed to execute '${method}' on '${iface}': ${message}`,
224
+ writable: true,
225
+ enumerable: true,
226
+ configurable: true,
227
+ })
228
+ throw error
229
+ }
230
+
231
+ // Wraps `proto[method]` with Chrome's argument count check; the wrapper's
232
+ // `length` is the required argument count, as Chrome's Function.length.
233
+ // napi pads missing arguments with undefined, so the native method cannot
234
+ // tell f(1) from f(1, undefined); an explicit undefined counts in Chrome.
235
+ function requireArguments(proto, brand, iface, method, required) {
236
+ const stash = nativeMethods(proto)
237
+ const native = (stash[method] ??= proto[method])
238
+ const wrapper = {
239
+ [method]() {
240
+ if (arguments.length < required) {
241
+ argumentCountError(brand, this, method, iface, required, arguments.length)
242
+ }
243
+ return native.apply(this, arguments)
244
+ },
245
+ }[method]
246
+ Object.defineProperty(wrapper, 'length', { value: required })
247
+ proto[method] = wrapper
248
+ }
249
+
250
+ const ctxBrand = CanvasRenderingContext2D.prototype.getContextAttributes
251
+ for (const [method, required] of [
252
+ ['arc', 5],
253
+ ['arcTo', 5],
254
+ ['bezierCurveTo', 6],
255
+ ['clearRect', 4],
256
+ ['createConicGradient', 3],
257
+ ['createLinearGradient', 4],
258
+ ['createRadialGradient', 6],
259
+ ['ellipse', 7],
260
+ ['fillRect', 4],
261
+ ['fillText', 3],
262
+ ['getImageData', 4],
263
+ ['lineTo', 2],
264
+ ['measureText', 1],
265
+ ['moveTo', 2],
266
+ ['quadraticCurveTo', 4],
267
+ ['rect', 4],
268
+ ['rotate', 1],
269
+ ['roundRect', 4],
270
+ ['scale', 2],
271
+ ['setLineDash', 1],
272
+ ['strokeRect', 4],
273
+ ['strokeText', 3],
274
+ ['transform', 6],
275
+ ['translate', 2],
276
+ ]) {
277
+ requireArguments(CanvasRenderingContext2D.prototype, ctxBrand, 'CanvasRenderingContext2D', method, required)
278
+ }
279
+
280
+ // getContext(contextId, options): Chrome needs the id. The native method is
281
+ // its own brand: with no arguments it converts undefined to 'undefined' and
282
+ // returns null, without side effects.
283
+ for (const [Class, iface] of [
284
+ [CanvasElement, 'HTMLCanvasElement'],
285
+ [SVGCanvas, 'SVGCanvas'],
286
+ ]) {
287
+ const stash = nativeMethods(Class.prototype)
288
+ requireArguments(Class.prototype, (stash.getContext ??= Class.prototype.getContext), iface, 'getContext', 1)
289
+ }
290
+
291
+ const pathBrand = Path2D.prototype.getFillType
292
+ for (const [method, required] of [
293
+ ['arc', 5],
294
+ ['arcTo', 5],
295
+ ['bezierCurveTo', 6],
296
+ ['ellipse', 7],
297
+ ['lineTo', 2],
298
+ ['moveTo', 2],
299
+ ['quadraticCurveTo', 4],
300
+ ['rect', 4],
301
+ ['roundRect', 4],
302
+ ]) {
303
+ requireArguments(Path2D.prototype, pathBrand, 'Path2D', method, required)
304
+ }
305
+
306
+ // The argument-count markers for 0 to 9 arguments. napi pads missing
307
+ // arguments with undefined, so the wrappers below pass the real count after
308
+ // the positional arguments, as one of these markers: the native methods read
309
+ // a count only from a marker, and any other value there (from a raw
310
+ // js-binding call) is an extra argument.
311
+ const ARGUMENT_COUNTS = _argumentCounts()
312
+
313
+ // new ImageData(): Chrome checks `new` and the real argument count before it
314
+ // picks an overload (image_data.idl). The class napi-rs makes sees neither,
315
+ // so a native function checks them and builds the instance itself, from
316
+ // new.target.prototype. Instances share the class prototype, so instanceof
317
+ // works for those that createImageData and getImageData return.
318
+ const ImageData = _imageDataConstructor()
319
+ Object.defineProperty(ImageData, 'length', { value: 2 })
320
+ Object.defineProperty(ImageData, 'prototype', { value: NativeImageData.prototype, writable: false })
321
+ Object.defineProperty(NativeImageData.prototype, 'constructor', {
322
+ value: ImageData,
323
+ writable: true,
324
+ enumerable: false,
325
+ configurable: true,
326
+ })
327
+
328
+ // What the wrappers below pass after their `n` positional arguments, for a
329
+ // call with `count` (1 to `n`) of them, the last one `last`. Without a marker
330
+ // the native method counts up to the last argument that is not undefined:
331
+ // that is `count` unless `last` is an explicit undefined, and only then is
332
+ // the marker needed.
333
+ function argumentCount(count, last) {
334
+ return last === undefined ? ARGUMENT_COUNTS[count] : undefined
335
+ }
336
+
337
+ // fill(), clip(), stroke(), isPointInPath() and isPointInStroke(): WebIDL
338
+ // picks the overload from the argument count (canvas_2d_recorder_context.idl),
339
+ // and an explicit undefined counts: fill(path, undefined) is the nonzero
340
+ // fill of path, fill(undefined, 'evenodd') a TypeError.
341
+ // These wrappers and drawImage's read only the arguments the call has: past
342
+ // arguments.length, arguments[i] would read Object.prototype[i], which
343
+ // Chrome never reads.
344
+ const _fill = (ctxNative.fill ??= CanvasRenderingContext2D.prototype.fill)
345
+ CanvasRenderingContext2D.prototype.fill = function fill() {
346
+ const count = Math.min(arguments.length, 2)
347
+ return _fill.call(
348
+ this,
349
+ count > 0 ? arguments[0] : undefined,
350
+ count > 1 ? arguments[1] : undefined,
351
+ count === 0 ? undefined : argumentCount(count, arguments[count - 1]),
352
+ )
353
+ }
354
+
355
+ const _clip = (ctxNative.clip ??= CanvasRenderingContext2D.prototype.clip)
356
+ CanvasRenderingContext2D.prototype.clip = function clip() {
357
+ const count = Math.min(arguments.length, 2)
358
+ return _clip.call(
359
+ this,
360
+ count > 0 ? arguments[0] : undefined,
361
+ count > 1 ? arguments[1] : undefined,
362
+ count === 0 ? undefined : argumentCount(count, arguments[count - 1]),
363
+ )
364
+ }
365
+
366
+ const _stroke = (ctxNative.stroke ??= CanvasRenderingContext2D.prototype.stroke)
367
+ CanvasRenderingContext2D.prototype.stroke = function stroke() {
368
+ if (arguments.length === 0) {
369
+ return _stroke.call(this, undefined, undefined)
370
+ }
371
+ const path = arguments[0]
372
+ return _stroke.call(this, path, argumentCount(1, path))
373
+ }
374
+
375
+ const _isPointInPath = (ctxNative.isPointInPath ??= CanvasRenderingContext2D.prototype.isPointInPath)
376
+ CanvasRenderingContext2D.prototype.isPointInPath = function isPointInPath() {
377
+ if (arguments.length < 2) {
378
+ argumentCountError(ctxBrand, this, 'isPointInPath', 'CanvasRenderingContext2D', 2, arguments.length)
379
+ }
380
+ const count = Math.min(arguments.length, 4)
381
+ return _isPointInPath.call(
382
+ this,
383
+ arguments[0],
384
+ arguments[1],
385
+ count > 2 ? arguments[2] : undefined,
386
+ count > 3 ? arguments[3] : undefined,
387
+ // (x, y, undefined) converts as (x, y) when x is not an object (only an
388
+ // object can be a Path2D), so the count is not needed.
389
+ count === 3 && typeof arguments[0] !== 'object' ? undefined : argumentCount(count, arguments[count - 1]),
390
+ )
391
+ }
392
+ Object.defineProperty(CanvasRenderingContext2D.prototype.isPointInPath, 'length', { value: 2 })
393
+
394
+ const _isPointInStroke = (ctxNative.isPointInStroke ??= CanvasRenderingContext2D.prototype.isPointInStroke)
395
+ CanvasRenderingContext2D.prototype.isPointInStroke = function isPointInStroke() {
396
+ if (arguments.length < 2) {
397
+ argumentCountError(ctxBrand, this, 'isPointInStroke', 'CanvasRenderingContext2D', 2, arguments.length)
398
+ }
399
+ const count = Math.min(arguments.length, 3)
400
+ return _isPointInStroke.call(
401
+ this,
402
+ arguments[0],
403
+ arguments[1],
404
+ count > 2 ? arguments[2] : undefined,
405
+ argumentCount(count, arguments[count - 1]),
406
+ )
407
+ }
408
+ Object.defineProperty(CanvasRenderingContext2D.prototype.isPointInStroke, 'length', { value: 2 })
409
+
410
+ // A TypeError as Chrome's bindings throw it, as in argumentCountError: the
411
+ // stack keeps the bare message, and `message` gets the prefix.
412
+ function contextTypeError(prefix, message) {
413
+ const error = new TypeError(message)
414
+ void error.stack
415
+ Object.defineProperty(error, 'message', {
416
+ value: prefix + message,
417
+ writable: true,
418
+ enumerable: true,
419
+ configurable: true,
420
+ })
421
+ return error
422
+ }
423
+
424
+ // An `unrestricted double` member of a matrix dictionary; undefined when it
425
+ // is absent. The native ToNumber keeps the engine's texts, and the error
426
+ // names the member, as in Chrome.
427
+ function matrixMember(value, key, dictionary, prefix) {
428
+ if (typeof value === 'number' || value === undefined) return value
429
+ return toNumber(value, `${prefix}Failed to read the '${key}' property from '${dictionary}': `)
430
+ }
431
+
432
+ // a and m11 (and so on) disagree: both given and not equal. Two NaNs agree.
433
+ const mismatch = (x, y) => x !== undefined && y !== undefined && x !== y && (x === x || y === y)
434
+ // A 3D member against its identity value; absent is the identity. As C++
435
+ // truthiness, NaN counts as 3D and -0 as 0.
436
+ const notZero = (v) => v !== undefined && v !== 0
437
+ const notOne = (v) => v !== undefined && v !== 1
438
+
439
+ // The matrix of a DOMMatrix2DInit, or of a DOMMatrixInit when `full`, as
440
+ // [m11, m12, m21, m22, m41, m42]; undefined and null are {}. As Blink's
441
+ // bindings, every member is read with [[Get]], in order (a..f, m11, m12,
442
+ // m21, m22, m41, m42, then is2D and m13..m44), then checked as
443
+ // DOMMatrixReadOnly::ValidateAndFixup (dom_matrix_read_only.cc). A DOMMatrix
444
+ // is read the same way: an own property, a patched getter or a Proxy may
445
+ // make its members disagree. The result is one shared array: read it before
446
+ // any other user code runs.
447
+ const MATRIX = [1, 0, 0, 1, 0, 0]
448
+ function matrix2DFromInit(init, prefix, full) {
449
+ if (init === undefined || init === null) {
450
+ MATRIX[0] = 1
451
+ MATRIX[1] = 0
452
+ MATRIX[2] = 0
453
+ MATRIX[3] = 1
454
+ MATRIX[4] = 0
455
+ MATRIX[5] = 0
456
+ return MATRIX
457
+ }
458
+ if (typeof init !== 'object' && typeof init !== 'function') {
459
+ throw contextTypeError(prefix, `The provided value is not of type '${full ? 'DOMMatrixInit' : 'DOMMatrix2DInit'}'.`)
460
+ }
461
+ const D2 = 'DOMMatrix2DInit'
462
+ const a = matrixMember(init.a, 'a', D2, prefix)
463
+ const b = matrixMember(init.b, 'b', D2, prefix)
464
+ const c = matrixMember(init.c, 'c', D2, prefix)
465
+ const d = matrixMember(init.d, 'd', D2, prefix)
466
+ const e = matrixMember(init.e, 'e', D2, prefix)
467
+ const f = matrixMember(init.f, 'f', D2, prefix)
468
+ const m11 = matrixMember(init.m11, 'm11', D2, prefix)
469
+ const m12 = matrixMember(init.m12, 'm12', D2, prefix)
470
+ const m21 = matrixMember(init.m21, 'm21', D2, prefix)
471
+ const m22 = matrixMember(init.m22, 'm22', D2, prefix)
472
+ const m41 = matrixMember(init.m41, 'm41', D2, prefix)
473
+ const m42 = matrixMember(init.m42, 'm42', D2, prefix)
474
+ let is3DIn2D = false
475
+ if (full) {
476
+ const D = 'DOMMatrixInit'
477
+ const is2D = init.is2D
478
+ const m13 = matrixMember(init.m13, 'm13', D, prefix)
479
+ const m14 = matrixMember(init.m14, 'm14', D, prefix)
480
+ const m23 = matrixMember(init.m23, 'm23', D, prefix)
481
+ const m24 = matrixMember(init.m24, 'm24', D, prefix)
482
+ const m31 = matrixMember(init.m31, 'm31', D, prefix)
483
+ const m32 = matrixMember(init.m32, 'm32', D, prefix)
484
+ const m33 = matrixMember(init.m33, 'm33', D, prefix)
485
+ const m34 = matrixMember(init.m34, 'm34', D, prefix)
486
+ const m43 = matrixMember(init.m43, 'm43', D, prefix)
487
+ const m44 = matrixMember(init.m44, 'm44', D, prefix)
488
+ // is2D is a boolean member: ToBoolean when present.
489
+ is3DIn2D =
490
+ is2D !== undefined &&
491
+ !!is2D &&
492
+ (notZero(m31) ||
493
+ notZero(m32) ||
494
+ notZero(m13) ||
495
+ notZero(m23) ||
496
+ notZero(m43) ||
497
+ notZero(m14) ||
498
+ notZero(m24) ||
499
+ notZero(m34) ||
500
+ notOne(m33) ||
501
+ notOne(m44))
502
+ }
503
+ if (
504
+ mismatch(a, m11) ||
505
+ mismatch(b, m12) ||
506
+ mismatch(c, m21) ||
507
+ mismatch(d, m22) ||
508
+ mismatch(e, m41) ||
509
+ mismatch(f, m42)
510
+ ) {
511
+ throw contextTypeError(prefix, 'Property mismatch on matrix initialization.')
512
+ }
513
+ if (is3DIn2D) {
514
+ throw contextTypeError(prefix, 'The is2D member is set to true but the input matrix is a 3d matrix.')
515
+ }
516
+ MATRIX[0] = m11 !== undefined ? m11 : a !== undefined ? a : 1
517
+ MATRIX[1] = m12 !== undefined ? m12 : b !== undefined ? b : 0
518
+ MATRIX[2] = m21 !== undefined ? m21 : c !== undefined ? c : 0
519
+ MATRIX[3] = m22 !== undefined ? m22 : d !== undefined ? d : 1
520
+ MATRIX[4] = m41 !== undefined ? m41 : e !== undefined ? e : 0
521
+ MATRIX[5] = m42 !== undefined ? m42 : f !== undefined ? f : 0
522
+ return MATRIX
523
+ }
524
+
525
+ // setTransform(): six or more arguments are six numbers, fewer a DOMMatrixInit
526
+ // (canvas_2d_recorder_context.idl), and an explicit undefined counts. The
527
+ // DOMMatrixInit is read above; the native method takes six numbers. It reads
528
+ // a first argument that is not a number as a DOMMatrixInit, the form a raw
529
+ // js-binding call may use, so ToNumber runs here for such an `a`.
530
+ const _setTransform = (ctxNative.setTransform ??= CanvasRenderingContext2D.prototype.setTransform)
531
+ // A cheap native method: on another receiver it throws 'Illegal invocation',
532
+ // which Chrome checks before it converts any argument.
533
+ const ctxReceiver = CanvasRenderingContext2D.prototype.isContextLost
534
+ const SET_TRANSFORM = "Failed to execute 'setTransform' on 'CanvasRenderingContext2D': "
535
+ CanvasRenderingContext2D.prototype.setTransform = function setTransform() {
536
+ if (arguments.length >= 6) {
537
+ let a = arguments[0]
538
+ if (typeof a !== 'number') {
539
+ ctxReceiver.call(this)
540
+ a = toNumber(a, SET_TRANSFORM)
541
+ }
542
+ return _setTransform.call(this, a, arguments[1], arguments[2], arguments[3], arguments[4], arguments[5])
543
+ }
544
+ // Past arguments.length, arguments[0] would read Object.prototype[0].
545
+ const init = arguments.length > 0 ? arguments[0] : undefined
546
+ if (init !== undefined && init !== null) ctxReceiver.call(this)
547
+ const m = matrix2DFromInit(init, SET_TRANSFORM, true)
548
+ return _setTransform.call(this, m[0], m[1], m[2], m[3], m[4], m[5])
549
+ }
550
+
551
+ // addPath(path, transform = {}): Chrome checks the receiver, the argument
552
+ // count and the path, then reads the DOMMatrix2DInit, read above. The native
553
+ // method takes six numbers after the path; anything else there is a
554
+ // DOMMatrix2DInit, which only a raw js-binding call passes. Without a
555
+ // transform (undefined or null is `{}`), a native method that takes only the
556
+ // path adds it as it is; Chrome's Path2D has no such method, so it comes off
557
+ // the prototype.
558
+ const pathNative = nativeMethods(Path2D.prototype)
559
+ const _addPath = (pathNative.addPath ??= Path2D.prototype.addPath)
560
+ const _addPathWithoutTransform = (pathNative._addPathWithoutTransform ??= Path2D.prototype._addPathWithoutTransform)
561
+ delete Path2D.prototype._addPathWithoutTransform
562
+ const ADD_PATH = "Failed to execute 'addPath' on 'Path2D': "
563
+ Path2D.prototype.addPath = function addPath() {
564
+ if (arguments.length < 1) {
565
+ argumentCountError(pathBrand, this, 'addPath', 'Path2D', 1, arguments.length)
566
+ }
567
+ const path = arguments[0]
568
+ // Past arguments.length, arguments[1] would read Object.prototype[1].
569
+ const transform = arguments.length > 1 ? arguments[1] : undefined
570
+ if (transform === undefined || transform === null) {
571
+ return _addPathWithoutTransform.call(this, path)
572
+ }
573
+ pathBrand.call(this)
574
+ try {
575
+ pathBrand.call(path)
576
+ } catch {
577
+ throw contextTypeError(ADD_PATH, "parameter 1 is not of type 'Path2D'.")
578
+ }
579
+ const m = matrix2DFromInit(transform, ADD_PATH, false)
580
+ return _addPath.call(this, path, m[0], m[1], m[2], m[3], m[4], m[5])
581
+ }
582
+ Object.defineProperty(Path2D.prototype.addPath, 'length', { value: 1 })
583
+
584
+ // createImageData(): WebIDL picks the overload from the argument count, and an
585
+ // explicit undefined counts: createImageData(imagedata, undefined) is the
586
+ // (sw, sh) form.
587
+ const _createImageData = (ctxNative.createImageData ??= CanvasRenderingContext2D.prototype.createImageData)
588
+
589
+ CanvasRenderingContext2D.prototype.createImageData = function createImageData() {
590
+ const count = arguments.length
591
+ // Past arguments.length, arguments[i] would read Object.prototype[i]: pass
592
+ // undefined there, as napi pads missing arguments.
593
+ return _createImageData.call(
594
+ this,
595
+ count > 0 ? arguments[0] : undefined,
596
+ count > 1 ? arguments[1] : undefined,
597
+ count > 2 ? arguments[2] : undefined,
598
+ count > 3 ? arguments[3] : undefined,
599
+ ARGUMENT_COUNTS[Math.min(count, 4)],
600
+ )
601
+ }
602
+ Object.defineProperty(CanvasRenderingContext2D.prototype.createImageData, 'length', { value: 1 })
603
+
604
+ // putImageData(imagedata, dx, dy) or (imagedata, dx, dy, dirtyX, dirtyY,
605
+ // dirtyWidth, dirtyHeight): as in Chrome, it needs 3 arguments; the native
606
+ // method picks the overload from the argument count (3 or 7).
607
+ const _putImageData = (ctxNative.putImageData ??= CanvasRenderingContext2D.prototype.putImageData)
608
+
609
+ CanvasRenderingContext2D.prototype.putImageData = function putImageData() {
610
+ const count = arguments.length
611
+ if (count < 3) {
612
+ argumentCountError(ctxBrand, this, 'putImageData', 'CanvasRenderingContext2D', 3, count)
613
+ }
614
+ // Past arguments.length, arguments[i] would read Object.prototype[i]: pass
615
+ // undefined there, as napi pads missing arguments.
616
+ return _putImageData.call(
617
+ this,
618
+ arguments[0],
619
+ arguments[1],
620
+ arguments[2],
621
+ count > 3 ? arguments[3] : undefined,
622
+ count > 4 ? arguments[4] : undefined,
623
+ count > 5 ? arguments[5] : undefined,
624
+ count > 6 ? arguments[6] : undefined,
625
+ ARGUMENT_COUNTS[Math.min(count, 7)],
626
+ )
627
+ }
628
+ Object.defineProperty(CanvasRenderingContext2D.prototype.putImageData, 'length', { value: 3 })
629
+
630
+ // createPattern(image, repetitionType): as in Chrome, both arguments are
631
+ // required, and the image is converted before the repetition, a
632
+ // [LegacyNullToEmptyString] DOMString (canvas_2d_recorder_context.idl), so
633
+ // null is '' and undefined is 'undefined'.
634
+ const _createPattern = (ctxNative.createPattern ??= CanvasRenderingContext2D.prototype.createPattern)
635
+
636
+ CanvasRenderingContext2D.prototype.createPattern = function createPattern(image, repetition) {
637
+ return _createPattern.call(this, image, repetition, ARGUMENT_COUNTS[Math.min(arguments.length, 4)])
638
+ }
639
+
640
+ // addColorStop(offset, color): both arguments are required. CanvasGradient
641
+ // has no other native method to check the receiver first, so the native
642
+ // method itself reads the real count from the marker after them.
643
+ const gradientNative = nativeMethods(CanvasGradient.prototype)
644
+ const _addColorStop = (gradientNative.addColorStop ??= CanvasGradient.prototype.addColorStop)
645
+ CanvasGradient.prototype.addColorStop = function addColorStop(offset, color) {
646
+ return _addColorStop.call(this, offset, color, ARGUMENT_COUNTS[Math.min(arguments.length, 2)])
647
+ }
648
+
649
+ // Workaround for webpack bundling issue with drawImage
650
+ // Store the original drawImage method
651
+ const _drawImage = (ctxNative.drawImage ??= CanvasRenderingContext2D.prototype.drawImage)
652
+
653
+ // Override drawImage to ensure proper type recognition in bundled environments.
654
+ // As in Chrome, it needs 3 arguments; the native method picks the overload
655
+ // from the argument count (3, 5 or 9).
656
+ CanvasRenderingContext2D.prototype.drawImage = function drawImage() {
657
+ if (arguments.length < 3) {
658
+ argumentCountError(ctxBrand, this, 'drawImage', 'CanvasRenderingContext2D', 3, arguments.length)
659
+ }
660
+ let image = arguments[0]
661
+ // If the image is a Canvas-like object but not recognized due to bundling,
662
+ // we need to ensure it's properly identified
663
+ if (image && typeof image === 'object') {
664
+ // First check if it's a wrapped canvas object
665
+ if (image.canvas instanceof CanvasElement || image.canvas instanceof SVGCanvas) {
666
+ image = image.canvas
667
+ } else if (image._canvas instanceof CanvasElement || image._canvas instanceof SVGCanvas) {
668
+ image = image._canvas
669
+ }
670
+ // Then check if it's a Canvas-like object by checking for getContext method
671
+ else if (typeof image.getContext === 'function' && image.width && image.height) {
672
+ // If it has canvas properties but isn't recognized as CanvasElement or SVGCanvas,
673
+ // try to correct the prototype chain
674
+ if (!(image instanceof CanvasElement) && !(image instanceof SVGCanvas)) {
675
+ // Try to create a proper CanvasElement from the canvas-like object
676
+ // This helps when webpack has transformed the prototype chain
677
+ Object.setPrototypeOf(image, CanvasElement.prototype)
678
+ }
679
+ }
680
+ }
681
+
682
+ // Call the original drawImage with the potentially corrected image
683
+ const count = Math.min(arguments.length, 9)
684
+ return _drawImage.call(
685
+ this,
686
+ image,
687
+ arguments[1],
688
+ arguments[2],
689
+ count > 3 ? arguments[3] : undefined,
690
+ count > 4 ? arguments[4] : undefined,
691
+ count > 5 ? arguments[5] : undefined,
692
+ count > 6 ? arguments[6] : undefined,
693
+ count > 7 ? arguments[7] : undefined,
694
+ count > 8 ? arguments[8] : undefined,
695
+ argumentCount(count, arguments[count - 1]),
696
+ )
697
+ }
698
+ Object.defineProperty(CanvasRenderingContext2D.prototype.drawImage, 'length', { value: 3 })
699
+
700
+ function createCanvas(width, height, flag) {
701
+ const isSvgBackend = typeof flag !== 'undefined'
702
+ return isSvgBackend ? new SVGCanvas(width, height, flag) : new CanvasElement(width, height)
703
+ }
704
+
705
+ class Canvas {
706
+ constructor(width, height, flag) {
707
+ return createCanvas(width, height, flag)
708
+ }
709
+
710
+ static [Symbol.hasInstance](instance) {
711
+ return instance instanceof CanvasElement || instance instanceof SVGCanvas
712
+ }
713
+ }
714
+
715
+ if (!process.env.DISABLE_SYSTEM_FONTS_LOAD) {
716
+ // Installed fonts and the per-user font folders: FreeType by default;
717
+ // CoreText's on macOS after setTextRenderer('system'). On macOS that is
718
+ // /Library/Fonts (all users) and ~/Library/Fonts, after
719
+ // /System/Library/Fonts, as CoreText lists them.
720
+ const homedirPath = homedir()
721
+ const userFontDirs =
722
+ {
723
+ win32: [join(homedirPath, 'AppData', 'Local', 'Microsoft', 'Windows', 'Fonts')],
724
+ darwin: ['/Library/Fonts', join(homedirPath, 'Library', 'Fonts')],
725
+ linux: [join('usr', 'local', 'share', 'fonts'), join(homedirPath, '.fonts')],
726
+ }[platform()] ?? []
727
+ GlobalFonts.enableSystemFonts(userFontDirs)
728
+ }
729
+
730
+ module.exports = {
731
+ clearAllCache,
732
+ setTextRenderer,
733
+ getTextRenderer,
734
+ Canvas,
735
+ createCanvas,
736
+ Path2D,
737
+ ImageData,
738
+ Image,
739
+ PathOp,
740
+ FillType,
741
+ StrokeCap,
742
+ StrokeJoin,
743
+ SvgExportFlag,
744
+ PngFilter,
745
+ GlobalFonts: GlobalFonts,
746
+ convertSVGTextToPath,
747
+ DOMPoint,
748
+ DOMMatrix,
749
+ DOMRect,
750
+ loadImage,
751
+ FontKey,
752
+ // Export these for better webpack compatibility
753
+ CanvasElement,
754
+ SVGCanvas,
755
+ PDFDocument: PdfDocument,
756
+ // GIF encoding
757
+ GifEncoder,
758
+ GifDisposal,
759
+ // Lottie animation
760
+ LottieAnimation,
761
+ }