ag-psd 34.2.2 → 34.2.4

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.
Files changed (64) hide show
  1. package/.v8-cache/v26.13.0-x64-310b2ce3/4511bacf +0 -0
  2. package/.v8-cache/v26.13.0-x64-310b2ce3/71df9cb3 +0 -0
  3. package/.v8-cache/v26.13.0-x64-310b2ce3/7ea06cea +0 -0
  4. package/.v8-cache/v26.13.0-x64-310b2ce3/932f0770 +0 -0
  5. package/.v8-cache/v26.13.0-x64-310b2ce3/a7e80865 +0 -0
  6. package/.v8-cache/v26.13.0-x64-310b2ce3/acc36e66 +0 -0
  7. package/.v8-cache/v26.13.0-x64-310b2ce3/b3c2fab7 +0 -0
  8. package/.v8-cache/v26.13.0-x64-310b2ce3/c314aece +0 -0
  9. package/.v8-cache/v26.13.0-x64-310b2ce3/dc86f000 +0 -0
  10. package/.v8-cache/v26.13.0-x64-310b2ce3/e03e2acd +0 -0
  11. package/.v8-cache/v26.13.0-x64-310b2ce3/e6735171 +0 -0
  12. package/CHANGELOG.md +9 -0
  13. package/README.md +23 -4
  14. package/dist/abr.js +12 -5
  15. package/dist/abr.js.map +1 -1
  16. package/dist/additionalInfo.js +1 -1
  17. package/dist/additionalInfo.js.map +1 -1
  18. package/dist/bundle.js +256 -78
  19. package/dist/descriptor.js +51 -16
  20. package/dist/descriptor.js.map +1 -1
  21. package/dist/engineData.d.ts +1 -0
  22. package/dist/engineData.js +4 -3
  23. package/dist/engineData.js.map +1 -1
  24. package/dist/helpers.d.ts +4 -0
  25. package/dist/helpers.js +11 -0
  26. package/dist/helpers.js.map +1 -1
  27. package/dist/imageResources.js +1 -1
  28. package/dist/imageResources.js.map +1 -1
  29. package/dist/psd.d.ts +1 -1
  30. package/dist/psdReader.d.ts +1 -0
  31. package/dist/psdReader.js +170 -46
  32. package/dist/psdReader.js.map +1 -1
  33. package/dist/text.js +5 -5
  34. package/dist/text.js.map +1 -1
  35. package/dist-es/abr.js +12 -5
  36. package/dist-es/abr.js.map +1 -1
  37. package/dist-es/additionalInfo.js +1 -1
  38. package/dist-es/additionalInfo.js.map +1 -1
  39. package/dist-es/descriptor.js +51 -16
  40. package/dist-es/descriptor.js.map +1 -1
  41. package/dist-es/engineData.d.ts +1 -0
  42. package/dist-es/engineData.js +4 -3
  43. package/dist-es/engineData.js.map +1 -1
  44. package/dist-es/helpers.d.ts +4 -0
  45. package/dist-es/helpers.js +11 -0
  46. package/dist-es/helpers.js.map +1 -1
  47. package/dist-es/imageResources.js +1 -1
  48. package/dist-es/imageResources.js.map +1 -1
  49. package/dist-es/psd.d.ts +1 -1
  50. package/dist-es/psdReader.d.ts +1 -0
  51. package/dist-es/psdReader.js +170 -46
  52. package/dist-es/psdReader.js.map +1 -1
  53. package/dist-es/text.js +5 -5
  54. package/dist-es/text.js.map +1 -1
  55. package/package.json +1 -1
  56. package/src/abr.ts +11 -5
  57. package/src/additionalInfo.ts +2 -2
  58. package/src/descriptor.ts +55 -19
  59. package/src/engineData.ts +1 -1
  60. package/src/helpers.ts +11 -0
  61. package/src/imageResources.ts +2 -2
  62. package/src/psd.ts +1 -1
  63. package/src/psdReader.ts +178 -43
  64. package/src/text.ts +5 -5
package/src/abr.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { BlnM, DescriptorUnitsValue, parseAngle, parsePercent, parseUnitsToNumber, readVersionAndDescriptor } from './descriptor';
2
2
  import { BlendMode, PatternInfo } from './psd';
3
+ import { arrayItem } from './helpers';
3
4
  import { checkSignature, consumeMemory, createReader, PsdReader, readBytes, readDataRLE, readInt16, readInt32, readPascalString, readPatternSafe, readSignature, readUint16, readUint32, readUint8, readUnicodeString, skipBytes } from './psdReader';
4
5
 
