psd 4.1.0 → 4.2.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.
Files changed (75) hide show
  1. package/README.md +139 -5
  2. package/dist/descriptor.js +6 -2
  3. package/dist/descriptor.js.map +1 -1
  4. package/dist/image.d.ts +22 -2
  5. package/dist/image.d.ts.map +1 -1
  6. package/dist/image.js +28 -10
  7. package/dist/image.js.map +1 -1
  8. package/dist/index.d.ts +9 -6
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +3 -1
  11. package/dist/index.js.map +1 -1
  12. package/dist/layer-info.d.ts +52 -5
  13. package/dist/layer-info.d.ts.map +1 -1
  14. package/dist/layer-info.js +32 -5
  15. package/dist/layer-info.js.map +1 -1
  16. package/dist/layer-styles.d.ts +10 -0
  17. package/dist/layer-styles.d.ts.map +1 -1
  18. package/dist/layer-styles.js +5 -5
  19. package/dist/layer-styles.js.map +1 -1
  20. package/dist/layer.d.ts +32 -0
  21. package/dist/layer.d.ts.map +1 -1
  22. package/dist/layer.js +55 -4
  23. package/dist/layer.js.map +1 -1
  24. package/dist/linked-files.d.ts +32 -0
  25. package/dist/linked-files.d.ts.map +1 -0
  26. package/dist/linked-files.js +45 -0
  27. package/dist/linked-files.js.map +1 -0
  28. package/dist/nodes.d.ts +11 -1
  29. package/dist/nodes.d.ts.map +1 -1
  30. package/dist/nodes.js +10 -0
  31. package/dist/nodes.js.map +1 -1
  32. package/dist/path-record.d.ts +28 -0
  33. package/dist/path-record.d.ts.map +1 -1
  34. package/dist/path-record.js +54 -1
  35. package/dist/path-record.js.map +1 -1
  36. package/dist/patterns.d.ts +24 -0
  37. package/dist/patterns.d.ts.map +1 -0
  38. package/dist/patterns.js +108 -0
  39. package/dist/patterns.js.map +1 -0
  40. package/dist/png.d.ts +11 -2
  41. package/dist/png.d.ts.map +1 -1
  42. package/dist/png.js +11 -2
  43. package/dist/png.js.map +1 -1
  44. package/dist/psd.d.ts +13 -2
  45. package/dist/psd.d.ts.map +1 -1
  46. package/dist/psd.js +23 -1
  47. package/dist/psd.js.map +1 -1
  48. package/dist/resources.d.ts +6 -0
  49. package/dist/resources.d.ts.map +1 -1
  50. package/dist/resources.js +18 -0
  51. package/dist/resources.js.map +1 -1
  52. package/dist/shapes.d.ts +94 -0
  53. package/dist/shapes.d.ts.map +1 -0
  54. package/dist/shapes.js +76 -0
  55. package/dist/shapes.js.map +1 -0
  56. package/dist/type-tool.d.ts +27 -2
  57. package/dist/type-tool.d.ts.map +1 -1
  58. package/dist/type-tool.js +29 -2
  59. package/dist/type-tool.js.map +1 -1
  60. package/package.json +3 -2
  61. package/src/descriptor.ts +6 -2
  62. package/src/image.ts +48 -12
  63. package/src/index.ts +17 -5
  64. package/src/layer-info.ts +74 -5
  65. package/src/layer-styles.ts +7 -5
  66. package/src/layer.ts +66 -4
  67. package/src/linked-files.ts +66 -0
  68. package/src/nodes.ts +14 -1
  69. package/src/path-record.ts +63 -2
  70. package/src/patterns.ts +113 -0
  71. package/src/png.ts +21 -2
  72. package/src/psd.ts +25 -1
  73. package/src/resources.ts +20 -0
  74. package/src/shapes.ts +156 -0
  75. package/src/type-tool.ts +45 -2
package/src/image.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { ChannelInfo, Layer } from './layer.ts';
2
- import { encodePng, inflate } from './png.ts';
2
+ import { encodePng, iccColorSpace, inflate } from './png.ts';
3
3
  import type { Header } from './psd.ts';
4
4
  import type { Reader } from './reader.ts';
5
5
  import type { Resources } from './resources.ts';
@@ -30,7 +30,7 @@ interface ColorModel {
30
30
  }
31
31
 
32
32
  /** The color model for a document. Throws for formats this library can't decode. Resources are only read for indexed images. */
