imagescript 4.0.0-rc.5 → 4.0.0

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.
@@ -1,14 +1,8 @@
1
- import { oneOf, checkNumber } from "./util/options.js";
1
+ import { oneOf, pixels } from "./util/options.js";
2
2
  const HORIZONTAL = ['left', 'center', 'right'];
3
3
  const VERTICAL = ['top', 'middle', 'bottom'];
4
4
  function boxSide(value, name) {
5
- if (value === undefined)
6
- return undefined;
7
- checkNumber(value, name);
8
- const side = Math.floor(value);
9
- if (!(side >= 1) || !Number.isFinite(side))
10
- throw new RangeError(`${name} must be a finite number from 1, not ${value}`);
11
- return side;
5
+ return value === undefined ? undefined : pixels(value, name);
12
6
  }
13
7
  export function textLayout(options) {
14
8
  const { width, height, wrapStyle, verticalAlign, horizontalAlign } = options;
@@ -2,7 +2,7 @@ export let littleEndian = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
2
2
  export function useLittleEndian(value) {
3
3
  littleEndian = value;
4
4
  }
5
- const words = (bitmap) => new Int32Array(bitmap.buffer, bitmap.byteOffset, bitmap.length >> 2);
5
+ const words = (bitmap) => new Int32Array(bitmap.buffer, bitmap.byteOffset, bitmap.length >>> 2);
6
6
  export function isOpaque(bitmap) {
7
7
  const pixels = words(bitmap);
8
8
  let all = -1;
@@ -8,11 +8,21 @@ export declare class LimitError extends RangeError {
8
8
  }
9
9
  /** The default of the decode options' maxPixels: 16383 squared (like sharp's limitInputPixels) */
10
10
  export declare const MAX_PIXELS: number;
11
+ /**
12
+ * What a frame of an animation counts at least: a frame takes memory however small it is (200000 frames of 1x1, a
13
+ * 4.6 MB GIF, took 720 MB), so the limit bounds the memory of tiny frames too
14
+ */
15
+ export declare const FRAME_PIXELS = 1024;
11
16
  /**
12
17
  * Throws if decoding an image of the given size would exceed the limit, before anything that size is allocated
13
- * @param count the number of such images (frames)
18
+ * @param count the number of such images (frames of an animation, each counting at least {@link FRAME_PIXELS})
14
19
  */
15
20
  export declare function checkPixels(width: number, height: number, limit: number, count?: number): void;
21
+ /**
22
+ * Throws a RangeError for an image that a format can't store: one message for all encoders, naming the format, what it
23
+ * allows and the size it got
24
+ */
25
+ export declare function checkFormatSize(format: string, width: number, height: number, max: number): void;
16
26
  /**
17
27
  * Throws a {@link LimitError} naming the operation if an image it makes would have more pixels than an image can
18
28
  * (the default `maxPixels` of the decoders): a shadow or outline of a huge size or offset would only fail allocating
@@ -25,11 +35,14 @@ export declare const MAX_BYTES_PER_PIXEL = 8;
25
35
  * samples per pixel
26
36
  */
27
37
  export declare function checkBytes(bytes: number, limit: number): void;
28
- /** Counts the pixels of decoded frames against a limit */
38
+ /** Counts the pixels of decoded frames against a limit, each frame at least `floor` ({@link FRAME_PIXELS} for animations) */
29
39
  export declare class PixelBudget {
40
+ private readonly floor;
30
41
  private left;
31
42
  private limit;
32
- constructor(limit: number);
43
+ private count;
44
+ private first;
45
+ constructor(limit: number, floor?: number);
33
46
  /** Throws if another frame of the given size would exceed the limit */
34
47
  take(width: number, height: number): void;
35
48
  }
@@ -2,9 +2,15 @@ export class LimitError extends RangeError {
2
2
  name = 'LimitError';
3
3
  }
4
4
  export const MAX_PIXELS = 0x3fff * 0x3fff;
5
+ export const FRAME_PIXELS = 1024;
5
6
  export function checkPixels(width, height, limit, count = 1) {
6
- if (!(width * height * count <= limit))
7
- throw new LimitError(`Image too large: ${count > 1 ? `${count} frames of ` : ''}${width}x${height} pixels exceed the limit of ${limit} (the decode options' maxPixels)`);
7
+ const floor = count > 1 && width * height < FRAME_PIXELS;
8
+ if (!((floor ? FRAME_PIXELS : width * height) * count <= limit))
9
+ throw new LimitError(`Image too large: ${count > 1 ? `${count} frames of ` : ''}${width}x${height} pixels exceed the limit of ${limit}${floor ? ` (each frame counts at least ${FRAME_PIXELS})` : ''} (the decode options' maxPixels)`);
10
+ }
11
+ export function checkFormatSize(format, width, height, max) {
12
+ if (!(width <= max && height <= max))
13
+ throw new RangeError(`${format}: images can be at most ${max} pixels wide and high, not ${width}x${height}`);
8
14
  }
9
15
  export function checkGrowth(width, height, what) {
10
16
  if (!(width * height <= MAX_PIXELS))
@@ -16,15 +22,24 @@ export function checkBytes(bytes, limit) {
16
22
  throw new LimitError(`Image too large: ${bytes} bytes of samples exceed what the limit of ${limit} pixels allows (the decode options' maxPixels)`);
17
23
  }
18
24
  export class PixelBudget {
25
+ floor;
19
26
  left;
20
27
  limit;
21
- constructor(limit) {
28
+ count = 0;
29
+ first = 0;
30
+ constructor(limit, floor = 0) {
31
+ this.floor = floor;
22
32
  this.limit = this.left = limit;
23
33
  }
24
34
  take(width, height) {
25
- this.left -= width * height;
35
+ const pixels = width * height;
36
+ if (++this.count === 1)
37
+ this.first = pixels;
38
+ else if (this.count === 2)
39
+ this.left -= Math.max(0, this.floor - this.first);
40
+ this.left -= this.count === 1 ? pixels : Math.max(pixels, this.floor);
26
41
  if (!(this.left >= 0))
27
- throw new LimitError(`Image too large: its frames exceed the limit of ${this.limit} pixels (the decode options' maxPixels)`);
42
+ throw new LimitError(`Image too large: ${this.count} frames exceed the limit of ${this.limit} pixels${this.floor ? `, at least ${this.floor} each` : ''} (the decode options' maxPixels)`);
28
43
  }
29
44
  }
30
45
  export async function decoding(decode) {
@@ -1,5 +1,7 @@
1
1
  /** Data accepted wherever binary input is expected */
2
2
  export type BinaryData = ArrayBuffer | ArrayBufferView;
3
+ /** Whether a value is binary data (an ArrayBuffer, a SharedArrayBuffer or a view), also one of another realm */
4
+ export declare function isBinaryData(value: unknown): value is BinaryData;
3
5
  /**
4
6
  * Returns a Uint8Array view of the given buffer without copying
5
7
  */
package/dist/util/mem.js CHANGED
@@ -1,13 +1,33 @@
1
+ import { shown } from "./options.js";
2
+ const byteLengthOf = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength').get;
3
+ const sharedByteLengthOf = typeof SharedArrayBuffer === 'undefined' ? null : Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, 'byteLength').get;
4
+ function isBuffer(value) {
5
+ if (typeof value !== 'object' || value === null)
6
+ return false;
7
+ for (const getter of [byteLengthOf, sharedByteLengthOf]) {
8
+ try {
9
+ getter?.call(value);
10
+ if (getter)
11
+ return true;
12
+ }
13
+ catch { }
14
+ }
15
+ return false;
16
+ }
17
+ export function isBinaryData(value) {
18
+ return ArrayBuffer.isView(value) || isBuffer(value);
19
+ }
1
20
  export function view(buffer) {
21
+ const data = ArrayBuffer.isView(buffer) ? buffer.buffer : buffer;
22
+ if (isBuffer(data) && data.detached === true)
23
+ throw new TypeError('Binary data has to be readable, not of a detached ArrayBuffer (one transferred, to a worker for one)');
2
24
  if (buffer instanceof Uint8Array && buffer.constructor === Uint8Array)
3
25
  return buffer;
4
- if (buffer instanceof ArrayBuffer)
5
- return new Uint8Array(buffer);
6
26
  if (ArrayBuffer.isView(buffer))
7
27
  return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
8
- if (typeof SharedArrayBuffer !== 'undefined' && buffer instanceof SharedArrayBuffer)
28
+ if (isBuffer(buffer))
9
29
  return new Uint8Array(buffer);
10
- throw new TypeError(`Binary data has to be an ArrayBuffer or a typed array like Uint8Array, not ${buffer === null ? 'null' : typeof buffer}`);
30
+ throw new TypeError(`Binary data has to be an ArrayBuffer or a typed array like Uint8Array, not ${shown(buffer)}`);
11
31
  }
12
32
  export function concat(parts) {
13
33
  let length = 0;
@@ -1,3 +1,4 @@
1
+ import { allocate } from "./options.js";
1
2
  const ALPHA = new Int32Array(new Uint8Array([0, 0, 0, 255]).buffer)[0];
2
3
  const ALPHA_COST = 4 / 3;
3
4
  export class Optimizer {
@@ -19,8 +20,8 @@ export class Optimizer {
19
20
  this.height = height;
20
21
  this.options = options;
21
22
  const size = width * height * 4;
22
- this.canvas = new Uint8Array(size);
23
- this.shown = new Uint8Array(size);
23
+ this.canvas = allocate(width, height, () => new Uint8Array(size));
24
+ this.shown = allocate(width, height, () => new Uint8Array(size));
24
25
  this.state = { canvas32: new Int32Array(this.canvas.buffer), shown32: new Int32Array(this.shown.buffer), width, replace: options.replace, tolerance: options.tolerance };
25
26
  this.cleared = { x: 0, y: 0, width, height };
26
27
  }
@@ -130,7 +131,7 @@ export class Compositor {
130
131
  constructor(width, height) {
131
132
  this.width = width;
132
133
  this.height = height;
133
- this.canvas = new Uint8Array(width * height * 4);
134
+ this.canvas = allocate(width, height, () => new Uint8Array(width * height * 4));
134
135
  }
135
136
  push(f) {
136
137
  const { canvas, width, height } = this;
@@ -3,8 +3,10 @@ export function shown(value) {
3
3
  return 'null';
4
4
  if (Array.isArray(value))
5
5
  return 'an array';
6
- if (typeof value === 'string')
7
- return `'${value}'`;
6
+ if (typeof value === 'string') {
7
+ const characters = Array.from(value.length > 80 ? value.slice(0, 82) : value);
8
+ return characters.length > 40 ? `'${characters.slice(0, 40).join('')}...'` : `'${value}'`;
9
+ }
8
10
  if (typeof value === 'number')
9
11
  return String(value);
10
12
  if (typeof value === 'object')
@@ -16,7 +18,7 @@ export function isOptions(value) {
16
18
  }
17
19
  export function checkOptions(value, usage) {
18
20
  if (value !== undefined && !isOptions(value))
19
- throw new TypeError(`${usage.split('(')[0]}() takes an options object, like ${usage}, not ${shown(value)}`);
21
+ throw new TypeError(`${usage.split('(')[0].replace(/^new /, '').replace(/^[a-z]\w*\./, '')}() takes an options object, like ${usage}, not ${shown(value)}`);
20
22
  }
21
23
  export function oneOf(value, allowed, name) {
22
24
  if (typeof value !== 'string' || !allowed.includes(value)) {
@@ -38,9 +40,32 @@ export function checkNumber(value, name) {
38
40
  export function finite(value, name) {
39
41
  checkNumber(value, name);
40
42
  if (!Number.isFinite(value))
41
- throw new RangeError(`Invalid ${name}: ${value}`);
43
+ throw new RangeError(`${name} must be finite, not ${value}`);
44
+ return value;
45
+ }
46
+ export function notNaN(value, name) {
47
+ checkNumber(value, name);
48
+ if (Number.isNaN(value))
49
+ throw new RangeError(`${name} must be a number, not NaN`);
50
+ return value;
51
+ }
52
+ export function atLeast(value, min, name) {
53
+ finite(value, name);
54
+ if (value < min)
55
+ throw new RangeError(`${name} must be ${min} or more, not ${value}`);
42
56
  return value;
43
57
  }
58
+ export function canvasSize(width, height) {
59
+ return [pixels(width, 'width'), pixels(height, 'height')];
60
+ }
61
+ export function allocate(width, height, make) {
62
+ try {
63
+ return make();
64
+ }
65
+ catch (err) {
66
+ throw new RangeError(`An image of ${width}x${height} pixels (${BigInt(width) * BigInt(height) * 4n} bytes) can't be allocated`, { cause: err });
67
+ }
68
+ }
44
69
  export function loopCount(value, name = 'loop count') {
45
70
  if (typeof value !== 'number')
46
71
  throw new TypeError(`${name} must be a number (Infinity or an integer from 0), not ${shown(value)}`);
@@ -65,12 +90,51 @@ export function fitDuration(duration, format) {
65
90
  throw new RangeError(`refuse frame durations that don't fit the format: ${format} frames last up to ${max} ms, not ${duration}`);
66
91
  return duration;
67
92
  }
93
+ export function instance(value, types, name) {
94
+ if (!types.some(type => value instanceof type))
95
+ throw new TypeError(`${name} must be ${types.map(type => `${/^[AEIOU]/.test(type.name) ? 'an' : 'a'} ${type.name}`).join(' or ')}, not ${shown(value)}`);
96
+ }
97
+ export function scaleFactor(factor, width, height) {
98
+ positive(factor, 'scale factor');
99
+ const largest = Math.floor(0x7fffffff / Math.max(width, height));
100
+ if (Math.max(width, height) * factor >= 0x7fffffff + 0.5)
101
+ throw new RangeError(`scale factor must be at most ${largest} for an image of ${width}x${height}, not ${factor}`);
102
+ return factor;
103
+ }
68
104
  export function nonNegative(value, name) {
69
105
  finite(value, name);
70
106
  if (value < 0)
71
107
  throw new RangeError(`${name} must be 0 or more, not ${value}`);
72
108
  return value;
73
109
  }
110
+ export function byte(value, name) {
111
+ finite(value, name);
112
+ const rounded = Math.round(value);
113
+ if (rounded < 0 || rounded > 255)
114
+ throw new RangeError(`${name} must be 0-255, not ${value}`);
115
+ return rounded;
116
+ }
117
+ export function pixels(value, name) {
118
+ finite(value, name);
119
+ const whole = Math.trunc(value);
120
+ if (whole < 1 || whole > 0x7fffffff)
121
+ throw new RangeError(`${name} must be 1-2147483647, not ${value}`);
122
+ return whole;
123
+ }
124
+ export function coordinate(value, last, name) {
125
+ if (!(value >= 0 && value <= last))
126
+ throw new RangeError(`${name} must be 0-${last}, not ${value}`);
127
+ return value;
128
+ }
129
+ export function cropBounds(width, height, x, y, regionWidth, regionHeight, what) {
130
+ const rx = Math.trunc(finite(x, 'x')), ry = Math.trunc(finite(y, 'y'));
131
+ const rw = Math.trunc(finite(regionWidth, 'width')), rh = Math.trunc(finite(regionHeight, 'height'));
132
+ const left = Math.max(0, rx), top = Math.max(0, ry);
133
+ const right = Math.min(width, rx + rw), bottom = Math.min(height, ry + rh);
134
+ if (right <= left || bottom <= top)
135
+ throw new RangeError(`crop region must be partly inside the ${width}x${height} ${what}, not ${regionWidth}x${regionHeight} at ${x},${y}`);
136
+ return [left, top, right - left, bottom - top];
137
+ }
74
138
  export function unitInterval(value, name) {
75
139
  finite(value, name);
76
140
  if (value < 0 || value > 1)
@@ -104,11 +168,8 @@ export function gainMapEmbed(value) {
104
168
  throw new TypeError(`gainMap must be true, false or an options object like { quality: 90, scale: 0.5 }, not ${shown(value)}`);
105
169
  const { quality: q, scale } = value;
106
170
  const options = {};
107
- if (q !== undefined) {
171
+ if (q !== undefined)
108
172
  options.quality = quality(q, 'gain map quality');
109
- if (options.quality < 1)
110
- throw new RangeError(`gain map quality must be 1-100, not ${options.quality}`);
111
- }
112
173
  if (scale !== undefined)
113
174
  options.scale = gainMapScale(scale);
114
175
  return options;
@@ -139,6 +200,6 @@ export function compressionLevel(value) {
139
200
  export function color(value, name = 'color') {
140
201
  const number = finite(value, name);
141
202
  if (!Number.isInteger(number) || number < -0x80000000 || number > 0xffffffff)
142
- throw new RangeError(`Invalid ${name}: ${value} (a color is an integer like 0xrrggbbaa)`);
203
+ throw new RangeError(`${name} must be an integer from -2147483648 to 4294967295, like 0xrrggbbaa, not ${value}`);
143
204
  return number >>> 0;
144
205
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "imagescript",
3
- "version": "4.0.0-rc.5",
3
+ "version": "4.0.0",
4
4
  "description": "Pure TypeScript image processing that runs everywhere",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",