@crabcrop/url 0.9.10 → 0.10.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.
@@ -9,20 +9,24 @@
9
9
  * pipeline and the equivalent hand-written string produce
10
10
  * byte-identical URLs. Validation throws at build time, like
11
11
  * `buildSrcSet` does for widths: a value the server would 400
12
- * never gets signed.
12
+ * never gets signed. The closed sets (formats, aligns, anchors,
13
+ * modes, factors, shapes) and the class-name checks come from
14
+ * the explainer (issue #482), so the builders and the
15
+ * explainer read one copy of them. The numeric bounds are
16
+ * still written on each side: the builders check numbers, the
17
+ * explainer checks their spellings.
13
18
  */
14
- const PER_FORMAT_QUALITY_FORMATS = [
15
- "avif",
16
- "gif",
17
- "jpeg",
18
- "jxl",
19
- "png",
20
- "webp",
21
- ];
22
- const MAX_DIMENSION = 16383;
19
+ import { BLEND_MODES, classFoldKey, CROP_ALIGNS, CURVE_CHANNELS, DPR_FACTORS, FLIP_AXES, IMAGE_FORMATS, isClassName, isOneOf, JPEG_SUBSAMPLINGS, MASK_SHAPES, MAX_OBJECTS_CLASSES, QUALITY_FORMATS, STUDIO_BACKDROPS, STUDIO_MODES, STUDIO_SHADOWS, TEXT_ANCHORS, UPSCALE_FACTORS, } from "./explain.js";
20
+ import { MAX_DIMENSION } from "./limits.js";
23
21
  function fail(what, value, rule) {
24
22
  throw new Error(`${what} must be ${rule}, got ${JSON.stringify(value)}`);
25
23
  }
24
+ /** A closed set spelled for an error message: `2 or 4`, `1, 1.5, 2, or 3`. */
25
+ function eitherOf(values, quote = false) {
26
+ const words = values.map((v) => (quote ? `"${v}"` : String(v)));
27
+ const last = words.pop();
28
+ return words.length === 1 ? `${words[0]} or ${last}` : `${words.join(", ")}, or ${last}`;
29
+ }
26
30
  function intIn(what, value, min, max) {
27
31
  if (!Number.isSafeInteger(value) || value < min || value > max) {
28
32
  fail(what, value, `an integer from ${min} to ${max}`);
@@ -36,19 +40,92 @@ function floatIn(what, value, min, max) {
36
40
  return value;
37
41
  }
38
42
  function positiveFloat(what, value) {
39
- if (!Number.isFinite(value) || value <= 0) {
43
+ // The server reads a 32-bit float: past its range the value
44
+ // is infinite there, and a positive value below it is zero.
45
+ const f32 = Math.fround(value);
46
+ if (!Number.isFinite(f32) || f32 <= 0) {
40
47
  fail(what, value, "a positive number");
41
48
  }
42
49
  return value;
43
50
  }
51
+ /** Spell `digits * 10^exponent` in plain decimal, no exponent. */
52
+ function plainDecimal(digits, exponent) {
53
+ const text = digits.toString();
54
+ if (exponent >= 0)
55
+ return text + "0".repeat(exponent);
56
+ const padded = text.padStart(1 - exponent, "0");
57
+ const whole = padded.slice(0, padded.length + exponent);
58
+ const fraction = padded.slice(padded.length + exponent).replace(/0+$/, "");
59
+ return fraction ? `${whole}.${fraction}` : whole;
60
+ }
44
61
  /**
45
- * The canonical number spelling: integers without a fraction,
62
+ * The canonical spelling of a 32-bit float parameter (issue
63
+ * #472). The server parses these arguments as `f32` and
64
+ * prints them back as Rust's float `Display` does: the
65
+ * shortest decimal that reads back as the same f32 (the
66
+ * closer of two, a tie going up), never an exponent. So the
67
+ * double `0.1 + 0.2` spells `0.3`, the form the server keys
68
+ * its cache on, not its 17-digit double spelling. The search
69
+ * is exact, on the float's binary value in BigInt
70
+ * arithmetic, so no double rounding can pick a spelling Rust
71
+ * would not.
72
+ */
73
+ function num(value) {
74
+ const f = Math.fround(value);
75
+ if (!Number.isFinite(f)) {
76
+ throw new Error(`${value} is outside the 32-bit float range the server parses`);
77
+ }
78
+ if (f === 0)
79
+ return "0";
80
+ const view = new DataView(new ArrayBuffer(4));
81
+ view.setFloat32(0, Math.abs(f));
82
+ const bits = view.getUint32(0);
83
+ const biased = bits >>> 23;
84
+ const fraction = bits & 0x7fffff;
85
+ const mantissa = BigInt(biased === 0 ? fraction : fraction | 0x800000);
86
+ // In units of a quarter ulp, 2^unit: the float sits at
87
+ // 4 * mantissa and reads back from any decimal strictly
88
+ // between the midpoints to its neighbors, which lie half as
89
+ // far below at a power of two (the binade below is finer).
90
+ // A decimal exactly on a midpoint rounds to the even
91
+ // mantissa, so the ends count only for an even one.
92
+ const unit = (biased === 0 ? 1 : biased) - 152;
93
+ const center = 4n * mantissa;
94
+ const low = fraction === 0 && biased > 1 ? center - 1n : center - 2n;
95
+ const high = center + 2n;
96
+ const inclusive = mantissa % 2n === 0n;
97
+ const sign = f < 0 ? "-" : "";
98
+ // From one decade above the value down, the first decimal
99
+ // exponent with a candidate in the interval gives the
100
+ // shortest spelling. Only the two neighbors of the value at
101
+ // that exponent can qualify, and an f32 needs at most nine
102
+ // significant digits, so the loop is short.
103
+ for (let k = Math.floor(Math.log10(Math.abs(f))) + 2;; k--) {
104
+ // Compare digits * 10^k with units * 2^unit as integers.
105
+ const binary = (unit > 0 ? 2n ** BigInt(unit) : 1n) * (k < 0 ? 10n ** BigInt(-k) : 1n);
106
+ const step = (unit < 0 ? 2n ** BigInt(-unit) : 1n) * (k > 0 ? 10n ** BigInt(k) : 1n);
107
+ const at = center * binary;
108
+ const below = (at / step) * step;
109
+ const above = below + step;
110
+ const lowEnd = low * binary;
111
+ const highEnd = high * binary;
112
+ const downFits = inclusive ? below >= lowEnd : below > lowEnd;
113
+ const upFits = inclusive ? above <= highEnd : above < highEnd;
114
+ if (downFits || upFits) {
115
+ const down = downFits && (!upFits || 2n * (at - below) < step);
116
+ return sign + plainDecimal((down ? below : above) / step, k);
117
+ }
118
+ }
119
+ }
120
+ /**
121
+ * The canonical spelling of a 64-bit float parameter (the
122
+ * convolution kernel's values): integers without a fraction,
46
123
  * other values in plain decimal (the grammar takes no
47
124
  * exponent forms). JavaScript's shortest round-trip spelling
48
125
  * agrees with the server's for the magnitudes the grammar
49
126
  * allows; exponent spellings are expanded to plain decimal.
50
127
  */
51
- function num(value) {
128
+ function kernelNum(value) {
52
129
  if (Number.isSafeInteger(value))
53
130
  return String(value);
54
131
  const s = String(value);
@@ -97,33 +174,13 @@ function encodeArg(text) {
97
174
  }
98
175
  function className(what, name) {
99
176
  const trimmed = name.trim();
100
- // The server's bound is on UTF-8 bytes, not UTF-16 code
101
- // units: a name of multibyte characters can pass a
102
- // length check here and still be rejected there, so
103
- // measure the encoded form, as the explainer does.
104
- const bytes = new TextEncoder().encode(trimmed).length;
105
- if (bytes < 1 || bytes > 64 || !/^[\p{L}\p{N} _.\-/]+$/u.test(trimmed)) {
177
+ if (!isClassName(trimmed)) {
106
178
  fail(what, name, "1 to 64 UTF-8 bytes of letters, digits, space, `_`, `.`, `-`, `/`");
107
179
  }
108
- return encodeArg(name);
180
+ // The server trims the name before it validates and keys
181
+ // on it, so the trimmed name is the canonical one.
182
+ return encodeArg(trimmed);
109
183
  }
110
- const CROP_ALIGNS = ["center", "smart", "face", "top", "bottom", "left", "right", "top-left", "top-right", "bottom-left", "bottom-right"];
111
- const ANCHORS = [
112
- "top-left",
113
- "top-center",
114
- "top-right",
115
- "center-left",
116
- "center",
117
- "center-right",
118
- "bottom-left",
119
- "bottom-center",
120
- "bottom-right",
121
- ];
122
- const BLEND_MODES = ["normal", "multiply", "screen", "overlay"];
123
- const CURVE_CHANNELS = ["rgb", "r", "g", "b"];
124
- const STUDIO_MODES = ["product", "scene"];
125
- const STUDIO_SHADOWS = ["soft", "strong", "none"];
126
- const IMAGE_FORMATS = ["jpeg", "jpg", "png", "webp", "jxl", "avif", "gif", "mp4", "webm"];
127
184
  /** Operation segments, one typed call per segment kind. */
128
185
  export const ops = {
129
186
  /** `300x200`; each side a Dimension (0 proportional, negative flips). */
@@ -149,7 +206,7 @@ export const ops = {
149
206
  },
150
207
  /** `crop:300x200` or `crop:300x200:smart`; an exact pixel box. */
151
208
  crop(width, height, align = "center") {
152
- if (!CROP_ALIGNS.includes(align)) {
209
+ if (!isOneOf(CROP_ALIGNS, align)) {
153
210
  fail("crop align", align, `one of ${CROP_ALIGNS.join(", ")}`);
154
211
  }
155
212
  const box = pixelBox("crop", width, height);
@@ -163,24 +220,35 @@ export const ops = {
163
220
  * Needs a detection model configured on the server; when
164
221
  * none of the classes is detected the render falls back
165
222
  * to the plain center crop of the same size. Duplicate
166
- * classes (case-insensitive) are spelled once, as the
167
- * server's canonical form spells them.
223
+ * classes (ASCII case-insensitive, as the server compares
224
+ * them: `E` repeats `e`, `É` does not repeat `é`) are
225
+ * spelled once, as the server's canonical form spells
226
+ * them; at most 32 distinct classes, and a 33rd throws,
227
+ * since the server rejects it with `invalid_crop`.
168
228
  */
169
229
  cropObjects(width, height, classes, scale = 1) {
170
- if (!Array.isArray(classes) || classes.length < 1 || classes.length > 32) {
171
- fail("crop objects classes", classes, "an array of 1 to 32 class names");
230
+ if (!Array.isArray(classes) || classes.length < 1) {
231
+ fail("crop objects classes", classes, "an array of 1 to 32 distinct class names");
172
232
  }
233
+ // The cap counts distinct names, as the server's parser
234
+ // does (issue #408): repeats fold first and cost nothing.
173
235
  const seen = new Set();
174
236
  const names = [];
175
237
  for (const name of classes) {
176
238
  const encoded = className("crop objects class", name);
177
- const key = typeof name === "string" ? name.trim().toLowerCase() : "";
239
+ const key = classFoldKey(name.trim());
178
240
  if (!seen.has(key)) {
241
+ if (names.length === MAX_OBJECTS_CLASSES) {
242
+ fail("crop objects classes", classes, "an array of 1 to 32 distinct class names");
243
+ }
179
244
  seen.add(key);
180
245
  names.push(encoded);
181
246
  }
182
247
  }
183
- if (!Number.isFinite(scale) || scale <= 0 || scale > 100) {
248
+ // Checked as the f32 the server reads (as are zoom, blur
249
+ // and gamma below): a positive double that rounds to f32
250
+ // zero would otherwise be spelled `0`, which it refuses.
251
+ if (!Number.isFinite(scale) || Math.fround(scale) <= 0 || scale > 100) {
184
252
  fail("crop objects scale", scale, "a number above 0 and at most 100");
185
253
  }
186
254
  const box = pixelBox("crop", width, height);
@@ -216,7 +284,7 @@ export const ops = {
216
284
  }
217
285
  return v;
218
286
  };
219
- if (!Number.isFinite(zoom) || zoom <= 0 || zoom > 100) {
287
+ if (!Number.isFinite(zoom) || Math.fround(zoom) <= 0 || zoom > 100) {
220
288
  fail("focalpoint zoom", zoom, "a number above 0 and at most 100");
221
289
  }
222
290
  return `focalpoint:${num(frac("focalpoint x", x))}x${num(frac("focalpoint y", y))}:${num(zoom)}`;
@@ -308,7 +376,8 @@ export const filter = {
308
376
  },
309
377
  /** Gaussian blur by sigma: positive, at most the server's 512 cap. */
310
378
  blur(sigma) {
311
- if (!Number.isFinite(sigma) || sigma <= 0 || sigma > 512) {
379
+ // The server also refuses a subnormal f32 sigma.
380
+ if (!Number.isFinite(sigma) || Math.fround(sigma) < 2 ** -126 || sigma > 512) {
312
381
  fail("blur sigma", sigma, "a positive number up to 512");
313
382
  }
314
383
  return `blur(${num(sigma)})`;
@@ -327,7 +396,7 @@ export const filter = {
327
396
  },
328
397
  /** Gamma correction divisor: 0 < g <= 10 (1 unchanged; above 1 brightens midtones). */
329
398
  gamma(value) {
330
- if (!Number.isFinite(value) || value <= 0 || value > 10) {
399
+ if (!Number.isFinite(value) || Math.fround(value) <= 0 || value > 10) {
331
400
  fail("gamma", value, "a number above 0 and at most 10");
332
401
  }
333
402
  return `gamma(${num(value)})`;
@@ -367,7 +436,7 @@ export const filter = {
367
436
  * nearest end value.
368
437
  */
369
438
  curve(channel, points) {
370
- if (!CURVE_CHANNELS.includes(channel)) {
439
+ if (!isOneOf(CURVE_CHANNELS, channel)) {
371
440
  fail("curve channel", channel, `one of ${CURVE_CHANNELS.join(", ")}`);
372
441
  }
373
442
  if (points.length < 2 || points.length > 16) {
@@ -401,7 +470,7 @@ export const filter = {
401
470
  }
402
471
  for (const v of values) {
403
472
  floatIn("convolution kernel value", v, -1024, 1024);
404
- if (!/^-?\d+(\.\d+)?$/.test(num(v))) {
473
+ if (!/^-?\d+(\.\d+)?$/.test(kernelNum(v))) {
405
474
  fail("convolution kernel value", v, "a plain decimal (the grammar takes no exponent forms)");
406
475
  }
407
476
  }
@@ -412,7 +481,7 @@ export const filter = {
412
481
  fail("convolution normalize", normalize, "a boolean or 0/1");
413
482
  }
414
483
  const flag = normalize === true || normalize === 1 ? 1 : 0;
415
- return `convolution(${values.map(num).join(",")},${flag})`;
484
+ return `convolution(${values.map(kernelNum).join(",")},${flag})`;
416
485
  },
417
486
  /**
418
487
  * Film grain: one noise value per pixel, added equally
@@ -469,8 +538,8 @@ export const filter = {
469
538
  parts.push(fallback === "auto" ? "auto" : String(intIn("quality", fallback, 1, 100)));
470
539
  }
471
540
  for (const name of names.sort()) {
472
- if (!PER_FORMAT_QUALITY_FORMATS.includes(name)) {
473
- fail("quality", name, `one of ${PER_FORMAT_QUALITY_FORMATS.join(", ")}`);
541
+ if (!isOneOf(QUALITY_FORMATS, name)) {
542
+ fail("quality", name, `one of ${QUALITY_FORMATS.join(", ")}`);
474
543
  }
475
544
  const value = entries[name];
476
545
  parts.push(`${name}:${value === "auto" ? "auto" : intIn("quality", value, 1, 100)}`);
@@ -489,7 +558,7 @@ export const filter = {
489
558
  * format cannot honour throws here, like the server's 400.
490
559
  */
491
560
  format(format, options = {}) {
492
- if (!IMAGE_FORMATS.includes(format)) {
561
+ if (!isOneOf(IMAGE_FORMATS, format)) {
493
562
  fail("format", format, `one of ${IMAGE_FORMATS.join(", ")}`);
494
563
  }
495
564
  // The output segment is the canonical spelling: the
@@ -505,8 +574,8 @@ export const filter = {
505
574
  if (options.progressive)
506
575
  args.push("progressive");
507
576
  if (options.subsampling !== undefined) {
508
- if (![444, 422, 420].includes(options.subsampling)) {
509
- fail("subsampling", options.subsampling, "one of 444, 422, 420");
577
+ if (!isOneOf(JPEG_SUBSAMPLINGS, options.subsampling)) {
578
+ fail("subsampling", options.subsampling, `one of ${JPEG_SUBSAMPLINGS.join(", ")}`);
510
579
  }
511
580
  args.push(`subsampling:${options.subsampling}`);
512
581
  }
@@ -560,7 +629,7 @@ export const filter = {
560
629
  * `studio("product")` are the same string.
561
630
  */
562
631
  studio(mode, options = {}) {
563
- if (!STUDIO_MODES.includes(mode)) {
632
+ if (!isOneOf(STUDIO_MODES, mode)) {
564
633
  fail("studio mode", mode, `one of ${STUDIO_MODES.join(", ")}`);
565
634
  }
566
635
  const { bg, shadow, pad } = options;
@@ -570,11 +639,11 @@ export const filter = {
570
639
  const parts = [mode];
571
640
  if (mode === "product") {
572
641
  if (bg !== undefined) {
573
- const value = bg === "white" || bg === "brand" || bg === "none" ? bg : hex6("studio bg", bg);
642
+ const value = isOneOf(STUDIO_BACKDROPS, bg) ? bg : hex6("studio bg", bg);
574
643
  parts.push(`bg:${value}`);
575
644
  }
576
645
  if (shadow !== undefined) {
577
- if (!STUDIO_SHADOWS.includes(shadow)) {
646
+ if (!isOneOf(STUDIO_SHADOWS, shadow)) {
578
647
  fail("studio shadow", shadow, `one of ${STUDIO_SHADOWS.join(", ")}`);
579
648
  }
580
649
  if (shadow !== "soft")
@@ -590,15 +659,15 @@ export const filter = {
590
659
  },
591
660
  /** AI upscale by the given factor. */
592
661
  upscale(factor) {
593
- if (factor !== 2 && factor !== 4) {
594
- fail("upscale factor", factor, "2 or 4");
662
+ if (!isOneOf(UPSCALE_FACTORS, factor)) {
663
+ fail("upscale factor", factor, eitherOf(UPSCALE_FACTORS));
595
664
  }
596
665
  return `upscale(${factor})`;
597
666
  },
598
667
  /** Device pixel ratio the sizes are multiplied by. */
599
668
  dpr(factor) {
600
- if (![1, 1.5, 2, 3].includes(factor)) {
601
- fail("dpr", factor, "1, 1.5, 2, or 3");
669
+ if (!isOneOf(DPR_FACTORS, factor)) {
670
+ fail("dpr", factor, eitherOf(DPR_FACTORS));
602
671
  }
603
672
  return `dpr(${num(factor)})`;
604
673
  },
@@ -621,8 +690,8 @@ export const filter = {
621
690
  return `border(${intIn("border width", width, 0, MAX_DIMENSION)},${hex6("border color", color)})`;
622
691
  },
623
692
  mask(shape) {
624
- if (shape !== "circle" && shape !== "ellipse") {
625
- fail("mask shape", shape, '"circle" or "ellipse"');
693
+ if (!isOneOf(MASK_SHAPES, shape)) {
694
+ fail("mask shape", shape, eitherOf(MASK_SHAPES, true));
626
695
  }
627
696
  return `mask(${shape})`;
628
697
  },
@@ -632,13 +701,13 @@ export const filter = {
632
701
  monochrome(color) {
633
702
  return `monochrome(${hex6("monochrome color", color)})`;
634
703
  },
635
- /** Mosaic block size in pixels: 1..16383. */
704
+ /** Mosaic block size in pixels: 1..{@link MAX_DIMENSION}. */
636
705
  pixelate(blockSize) {
637
706
  return `pixelate(${intIn("pixelate size", blockSize, 1, MAX_DIMENSION)})`;
638
707
  },
639
708
  flip(axis) {
640
- if (axis !== "h" && axis !== "v") {
641
- fail("flip axis", axis, '"h" or "v"');
709
+ if (!isOneOf(FLIP_AXES, axis)) {
710
+ fail("flip axis", axis, eitherOf(FLIP_AXES, true));
642
711
  }
643
712
  return `flip(${axis})`;
644
713
  },
@@ -660,7 +729,7 @@ export const filter = {
660
729
  intIn("overlay x", x, -2147483648, 2147483647);
661
730
  intIn("overlay y", y, -2147483648, 2147483647);
662
731
  intIn("overlay alpha", alpha, 0, 100);
663
- if (!BLEND_MODES.includes(blend)) {
732
+ if (!isOneOf(BLEND_MODES, blend)) {
664
733
  fail("overlay blend", blend, `one of ${BLEND_MODES.join(", ")}`);
665
734
  }
666
735
  if (url === "")
@@ -673,8 +742,8 @@ export const filter = {
673
742
  * canonical spelling is always eight lowercase hex digits.
674
743
  */
675
744
  text(content, size, color, anchor) {
676
- if (!ANCHORS.includes(anchor)) {
677
- fail("text anchor", anchor, `one of ${ANCHORS.join(", ")}`);
745
+ if (!isOneOf(TEXT_ANCHORS, anchor)) {
746
+ fail("text anchor", anchor, `one of ${TEXT_ANCHORS.join(", ")}`);
678
747
  }
679
748
  if (content === "")
680
749
  fail("text", content, "a non-empty label");
package/package.json CHANGED
@@ -13,15 +13,23 @@
13
13
  "name": "@crabcrop/url",
14
14
  "keywords": ["image", "url", "signing", "hmac", "cdn", "crabcrop"],
15
15
  "files": ["dist"],
16
+ "imports": {
17
+ "#crypto": {
18
+ "browser": "./dist/crypto/portable.js",
19
+ "node": "./dist/crypto/node.js",
20
+ "default": "./dist/crypto/portable.js"
21
+ }
22
+ },
16
23
  "publishConfig": { "access": "public" },
17
24
  "repository": { "type": "git", "url": "git+https://github.com/dayvson/crabcrop.git", "directory": "sdks/typescript" },
18
25
  "scripts": {
19
- "build": "tsc",
26
+ "build": "tsc && tsc -p tsconfig.browser.json",
20
27
  "prepack": "npm run build",
21
- "test": "node --test"
28
+ "pretest": "npm run build && tsc -p tsconfig.test.json",
29
+ "test": "node --test && node --conditions=browser --test"
22
30
  },
23
31
  "type": "module",
24
- "version": "0.9.10",
32
+ "version": "0.10.0",
25
33
  "devDependencies": {
26
34
  "@types/node": "^26.6.5",
27
35
  "typescript": "^7.0.2"