33
- function colorModel(header: Header, resources: () => Resources): ColorModel {
33
+ function colorModel(header: Header, resources: () => Pick<Resources, 'indexedColorCount' | 'transparencyIndex'>): ColorModel {
34
34
  const { mode, depth, channels, modeName } = header;
35
35
  if ((mode === 0) !== (depth === 1)) throw new Error(`Decoding ${depth}-bit ${modeName} images is not supported`);
36
36
  switch (mode) {
@@ -181,13 +181,12 @@ function to8Bit(data: Uint8Array, depth: number, width: number, height: number):
181
181
  }
182
182
 
183
183
  /**
184
- * Decodes `count` planes stored back to back after a single compression type, as 8-bit samples.
184
+ * Decodes `count` planes stored back to back with a single compression type, as 8-bit samples.
185
185
  * The composite image is stored this way, and so is each layer channel (with a count of 1).
186
186
  */
187
- async function readPlanes(r: Reader, end: number, count: number, width: number, height: number, header: Header): Promise<Uint8Array[]> {
187
+ async function readPlanes(r: Reader, compression: number, end: number, count: number, width: number, height: number, header: Header): Promise<Uint8Array[]> {
188
188
  const { depth } = header;
189
189
  if (depth !== 1 && depth !== 8 && depth !== 16) throw new Error(`Decoding ${depth}-bit images is not supported`);
190
- const compression = r.uint16();
191
190
  if (width === 0 || height === 0) return Array.from({ length: count }, () => new Uint8Array());
192
191
 
193
192
  const stride = rowBytes(width, depth);
@@ -217,8 +216,29 @@ async function readPlanes(r: Reader, end: number, count: number, width: number,
217
216
  }
218
217
 
219
218
  /** Decodes a single layer channel. */
220
- const readLayerChannel = async (reader: Reader, channel: ChannelInfo, width: number, height: number, header: Header) =>
221
- (await readPlanes(reader.at(channel.offset), channel.offset + channel.length, 1, width, height, header))[0]!;
219
+ async function readLayerChannel(reader: Reader, channel: ChannelInfo, width: number, height: number, header: Header) {
220
+ const r = reader.at(channel.offset);
221
+ return (await readPlanes(r, r.uint16(), channel.offset + channel.length, 1, width, height, header))[0]!;
222
+ }
223
+
224
+ /** A separately compressed plane, such as a pattern channel. */
225
+ export interface Plane {
226
+ /** 0, 1, 2... for colors, -1 for transparency. */
227
+ id: number;
228
+ compression: number;
229
+ /** Where the compressed data starts and ends. */
230
+ offset: number;
231
+ end: number;
232
+ }
233
+
234
+ /** Decodes planes to RGBA. `header` describes the planes, not the document; indexed colors come from its `colorModeData` with no transparent index. */
235
+ export async function decodePlanes(reader: Reader, header: Header, planes: Plane[]): Promise<RGBAImage> {
236
+ const { width, height } = header;
237
+ const model = colorModel(header, () => ({ indexedColorCount: undefined, transparencyIndex: undefined }));
238
+ const decoded = new Map<number, Uint8Array>();
239
+ for (const p of planes) decoded.set(p.id, (await readPlanes(reader.at(p.offset), p.compression, p.end, 1, width, height, header))[0]!);
240
+ return { width, height, data: toRgba(model, decoded, width * height) };
241
+ }
222
242
 
223
243
  /** Converts a cyan, magenta or yellow ink amount and the black amount to the matching RGB component. */
224
244
  const inkToRgb = (ink: number, k: number) => Math.min(Math.max((65535 - (ink * (255 - k) + (k << 8))) >> 8, 0), 255);
@@ -241,6 +261,20 @@ export function labToRgb(l: number, a: number, b: number): [number, number, numb
241
261
  ];
242
262
  }
243
263
 
264
+ export interface ToPngOptions {
265
+ /**
266
+ * Embed the document's ICC profile when it's an RGB profile. Defaults to `true`. Turn it off for
267
+ * smaller files when the colors are sRGB anyway, or when you manage color yourself.
268
+ */
269
+ embedProfile?: boolean;
270
+ }
271
+
272
+ /** The document's ICC profile if it should be embedded in an RGBA PNG; CMYK, Lab and grayscale profiles can't be. */
273
+ function rgbProfile(resources: Resources, { embedProfile = true }: ToPngOptions): Uint8Array | undefined {
274
+ const profile = embedProfile ? resources.iccProfile : undefined;
275
+ return profile && iccColorSpace(profile) === 'RGB ' ? profile : undefined;
276
+ }
277
+
244
278
  /** The flattened composite image stored at the end of the file. */
245
279
  export class CompositeImage {
246
280
  readonly #reader: Reader;
@@ -271,7 +305,7 @@ export class CompositeImage {
271
305
  const { width, height, channels: count } = header;
272
306
  const model = colorModel(header, this.#resources);
273
307
  const r = this.#reader.at(this.#reader.pos);
274
- const planes = await readPlanes(r, r.bytes.length, count, width, height, header);
308
+ const planes = await readPlanes(r, r.uint16(), r.bytes.length, count, width, height, header);
275
309
 
276
310
  const channels = new Map(planes.slice(0, model.colorCount).entries());
277
311
  // A single extra channel is transparency; more than that are saved selections and spot colors.
@@ -279,8 +313,9 @@ export class CompositeImage {
279
313
  return { width, height, data: toRgba(model, channels, width * height) };
280
314
  }
281
315
 
282
- async toPng(): Promise<Uint8Array> {
283
- return encodePng(await this.decode());
316
+ /** Encodes `decode()` as a PNG, with the document's ICC profile when it's an RGB profile (see `options`). */
317
+ async toPng(options: ToPngOptions = {}): Promise<Uint8Array> {
318
+ return encodePng(await this.decode(), { iccProfile: rgbProfile(this.#resources(), options) });
284
319
  }
285
320
  }
286
321
 
@@ -332,7 +367,8 @@ export class LayerImage {
332
367
  return { width: mask.width, height: mask.height, data: await readLayerChannel(this.#reader, channel, mask.width, mask.height, header) };
333
368
  }
334
369
 
335
- async toPng(): Promise<Uint8Array> {
336
- return encodePng(await this.decode());
370
+ /** Encodes `decode()` as a PNG, with the document's ICC profile when it's an RGB profile (see `options`). */
371
+ async toPng(options: ToPngOptions = {}): Promise<Uint8Array> {
372
+ return encodePng(await this.decode(), { iccProfile: rgbProfile(this.#resources(), options) });
337
373
  }
338
374
  }
package/src/index.ts CHANGED
@@ -9,9 +9,10 @@ export {
9
9
  type ChannelInfo,
10
10
  type GlobalMask,
11
11
  type InfoBlock,
12
+ type LayerKind,
12
13
  type Mask,
13
14
  } from './layer.ts';
14
- export type { LayerInfo } from './layer-info.ts';
15
+ export type { LayerInfo, PlacedLayer, Point } from './layer-info.ts';
15
16
  export { descriptorColor } from './layer-styles.ts';
16
17
  export type {
17
18
  Bevel,
@@ -27,12 +28,23 @@ export type {
27
28
  Shadow,
28
29
  Stroke,
29
30
  } from './layer-styles.ts';
30
- export { TypeTool, type RGBA, type TextAlignment, type TextRun, type Transform } from './type-tool.ts';
31
- export { CompositeImage, LayerImage, type GrayImage, type RGBAImage } from './image.ts';
32
- export { encodePng, type Pixels } from './png.ts';
31
+ export type { ShapeContent, VectorFill, VectorOrigination, VectorShape, VectorStroke } from './shapes.ts';
32
+ export {
33
+ TypeTool,
34
+ type RGBA,
35
+ type TextAlignment,
36
+ type TextBaseline,
37
+ type TextCaps,
38
+ type TextRun,
39
+ type Transform,
40
+ } from './type-tool.ts';
41
+ export { CompositeImage, LayerImage, type GrayImage, type RGBAImage, type ToPngOptions } from './image.ts';
42
+ export { encodePng, type Pixels, type PngOptions } from './png.ts';
43
+ export type { LinkedFile } from './linked-files.ts';
44
+ export { Pattern } from './patterns.ts';
33
45
  export { Resources } from './resources.ts';
34
46
  export type { Bounds, Guide, LayerComp, ResolutionInfo, ResourceBlock, SavedPath, Slice, Slices } from './resources.ts';
35
47
  export type { Descriptor, DescriptorClass, UnitValue } from './descriptor.ts';
36
- export type { PathPoint, PathRecord } from './path-record.ts';
48
+ export { pathToSvg, type PathPoint, type PathRecord } from './path-record.ts';
37
49
  export { parseEngineData, type EngineDict, type EngineValue } from './engine-data.ts';
38
50
  export type { SpaceColor } from './reader.ts';
package/src/layer-info.ts CHANGED
@@ -4,6 +4,7 @@ import { readLayerStyles } from './layer-styles.ts';
4
4
  import { readPathRecords } from './path-record.ts';
5
5
  import type { Header } from './psd.ts';
6
6
  import type { Reader, SpaceColor } from './reader.ts';
7
+ import { readVectorFill, readVectorOrigination, readVectorStroke } from './shapes.ts';
7
8
  import { readLegacyTypeTool, TypeTool } from './type-tool.ts';
8
9
 
9
10
  interface Ctx {
@@ -340,6 +341,71 @@ function readEffectsLayer(r: Reader) {
340
341
  return effects;
341
342
  }
342
343
 
344
+ export interface Point {
345
+ x: number;
346
+ y: number;
347
+ }
348
+
349
+ /** A smart object's source and placement. The raw descriptor, including the warp, is `data`. */
350
+ export interface PlacedLayer {
351
+ /** The source file's ID in the document's linked file data. Copies of a smart object share it. */
352
+ fileId: string;
353
+ /** The page of a multi-page source such as a PDF, from 1. */
354
+ page: number;
355
+ totalPages: number;
356
+ /**
357
+ * Where the content's corners are in the document, in pixels: top left, top right, bottom
358
+ * right, bottom left. Unlike the layer's bounds, these include transparent edges and follow
359
+ * rotation. The raw values are in `data.Trnf`.
360
+ */
361
+ corners: [Point, Point, Point, Point];
362
+ /** The corners including any perspective or distort transform. Undefined in older files. */
363
+ nonAffineCorners: [Point, Point, Point, Point] | undefined;
364
+ /** The content's size, in its own pixels. */
365
+ size: { width: number; height: number };
366
+ /** The content's resolution, in pixels per inch. */
367
+ resolution: number;
368
+ /**
369
+ * Degrees clockwise, from the angle of the top edge. Only meaningful without skew or perspective.
370
+ */
371
+ rotation: number;
372
+ /**
373
+ * The corners' size relative to `size`. A flip makes `y` negative (a horizontal flip is a
374
+ * 180° rotation plus a vertical flip). Photoshop's W and H percentages are relative to the
375
+ * content's physical size instead, so they differ when `resolution` isn't the document's.
376
+ */
377
+ scale: { x: number; y: number };
378
+ /** The raw descriptor, for anything not covered above, such as the `warp`. */
379
+ data: Descriptor;
380
+ }
381
+
382
+ type Corners = PlacedLayer['corners'];
383
+
384
+ const corners = (values: number[]) =>
385
+ [0, 2, 4, 6].map((i) => ({ x: values[i]!, y: values[i + 1]! })) as Corners;
386
+
387
+ /** Normalizes a smart object's descriptor. */
388
+ export function readPlacedLayer(d: Descriptor): PlacedLayer {
389
+ if (d.Trnf?.length !== 8) throw new Error('Smart object descriptor has no transform');
390
+ const [topLeft, topRight, , bottomLeft] = corners(d.Trnf);
391
+ const top = { x: topRight.x - topLeft.x, y: topRight.y - topLeft.y };
392
+ const left = { x: bottomLeft.x - topLeft.x, y: bottomLeft.y - topLeft.y };
393
+ const size = { width: d['Sz '].Wdth as number, height: d['Sz '].Hght as number };
394
+ const flip = Math.sign(top.x * left.y - top.y * left.x) || 1;
395
+ return {
396
+ fileId: d.Idnt,
397
+ page: d.PgNm,
398
+ totalPages: d.totalPages,
399
+ corners: corners(d.Trnf),
400
+ nonAffineCorners: d.nonAffineTransform && corners(d.nonAffineTransform),
401
+ size,
402
+ resolution: d.Rslt.value,
403
+ rotation: (Math.atan2(top.y, top.x) * 180) / Math.PI,
404
+ scale: { x: Math.hypot(top.x, top.y) / size.width, y: (flip * Math.hypot(left.x, left.y)) / size.height },
405
+ data: d,
406
+ };
407
+ }
408
+
343
409
  function readMetadata(r: Reader) {
344
410
  const metadata: { layerComp?: Descriptor } = {};
345
411
  const count = r.int32();
@@ -501,8 +567,8 @@ const LAYER_INFO = {
501
567
  objectEffects: { keys: ['lfx2', 'lmfx', 'lfxs'], parse: (r: Reader) => readLayerStyles(descriptorAfter(8)(r)) },
502
568
  patternFill: { keys: ['PtFl'], parse: descriptorAfter(4) },
503
569
  photoFilter: { keys: ['phfl'], parse: readPhotoFilter },
504
- /** Smart object data. */
505
- placedLayer: { keys: ['SoLd', 'SoLE'], parse: descriptorAfter(12) },
570
+ /** Smart object data: its normalized source and placement, with the raw descriptor as `data`. */
571
+ placedLayer: { keys: ['SoLd', 'SoLE'], parse: (r: Reader) => readPlacedLayer(descriptorAfter(12)(r)) },
506
572
  posterize: { keys: ['post'], parse: (r: Reader) => r.int16() },
507
573
  referencePoint: { keys: ['fxrp'], parse: (r: Reader) => ({ x: r.float64(), y: r.float64() }) },
508
574
  sectionDivider: { keys: ['lsct'], parse: readDivider },
@@ -534,9 +600,12 @@ const LAYER_INFO = {
534
600
  },
535
601
  },
536
602
  vectorMaskAsGlobalMask: { keys: ['vmgm'], parse: flag },
537
- vectorOrigination: { keys: ['vogk'], parse: descriptorAfter(8) },
538
- vectorStroke: { keys: ['vstk'], parse: descriptorAfter(4) },
539
- vectorStrokeContent: { keys: ['vscg'], parse: descriptorAfter(8) },
603
+ /** Live shape properties: `shapes`, one per shape in the layer, and the raw descriptor as `data`. */
604
+ vectorOrigination: { keys: ['vogk'], parse: (r: Reader) => readVectorOrigination(descriptorAfter(8)(r)) },
605
+ /** A shape layer's stroke, and whether its fill and stroke are shown, with the raw descriptor as `data`. */
606
+ vectorStroke: { keys: ['vstk'], parse: (r: Reader) => readVectorStroke(descriptorAfter(4)(r)) },
607
+ /** A shape layer's fill: its `color`, `gradient` or `pattern`, with the raw descriptor as `data`. */
608
+ vectorStrokeContent: { keys: ['vscg'], parse: (r: Reader) => readVectorFill(descriptorAfter(8)(r)) },
540
609
  vibrance: {
541
610
  keys: ['vibA'],
542
611
  parse: (r: Reader) => {
@@ -36,6 +36,7 @@ export interface Shadow extends Effect {
36
36
  color: RGB | undefined;
37
37
  /** Degrees. */
38
38
  angle: number;
39
+ /** Use the document's `resources.globalAngle` instead of `angle`. */
39
40
  useGlobalLight: boolean;
40
41
  distance: number;
41
42
  /** "Spread" for drop shadows, "choke" for inner shadows, in pixels. */
@@ -78,6 +79,7 @@ export interface Bevel {
78
79
  soften: number;
79
80
  angle: number;
80
81
  altitude: number;
82
+ /** Use the document's `resources.globalAngle` and `globalAltitude` instead of `angle` and `altitude`. */
81
83
  useGlobalLight: boolean;
82
84
  highlight: { blendMode: BlendMode | string | undefined; color: RGB | undefined; opacity: number };
83
85
  shadow: { blendMode: BlendMode | string | undefined; color: RGB | undefined; opacity: number };
@@ -179,14 +181,14 @@ const BLEND_MODES: Record<string, BlendMode> = {
179
181
 
180
182
  /** Unit values (`{ value }`) and plain numbers as a number. */
181
183
  const num = (v: any): number => (typeof v === 'object' && v !== null ? v.value : (v ?? 0));
182
- const percent = (v: any) => num(v) / 100;
183
- const enumValue = (v: any): string | undefined => v?.value?.trim();
184
- const blendMode = (v: any) => {
184
+ export const percent = (v: any) => num(v) / 100;
185
+ export const enumValue = (v: any): string | undefined => v?.value?.trim();
186
+ export const blendMode = (v: any) => {
185
187
  const value = enumValue(v);
186
188
  return value === undefined ? undefined : (BLEND_MODES[value] ?? value);
187
189
  };
188
190
  const contour = (v: any): string | undefined => v?.['Nm '];
189
- const pattern = (v: any) => (v ? { name: v['Nm '] as string, id: v.Idnt as string } : undefined);
191
+ export const pattern = (v: any) => (v ? { name: v['Nm '] as string, id: v.Idnt as string } : undefined);
190
192
 
191
193
  /** Converts a descriptor color to RGB. */
192
194
  export function descriptorColor(c: Descriptor | undefined): RGB | undefined {
@@ -220,7 +222,7 @@ export function descriptorColor(c: Descriptor | undefined): RGB | undefined {
220
222
  }
221
223
  }
222
224
 
223
- function gradient(g: Descriptor | undefined): Gradient | undefined {
225
+ export function gradient(g: Descriptor | undefined): Gradient | undefined {
224
226
  if (!g) return undefined;
225
227
  const stop = (s: Descriptor) => ({ location: s.Lctn / 4096, midpoint: s.Mdpn / 100 });
226
228
  return {
package/src/layer.ts CHANGED
@@ -59,6 +59,18 @@ export interface Mask {
59
59
  relative: boolean;
60
60
  disabled: boolean;
61
61
  invert: boolean;
62
+ /** The user (pixel) mask's density, 0 to 1. 1 unless set in the Properties panel. */
63
+ density: number;
64
+ /** The user mask's feather, in pixels. */
65
+ feather: number;
66
+ /**
67
+ * The vector mask's density, 0 to 1. Photoshop stores it here, in the layer mask record, so it's
68
+ * only available when the layer has one: setting a vector mask's density or feather makes
69
+ * Photoshop write one.
70
+ */
71
+ vectorDensity: number;
72
+ /** The vector mask's feather, in pixels. */
73
+ vectorFeather: number;
62
74
  }
63
75
 
64
76
  export interface BlendingRange {
@@ -87,8 +99,17 @@ export interface GlobalMask {
87
99
  kind: number;
88
100
  }
89
101
 
102
+ /**
103
+ * What a layer is, as shown in Photoshop's layers panel. See `Layer.kind` for how it's decided.
104
+ * Video and 3D layers are `'pixel'`.
105
+ */
106
+ export type LayerKind = 'group' | 'text' | 'smartObject' | 'adjustment' | 'shape' | 'fill' | 'pixel';
107
+
108
+ const ADJUSTMENT_KEYS = ['brit', 'CgEd', 'levl', 'curv', 'expA', 'vibA', 'hue ', 'hue2', 'blnc', 'blwh', 'phfl', 'mixr', 'clrL', 'nvrt', 'post', 'thrs', 'selc', 'grdm'];
109
+ const FILL_KEYS = ['SoCo', 'GdFl', 'PtFl'];
110
+
90
111
  /** Tagged block keys whose length is 8 bytes in PSB files. */
91
- const BIG_KEYS = new Set(['LMsk', 'Lr16', 'Lr32', 'Layr', 'Mt16', 'Mt32', 'Mtrn', 'Alph', 'FMsk', 'lnk2', 'FEid', 'FXid', 'PxSD']);
112
+ const BIG_KEYS = new Set(['LMsk', 'Lr16', 'Lr32', 'Layr', 'Mt16', 'Mt32', 'Mtrn', 'Alph', 'FMsk', 'lnk2', 'lnk3', 'lnkE', 'FEid', 'FXid', 'PxSD']);
92
113
 
93
114
  export const readBlockLength = (r: Reader, header: Header, key: string) =>
94
115
  header.isBig && BIG_KEYS.has(key) ? r.int64() : r.uint32();
@@ -147,7 +168,7 @@ export class Layer {
147
168
  const extraLength = r.uint32();
148
169
  const end = r.pos + extraLength;
149
170
 
150
- this.mask = readMask(r);
171
+ this.mask = readMask(r, this.channels.some((c) => c.id === -3));
151
172
  this.blendingRanges = readBlendingRanges(r);
152
173
 
153
174
  const nameLength = ((r.uint8() + 4) & ~3) - 1; // padded to a multiple of 4, including the length byte
@@ -208,13 +229,37 @@ export class Layer {
208
229
  return divider ? divider.isHidden : this.name === '</Layer group>';
209
230
  }
210
231
 
232
+ /**
233
+ * What the layer is, from the blocks it has, checked in this order:
234
+ *
235
+ * 1. `'group'`: a group's start or end marker, including artboards.
236
+ * 2. `'text'`: has type tool data.
237
+ * 3. `'smartObject'`: has placed layer data, embedded or linked.
238
+ * 4. `'adjustment'`: has adjustment settings (levels, curves...), even if it also has a vector mask.
239
+ * 5. `'shape'`: has a vector mask and fill content. This includes a fill layer with a vector mask,
240
+ * which is how Photoshop has always stored shapes, so the two can't be told apart.
241
+ * 6. `'fill'`: a solid color, gradient or pattern fill layer.
242
+ * 7. `'pixel'`: anything else, including pixel layers with a vector mask drawn with a shape tool.
243
+ */
244
+ get kind(): LayerKind {
245
+ const has = (...keys: string[]) => this.infoBlocks.some((b) => keys.includes(b.key));
246
+ if (this.isFolder || this.isFolderEnd) return 'group';
247
+ if (has('TySh', 'tySh')) return 'text';
248
+ if (has('SoLd', 'SoLE', 'PlLd', 'plLd')) return 'smartObject';
249
+ if (has(...ADJUSTMENT_KEYS)) return 'adjustment';
250
+ const fill = has(...FILL_KEYS);
251
+ if ((fill || has('vscg')) && has('vmsk', 'vsms')) return 'shape';
252
+ return fill ? 'fill' : 'pixel';
253
+ }
254
+
211
255
  /** The layer's pixels. Decoding happens on demand. */
212
256
  get image(): LayerImage {
213
257
  return (this.#image ??= new LayerImage(this, this.#reader, this.#resources));
214
258
  }
215
259
  }
216
260
 
217
- function readMask(r: Reader): Mask | undefined {
261
+ /** `hasRealMask`: the layer has a real user mask channel (-3), whose fields precede the parameters. */
262
+ function readMask(r: Reader, hasRealMask: boolean): Mask | undefined {
218
263
  const size = r.uint32();
219
264
  if (size === 0) return undefined;
220
265
  const end = r.pos + size;
@@ -224,6 +269,19 @@ function readMask(r: Reader): Mask | undefined {
224
269
  const right = r.int32();
225
270
  const defaultColor = r.uint8();
226
271
  const flags = r.uint8();
272
+ // Photoshop only writes parameters that differ from these defaults.
273
+ const params = { density: 1, feather: 0, vectorDensity: 1, vectorFeather: 0 };
274
+ if (flags & 0x10) {
275
+ // The spec puts the parameters first, but Photoshop writes the real user mask's flags,
276
+ // default color and rectangle before them. Its size can't tell them apart, the channel can.
277
+ if (hasRealMask && size >= 36) r.skip(18);
278
+ const present = r.uint8();
279
+ if (present & 0x01) params.density = r.uint8() / 255;
280
+ if (present & 0x02) params.feather = r.float64();
281
+ if (present & 0x04) params.vectorDensity = r.uint8() / 255;
282
+ if (present & 0x08) params.vectorFeather = r.float64();
283
+ if (r.pos > end) throw new Error(`Layer mask parameters overrun the ${size} byte mask record`);
284
+ }
227
285
  r.seek(end);
228
286
  return {
229
287
  top,
@@ -236,6 +294,7 @@ function readMask(r: Reader): Mask | undefined {
236
294
  relative: (flags & 0x01) > 0,
237
295
  disabled: (flags & 0x02) > 0,
238
296
  invert: (flags & 0x04) > 0,
297
+ ...params,
239
298
  };
240
299
  }
241
300
 
@@ -257,6 +316,8 @@ export interface LayerSection {
257
316
  globalMask: GlobalMask | undefined;
258
317
  /** The first alpha channel of the composite image holds the merged transparency. */
259
318
  mergedAlpha: boolean;
319
+ /** Document-wide tagged blocks after the global mask, such as linked files and patterns. */
320
+ infoBlocks: InfoBlock[];
260
321
  }
261
322
 
262
323
  /**
@@ -264,7 +325,7 @@ export interface LayerSection {
264
325
  * `resources` is only read when decoding indexed color layers, which need the color table.
265
326
  */
266
327
  export function readLayerSection(r: Reader, header: Header, resources: () => Resources): LayerSection {
267
- const section: LayerSection = { layers: [], globalMask: undefined, mergedAlpha: false };
328
+ const section: LayerSection = { layers: [], globalMask: undefined, mergedAlpha: false, infoBlocks: [] };
268
329
  const length = header.isBig ? r.int64() : r.uint32();
269
330
  const end = r.pos + length;
270
331
  if (length === 0) return section;
@@ -305,6 +366,7 @@ export function readLayerSection(r: Reader, header: Header, resources: () => Res
305
366
  const key = r.ascii(4);
306
367
  const blockLength = pad2(readBlockLength(r, header, key));
307
368
  const blockEnd = r.pos + blockLength;
369
+ section.infoBlocks.push({ key, offset: r.pos, length: blockLength });
308
370
  if (key === `Lr${header.depth}`) {
309
371
  section.layers = [];
310
372
  readLayers(blockLength);
@@ -0,0 +1,66 @@
1
+ import { readDescriptor, type Descriptor } from './descriptor.ts';
2
+ import type { Reader } from './reader.ts';
3
+
4
+ const TYPES = { liFD: 'embedded', liFE: 'external', liFA: 'alias' } as const;
5
+
6
+ /** A file placed in the document as a smart object, from the `lnk2`, `lnk3`, `lnkD` or `lnkE` blocks. */
7
+ export interface LinkedFile {
8
+ /** The unique ID that smart object layers refer to in `info.placedLayer.fileId`. */
9
+ id: string;
10
+ /** The original file name. */
11
+ name: string;
12
+ /** Whether the file is embedded in the document, or a link to an external file or alias. */
13
+ type: (typeof TYPES)[keyof typeof TYPES];
14
+ /** The file type code, such as `'8BPB'` for PSD and PSB or `'png '`. Can be empty. */
15
+ fileType: string;
16
+ /** The creator code. Can be empty. */
17
+ creator: string;
18
+ version: number;
19
+ /**
20
+ * The file contents, for embedded files and external files that store a copy. Embedded PSD and
21
+ * PSB files can be opened with `new PSD(data)`.
22
+ */
23
+ data?: Uint8Array;
24
+ /** For external files: where the file was, with keys such as `fullPath`, `relPath` and `originalPath`. */
25
+ location?: Descriptor;
26
+ }
27
+
28
+ /** Reads the linked files in a `lnk2`, `lnk3`, `lnkD` or `lnkE` block. The data is a view into the file, not a copy. */
29
+ export function readLinkedFiles(r: Reader, end: number): LinkedFile[] {
30
+ const files: LinkedFile[] = [];
31
+ // Each file is a length-prefixed record padded to 4 bytes. Some blocks end with padding too short to hold one.
32
+ while (r.pos + 8 <= end) {
33
+ const length = r.int64();
34
+ const next = r.pos + ((length + 3) & ~3);
35
+ if (r.pos + length > end) throw new Error(`Linked file of ${length} bytes overruns its block`);
36
+
37
+ const key = r.ascii(4);
38
+ const type = TYPES[key as keyof typeof TYPES];
39
+ if (!type) throw new Error(`Unknown linked file type '${key}'`);
40
+ const version = r.uint32();
41
+ const id = r.pascal();
42
+ const name = r.unicode();
43
+ const fileType = r.ascii(4);
44
+ const creator = r.ascii(4);
45
+ const dataLength = r.int64();
46
+ if (r.bool()) {
47
+ r.skip(4); // descriptor version
48
+ readDescriptor(r); // open file descriptor
49
+ }
50
+
51
+ const file: LinkedFile = { id, name, type, fileType, creator, version };
52
+ if (type === 'external') {
53
+ r.skip(4); // descriptor version
54
+ file.location = readDescriptor(r);
55
+ if (version > 3) r.skip(16); // modification time: year (4), month, day, hour, minute (1 each), seconds (8)
56
+ r.skip(8); // the external file's size
57
+ if (version >= 2 && dataLength > 0) file.data = r.bytesView(dataLength);
58
+ } else if (type === 'embedded') {
59
+ file.data = r.bytesView(dataLength);
60
+ }
61
+ // Version 5+ fields (child document ID, modification time, lock state) aren't read.
62
+ files.push(file);
63
+ r.seek(next);
64
+ }
65
+ return files;
66
+ }
package/src/nodes.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { LayerImage } from './image.ts';
2
- import type { BlendMode, Layer } from './layer.ts';
2
+ import type { BlendMode, Layer, LayerKind } from './layer.ts';
3
3
  import type { LayerInfo } from './layer-info.ts';
4
+ import type { LinkedFile } from './linked-files.ts';
4
5
  import type { PSD } from './psd.ts';
5
6
  import type { LayerComp } from './resources.ts';
6
7
 
@@ -180,6 +181,11 @@ abstract class LayerBackedNode extends BaseNode {
180
181
  return this.layer.info;
181
182
  }
182
183
 
184
+ /** `'group'`, `'text'`, `'shape'`, `'pixel'`... See `Layer.kind` for how it's decided. */
185
+ get kind(): LayerKind {
186
+ return this.layer.kind;
187
+ }
188
+
183
189
  /** Visible, accounting for clipping masks and the tree's layer comp. */
184
190
  get visible(): boolean {
185
191
  if (this.layer.clipped && this.clippingMask?.visible === false) return false;
@@ -272,6 +278,7 @@ abstract class LayerBackedNode extends BaseNode {
272
278
  toJSON() {
273
279
  return {
274
280
  type: this.type,
281
+ kind: this.kind,
275
282
  id: this.id,
276
283
  name: this.name,
277
284
  visible: this.visible,
@@ -317,6 +324,12 @@ export class LayerNode extends LayerBackedNode {
317
324
  return this.layer.image;
318
325
  }
319
326
 
327
+ /** For smart object layers, the placed file from `psd.linkedFiles`. */
328
+ get linkedFile(): LinkedFile | undefined {
329
+ const id = this.layer.info.placedLayer?.fileId;
330
+ return id === undefined ? undefined : this.root.psd.linkedFiles.find((f) => f.id === id);
331
+ }
332
+
320
333
  get isEmpty(): boolean {
321
334
  return this.width === 0 || this.height === 0;
322
335
  }
@@ -7,7 +7,17 @@ export interface PathPoint {
7
7
 
8
8
  /** One 26-byte record of a vector path (vector masks, saved paths, the work path). */
9
9
  export type PathRecord =
10
- | { recordType: 0 | 3; numPoints: number }
10
+ | {
11
+ /** 0 starts a closed subpath, 3 an open one. */
12
+ recordType: 0 | 3;
13
+ numPoints: number;
14
+ /**
15
+ * How this subpath combines with the shape built from the ones before it. Undocumented by Adobe:
16
+ * 1 combine (union), 2 subtract, 3 intersect, 0 exclude (xor), and -1 for a subpath that belongs
17
+ * to the same component as the previous one, like the inner contour of a ring.
18
+ */
19
+ operation: number;
20
+ }
11
21
  | {
12
22
  recordType: 1 | 2 | 4 | 5;
13
23
  /** Closed subpath records are 1 and 2; open are 4 and 5. */
@@ -34,7 +44,7 @@ function readPathRecord(r: Reader): PathRecord {
34
44
  switch (recordType) {
35
45
  case 0:
36
46
  case 3:
37
- record = { recordType, numPoints: r.int16() };
47
+ record = { recordType, numPoints: r.int16(), operation: r.int16() };
38
48
  break;
39
49
  case 1:
40
50
  case 2:
@@ -67,3 +77,54 @@ function readPathRecord(r: Reader): PathRecord {
67
77
  r.seek(start + 26);
68
78
  return record;
69
79
  }
80
+
81
+ /**
82
+ * Converts path records (`vectorMask.paths`, `workPath`, `savedPaths[].records`) to SVG path data, with one
83
+ * entry per shape component. Knot coordinates are fractions of the document size, so pass `psd.width` and
84
+ * `psd.height` to get document pixels.
85
+ *
86
+ * Fill each component with the even-odd rule. Photoshop then combines the components in order, starting
87
+ * from an empty canvas (or a full one if the first operation is subtract or intersect), by `operation`:
88
+ * 1 combine (union), 2 subtract, 3 intersect, 0 exclude (xor). The subpaths of one component, such as the
89
+ * two contours of a ring, share a `d`.
90
+ *
91
+ * Every knot becomes a cubic Bézier; closed subpaths end in `Z` and open ones don't. Other records,
92
+ * including the initial fill (8), are ignored. Throws if the knots don't match their subpath records.
93
+ *
94
+ * @example
95
+ * const [shape] = pathToSvg(node.info.vectorMask.paths, psd.width, psd.height);
96
+ * `<svg viewBox="0 0 ${psd.width} ${psd.height}"><path fill-rule="evenodd" d="${shape.d}"/></svg>`;
97
+ */
98
+ export function pathToSvg(records: readonly PathRecord[], width: number, height: number): { operation: number; d: string }[] {
99
+ const num = (n: number) => String(Math.round(n * 1000) / 1000 + 0); // + 0 turns -0 into 0
100
+ const xy = (p: PathPoint) => `${num(p.horiz * width)} ${num(p.vert * height)}`;
101
+ type Knot = Extract<PathRecord, { anchor: PathPoint }>;
102
+ const subpaths: { closed: boolean; operation: number; numPoints: number; knots: Knot[] }[] = [];
103
+
104
+ records.forEach((record, i) => {
105
+ if (record.recordType === 0 || record.recordType === 3) {
106
+ subpaths.push({ closed: record.recordType === 0, operation: record.operation, numPoints: record.numPoints, knots: [] });
107
+ } else if ('anchor' in record) {
108
+ const subpath = subpaths.at(-1);
109
+ if (!subpath || subpath.knots.length === subpath.numPoints || subpath.closed !== record.closed) {
110
+ throw new Error(`Path record ${i} is a knot outside of a ${record.closed ? 'closed' : 'open'} subpath`);
111
+ }
112
+ subpath.knots.push(record);
113
+ }
114
+ });
115
+
116
+ const components: { operation: number; d: string }[] = [];
117
+ for (const { closed, operation, numPoints, knots } of subpaths) {
118
+ if (knots.length !== numPoints) throw new Error(`Subpath has ${knots.length} of its ${numPoints} knots`);
119
+ let d = '';
120
+ if (knots.length) {
121
+ const segments = knots.slice(1).map((k, i) => `C${xy(knots[i]!.leaving)} ${xy(k.preceding)} ${xy(k.anchor)}`);
122
+ if (closed) segments.push(`C${xy(knots.at(-1)!.leaving)} ${xy(knots[0]!.preceding)} ${xy(knots[0]!.anchor)}Z`);
123
+ d = `M${xy(knots[0]!.anchor)}${segments.join('')}`;
124
+ }
125
+ if (operation !== -1) components.push({ operation, d });
126
+ else if (components.length) components.at(-1)!.d += d;
127
+ else throw new Error('The first subpath continues a shape component that does not exist');
128
+ }
129
+ return components;
130
+ }