5
6
  export interface Abr {
@@ -422,7 +423,7 @@ const toBrushType = new Map<string, 'brush' | 'mixer brush' | 'smudge brush'>([
422
423
 
423
424
  function parseDynamics(desc: DynamicsDescriptor): BrushDynamics {
424
425
  return {
425
- control: dynamicsControl[desc.bVTy] as any,
426
+ control: arrayItem(dynamicsControl, desc.bVTy) as any,
426
427
  steps: desc.fStp,
427
428
  jitter: parsePercent(desc.jitter),
428
429
  minimum: parsePercent(desc['Mnm ']),
@@ -461,7 +462,7 @@ function parseBrushShape(desc: BrushShapeDescriptor): BrushShape {
461
462
  case 'dBrush':
462
463
  return {
463
464
  type: 'dynamic',
464
- shape: dynamicBrushShapeShapes[desc['Shp ']],
465
+ shape: arrayItem(dynamicBrushShapeShapes, desc['Shp '])!,
465
466
  angle: parseAngle(desc.Angl),
466
467
  size: parseUnitsToNumber(desc.Dmtr, 'Pixels'),
467
468
  density: parsePercent(desc.Dnst),
@@ -480,14 +481,14 @@ function parseBrushShape(desc: BrushShapeDescriptor): BrushShape {
480
481
  type: 'tips',
481
482
  angle: parseAngle(desc.Angl),
482
483
  size: parseUnitsToNumber(desc.Dmtr, 'Pixels'),
483
- shape: dynamicBrushShapeShapes[desc['Shp ']],
484
+ shape: arrayItem(dynamicBrushShapeShapes, desc['Shp '])!,
484
485
  physics: desc.physics,
485
486
  spacing: parsePercent(desc.Spcn),
486
487
  spacingOn: desc.Intr,
487
488
  flipX: desc.flipX,
488
489
  flipY: desc.flipY,
489
490
  // tips:
490
- tipsType: tipsBrushShapeShapes[desc.dtipsType],
491
+ tipsType: arrayItem(tipsBrushShapeShapes, desc.dtipsType)!,
491
492
  tipsLengthRatio: parsePercent(desc.dtipsLengthRatio),
492
493
  tipsHardness: parsePercent(desc.dtipsHardness),
493
494
  ...((desc.dtipsGridSize && desc.dtipsErodibleTipHeightMap) ? {
@@ -534,7 +535,12 @@ export interface ReadAbrOptions {
534
535
  // descriptor can't make the parser read (and allocate) data out into the rest of the file
535
536
  function readSectionDescriptor(reader: PsdReader, end: number) {
536
537
  const sectionReader = createReader(reader.view.buffer, reader.view.byteOffset + reader.offset, end - reader.offset);
537
- return readVersionAndDescriptor(sectionReader, true);
538
+ sectionReader.totalMemoryLimit = reader.totalMemoryLimit; // share the budget with the section reader
539
+ try {
540
+ return readVersionAndDescriptor(sectionReader, true);
541
+ } finally {
542
+ reader.totalMemoryLimit = sectionReader.totalMemoryLimit; // carry section consumption back to the shared budget
543
+ }
538
544
  }
539
545
 
540
546
  export function readAbr(buffer: ArrayBufferView, options: ReadAbrOptions = {}): Abr {
@@ -1,6 +1,6 @@
1
1
  import { fromByteArray, toByteArray } from 'base64-js';
2
2
  import { readEffects, writeEffects } from './effectsHelpers';
3
- import { clamp, createEnum, layerColors, MOCK_HANDLERS, normalizeLabAB } from './helpers';
3
+ import { arrayItem, clamp, createEnum, layerColors, MOCK_HANDLERS, normalizeLabAB } from './helpers';
4
4
  import { LayerAdditionalInfo, LevelsFilterAdjustment, BezierPath, Psd, BrightnessAdjustment, ExposureAdjustment, VibranceAdjustment, ColorBalanceAdjustment, BlackAndWhiteAdjustment, PhotoFilterAdjustment, ChannelMixerChannel, ChannelMixerAdjustment, PosterizeAdjustment, ThresholdAdjustment, GradientMapAdjustment, CMYK, SelectiveColorAdjustment, ColorLookupAdjustment, LevelsAdjustmentChannel, LevelsAdjustment, CurvesAdjustment, CurvesAdjustmentChannel, HueSaturationAdjustment, HueSaturationAdjustmentChannel, PresetInfo, Color, ColorBalanceValues, WriteOptions, LinkedFile, PlacedLayerType, Warp, KeyDescriptorItem, BooleanOperation, LayerEffectsInfo, Annotation, VectorPathData, AnimationFrame, Timeline, PlacedLayerFilter, UnitsValue, Filter, PlacedLayer, Layer, CameraRawColors, CameraRawCurvePoint, CameraRawFilterSettings, Knockout, LayerStateBlendOptions, LayerStateText } from './psd';
5
5
  import { PsdReader, readSignature, readUnicodeString, skipBytes, readUint32, readUint8, readFloat64, readUint16, readBytes, readInt16, checkSignature, readFloat32, readFixedPointPath32, readSection, readColor, readInt32, readPascalString, readUnicodeStringWithLength, readAsciiString, readPatternSafe, readLayerInfo } from './psdReader';
6
6
  import { PsdWriter, writeZeros, writeSignature, writeBytes, writeUint32, writeUint16, writeFloat64, writeUint8, writeInt16, writeFloat32, writeFixedPointPath32, writeUnicodeString, writeSection, writeUnicodeStringWithPadding, writeColor, writePascalString, writeInt32, writePattern, writeUint64 } from './psdWriter';
@@ -4117,7 +4117,7 @@ addHandler(
4117
4117
  target.placedLayer = {
4118
4118
  id: desc.Idnt,
4119
4119
  placed: desc.placed,
4120
- type: placedLayerTypes[desc.Type],
4120
+ type: arrayItem(placedLayerTypes, desc.Type)!,
4121
4121
  pageNumber: desc.PgNm,
4122
4122
  totalPages: desc.totalPages,
4123
4123
  frameStep: frac(desc.frameStep),
package/src/descriptor.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { createEnum, normalizeLabAB, denormalizeLabAB } from './helpers';
2
- import { setProperty } from './engineData';
1
+ import { createEnum, normalizeLabAB, denormalizeLabAB, ownValue } from './helpers';
2
+ import { NODE_COST, setProperty } from './engineData';
3
3
  import {
4
4
  AntiAlias, BevelDirection, BevelStyle, BevelTechnique, BlendMode, Color, ColorStop, EffectContour,
5
5
  EffectNoiseGradient, EffectPattern, EffectSolidGradient, ExtraGradientInfo, ExtraPatternInfo,
@@ -12,7 +12,7 @@ import {
12
12
  } from './psd';
13
13
  import {
14
14
  PsdReader, readSignature, readUnicodeString, readUint32, readUint8, readFloat64,
15
- readBytes, readAsciiString, readInt32, readFloat32, readInt32LE, readUnicodeStringWithLengthLE
15
+ readBytes, readAsciiString, readInt32, readFloat32, readInt32LE, readUnicodeStringWithLengthLE, consumeMemory
16
16
  } from './psdReader';
17
17
  import {
18
18
  PsdWriter, writeSignature, writeBytes, writeUint32, writeFloat64, writeUint8,
@@ -415,7 +415,7 @@ function getTypeByKey(key: string, value: any, root: string, parent: any) {
415
415
  } else if (key === 'LghD' && parent._classID === 'oilPaint') {
416
416
  return 'long';
417
417
  } else {
418
- return fieldToType[key];
418
+ return ownValue(fieldToType, key);
419
419
  }
420
420
  }
421
421
 
@@ -441,12 +441,14 @@ export function writeAsciiStringOrClassId(writer: PsdWriter, value: string) {
441
441
 
442
442
  export function readDescriptorStructure(reader: PsdReader, includeClass: boolean, depth = 0) {
443
443
  const struct = readClassStructure(reader);
444
+ consumeMemory(reader, NODE_COST);
444
445
  const object: any = includeClass ? { _name: struct.name, _classID: struct.classID } : {};
445
446
  // console.log('>> ', struct);
446
447
  const itemsCount = readUint32(reader);
447
448
 
448
449
  for (let i = 0; i < itemsCount; i++) {
449
450
  const key = readAsciiStringOrClassId(reader);
451
+ consumeMemory(reader, key.length);
450
452
  const type = readSignature(reader);
451
453
  // console.log(`> '${key}' '${type}'`);
452
454
  const data = readOSType(reader, type, includeClass, depth + 1);
@@ -481,10 +483,10 @@ export function writeDescriptorStructure(writer: PsdWriter, name: string, classI
481
483
  for (const key of keys) {
482
484
  let type: string | undefined = getTypeByKey(key, value[key], root, value);
483
485
  let childRoot = root;
484
- let extType = fieldToExtType[key];
486
+ let extType = ownValue(fieldToExtType, key);
485
487
 
486
488
  if (classId === cameraRawFilterClassID) {
487
- type = cameraRawFilterKeyTypes[key] ?? 'long'; // other settings are integer levels
489
+ type = ownValue(cameraRawFilterKeyTypes, key) ?? 'long'; // other settings are integer levels
488
490
  childRoot = cameraRawFilterClassID; // lists (curves) contain integer levels
489
491
  }
490
492
 
@@ -587,9 +589,14 @@ export function writeDescriptorStructure(writer: PsdWriter, name: string, classI
587
589
  // arbitrarily deep, which would overflow the call stack (RangeError), so the depth is capped
588
590
  const maxDescriptorDepth = 1000;
589
591
 
592
+ // Parsed values (and lengths of strings) are charged against `totalMemoryLimit`, the charge is not returned when
593
+ // parsed descriptor is discarded. Crafted files can declare lists and descriptors with millions of few byte items,
594
+ // building an object graph many times larger than the file.
590
595
  function readOSType(reader: PsdReader, type: string, includeClass: boolean, depth: number) {
591
596
  if (depth > maxDescriptorDepth) throw new Error('Descriptor is nested too deeply');
592
597
 
598
+ consumeMemory(reader, NODE_COST);
599
+
593
600
  switch (type) {
594
601
  case 'obj ': // Reference
595
602
  return readReferenceStructure(reader);
@@ -624,11 +631,15 @@ function readOSType(reader: PsdReader, type: string, includeClass: boolean, dept
624
631
  if (!unit) throw new Error(`Invalid units: ${units}`);
625
632
  return { units: unit, value };
626
633
  }
627
- case 'TEXT': // String
628
- return readUnicodeString(reader);
634
+ case 'TEXT': { // String
635
+ const value = readUnicodeString(reader);
636
+ consumeMemory(reader, value.length * 2);
637
+ return value;
638
+ }
629
639
  case 'enum': { // Enumerated
630
640
  const enumType = readAsciiStringOrClassId(reader);
631
641
  const value = readAsciiStringOrClassId(reader);
642
+ consumeMemory(reader, enumType.length + value.length);
632
643
  return `${enumType}.${value}`;
633
644
  }
634
645
  case 'long': // Integer
@@ -645,7 +656,9 @@ function readOSType(reader: PsdReader, type: string, includeClass: boolean, dept
645
656
  return readClassStructure(reader);
646
657
  case 'alis': { // Alias
647
658
  const length = readInt32(reader);
648
- return readAsciiString(reader, length);
659
+ const value = readAsciiString(reader, length);
660
+ consumeMemory(reader, value.length);
661
+ return value;
649
662
  }
650
663
  case 'tdta': { // Raw Data
651
664
  const length = readInt32(reader);
@@ -666,6 +679,7 @@ function readOSType(reader: PsdReader, type: string, includeClass: boolean, dept
666
679
  readSignature(reader); // UnFl
667
680
  readSignature(reader); // units ? '#Pxl'
668
681
  const valuesCount = readInt32(reader);
682
+ consumeMemory(reader, NODE_COST + type1.length + Math.max(0, valuesCount) * 8);
669
683
  const values: number[] = [];
670
684
  for (let j = 0; j < valuesCount; j++) {
671
685
  values.push(readFloat64(reader));
@@ -682,6 +696,7 @@ function readOSType(reader: PsdReader, type: string, includeClass: boolean, dept
682
696
  /*const pathSize =*/ readInt32LE(reader); // the same as length
683
697
  const charsCount = readInt32LE(reader);
684
698
  const path = readUnicodeStringWithLengthLE(reader, charsCount);
699
+ consumeMemory(reader, path.length * 2);
685
700
  return { sig, path };
686
701
  }
687
702
  default:
@@ -714,9 +729,9 @@ function writeOSType(writer: PsdWriter, type: string, value: any, key: string, e
714
729
  writeInt32(writer, value.length);
715
730
 
716
731
  for (let i = 0; i < value.length; i++) {
717
- const type = root === cameraRawFilterClassID ? 'long' : (fieldToArrayType[key] ?? guessOSType(value[i]));
732
+ const type = root === cameraRawFilterClassID ? 'long' : (ownValue(fieldToArrayType, key) ?? guessOSType(value[i]));
718
733
  writeSignature(writer, type || 'long');
719
- writeOSType(writer, type || 'long', value[i], `${key}[]`, fieldToArrayExtType[key], root);
734
+ writeOSType(writer, type || 'long', value[i], `${key}[]`, ownValue(fieldToArrayExtType, key), root);
720
735
  if (writer.logMissingFeatures && !type) writer.log(`Missing descriptor array type for: '${key}' in`, value);
721
736
  }
722
737
  break;
@@ -782,7 +797,7 @@ function writeOSType(writer: PsdWriter, type: string, value: any, key: string, e
782
797
  case 'ObAr': { // Object array
783
798
  writeInt32(writer, 16); // version
784
799
  writeUnicodeStringWithPadding(writer, ''); // name
785
- const type = ObArTypes[key];
800
+ const type = ownValue(ObArTypes, key);
786
801
  if (!type) throw new Error(`Not implemented ObArType for: ${key}`);
787
802
  writeAsciiStringOrClassId(writer, type);
788
803
  writeInt32(writer, value.length);
@@ -838,12 +853,16 @@ function readReferenceStructure(reader: PsdReader) {
838
853
 
839
854
  for (let i = 0; i < itemsCount; i++) {
840
855
  const type = readSignature(reader);
856
+ consumeMemory(reader, NODE_COST); // see readOSType
841
857
 
842
858
  switch (type) {
843
- case 'prop': // Property
859
+ case 'prop': { // Property
844
860
  readClassStructure(reader);
845
- items.push(readAsciiStringOrClassId(reader));
861
+ const value = readAsciiStringOrClassId(reader);
862
+ consumeMemory(reader, value.length);
863
+ items.push(value);
846
864
  break;
865
+ }
847
866
  case 'Clss': // Class
848
867
  items.push(readClassStructure(reader));
849
868
  break;
@@ -851,6 +870,7 @@ function readReferenceStructure(reader: PsdReader) {
851
870
  readClassStructure(reader);
852
871
  const typeID = readAsciiStringOrClassId(reader);
853
872
  const enumValue = readAsciiStringOrClassId(reader);
873
+ consumeMemory(reader, typeID.length + enumValue.length);
854
874
  items.push(`${typeID}.${enumValue}`);
855
875
  break;
856
876
  }
@@ -862,10 +882,13 @@ function readReferenceStructure(reader: PsdReader) {
862
882
  case 'indx': // Index
863
883
  items.push(readInt32(reader));
864
884
  break;
865
- case 'name': // Name
885
+ case 'name': { // Name
866
886
  readClassStructure(reader);
867
- items.push(readUnicodeString(reader));
887
+ const value = readUnicodeString(reader);
888
+ consumeMemory(reader, value.length * 2);
889
+ items.push(value);
868
890
  break;
891
+ }
869
892
  default:
870
893
  throw new Error(`Invalid descriptor reference type: ${type}`);
871
894
  }
@@ -950,6 +973,7 @@ function writeReferenceStructure(writer: PsdWriter, _key: string, items: any[])
950
973
  function readClassStructure(reader: PsdReader) {
951
974
  const name = readUnicodeString(reader);
952
975
  const classID = readAsciiStringOrClassId(reader);
976
+ consumeMemory(reader, name.length * 2 + classID.length);
953
977
  return { name, classID };
954
978
  }
955
979
 
@@ -961,9 +985,21 @@ export function writeClassStructure(writer: PsdWriter, name: string, classID: st
961
985
  export function readVersionAndDescriptor(reader: PsdReader, includeClass = false) {
962
986
  const version = readUint32(reader);
963
987
  if (version !== 16) throw new Error(`Invalid descriptor version: ${version}`);
964
- const desc = readDescriptorStructure(reader, includeClass);
965
- // console.log(require('util').inspect(desc, false, 99, true));
966
- return desc;
988
+
989
+ // descriptor can't be read past the end of its section, otherwise many small sections could all parse the same
990
+ // large block of data from the rest of the file (the reader returns to the section end after reading a section),
991
+ // the view is shortened with the same start, so the offsets stay the same
992
+ const view = reader.view;
993
+ const end = reader.sectionEnd;
994
+ if (end !== undefined && end < view.byteLength) reader.view = new DataView(view.buffer, view.byteOffset, end);
995
+
996
+ try {
997
+ const desc = readDescriptorStructure(reader, includeClass);
998
+ // console.log(require('util').inspect(desc, false, 99, true));
999
+ return desc;
1000
+ } finally {
1001
+ reader.view = view;
1002
+ }
967
1003
  }
968
1004
 
969
1005
  export function writeVersionAndDescriptor(writer: PsdWriter, name: string, classID: string, descriptor: any, root = '') {
package/src/engineData.ts CHANGED
@@ -21,7 +21,7 @@ export function setProperty(target: any, key: string, value: any) {
21
21
  // estimated cost of one parsed node (array/object/value) with V8 overhead, charged against
22
22
  // `totalMemoryLimit` so malformed data of single-byte tokens (e.g. '[[[[...') can't build an
23
23
  // unbounded object graph that bypasses the limit
24
- const NODE_COST = 64;
24
+ export const NODE_COST = 64;
25
25
 
26
26
  export function parseEngineData(data: number[] | Uint8Array, reader: Pick<PsdReader, 'log' | 'totalMemoryLimit'>) {
27
27
  let index = 0;
package/src/helpers.ts CHANGED
@@ -157,6 +157,17 @@ export function clamp(value: number, min: number, max: number) {
157
157
  return value < min ? min : (value > max ? max : value);
158
158
  }
159
159
 
160
+ // index read from a file can be any type (e.g. string '__proto__' or a list coerced to 'length'),
161
+ // only integer indexes within the array return an item, so inherited properties are never returned
162
+ export function arrayItem<T>(array: readonly T[], index: unknown): T | undefined {
163
+ return (typeof index === 'number' && Number.isInteger(index) && index >= 0 && index < array.length) ? array[index] : undefined;
164
+ }
165
+
166
+ // key read from a file can be a name of an inherited property (e.g. 'constructor' or 'toString')
167
+ export function ownValue<T>(dict: { [key: string]: T; }, key: string): T | undefined {
168
+ return Object.prototype.hasOwnProperty.call(dict, key) ? dict[key] : undefined;
169
+ }
170
+
160
171
  export function hasAlpha(data: PixelData) {
161
172
  const size = data.width * data.height * 4;
162
173
  const max = data.data instanceof Float32Array ? 1 : (data.data instanceof Uint16Array ? 0xffff : 0xff);
@@ -3,7 +3,7 @@ import { Animations, BlendMode, Color, HalftoneScreen, ImageResources, KeyDescri
3
3
  import { KeyDescriptorListDescriptor, parseKeyDescriptorList, readVectorMask, serializeKeyDescriptorList, writeVectorMask } from './additionalInfo';
4
4
  import { PsdReader, readUnicodeString, readUint32, readUint16, readUint8, readFloat64, readBytes, skipBytes, readFloat32, readInt16, readFixedPoint32, readSignature, checkSignature, readSection, readColor, readInt32, readAsciiString, decodeUtf8, getUtf8StrictDecoder, getGbkStrictDecoder } from './psdReader';
5
5
  import { PsdWriter, writeUnicodeString, writeUint32, writeUint8, writeFloat64, writeUint16, writeBytes, writeInt16, writeFloat32, writeFixedPoint32, writeUnicodeStringWithPadding, writeColor, writeSignature, writeSection, writeInt32, writeAsciiString, writeZeros } from './psdWriter';
6
- import { clamp, ColorSpace, createCanvasFromData, createEnum, createImageData, imageDataToCanvas, MOCK_HANDLERS } from './helpers';
6
+ import { arrayItem, clamp, ColorSpace, createCanvasFromData, createEnum, createImageData, imageDataToCanvas, MOCK_HANDLERS } from './helpers';
7
7
  import { encodeString } from './utf8';
8
8
  import { ESliceBGColorType, ESliceHorzAlign, ESliceOrigin, ESliceType, ESliceVertAlign, frac, FractionDescriptor, parseTrackList, pathSelectionStateToReference, DescriptorReferenceItem, readVersionAndDescriptor, serializeTrackList, TimelineTrackDescriptor, TimeScopeDescriptor, writeVersionAndDescriptor, DescriptorColor, DescriptorUnitsValue, parseColor, serializeColor, parseUnits, unitsValue, parsePercent, unitsPercentF , outputSettingsRoot } from './descriptor';
9
9
 
@@ -1161,7 +1161,7 @@ addHandler(
1161
1161
  frameSpacing: desc.Spcn,
1162
1162
  minOpacity: desc.minOpacity / 100,
1163
1163
  maxOpacity: desc.maxOpacity / 100,
1164
- blendMode: onionSkinsBlendModes[desc.BlnM] || 'normal',
1164
+ blendMode: arrayItem(onionSkinsBlendModes, desc.BlnM) || 'normal',
1165
1165
  };
1166
1166
  },
1167
1167
  (writer, target) => {
package/src/psd.ts CHANGED
@@ -2122,7 +2122,7 @@ export interface ReadOptions {
2122
2122
  skipThumbnail?: boolean;
2123
2123
  /** Does not load linked files (used in smart-objects). */
2124
2124
  skipLinkedFilesData?: boolean;
2125
- /** Total memory limit to use when decoding bitmaps (default: 2GB). */
2125
+ /** Total memory limit in bytes for data decoded while reading the file: bitmaps, thumbnail, data buffers and parsed structures (descriptors, text engine data) (default: 2GB), set to `undefined` explicitly to disable. Does not apply to functions decoding bitmaps on demand (see "Use in production" section of README). */
2126
2126
  totalMemoryLimit?: number;
2127
2127
  /** Throws exception if features are missing. */
2128
2128
  throwForMissingFeatures?: boolean;
package/src/psdReader.ts CHANGED
@@ -31,6 +31,7 @@ export interface PsdReader extends ReadOptions {
31
31
  layersInGlobalInfo?: boolean; // layers were read from Lr16/Lr32/Layr global additional info
32
32
  imageResourcesWhitelistSet?: Set<string>; // `imageResourcesWhitelist` option converted to a Set
33
33
  log(...args: any[]): void;
34
+ sectionEnd?: number; // end offset of the innermost section being read (descriptors are not read past it)
34
35
  // text decoders, created lazily (null if not supported)
35
36
  utf8Decoder?: TextDecoder | null;
36
37
  utf8StrictDecoder?: TextDecoder | null;
@@ -1148,7 +1149,8 @@ function readImageData(reader: PsdReader, psd: Psd) {
1148
1149
  if (supportedColorModes.indexOf(psd.colorMode!) === -1)
1149
1150
  throw new Error(`Color mode not supported: ${psd.colorMode}`);
1150
1151
 
1151
- if (compression !== Compression.RawData && compression !== Compression.RleCompressed)
1152
+ if (compression !== Compression.RawData && compression !== Compression.RleCompressed &&
1153
+ compression !== Compression.ZipWithoutPrediction && compression !== Compression.ZipWithPrediction)
1152
1154
  throw new Error(`Compression type not supported: ${compression}`);
1153
1155
 
1154
1156
  const imageData = createImageDataBitDepth(width, height, bitsPerChannel, 4, reader.totalMemoryLimit);
@@ -1166,7 +1168,7 @@ function readImageData(reader: PsdReader, psd: Psd) {
1166
1168
  bytes = readBytes(reader, rowBytes * height);
1167
1169
  } else {
1168
1170
  bytes = new Uint8Array(rowBytes * height);
1169
- readDataRLE(reader, { data: bytes, width: rowBytes, height }, rowBytes, height, 8, 1, [0], reader.large);
1171
+ readCompositeChannels(reader, compression, { data: bytes, width: rowBytes, height }, 8, 1, [0]);
1170
1172
  }
1171
1173
 
1172
1174
  decodeBitmap(bytes, imageData.data, width, height);
@@ -1258,11 +1260,80 @@ function readCompositeChannels(reader: PsdReader, compression: Compression, pixe
1258
1260
  }
1259
1261
  } else if (compression === Compression.RleCompressed) {
1260
1262
  readDataRLE(reader, pixelData, pixelData.width, pixelData.height, bitsPerChannel, step, offsets, reader.large);
1263
+ } else if (compression === Compression.ZipWithoutPrediction || compression === Compression.ZipWithPrediction) {
1264
+ readCompositeChannelsZip(reader, pixelData, bitsPerChannel, step, offsets, compression === Compression.ZipWithPrediction);
1261
1265
  } else {
1262
1266
  throw new Error(`Compression not supported: ${compression}`);
1263
1267
  }
1264
1268
  }
1265
1269
 
1270
+ // Zip compressed composite image data has no lengths of channels. Applications that write it (Photoshop writes RLE)
1271
+ // store each channel as a separate zlib stream, like channels of layers, or all the channels in one stream. Reads all
1272
+ // the remaining data, the composite image is the last section of the file.
1273
+ function readCompositeChannelsZip(reader: PsdReader, pixelData: PixelData, bitsPerChannel: number, step: number, offsets: number[], prediction: boolean) {
1274
+ const { width, height } = pixelData;
1275
+ const bpv = bytesPerValue(bitsPerChannel);
1276
+ const channelSize = width * height * bpv;
1277
+ verifyArrayType(pixelData.data, bpv);
1278
+
1279
+ const input = readBytes(reader, Math.max(0, reader.view.byteLength - reader.offset));
1280
+ consumeMemory(reader, channelSize);
1281
+
1282
+ try {
1283
+ const channel = new Uint8Array(channelSize);
1284
+
1285
+ for (let i = 0, position = 0; i < offsets.length && position < input.length; i++) {
1286
+ if (i) channel.fill(0);
1287
+ const stream = inflateZlibStream(input.subarray(position), channel);
1288
+
1289
+ if (i === 0 && stream.overflow) {
1290
+ readCompositeChannelsZipSingleStream(reader, input, pixelData, bpv, step, offsets, prediction);
1291
+ return;
1292
+ }
1293
+
1294
+ if (stream.overflow) {
1295
+ warnOrThrow(reader, zipOverflow.message);
1296
+ } else if (!stream.complete) {
1297
+ warnOrThrow(reader, 'Invalid zip data: unexpected end of data');
1298
+ }
1299
+
1300
+ if (offsets[i] >= 0) writeZipChannel(channel, pixelData, width, height, bpv, step, offsets[i], prediction);
1301
+ position += stream.length;
1302
+ }
1303
+ } finally {
1304
+ recoverMemory(reader, channelSize);
1305
+ }
1306
+ }
1307
+
1308
+ // all the channels in one zlib stream, one after another
1309
+ function readCompositeChannelsZipSingleStream(
1310
+ reader: PsdReader, input: Uint8Array, pixelData: PixelData, bpv: number, step: number, offsets: number[], prediction: boolean
1311
+ ) {
1312
+ const { width, height } = pixelData;
1313
+ const channelSize = width * height * bpv;
1314
+ const size = channelSize * offsets.length;
1315
+ consumeMemory(reader, size);
1316
+
1317
+ try {
1318
+ const channels = new Uint8Array(size);
1319
+ const stream = inflateZlibStream(input, channels);
1320
+
1321
+ if (stream.overflow) {
1322
+ warnOrThrow(reader, zipOverflow.message);
1323
+ } else if (!stream.complete) {
1324
+ warnOrThrow(reader, 'Invalid zip data: unexpected end of data');
1325
+ }
1326
+
1327
+ for (let i = 0; i < offsets.length; i++) {
1328
+ if (offsets[i] < 0) continue;
1329
+ const channel = channels.subarray(i * channelSize, (i + 1) * channelSize);
1330
+ writeZipChannel(channel, pixelData, width, height, bpv, step, offsets[i], prediction);
1331
+ }
1332
+ } finally {
1333
+ recoverMemory(reader, size);
1334
+ }
1335
+ }
1336
+
1266
1337
  // un-premultiplies colors from white matte, used for composite image of documents with global alpha
1267
1338
  function removeWhiteMatte({ data, width, height }: PixelData) {
1268
1339
  const size = width * height * 4;
@@ -1469,6 +1540,55 @@ function inflateLimited(compressed: Uint8Array, expectedSize: number, reader: Ps
1469
1540
  return output;
1470
1541
  }
1471
1542
 
1543
+ // Inflates the zlib stream at the start of `input` into `output`. Returns the length of the stream in `input`
1544
+ // (header and checksum included) and whether the stream ended within `input` without exceeding `output`.
1545
+ // The data is inflated as raw deflate data, because in zlib mode pako continues into the stream that follows as if
1546
+ // it was part of the same data. The checksum is not verified.
1547
+ function inflateZlibStream(input: Uint8Array, output: Uint8Array) {
1548
+ const cmf = input[0], flg = input[1];
1549
+
1550
+ // deflate compression method, valid header check bits, no preset dictionary
1551
+ if (input.length < 2 || (cmf & 0x0f) !== 8 || ((cmf << 8) | flg) % 31 !== 0 || (flg & 0x20) !== 0) {
1552
+ throw new Error('Invalid zip data: incorrect header check');
1553
+ }
1554
+
1555
+ let written = 0;
1556
+ let overflow = false;
1557
+ let ended = false;
1558
+ let deflateLength = 0;
1559
+
1560
+ const inflator = new Inflate({ chunkSize: Math.max(1024, Math.min(output.length, 0x10000)), raw: true });
1561
+ inflator.onData = (chunk: any) => {
1562
+ const data = chunk as Uint8Array;
1563
+ const count = Math.min(data.length, output.length - written);
1564
+ if (count > 0) output.set(count === data.length ? data : data.subarray(0, count), written);
1565
+ written += count;
1566
+
1567
+ if (count < data.length) {
1568
+ overflow = true;
1569
+ throw zipOverflow;
1570
+ }
1571
+ };
1572
+ inflator.onEnd = (status: number) => {
1573
+ inflator.err = status;
1574
+ inflator.msg = (inflator as any).strm?.msg || '';
1575
+ ended = true;
1576
+ deflateLength = (inflator as any).strm?.next_in ?? 0;
1577
+ };
1578
+
1579
+ try {
1580
+ inflator.push(input.subarray(2), true);
1581
+ } catch (e) {
1582
+ if (e !== zipOverflow) throw e;
1583
+ }
1584
+
1585
+ if (overflow) return { length: input.length, complete: false, overflow };
1586
+ if (inflator.err) throw new Error(`Invalid zip data: ${inflator.msg}`);
1587
+ if (!ended) return { length: input.length, complete: false, overflow }; // data ends before the stream does
1588
+
1589
+ return { length: Math.min(input.length, 2 + deflateLength + 4), complete: true, overflow };
1590
+ }
1591
+
1472
1592
  export function readDataZip(
1473
1593
  compressed: Uint8Array, pixelData: PixelData | undefined, width: number, height: number, bitDepth: number, step: number,
1474
1594
  offset: number, prediction: boolean, reader?: PsdReader
@@ -1477,62 +1597,69 @@ export function readDataZip(
1477
1597
 
1478
1598
  if (!pixelData || offset < 0 || offset >= step) return;
1479
1599
 
1480
- const data = pixelData.data;
1481
- verifyArrayType(data, bpv);
1600
+ verifyArrayType(pixelData.data, bpv);
1482
1601
 
1483
1602
  const expectedSize = width * height * bpv;
1484
1603
  if (reader) consumeMemory(reader, expectedSize);
1485
1604
 
1486
1605
  try {
1487
- const decompressed = inflateLimited(compressed, expectedSize, reader);
1606
+ writeZipChannel(inflateLimited(compressed, expectedSize, reader), pixelData, width, height, bpv, step, offset, prediction);
1607
+ } finally {
1608
+ if (reader) recoverMemory(reader, expectedSize);
1609
+ }
1610
+ }
1488
1611
 
1489
- if (bpv === 1) {
1490
- for (let y = 0, i = 0; y < height; y++) {
1491
- let prev = 0;
1612
+ // writes inflated values of one channel to `pixelData` (modifies `decompressed` when decoding 32bit prediction)
1613
+ function writeZipChannel(
1614
+ decompressed: Uint8Array, pixelData: PixelData, width: number, height: number, bpv: number, step: number,
1615
+ offset: number, prediction: boolean
1616
+ ) {
1617
+ const data = pixelData.data;
1492
1618
 
1493
- for (let x = 0, p = offset + y * width * step; x < width; x++, i++, p += step) {
1494
- let v = decompressed[i];
1495
- if (prediction) v = prev = (prev + v) & 0xff;
1496
- data[p] = v;
1497
- }
1619
+ if (bpv === 1) {
1620
+ for (let y = 0, i = 0; y < height; y++) {
1621
+ let prev = 0;
1622
+
1623
+ for (let x = 0, p = offset + y * width * step; x < width; x++, i++, p += step) {
1624
+ let v = decompressed[i];
1625
+ if (prediction) v = prev = (prev + v) & 0xff;
1626
+ data[p] = v;
1498
1627
  }
1499
- } else if (bpv === 2) {
1500
- for (let y = 0, i = 0; y < height; y++) {
1501
- let prev = 0;
1502
-
1503
- for (let x = 0, p = offset + y * width * step; x < width; x++, i += 2, p += step) {
1504
- let v = (decompressed[i] << 8) | decompressed[i + 1];
1505
- if (prediction) v = prev = (prev + v) & 0xffff;
1506
- data[p] = v;
1507
- }
1628
+ }
1629
+ } else if (bpv === 2) {
1630
+ for (let y = 0, i = 0; y < height; y++) {
1631
+ let prev = 0;
1632
+
1633
+ for (let x = 0, p = offset + y * width * step; x < width; x++, i += 2, p += step) {
1634
+ let v = (decompressed[i] << 8) | decompressed[i + 1];
1635
+ if (prediction) v = prev = (prev + v) & 0xffff;
1636
+ data[p] = v;
1508
1637
  }
1509
- } else {
1510
- const dst = new Uint32Array(data.buffer, data.byteOffset, data.length);
1638
+ }
1639
+ } else {
1640
+ const dst = new Uint32Array(data.buffer, data.byteOffset, data.length);
1511
1641
 
1512
- if (prediction) {
1513
- // bytes are delta encoded per row and stored in planar order (all 1st bytes, all 2nd bytes, ...)
1514
- decodePredicted(decompressed, width * 4, height);
1642
+ if (prediction) {
1643
+ // bytes are delta encoded per row and stored in planar order (all 1st bytes, all 2nd bytes, ...)
1644
+ decodePredicted(decompressed, width * 4, height);
1515
1645
 
1516
- for (let y = 0, di = offset; y < height; y++) {
1517
- let a = width * 4 * y;
1646
+ for (let y = 0, di = offset; y < height; y++) {
1647
+ let a = width * 4 * y;
1518
1648
 
1519
- for (let x = 0; x < width; x++, a++, di += step) {
1520
- const b = a + width;
1521
- const c = b + width;
1522
- const d = c + width;
1523
- dst[di] = ((decompressed[a] << 24) | (decompressed[b] << 16) | (decompressed[c] << 8) | decompressed[d]) >>> 0;
1524
- }
1649
+ for (let x = 0; x < width; x++, a++, di += step) {
1650
+ const b = a + width;
1651
+ const c = b + width;
1652
+ const d = c + width;
1653
+ dst[di] = ((decompressed[a] << 24) | (decompressed[b] << 16) | (decompressed[c] << 8) | decompressed[d]) >>> 0;
1525
1654
  }
1526
- } else {
1527
- const view = new DataView(decompressed.buffer, decompressed.byteOffset, decompressed.byteLength);
1655
+ }
1656
+ } else {
1657
+ const view = new DataView(decompressed.buffer, decompressed.byteOffset, decompressed.byteLength);
1528
1658
 
1529
- for (let i = 0, j = 0, di = offset, size = width * height; i < size; i++, j += 4, di += step) {
1530
- dst[di] = view.getUint32(j, false);
1531
- }
1659
+ for (let i = 0, j = 0, di = offset, size = width * height; i < size; i++, j += 4, di += step) {
1660
+ dst[di] = view.getUint32(j, false);
1532
1661
  }
1533
1662
  }
1534
- } finally {
1535
- if (reader) recoverMemory(reader, expectedSize);
1536
1663
  }
1537
1664
  }
1538
1665
 
@@ -1722,7 +1849,15 @@ export function readSection<T>(
1722
1849
  let end = reader.offset + length;
1723
1850
  if (end > reader.view.byteLength) throw new Error('Section exceeds file size');
1724
1851
 
1725
- const result = func(() => end - reader.offset);
1852
+ const parentSectionEnd = reader.sectionEnd;
1853
+ reader.sectionEnd = end;
1854
+ let result: T;
1855
+
1856
+ try {
1857
+ result = func(() => end - reader.offset);
1858
+ } finally {
1859
+ reader.sectionEnd = parentSectionEnd;
1860
+ }
1726
1861
 
1727
1862
  if (reader.offset !== end) {
1728
1863
  if (reader.offset > end) {
package/src/text.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { TextStyle, LayerTextData, ParagraphStyle, Font, AntiAlias, TextGridInfo, Justification, Color, TextPath, TextStyleRun } from './psd';
2
- import { clamp } from './helpers';
2
+ import { arrayItem, clamp } from './helpers';
3
3
 
4
4
  interface Adjustments {
5
5
  Axis: number[];
@@ -542,7 +542,7 @@ export function decodeEngineData(engineData: EngineData) {
542
542
 
543
543
  const result: LayerTextData = {
544
544
  text,
545
- antiAlias: antialias[engineDict.AntiAlias] ?? 'smooth',
545
+ antiAlias: arrayItem(antialias, engineDict.AntiAlias) ?? 'smooth',
546
546
  useFractionalGlyphWidths: !!engineDict.UseFractionalGlyphWidths,
547
547
  superscriptSize: resourceDict.SuperscriptSize,
548
548
  superscriptPosition: resourceDict.SuperscriptPosition,
@@ -606,9 +606,9 @@ export function decodeEngineData(engineData: EngineData) {
606
606
  const styleRun = engineDict.StyleRun;
607
607
 
608
608
  // style runs without a font use the font of the normal style sheet
609
- const normalStyleSheet = resourceDict.StyleSheetSet?.[resourceDict.TheNormalStyleSheet ?? 0]?.StyleSheetData;
610
- const normalFontIndex = normalStyleSheet?.Font;
611
- const normalFont = (normalFontIndex !== undefined ? fonts[normalFontIndex] : undefined) ?? fonts[0];
609
+ const styleSheetSet = Array.isArray(resourceDict.StyleSheetSet) ? resourceDict.StyleSheetSet : [];
610
+ const normalStyleSheet = arrayItem(styleSheetSet, resourceDict.TheNormalStyleSheet ?? 0)?.StyleSheetData;
611
+ const normalFont = arrayItem(fonts, normalStyleSheet?.Font) ?? fonts[0];
612
612
 
613
613
  result.style = {}; // decodeStyle(styleSheetData, fonts);
614
614
  result.styleRuns = [];