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