@kitschpatrol/aphex 0.1.5 → 0.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.
package/dist/index.js CHANGED
@@ -6,15 +6,14 @@ import { spawn } from "node:child_process";
6
6
  import { ExifTool } from "exiftool-vendored";
7
7
  import { createLogger, injectionHelper } from "lognow";
8
8
  import os from "node:os";
9
- import { slug } from "github-slugger";
10
9
  import { fileURLToPath } from "node:url";
10
+ import { slug } from "github-slugger";
11
11
  import { createDefu } from "defu";
12
12
  import { imageSizeFromFile } from "image-size/fromFile";
13
13
  import { lookup, mimes } from "mrmime";
14
14
  import { Piscina } from "piscina";
15
15
  import { deepEqual } from "fast-equals";
16
- //#endregion
17
- //#region src/utilities/log.ts
16
+ // src/utilities/log.ts
18
17
  /**
19
18
  * The default logger instance for the library.
20
19
  */
@@ -29,8 +28,7 @@ let log = createLogger("@kitschpatrol/aphex");
29
28
  function setLogger(logger) {
30
29
  log = injectionHelper(logger);
31
30
  }
32
- //#endregion
33
- //#region src/utilities/exiftool.ts
31
+ // src/utilities/exiftool.ts
34
32
  /**
35
33
  * Centralized exiftool instance management
36
34
  *
@@ -38,10 +36,13 @@ function setLogger(logger) {
38
36
  * management to prevent hanging processes. The exiftool-vendored library spawns
39
37
  * persistent Perl processes that must be explicitly ended.
40
38
  */
41
- const exiftoolInstance = new ExifTool({
42
- maxProcs: 4,
43
- onIdleIntervalMillis: 1e3
44
- });
39
+ function createExiftool() {
40
+ return new ExifTool({
41
+ maxProcs: 4,
42
+ onIdleIntervalMillis: 1e3
43
+ });
44
+ }
45
+ let exiftoolInstance = createExiftool();
45
46
  let cleanupScheduled = false;
46
47
  let processExitHandlerInstalled = false;
47
48
  /**
@@ -49,13 +50,15 @@ let processExitHandlerInstalled = false;
49
50
  */
50
51
  function getExiftool() {
51
52
  scheduleProcessCleanup();
53
+ if (exiftoolInstance.ended) exiftoolInstance = createExiftool();
52
54
  return exiftoolInstance;
53
55
  }
54
56
  /**
55
57
  * End the exiftool process gracefully
56
58
  *
57
59
  * This should be called when you're done using exiftool to prevent hanging
58
- * processes. It's safe to call multiple times.
60
+ * processes. It's safe to call multiple times, and exiftool starts again the
61
+ * next time it's needed.
59
62
  */
60
63
  async function endExiftool() {
61
64
  if (exiftoolInstance.pids.length === 0) return;
@@ -105,8 +108,7 @@ function scheduleProcessCleanup() {
105
108
  })();
106
109
  });
107
110
  }
108
- //#endregion
109
- //#region src/utilities/file.ts
111
+ // src/utilities/file.ts
110
112
  /**
111
113
  * Removes the file extension from a file path
112
114
  */
@@ -165,8 +167,7 @@ async function getTempDirectory(...labels) {
165
167
  const prefix = labels.length > 0 ? `com.kitschpatrol.aphex.${labels.map((l) => l.toLowerCase()).join(".")}.` : "com.kitschpatrol.aphex.";
166
168
  return fse.mkdtemp(path.join(os.tmpdir(), prefix));
167
169
  }
168
- //#endregion
169
- //#region src/utilities/general.ts
170
+ // src/utilities/general.ts
170
171
  const UUID_REGEX = /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/iv;
171
172
  /**
172
173
  * Sips makes a mess of the temp folder and does not respect TMPDIR, so we need
@@ -197,13 +198,12 @@ function ensureArray(value) {
197
198
  return Array.isArray(value) ? value : [value];
198
199
  }
199
200
  /**
200
- * Ensure the length has a single item
201
+ * Assert that the array has exactly one element
201
202
  */
202
203
  function assertSingleElement(array) {
203
204
  if (array.length !== 1) throw new Error(`Expected array of length 1, got ${array.length}`);
204
205
  }
205
- //#endregion
206
- //#region src/utilities/paths.ts
206
+ // src/utilities/paths.ts
207
207
  /**
208
208
  * Import.meta.dirname for Node >= 20.19.0
209
209
  *
@@ -221,7 +221,7 @@ function getPackageAssetsPath(meta) {
221
221
  return path.basename(dirname) === "dist" ? path.join(dirname, "assets") : path.join("src", "assets");
222
222
  }
223
223
  /**
224
- * Asset directory path of package or distribution folder (Copied by tsdown)
224
+ * Workers directory path of package or distribution folder (Copied by tsdown)
225
225
  */
226
226
  function getPackageWorkersPath(meta) {
227
227
  const dirname = getDirname(meta);
@@ -235,60 +235,81 @@ function getPackageBinPath(meta) {
235
235
  const dirname = getDirname(meta);
236
236
  return path.basename(dirname) === "dist" ? path.join(dirname) : path.join("dist");
237
237
  }
238
- //#endregion
239
- //#region src/aphex-swift/cli-bridge.ts
240
- const SHELL_SPECIAL_CHARS_REGEX = /[\s'"\\]/v;
238
+ // src/aphex-swift/cli-bridge.ts
239
+ const SHELL_SAFE_REGEX = /^[\w\-.\/:=+,%@]+$/v;
240
+ const SESSION_RESTART_EXIT_CODE = 75;
241
241
  let interactiveProcess;
242
242
  let currentRequest;
243
+ let commandQueue = [];
244
+ const stoppedProcesses = /* @__PURE__ */ new WeakSet();
243
245
  /**
244
246
  * Start an interactive session with aphex-swift. Commands will be sent to this
245
247
  * persistent process instead of spawning new ones.
246
248
  *
249
+ * If the process ends on its own after it has answered a command, or to get rid
250
+ * of a render that timed out, another one takes its place and carries on with
251
+ * the commands that were waiting.
252
+ *
247
253
  * @throws {Error} If the session is already active or fails to start
248
254
  */
249
255
  async function interactiveSessionStart() {
250
256
  if (interactiveProcess !== void 0) throw new Error("Interactive session is already active");
251
- const binPath = getPackageBinPath(import.meta);
252
- interactiveProcess = spawn("./aphex-swift", ["interactive"], {
253
- cwd: binPath,
257
+ spawnInteractiveProcess();
258
+ await new Promise((resolve) => {
259
+ setTimeout(resolve, 100);
260
+ });
261
+ }
262
+ function spawnInteractiveProcess() {
263
+ const child = spawn("./aphex-swift", ["interactive"], {
264
+ cwd: getPackageBinPath(import.meta),
254
265
  stdio: [
255
266
  "pipe",
256
267
  "pipe",
257
268
  "pipe"
258
269
  ]
259
270
  });
260
- interactiveProcess.stdout?.on("data", (data) => {
261
- if (currentRequest === void 0) return;
271
+ interactiveProcess = child;
272
+ let hasResponded = false;
273
+ child.stdin.on("error", () => void 0);
274
+ child.stdout.on("data", (data) => {
275
+ if (interactiveProcess !== child || currentRequest === void 0) return;
262
276
  currentRequest.buffer += data.toString();
263
277
  try {
264
278
  JSON.parse(currentRequest.buffer);
265
279
  const response = currentRequest.buffer;
266
280
  const request = currentRequest;
267
281
  currentRequest = void 0;
282
+ hasResponded = true;
268
283
  request.resolve(response);
269
284
  processNextCommand();
270
285
  } catch {}
271
286
  });
272
- interactiveProcess.stderr?.on("data", (data) => {
273
- if (currentRequest === void 0) return;
287
+ child.stderr.on("data", (data) => {
288
+ if (interactiveProcess !== child || currentRequest === void 0) return;
274
289
  const error = new Error(data.toString().trim());
275
290
  const request = currentRequest;
276
291
  currentRequest = void 0;
277
292
  request.reject(error);
278
293
  processNextCommand();
279
294
  });
280
- interactiveProcess.on("close", (code) => {
295
+ child.on("close", (code) => {
296
+ if (interactiveProcess !== child) return;
297
+ interactiveProcess = void 0;
298
+ const interrupted = currentRequest;
299
+ currentRequest = void 0;
281
300
  const error = /* @__PURE__ */ new Error(`Interactive session exited with code ${code}`);
282
- if (currentRequest !== void 0) {
283
- currentRequest.reject(error);
284
- currentRequest = void 0;
301
+ const restart = !stoppedProcesses.has(child) && (hasResponded || code === SESSION_RESTART_EXIT_CODE);
302
+ if (interrupted !== void 0) {
303
+ if (restart && code === SESSION_RESTART_EXIT_CODE) commandQueue.unshift(interrupted);
304
+ else interrupted.reject(error);
305
+ }
306
+ if (restart) {
307
+ spawnInteractiveProcess();
308
+ processNextCommand();
309
+ return;
285
310
  }
286
311
  for (const queued of commandQueue) queued.reject(error);
287
312
  commandQueue = [];
288
- interactiveProcess = void 0;
289
- });
290
- await new Promise((resolve) => {
291
- setTimeout(resolve, 100);
292
313
  });
293
314
  }
294
315
  /**
@@ -297,6 +318,7 @@ async function interactiveSessionStart() {
297
318
  async function interactiveSessionStop() {
298
319
  if (interactiveProcess === void 0) return;
299
320
  const processToStop = interactiveProcess;
321
+ stoppedProcesses.add(processToStop);
300
322
  processToStop.stdin?.write("exit\n");
301
323
  processToStop.stdin?.end();
302
324
  await new Promise((resolve) => {
@@ -319,14 +341,12 @@ async function interactiveSessionStop() {
319
341
  function isInteractiveSessionActive() {
320
342
  return interactiveProcess !== void 0;
321
343
  }
322
- let commandQueue = [];
323
344
  function processNextCommand() {
324
345
  if (currentRequest !== void 0 || interactiveProcess === void 0 || commandQueue.length === 0) return;
325
346
  const next = commandQueue.shift();
326
347
  currentRequest = {
327
- buffer: "",
328
- reject: next.reject,
329
- resolve: next.resolve
348
+ ...next,
349
+ buffer: ""
330
350
  };
331
351
  interactiveProcess.stdin?.write(next.command + "\n");
332
352
  }
@@ -346,10 +366,11 @@ async function executeInteractiveCommand(command) {
346
366
  }
347
367
  /**
348
368
  * Escape and join arguments into a single command string for interactive mode.
349
- * Arguments with spaces or special characters are quoted.
369
+ * Any argument that isn't plainly safe is wrapped in single quotes, which a
370
+ * shell takes literally.
350
371
  */
351
372
  function escapeCommand(args) {
352
- return args.map((arg) => SHELL_SPECIAL_CHARS_REGEX.test(arg) ? `'${arg.replaceAll("'", String.raw`'\''`)}'` : arg).join(" ");
373
+ return args.map((arg) => SHELL_SAFE_REGEX.test(arg) ? arg : `'${arg.replaceAll("'", String.raw`'\''`)}'`).join(" ");
353
374
  }
354
375
  /**
355
376
  * Runtime type guard for ResourceInfo
@@ -404,10 +425,16 @@ function assertAlbumInfoArray(value) {
404
425
  if (!isAlbumInfoArray(value)) throw new Error("Invalid AlbumInfo array");
405
426
  }
406
427
  /**
407
- * Get photo asset information for given identifiers (ID, filename, album name,
408
- * or photo path)
428
+ * Look up photos in the Photos.app library.
409
429
  *
410
- * @throws {Error} If the command fails
430
+ * @param identifiers Photo UUIDs, paths like `Album/Title` or
431
+ * `Album/IMG_1234.jpeg`, or album UUIDs and paths, which stand for every
432
+ * photo in the album.
433
+ * @param caseSensitive Whether titles, file names, and album paths have to
434
+ * match exactly.
435
+ *
436
+ * @returns One entry per photo found. Empty if no identifiers are passed.
437
+ * @throws {Error} If nothing matches, or the command fails.
411
438
  */
412
439
  async function aphexPhotoInfo(identifiers, caseSensitive = false) {
413
440
  const identifiersArray = ensureArray(identifiers);
@@ -429,9 +456,13 @@ async function aphexPhotoInfo(identifiers, caseSensitive = false) {
429
456
  }
430
457
  }
431
458
  /**
432
- * Get album info
459
+ * Look up albums in the Photos.app library.
460
+ *
461
+ * @param identifiers Album UUIDs, or paths like `Album` or `Folder/Album`.
462
+ * @param caseSensitive Whether album paths have to match exactly.
433
463
  *
434
- * @throws {Error} If the command fails
464
+ * @returns One entry per album found. Empty if no identifiers are passed.
465
+ * @throws {Error} If nothing matches, or the command fails.
435
466
  */
436
467
  async function aphexAlbumInfo(identifiers, caseSensitive = false) {
437
468
  const identifiersArray = ensureArray(identifiers);
@@ -452,12 +483,38 @@ async function aphexAlbumInfo(identifiers, caseSensitive = false) {
452
483
  throw new Error(`Error fetching album info: ${stdout}`);
453
484
  }
454
485
  }
486
+ const LEADING_HASH_REGEX = /^#/v;
487
+ function getRenderArguments(options) {
488
+ const { background, bitDepth, colorProfile, format, includeLocation, includeMetadata, maxHeight, maxWidth, preserveAlpha, quality } = options;
489
+ const canHoldAlpha = format === "png" || format === "tiff";
490
+ return [
491
+ "--format",
492
+ format,
493
+ ...colorProfile === void 0 ? [] : ["--color-profile", colorProfile],
494
+ ...quality !== void 0 && format === "jpeg" ? ["--quality", String(quality)] : [],
495
+ ...bitDepth !== void 0 && format === "tiff" ? ["--bit-depth", String(bitDepth)] : [],
496
+ ...maxWidth === void 0 ? [] : ["--max-width", String(Math.floor(maxWidth))],
497
+ ...maxHeight === void 0 ? [] : ["--max-height", String(Math.floor(maxHeight))],
498
+ ...includeMetadata === true ? ["--include-metadata"] : [],
499
+ ...includeLocation === true ? ["--include-location"] : [],
500
+ ...background === void 0 ? [] : ["--background", background.replace(LEADING_HASH_REGEX, "")],
501
+ ...preserveAlpha === true && background === void 0 && canHoldAlpha ? ["--preserve-alpha"] : []
502
+ ];
503
+ }
455
504
  /**
456
- * Export photos for given identifiers to a destination directory
505
+ * Export photos from the Photos.app library to a directory with aphex-swift.
457
506
  *
458
- * @throws {Error} If the command fails
507
+ * By default this copies the image stored in the library: the original, or for
508
+ * an edited photo, the edited image Photos.app saved.
509
+ *
510
+ * @param identifiers Photo or album identifiers, see `aphexPhotoInfo`.
511
+ * @param destination An existing directory.
512
+ *
513
+ * @returns The paths of the exported files.
514
+ * @throws {Error} If nothing could be exported, or the command fails.
459
515
  */
460
- async function aphexExport(identifiers, destination, caseSensitive = false, originals = false) {
516
+ async function aphexExport(identifiers, destination, options = {}) {
517
+ const { caseSensitive = false, originals = false, render } = options;
461
518
  const identifiersArray = ensureArray(identifiers);
462
519
  if (identifiersArray.length === 0) return [];
463
520
  const args = [
@@ -466,7 +523,8 @@ async function aphexExport(identifiers, destination, caseSensitive = false, orig
466
523
  "--destination",
467
524
  destination,
468
525
  ...caseSensitive ? ["--case-sensitive"] : [],
469
- ...originals ? ["--originals"] : []
526
+ ...originals ? ["--originals"] : [],
527
+ ...render === void 0 ? [] : getRenderArguments(render)
470
528
  ];
471
529
  let stdout;
472
530
  if (isInteractiveSessionActive()) stdout = await executeInteractiveCommand(escapeCommand(args));
@@ -488,8 +546,7 @@ function dateReviver$1(key, value) {
488
546
  ].includes(key)) return value.length > 0 ? new Date(value) : void 0;
489
547
  return value;
490
548
  }
491
- //#endregion
492
- //#region src/aphex-swift/identifiers.ts
549
+ // src/aphex-swift/identifiers.ts
493
550
  /**
494
551
  * Takes a mix of photos, albums, strings, all resolved to a single array of
495
552
  * PhotoInfo objects
@@ -518,8 +575,7 @@ async function resolvePhotoIdentifier(identifier) {
518
575
  if (aphexPhotoInfoResult.length > 1) throw new Error(`Multiple photo assets found for identifier "${identifier} — is it an album?"`);
519
576
  return photoInfo;
520
577
  }
521
- //#endregion
522
- //#region src/utilities/defaults.ts
578
+ // src/utilities/defaults.ts
523
579
  const mergeDefaultsInternal = createDefu((object, key, value) => {
524
580
  if (Array.isArray(object[key]) && Array.isArray(value)) {
525
581
  const merged = [.../* @__PURE__ */ new Set([...object[key], ...value])];
@@ -532,11 +588,9 @@ const mergeDefaultsInternal = createDefu((object, key, value) => {
532
588
  * Merge, treating arrays like sets
533
589
  */
534
590
  function mergeDefaults(options, defaults) {
535
- if (options === void 0) return defaults;
536
- return mergeDefaultsInternal(options, defaults);
591
+ return options === void 0 ? defaults : mergeDefaultsInternal(options, defaults);
537
592
  }
538
- //#endregion
539
- //#region src/utilities/image/mime.ts
593
+ // src/utilities/image/mime.ts
540
594
  mimes.arw = "image/arw";
541
595
  mimes.cr2 = "image/cr2";
542
596
  mimes.cr3 = "image/cr3";
@@ -586,8 +640,7 @@ function lookupImageMimeType(imagePath, validate = false) {
586
640
  if (shouldValidate && matchedMimeTypes === void 0) throw new Error(`Invalid image MIME type: ${mime} for ${imagePath}`);
587
641
  return matchedMimeTypes;
588
642
  }
589
- //#endregion
590
- //#region src/utilities/image/color.ts
643
+ // src/utilities/image/color.ts
591
644
  const SIPS_PROFILE_REGEX = /profile: (.+)/v;
592
645
  /**
593
646
  * Get the color profile of an image
@@ -706,8 +759,7 @@ async function normalizeColorProfile(imagePath, preserveColorProfiles = [
706
759
  await convertColorProfile(imagePath, defaultColorProfile);
707
760
  return "converted";
708
761
  }
709
- //#endregion
710
- //#region src/utilities/image/tags.ts
762
+ // src/utilities/image/tags.ts
711
763
  const VALID_LABELS = [
712
764
  "animation",
713
765
  "diagram",
@@ -859,8 +911,7 @@ async function cloneTags(sourceImagePath, destinationImagePath, includeKeys, for
859
911
  if (Object.keys(tagsToAssign).length > 0) await setTags(destinationImagePath, tagsToAssign);
860
912
  return Object.keys(tagsToAssign);
861
913
  }
862
- //#endregion
863
- //#region src/utilities/image/image.ts
914
+ // src/utilities/image/image.ts
864
915
  /**
865
916
  * Get all available information about an image
866
917
  */
@@ -885,12 +936,22 @@ async function getImageDimensions(imagePath) {
885
936
  height
886
937
  };
887
938
  }
939
+ const RAW_MIME_TYPES = /* @__PURE__ */ new Set([
940
+ "arw",
941
+ "cr2",
942
+ "cr3",
943
+ "crw",
944
+ "dng",
945
+ "nef",
946
+ "pef"
947
+ ]);
888
948
  /**
889
- * Check if an image has an alpha channel
949
+ * Check if an image has transparency: an alpha channel in which at least one
950
+ * pixel is not fully opaque
890
951
  */
891
952
  async function hasAlpha(imagePath) {
892
953
  const mime = lookupImageMimeType(imagePath, true);
893
- if (mime === "jpeg") return false;
954
+ if (mime === "jpeg" || RAW_MIME_TYPES.has(mime)) return false;
894
955
  if (mime !== "psd" && mime !== "tiff") {
895
956
  const { stdout: channelOutput } = await execa("identify", [
896
957
  "-format",
@@ -918,23 +979,27 @@ async function hasAlpha(imagePath) {
918
979
  throw new Error(`Error checking file: ${String(error)}`, { cause: error });
919
980
  }
920
981
  }
921
- //#endregion
922
- //#region src/pipeline/engines/applescript.ts
982
+ // src/pipeline/engines/applescript.ts
923
983
  const UUID_SUFFIX_PHOTO = "/L0/001";
924
984
  function escapeForAppleScript(text) {
925
985
  return text.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"");
926
986
  }
927
987
  /**
928
- * Export a photo via AppleScript using the Photos app's scripting dictionary
988
+ * Export a photo with the `export` command of the Photos.app AppleScript
989
+ * dictionary.
990
+ *
991
+ * Photos.app decides what comes out: a JPEG it renders from the photo and its
992
+ * edits, or with `forceOriginal`, the original file as it was imported.
929
993
  *
930
994
  * @param photoUuid - UUID of the photo to export
931
- * @param forceOriginal - Whether to force export of original version
995
+ * @param forceOriginal - Whether to export the original file, ignoring edits
932
996
  *
933
- * @returns Promise<string> - Path to the exported file
997
+ * @returns The path of the exported file, in a new temporary directory. Move it
998
+ * and remove the directory afterwards.
934
999
  */
935
1000
  async function exportViaAppleScript(photoUuid, forceOriginal = false) {
936
1001
  const tempDirectory = await getTempDirectory("engine", "applescript");
937
- const exportFlag = forceOriginal ? "with originals" : "without originals";
1002
+ const exportFlag = forceOriginal ? "with using originals" : "without using originals";
938
1003
  const appleScript = `
939
1004
  tell application "Photos"
940
1005
  -- Find the media item by UUID
@@ -942,25 +1007,21 @@ async function exportViaAppleScript(photoUuid, forceOriginal = false) {
942
1007
 
943
1008
  -- Export the photo to temp directory
944
1009
  export {targetPhoto} to POSIX file "${escapeForAppleScript(tempDirectory)}" ${exportFlag}
945
-
946
- -- Get the exported file name
947
- set photoFilename to filename of targetPhoto
948
-
949
- -- Return the filename for path construction
950
- return photoFilename
951
1010
  end tell
952
1011
  `;
953
1012
  try {
954
- const { stdout } = await execa("osascript", ["-e", appleScript]);
955
- const exportedFileName = stdout.trim();
956
- return path.join(tempDirectory, exportedFileName);
1013
+ await execa("osascript", ["-e", appleScript]);
957
1014
  } catch (error) {
958
1015
  const errorMessage = error instanceof Error ? error.message : String(error);
959
1016
  throw new Error(`Failed to export photo via AppleScript: ${errorMessage}`, { cause: error });
960
1017
  }
1018
+ const entries = await fse.readdir(tempDirectory);
1019
+ const images = entries.filter((name) => lookupImageMimeType(name) !== void 0);
1020
+ const [exportedFileName] = images;
1021
+ if (exportedFileName === void 0 || images.length > 1) throw new Error(`Expected the AppleScript export of photo "${photoUuid}" to produce one image, but found ${String(images.length)}: ${JSON.stringify(entries)}`);
1022
+ return path.join(tempDirectory, exportedFileName);
961
1023
  }
962
- //#endregion
963
- //#region src/pipeline/engines/applescript-gui.ts
1024
+ // src/pipeline/engines/applescript-gui.ts
964
1025
  /** Apple's defaults, but these are overridden by Aphex by default */
965
1026
  const defaultExportViaAppleScriptGuiOptions = {
966
1027
  colorProfile: "Most Compatible",
@@ -976,42 +1037,130 @@ const defaultExportViaAppleScriptGuiOptions = {
976
1037
  subfolderFormat: "None",
977
1038
  tiffBitDepth: 8
978
1039
  };
1040
+ const GUI_COLOR_PROFILES = {
1041
+ "adobe-rgb": "AdobeRGB",
1042
+ "display-p3": "Display P3",
1043
+ "most-compatible": "Most Compatible",
1044
+ original: "Original",
1045
+ srgb: "sRGB"
1046
+ };
1047
+ const GUI_PHOTO_KINDS = {
1048
+ heic: "HEIC",
1049
+ jpeg: "JPEG",
1050
+ png: "PNG",
1051
+ tiff: "TIFF"
1052
+ };
1053
+ const GUI_JPEG_QUALITIES = [
1054
+ {
1055
+ name: "Low (smallest Size)",
1056
+ quality: .25
1057
+ },
1058
+ {
1059
+ name: "Medium",
1060
+ quality: .5
1061
+ },
1062
+ {
1063
+ name: "High",
1064
+ quality: .75
1065
+ },
1066
+ {
1067
+ name: "Maximum",
1068
+ quality: 1
1069
+ }
1070
+ ];
1071
+ /**
1072
+ * Work out the export sheet settings that come closest to a set of
1073
+ * `swift-render` options, for exporting through the GUI what couldn't be
1074
+ * rendered. The sheet drives the same renderer, so matching settings give the
1075
+ * same image.
1076
+ *
1077
+ * Transparency is not covered: the sheet always flattens it onto white,
1078
+ * whatever `preserveAlpha` and `background` say.
1079
+ *
1080
+ * @returns The settings, and whether they match the options exactly. They can't
1081
+ * for a JPEG quality between the sheet's four levels, or for a width and a
1082
+ * height limit that differ.
1083
+ */
1084
+ function getAppleScriptGuiOptionsForRender(renderOptions) {
1085
+ const { bitDepth, colorProfile, format, includeLocation, includeMetadata, quality } = renderOptions;
1086
+ const maxWidth = renderOptions.maxWidth === void 0 ? void 0 : Math.floor(renderOptions.maxWidth);
1087
+ const maxHeight = renderOptions.maxHeight === void 0 ? void 0 : Math.floor(renderOptions.maxHeight);
1088
+ let exact = true;
1089
+ const options = {
1090
+ colorProfile: GUI_COLOR_PROFILES[colorProfile],
1091
+ includeLocation,
1092
+ includeMetadata,
1093
+ photoKind: GUI_PHOTO_KINDS[format],
1094
+ photoSize: "Full Size",
1095
+ tiffBitDepth: bitDepth
1096
+ };
1097
+ if (format === "jpeg") {
1098
+ let closest = GUI_JPEG_QUALITIES[0];
1099
+ for (const level of GUI_JPEG_QUALITIES) if (Math.abs(level.quality - quality) < Math.abs(closest.quality - quality)) closest = level;
1100
+ options.jpegQuality = closest.name;
1101
+ exact &&= closest.quality === quality;
1102
+ }
1103
+ if (maxWidth !== void 0 || maxHeight !== void 0) {
1104
+ options.photoSize = "Custom";
1105
+ if (maxWidth === void 0 || maxHeight === void 0) {
1106
+ options.maxSizeType = maxWidth === void 0 ? "Height" : "Width";
1107
+ options.maxSizeValue = maxWidth ?? maxHeight;
1108
+ } else {
1109
+ options.maxSizeType = "Dimension";
1110
+ options.maxSizeValue = Math.min(maxWidth, maxHeight);
1111
+ exact &&= maxWidth === maxHeight;
1112
+ }
1113
+ }
1114
+ return {
1115
+ exact,
1116
+ options
1117
+ };
1118
+ }
979
1119
  /**
980
- * Export a photo via the Photos.app GUI to a temporary directory Clean up and
981
- * move the file as needed afterwards
1120
+ * Export a photo, or every photo in an album, through the Photos.app export
1121
+ * sheet, by automating its GUI with AppleScript.
1122
+ *
1123
+ * @returns The paths of the exported files, in a new temporary directory. Move
1124
+ * them and remove the directory afterwards.
982
1125
  */
983
1126
  async function exportViaAppleScriptGui(uuid, options) {
984
1127
  const tempDirectory = await getTempDirectory("engine", "applescript-gui");
985
1128
  const { colorProfile, fileName, includeLocation, includeMetadata, jpegQuality, maxSizeType, maxSizeValue, photoKind, photoSize, sequentialPrefix, subfolderFormat, tiffBitDepth } = mergeDefaults(options, defaultExportViaAppleScriptGuiOptions);
986
1129
  const appleScriptPath = path.join(getPackageAssetsPath(import.meta), "applescript-gui.applescript");
987
- const { failed, stderr } = await execa("osascript", [
988
- appleScriptPath,
989
- uuid,
990
- tempDirectory,
991
- photoKind,
992
- jpegQuality,
993
- tiffBitDepth.toString(),
994
- colorProfile,
995
- photoSize,
996
- maxSizeType,
997
- maxSizeValue.toString(),
998
- includeMetadata.toString(),
999
- includeLocation.toString(),
1000
- fileName,
1001
- sequentialPrefix,
1002
- subfolderFormat
1003
- ]);
1004
- if (failed) throw new Error(`Error exporting album "${uuid}": ${stderr}`);
1005
- const results = stderr.split("\n").filter((line) => line.trim() !== "");
1006
- if (results.length === 0) throw new Error(`No photos exported for album "${uuid}"`);
1007
- if (typeof results[0] !== "string") throw new TypeError(`Unexpected export results for album "${uuid}": ${JSON.stringify(results)}`);
1130
+ let stderr;
1131
+ try {
1132
+ stderr = (await execa("osascript", [
1133
+ appleScriptPath,
1134
+ uuid,
1135
+ tempDirectory,
1136
+ photoKind,
1137
+ jpegQuality,
1138
+ tiffBitDepth.toString(),
1139
+ colorProfile,
1140
+ photoSize,
1141
+ maxSizeType,
1142
+ maxSizeValue.toString(),
1143
+ includeMetadata.toString(),
1144
+ includeLocation.toString(),
1145
+ fileName,
1146
+ sequentialPrefix,
1147
+ subfolderFormat
1148
+ ])).stderr;
1149
+ } catch (error) {
1150
+ const errorMessage = error instanceof Error ? error.message : String(error);
1151
+ throw new Error(`Failed to export "${uuid}" via the Photos GUI: ${errorMessage}`, { cause: error });
1152
+ }
1153
+ const results = stderr.split("\n").filter((line) => line.startsWith(`${tempDirectory}/`));
1154
+ if (results.length === 0) throw new Error(`No files exported for "${uuid}" via the Photos GUI. Output: ${stderr}`);
1008
1155
  return results;
1009
1156
  }
1010
- //#endregion
1011
- //#region src/pipeline/engines/file-system.ts
1157
+ // src/pipeline/engines/file-system.ts
1012
1158
  /**
1013
- * Export a photo via direct file system copy of the original or edited file to
1014
- * a temporary directory Clean up and move the file as needed afterwards
1159
+ * Export a photo by copying its file straight out of the Photos.app library
1160
+ * folder: the edited image if the photo has edits, the original otherwise.
1161
+ *
1162
+ * @returns The path of the copy, in a new temporary directory. Move it and
1163
+ * remove the directory afterwards.
1015
1164
  */
1016
1165
  async function exportViaFileSystem(photoUuid, forceOriginal = false) {
1017
1166
  const [photoInfo] = isPhotoInfo(photoUuid) ? [photoUuid] : await aphexPhotoInfo(photoUuid);
@@ -1027,18 +1176,83 @@ async function exportViaFileSystem(photoUuid, forceOriginal = false) {
1027
1176
  await fse.copy(edited.filePath, destinationPath, { overwrite: true });
1028
1177
  return destinationPath;
1029
1178
  }
1030
- //#endregion
1031
- //#region src/pipeline/engines/swift-photokit.ts
1179
+ // src/pipeline/engines/swift-photokit.ts
1032
1180
  /**
1033
- * Export a photo via aphex-swift command line tool using PhotoKit
1181
+ * Export a photo by asking PhotoKit for the image stored in the library, via
1182
+ * the aphex-swift command line tool. That is the untouched original, or for an
1183
+ * edited photo, the compressed image Photos.app saved with the edit.
1184
+ *
1185
+ * @returns The path of the file, in a new temporary directory. Move it and
1186
+ * remove the directory afterwards.
1034
1187
  */
1035
1188
  async function exportViaSwiftPhotoKit(photoUuid) {
1036
1189
  const [result] = await aphexExport(photoUuid, await getTempDirectory("engine", "swift-photokit"));
1037
1190
  if (result === void 0) throw new Error(`Export via PhotoKit returned no files for photo "${photoUuid}"`);
1038
1191
  return result;
1039
1192
  }
1040
- //#endregion
1041
- //#region src/pipeline/image-export.ts
1193
+ // src/pipeline/engines/swift-render.ts
1194
+ /** Equivalent to what the Photos.app export sheet starts out with */
1195
+ const defaultExportViaSwiftRenderOptions = {
1196
+ background: void 0,
1197
+ bitDepth: 8,
1198
+ colorProfile: "most-compatible",
1199
+ format: "jpeg",
1200
+ includeLocation: true,
1201
+ includeMetadata: true,
1202
+ maxHeight: void 0,
1203
+ maxWidth: void 0,
1204
+ preserveAlpha: false,
1205
+ quality: .75
1206
+ };
1207
+ const HEX_COLOR_REGEX = /^#?[\da-f]{6}$/iv;
1208
+ /**
1209
+ * Check render options before anything is exported with them. A bad value would
1210
+ * otherwise only show up as a failed render, one photo at a time.
1211
+ *
1212
+ * @throws {TypeError} Naming the option that is wrong
1213
+ */
1214
+ function assertValidSwiftRenderOptions(options) {
1215
+ const { background, maxHeight, maxWidth, quality } = options;
1216
+ if (!(quality >= 0) || !(quality <= 1)) throw new TypeError(`swiftRenderOptions.quality must be from 0 to 1, got ${String(quality)}`);
1217
+ for (const [name, value] of [["maxWidth", maxWidth], ["maxHeight", maxHeight]]) if (value !== void 0 && !(value >= 1)) throw new TypeError(`swiftRenderOptions.${name} must be at least 1, got ${String(value)}`);
1218
+ if (background !== void 0 && !HEX_COLOR_REGEX.test(background)) throw new TypeError(`swiftRenderOptions.background must be six hexadecimal digits like "ff8800", got "${background}"`);
1219
+ }
1220
+ /**
1221
+ * Export a photo by re-rendering it, and any edits made to it in Photos.app, at
1222
+ * full quality via the aphex-swift command line tool.
1223
+ *
1224
+ * This produces the same pixels as File → Export in Photos.app without
1225
+ * automating its GUI, where the other engines return the compressed image that
1226
+ * Photos.app saved when the photo was edited. It can also keep transparency,
1227
+ * which Photos.app flattens onto white. It relies on private Photos APIs, so it
1228
+ * can stop working after a macOS update.
1229
+ *
1230
+ * @returns The path of the rendered file, in a new temporary directory. Move it
1231
+ * and remove the directory afterwards.
1232
+ */
1233
+ async function exportViaSwiftRender(photoUuid, options) {
1234
+ const resolvedOptions = mergeDefaults(options, defaultExportViaSwiftRenderOptions);
1235
+ assertValidSwiftRenderOptions(resolvedOptions);
1236
+ const { background, maxHeight, maxWidth, ...rest } = resolvedOptions;
1237
+ const tempDirectory = await getTempDirectory("engine", "swift-render");
1238
+ try {
1239
+ const [result] = await aphexExport(photoUuid, tempDirectory, { render: {
1240
+ ...rest,
1241
+ background,
1242
+ maxHeight,
1243
+ maxWidth
1244
+ } });
1245
+ if (result === void 0) throw new Error(`Export via render returned no files for photo "${photoUuid}"`);
1246
+ return result;
1247
+ } catch (error) {
1248
+ await fse.rm(tempDirectory, {
1249
+ force: true,
1250
+ recursive: true
1251
+ });
1252
+ throw error;
1253
+ }
1254
+ }
1255
+ // src/pipeline/image-export.ts
1042
1256
  const defaultExportApplePhotoOptions = {
1043
1257
  appleScriptGuiOptions: {
1044
1258
  colorProfile: "sRGB",
@@ -1054,24 +1268,24 @@ const defaultExportApplePhotoOptions = {
1054
1268
  subfolderFormat: "None",
1055
1269
  tiffBitDepth: 8
1056
1270
  },
1057
- engineEdited: "photos-gui",
1058
- engineEditedAlpha: "swift-photokit",
1271
+ engineEdited: "swift-render",
1272
+ engineEditedAlpha: "swift-render",
1059
1273
  engineOriginal: {
1060
- arw: "photos-gui",
1274
+ arw: "swift-render",
1061
1275
  avif: "swift-photokit",
1062
- cr2: "photos-gui",
1063
- cr3: "photos-gui",
1064
- crw: "photos-gui",
1065
- dng: "photos-gui",
1276
+ cr2: "swift-render",
1277
+ cr3: "swift-render",
1278
+ crw: "swift-render",
1279
+ dng: "swift-render",
1066
1280
  gif: "swift-photokit",
1067
1281
  heic: "swift-photokit",
1068
1282
  heif: "swift-photokit",
1069
1283
  jpeg: "swift-photokit",
1070
- nef: "photos-gui",
1071
- pef: "photos-gui",
1072
- png: "photos-gui",
1073
- psd: "photos-gui",
1074
- tiff: "photos-gui",
1284
+ nef: "swift-render",
1285
+ pef: "swift-render",
1286
+ png: "swift-render",
1287
+ psd: "swift-render",
1288
+ tiff: "swift-render",
1075
1289
  webp: "swift-photokit"
1076
1290
  },
1077
1291
  engineOriginalAlpha: "swift-photokit",
@@ -1082,21 +1296,37 @@ const defaultExportApplePhotoOptions = {
1082
1296
  "fileName",
1083
1297
  "uuid"
1084
1298
  ],
1085
- fileNameSluggify: true
1299
+ fileNameSluggify: true,
1300
+ swiftRenderOptions: {
1301
+ background: void 0,
1302
+ bitDepth: 8,
1303
+ colorProfile: "srgb",
1304
+ format: "png",
1305
+ includeLocation: false,
1306
+ includeMetadata: false,
1307
+ maxHeight: void 0,
1308
+ maxWidth: void 0,
1309
+ preserveAlpha: true,
1310
+ quality: 1
1311
+ }
1086
1312
  };
1087
1313
  /**
1088
- * Export a batch of photos
1314
+ * Export photos and albums from the Photos.app library to a directory, each
1315
+ * photo through the engine the options pick for it. No processing, metadata, or
1316
+ * sync.
1089
1317
  */
1090
1318
  async function exportApplePhotos(identifiers, destinationDirectory, options) {
1091
1319
  const resolvedOptions = mergeDefaults(options, defaultExportApplePhotoOptions);
1320
+ assertValidSwiftRenderOptions(resolvedOptions.swiftRenderOptions);
1092
1321
  const photoInfos = await resolveIdentifiers(identifiers);
1093
1322
  const exportedPhotos = [];
1094
1323
  for (const photoInfo of photoInfos) {
1095
- const engine = await getEngineForPhoto(photoInfo, resolvedOptions);
1324
+ const { degraded, engine, path: exportedPath } = await exportPhotoWithEngine(photoInfo, await getEngineForPhoto(photoInfo, resolvedOptions), resolvedOptions);
1096
1325
  const exportedPhoto = {
1326
+ exportDegraded: degraded,
1097
1327
  exportEngine: engine,
1098
1328
  exportOptions: resolvedOptions,
1099
- path: await exportPhotoWithEngine(photoInfo, engine, resolvedOptions),
1329
+ path: exportedPath,
1100
1330
  photoInfo
1101
1331
  };
1102
1332
  const resolvedDestinationDirectory = await ensureDirectoryExists(destinationDirectory);
@@ -1112,19 +1342,75 @@ async function exportApplePhotos(identifiers, destinationDirectory, options) {
1112
1342
  }
1113
1343
  return exportedPhotos;
1114
1344
  }
1345
+ /**
1346
+ * Returns the engine along with the path, since an engine can fall back to
1347
+ * another one, and whether that left the file short of what the options ask
1348
+ * for
1349
+ */
1115
1350
  async function exportPhotoWithEngine(photoInfo, engine, options) {
1116
1351
  switch (engine) {
1117
- case "applescript": return exportViaAppleScript(photoInfo.uuid);
1118
- case "file-system": return exportViaFileSystem(photoInfo);
1119
- case "photos-gui": {
1120
- const [exportedPath] = await exportViaAppleScriptGui(photoInfo.uuid, options.appleScriptGuiOptions);
1121
- if (exportedPath === void 0) throw new Error(`Photos GUI export returned no files for photo "${photoInfo.uuid}"`);
1122
- return exportedPath;
1352
+ case "applescript": return {
1353
+ degraded: false,
1354
+ engine,
1355
+ path: await exportViaAppleScript(photoInfo.uuid)
1356
+ };
1357
+ case "file-system": return {
1358
+ degraded: false,
1359
+ engine,
1360
+ path: await exportViaFileSystem(photoInfo)
1361
+ };
1362
+ case "photos-gui": return {
1363
+ degraded: false,
1364
+ engine,
1365
+ path: await exportViaPhotosGui(photoInfo, options.appleScriptGuiOptions)
1366
+ };
1367
+ case "swift-photokit": return {
1368
+ degraded: false,
1369
+ engine,
1370
+ path: await exportViaSwiftPhotoKit(photoInfo.uuid)
1371
+ };
1372
+ case "swift-render": try {
1373
+ return {
1374
+ degraded: false,
1375
+ engine,
1376
+ path: await exportViaSwiftRender(photoInfo.uuid, options.swiftRenderOptions)
1377
+ };
1378
+ } catch (error) {
1379
+ return exportViaPhotosGuiInsteadOfRender(photoInfo, options, error);
1123
1380
  }
1124
- case "swift-photokit": return exportViaSwiftPhotoKit(photoInfo.uuid);
1125
1381
  }
1126
1382
  }
1127
- /** Also normalizes */
1383
+ async function exportViaPhotosGui(photoInfo, guiOptions) {
1384
+ const [exportedPath] = await exportViaAppleScriptGui(photoInfo.uuid, guiOptions);
1385
+ if (exportedPath === void 0) throw new Error(`Photos GUI export returned no files for photo "${photoInfo.uuid}"`);
1386
+ return exportedPath;
1387
+ }
1388
+ /**
1389
+ * Export a photo that failed to render through the Photos.app GUI instead.
1390
+ *
1391
+ * Rendering depends on private Photos APIs that a macOS update can break. The
1392
+ * export sheet drives the same renderer the slow way, so it is set up to match
1393
+ * the render options instead of `appleScriptGuiOptions`, which only supply the
1394
+ * settings that have no counterpart, like file naming.
1395
+ */
1396
+ async function exportViaPhotosGuiInsteadOfRender(photoInfo, options, renderError) {
1397
+ const { exact, options: guiOptions } = getAppleScriptGuiOptionsForRender(options.swiftRenderOptions);
1398
+ const shortfall = [...rendersTransparency(options.swiftRenderOptions) && await originalHasTransparency(photoInfo) ? ["its transparency is flattened onto white"] : [], ...exact ? [] : ["the size or JPEG quality is only approximate"]];
1399
+ log.warn(`Rendering photo "${photoInfo.title ?? photoInfo.uuid}" failed, falling back to the Photos.app GUI: ${renderError instanceof Error ? renderError.message : String(renderError)}${shortfall.length === 0 ? "" : ` The GUI can't match the render options: ${shortfall.join(", and ")}. The photo will be exported again on the next sync.`}`);
1400
+ return {
1401
+ degraded: shortfall.length > 0,
1402
+ engine: "photos-gui",
1403
+ path: await exportViaPhotosGui(photoInfo, {
1404
+ ...options.appleScriptGuiOptions,
1405
+ ...guiOptions
1406
+ })
1407
+ };
1408
+ }
1409
+ /**
1410
+ * Work out the path an exported photo should end up at: the directory and
1411
+ * extension of `filePath`, with a file name chosen by the first naming strategy
1412
+ * the photo has a value for.
1413
+ */
1128
1414
  function getImagePathWithFileName(photoInfo, filePath, sluggify = true, fileNameAppendUuidFragment = false, normalizeExtensions = true, namingStrategyPrecedence = [
1129
1415
  "title",
1130
1416
  "fileName",
@@ -1165,20 +1451,40 @@ async function getEngineForPhoto(photoInfo, options) {
1165
1451
  if (engine === void 0) throw new Error(`No export engine found for original photo "${photoInfo.title}" of type "${type}"${alpha ? " with alpha channel" : ""}`);
1166
1452
  return engine;
1167
1453
  }
1168
- const alpha = await hasAlpha(photoInfo.edited.filePath);
1169
- if (alpha) log.warn(`Edited photo "${photoInfo.title}" has true transparency, it probably won't export correctly. Only un-edited files preserve transparency on export.`);
1454
+ const alpha = await originalHasTransparency(photoInfo);
1170
1455
  const type = lookupImageMimeType(photoInfo.edited.filePath, true);
1171
1456
  const engine = alpha ? typeof engineEditedAlpha === "string" ? engineEditedAlpha : engineEditedAlpha[type] : typeof engineEdited === "string" ? engineEdited : engineEdited[type];
1457
+ if (alpha && (engine !== "swift-render" || !rendersTransparency(options.swiftRenderOptions))) log.warn(`Edited photo "${photoInfo.title ?? photoInfo.uuid}" has transparency, which the "${String(engine)}" engine will flatten onto white. Only swift-render can keep it, with "preserveAlpha" and a "png" or "tiff" format.`);
1172
1458
  if (engine === void 0) throw new Error(`No export engine found for edited photo "${photoInfo.title}" of type "${type}"${alpha ? " with alpha channel" : ""}`);
1173
1459
  return engine;
1174
1460
  }
1175
1461
  /**
1462
+ * Whether a photo's original has transparency. An original that can't be
1463
+ * inspected, such as a camera raw format ImageMagick doesn't know, is taken to
1464
+ * have none, so that it doesn't stop the export.
1465
+ */
1466
+ async function originalHasTransparency(photoInfo) {
1467
+ try {
1468
+ return await hasAlpha(photoInfo.original.filePath);
1469
+ } catch (error) {
1470
+ log.debug(`Could not check "${photoInfo.original.fileName}" for transparency, assuming it has none: ${error instanceof Error ? error.message : String(error)}`);
1471
+ return false;
1472
+ }
1473
+ }
1474
+ /**
1475
+ * Whether swift-render will deal with transparency itself, by keeping it or by
1476
+ * flattening it onto a chosen color, instead of leaving it to be flattened onto
1477
+ * white
1478
+ */
1479
+ function rendersTransparency(options) {
1480
+ return options.background !== void 0 || options.preserveAlpha && (options.format === "png" || options.format === "tiff");
1481
+ }
1482
+ /**
1176
1483
  * Export a single album to a folder Optionally sync the output directory with
1177
1484
  * the album, deleting any images that are no longer in the album Optionally
1178
1485
  * audit the album for duplicate titles Does NOT further process the images
1179
1486
  */
1180
- //#endregion
1181
- //#region src/pipeline/image-metadata.ts
1487
+ // src/pipeline/image-metadata.ts
1182
1488
  const defaultManageMetadataOptions = {
1183
1489
  syncToEdited: true,
1184
1490
  syncToTarget: true,
@@ -1195,19 +1501,23 @@ const defaultManageMetadataOptions = {
1195
1501
  /**
1196
1502
  * Manage metadata for a batch of photos
1197
1503
  */
1198
- async function manageMetadataBatch(identifiers, targetFilePaths, options, exportOptions) {
1504
+ async function manageMetadataBatch(identifiers, targetFilePaths, { exportOptions, exportResults, options } = {}) {
1199
1505
  const photoInfos = await resolveIdentifiers(identifiers);
1200
1506
  if (photoInfos.length !== targetFilePaths.length) throw new Error("Photo infos and target files length mismatch");
1201
1507
  return Promise.all(photoInfos.map(async (photoInfo, index) => {
1202
1508
  const targetFilePath = targetFilePaths[index];
1203
1509
  if (targetFilePath === void 0) throw new Error(`Missing target file path for photo "${photoInfo.uuid}"`);
1204
- return manageMetadata(photoInfo, targetFilePath, options, exportOptions);
1510
+ return manageMetadata(photoInfo, targetFilePath, {
1511
+ exportOptions,
1512
+ exportResult: exportResults?.[index],
1513
+ options
1514
+ });
1205
1515
  }));
1206
1516
  }
1207
1517
  /**
1208
- * Manage metadata...
1518
+ * Carry metadata over to one exported photo, as configured in `options`
1209
1519
  */
1210
- async function manageMetadata(identifier, targetFilePath, options, exportOptions) {
1520
+ async function manageMetadata(identifier, targetFilePath, { exportOptions, exportResult, options } = {}) {
1211
1521
  const resolvedOptions = mergeDefaults(options, defaultManageMetadataOptions);
1212
1522
  const photoInfo = await resolvePhotoIdentifier(identifier);
1213
1523
  let tagsToTarget;
@@ -1215,6 +1525,7 @@ async function manageMetadata(identifier, targetFilePath, options, exportOptions
1215
1525
  let tagsToEdited;
1216
1526
  if (photoInfo.edited && resolvedOptions.syncToEdited) tagsToEdited = await cloneTags(photoInfo.original.filePath, photoInfo.edited.filePath, resolvedOptions.tagsToSync);
1217
1527
  if (exportOptions !== void 0 && resolvedOptions.writeAphexMetadata) await setTags(targetFilePath, { aphexMetadata: {
1528
+ ...exportResult,
1218
1529
  exportOptions,
1219
1530
  photoInfo
1220
1531
  } });
@@ -1227,8 +1538,7 @@ async function manageMetadata(identifier, targetFilePath, options, exportOptions
1227
1538
  validationResult
1228
1539
  };
1229
1540
  }
1230
- //#endregion
1231
- //#region src/utilities/image/convert.ts
1541
+ // src/utilities/image/convert.ts
1232
1542
  /**
1233
1543
  * Optimize a PNG image
1234
1544
  */
@@ -1269,7 +1579,7 @@ async function resizePngToFit(imagePath, destinationDirectory, maxWidth, maxHeig
1269
1579
  return destinationImagePath;
1270
1580
  }
1271
1581
  /**
1272
- * Resize a PNG image to fit within a maximum width and height
1582
+ * Convert an image to a JPEG
1273
1583
  */
1274
1584
  async function convertToJpeg(sourceImagePath, destinationDirectory, quality, force = false, engine = "mozjpeg") {
1275
1585
  const mime = lookupImageMimeType(sourceImagePath, [
@@ -1366,11 +1676,11 @@ async function convertToPng(sourceImagePath, destinationDirectory, force = false
1366
1676
  "--setProperty",
1367
1677
  "format",
1368
1678
  "png",
1369
- ...restoreColorProfile !== void 0 && restoreColorProfile !== "None" ? [
1679
+ ...restoreColorProfile === void 0 || restoreColorProfile === "None" ? [] : [
1370
1680
  "--setProperty",
1371
1681
  "profile",
1372
1682
  getPathToColorProfile(restoreColorProfile)
1373
- ] : [],
1683
+ ],
1374
1684
  sourceImagePath,
1375
1685
  "--out",
1376
1686
  destinationImagePath
@@ -1516,8 +1826,7 @@ async function compressImage(sourceImagePath, destinationDirectory, options) {
1516
1826
  path: destinationImagePath
1517
1827
  };
1518
1828
  }
1519
- //#endregion
1520
- //#region src/utilities/image/compare.ts
1829
+ // src/utilities/image/compare.ts
1521
1830
  const SSIM_REGEX = /All:\s*([\d.]+)/v;
1522
1831
  const PSNR_REGEX = /average:\s*([\d.]+)/v;
1523
1832
  /**
@@ -1630,8 +1939,7 @@ async function calculatePSNRInternal(image1, image2) {
1630
1939
  const psnrValue = PSNR_REGEX.exec(result.stderr)?.[1];
1631
1940
  return psnrValue === void 0 ? 0 : Number(psnrValue);
1632
1941
  }
1633
- //#endregion
1634
- //#region src/pipeline/image-process.ts
1942
+ // src/pipeline/image-process.ts
1635
1943
  const defaultProcessImageOptions = {
1636
1944
  defaultColorProfile: "sRGB IEC61966-2.1",
1637
1945
  forceCompression: false,
@@ -1769,8 +2077,7 @@ function isProcessImageResultReport(object) {
1769
2077
  if (object.similarity !== void 0) return typeof object.similarity.dssim === "number" && typeof object.similarity.psnr === "number" && typeof object.similarity.ssim === "number";
1770
2078
  return true;
1771
2079
  }
1772
- //#endregion
1773
- //#region src/pipeline/image-sync.ts
2080
+ // src/pipeline/image-sync.ts
1774
2081
  async function getDestinationFiles(destinationDirectory) {
1775
2082
  const files = (await fse.readdir(destinationDirectory, { withFileTypes: true })).filter((entry) => entry.isFile());
1776
2083
  return Promise.all(files.map(async (file) => {
@@ -1797,7 +2104,7 @@ async function getDestinationFiles(destinationDirectory) {
1797
2104
  *
1798
2105
  * TODO how to handle non-image files?
1799
2106
  */
1800
- async function getSyncPlanForImages(identifiers, destinationDirectory, options, exportOptions) {
2107
+ async function getSyncPlanForImages(identifiers, destinationDirectory, { exportOptions, options } = {}) {
1801
2108
  const resolvedOptions = mergeDefaults(options, defaultSyncOptions);
1802
2109
  const resolvedExportOptions = mergeDefaults(exportOptions, defaultExportOptions);
1803
2110
  const photoInfos = await resolveIdentifiers(identifiers);
@@ -1841,9 +2148,17 @@ async function getSyncPlanForImages(identifiers, destinationDirectory, options,
1841
2148
  return syncResult;
1842
2149
  }
1843
2150
  /**
2151
+ * The options an export was made with are kept as JSON in the exported file.
2152
+ * JSON drops options that are `undefined`, so current options only compare
2153
+ * equal to stored ones after the same round trip.
2154
+ */
2155
+ function asStored(options) {
2156
+ return JSON.parse(JSON.stringify(options));
2157
+ }
2158
+ /**
1844
2159
  * See if there's a difference between the source image and the target image
1845
2160
  *
1846
- * @returns Undefined if the, or the reason for the difference if found
2161
+ * @returns The first strategy that found a difference, or false if none did
1847
2162
  */
1848
2163
  async function isDifferent(diffStrategies, sourcePhotoInfo, sourcePhotoFileBaseName, matchPhotoFilePath, matchPhotoTags, exportOptions, forceUpdate) {
1849
2164
  if (forceUpdate) return "force-update";
@@ -1853,24 +2168,23 @@ async function isDifferent(diffStrategies, sourcePhotoInfo, sourcePhotoFileBaseN
1853
2168
  case "exif-tags":
1854
2169
  sourceTags ??= await getTags(sourcePhotoInfo.original.filePath);
1855
2170
  return matchPhotoTags === void 0 || sourceTags.credit !== matchPhotoTags.credit || sourceTags.creator !== matchPhotoTags.creator || sourceTags.description !== matchPhotoTags.description || sourceTags.preservedFileName !== matchPhotoTags.preservedFileName || sourceTags.label !== matchPhotoTags.label;
1856
- case "export-options": return matchPhotoTags === void 0 || !deepEqual(exportOptions.exportOptions, matchPhotoTags.aphexMetadata?.exportOptions.exportOptions);
2171
+ case "export-options": return matchPhotoTags === void 0 || matchPhotoTags.aphexMetadata?.exportDegraded === true || !deepEqual(asStored(exportOptions.exportOptions), matchPhotoTags.aphexMetadata?.exportOptions.exportOptions);
1857
2172
  case "file-name": return stripExtension(path.basename(matchPhotoFilePath)) !== sourcePhotoFileBaseName;
1858
2173
  case "force-update": return true;
1859
2174
  case "metadata-options":
1860
2175
  sourceTags ??= await getTags(sourcePhotoInfo.original.filePath);
1861
- return matchPhotoTags === void 0 || !deepEqual(exportOptions.metadataOptions, matchPhotoTags.aphexMetadata?.exportOptions.metadataOptions);
2176
+ return matchPhotoTags === void 0 || !deepEqual(asStored(exportOptions.metadataOptions), matchPhotoTags.aphexMetadata?.exportOptions.metadataOptions);
1862
2177
  case "photo-info": return matchPhotoTags === void 0 || !deepEqual(sourcePhotoInfo, matchPhotoTags.aphexMetadata?.photoInfo);
1863
- case "process-options": return matchPhotoTags === void 0 || !deepEqual(exportOptions.processOptions, matchPhotoTags.aphexMetadata?.exportOptions.processOptions);
2178
+ case "process-options": return matchPhotoTags === void 0 || !deepEqual(asStored(exportOptions.processOptions), matchPhotoTags.aphexMetadata?.exportOptions.processOptions);
1864
2179
  }
1865
2180
  }
1866
2181
  for (const diffStrategy of diffStrategies) if (await strategyFindsDifference(diffStrategy)) return diffStrategy;
1867
2182
  return false;
1868
2183
  }
1869
- //#endregion
1870
- //#region src/index.ts
2184
+ // src/index.ts
1871
2185
  /**
1872
- * Helper for deep merging ExportOptions object against library defaults.
1873
- * Exported for unplugin-aphex.
2186
+ * Fill in everything a partial `ExportOptions` object leaves out with the
2187
+ * library defaults. Exported for unplugin-aphex.
1874
2188
  */
1875
2189
  function mergeDefaultExportOptions(options) {
1876
2190
  return mergeDefaults(options, defaultExportOptions);
@@ -1895,7 +2209,14 @@ const defaultExportOptions = {
1895
2209
  syncOptions: defaultSyncOptions
1896
2210
  };
1897
2211
  /**
1898
- * Export a single photo
2212
+ * Export a single photo from the Photos.app library to a directory.
2213
+ *
2214
+ * @param identifier A photo's UUID, a path like `Album/Title` or
2215
+ * `Folder/Album/IMG_1234.jpeg`, or a `PhotoInfo` from `getPhotoInfo`.
2216
+ * @param destinationDirectory Created if it doesn't exist. A leading `~` is
2217
+ * expanded.
2218
+ * @param options Anything left out falls back to the library defaults.
2219
+ * @throws {Error} If the identifier matches no photo, or more than one.
1899
2220
  */
1900
2221
  async function exportPhoto(identifier, destinationDirectory, options) {
1901
2222
  const result = await exportPhotos([await resolvePhotoIdentifier(identifier)], destinationDirectory, options);
@@ -1903,7 +2224,23 @@ async function exportPhoto(identifier, destinationDirectory, options) {
1903
2224
  return result[0];
1904
2225
  }
1905
2226
  /**
1906
- * Export photos
2227
+ * Export any number of photos and albums from the Photos.app library to a
2228
+ * directory.
2229
+ *
2230
+ * Each photo goes through the stages that are enabled in `options`: checking
2231
+ * whether an up-to-date export already exists, exporting from Photos.app,
2232
+ * processing, and writing metadata.
2233
+ *
2234
+ * @param identifiers Any mix of photo and album identifiers: UUIDs, paths like
2235
+ * `Album/Title` or `Folder/Album`, and `PhotoInfo` or `AlbumInfo` objects. An
2236
+ * album stands for every photo in it.
2237
+ * @param destinationDirectory Created if it doesn't exist. A leading `~` is
2238
+ * expanded.
2239
+ * @param options Anything left out falls back to the library defaults.
2240
+ *
2241
+ * @returns One result per photo, in a flat list. A photo that is identified
2242
+ * more than once is exported once.
2243
+ * @throws {Error} If the identifiers match no photos.
1907
2244
  */
1908
2245
  async function exportPhotos(identifiers, destinationDirectory, options) {
1909
2246
  const resolvedOptions = mergeDefaultExportOptions(options);
@@ -1912,8 +2249,10 @@ async function exportPhotos(identifiers, destinationDirectory, options) {
1912
2249
  const photoInfos = await resolveIdentifiers(identifiers);
1913
2250
  let syncResult;
1914
2251
  if (syncOptions !== "disabled") {
1915
- syncResult = await getSyncPlanForImages(photoInfos, resolvedDestinationDirectory, syncOptions, resolvedOptions);
1916
- await Promise.all(syncResult.toDelete.map(async (file) => fse.rm(file, { force: true })));
2252
+ syncResult = await getSyncPlanForImages(photoInfos, resolvedDestinationDirectory, {
2253
+ exportOptions: resolvedOptions,
2254
+ options: syncOptions
2255
+ });
1917
2256
  if (syncResult.plan.length !== photoInfos.length) throw new Error("Sync plan length does not match photos length");
1918
2257
  }
1919
2258
  const exportResults = photoInfos.map((photoInfo, index) => {
@@ -1930,7 +2269,10 @@ async function exportPhotos(identifiers, destinationDirectory, options) {
1930
2269
  }
1931
2270
  };
1932
2271
  });
1933
- if (exportResults.every((exportResult) => exportResult.results.syncResult?.status === "unchanged")) return exportResults;
2272
+ if (exportResults.every((exportResult) => exportResult.results.syncResult?.status === "unchanged")) {
2273
+ await deleteStaleFiles(syncResult?.toDelete, exportResults);
2274
+ return exportResults;
2275
+ }
1934
2276
  const seenBaseNames = /* @__PURE__ */ new Set();
1935
2277
  let hasCollision = false;
1936
2278
  for (const exportResult of exportResults) {
@@ -1973,16 +2315,58 @@ async function exportPhotos(identifiers, destinationDirectory, options) {
1973
2315
  }
1974
2316
  if (metadataOptions !== "disabled") {
1975
2317
  const targetPhotos = exportResults.filter((exportResult) => exportResult.results.syncResult?.status !== "unchanged");
1976
- const metadataResults = await manageMetadataBatch(targetPhotos.map((exportResult) => exportResult.photoInfo), targetPhotos.map((exportResult) => exportResult.path), metadataOptions, resolvedOptions);
2318
+ const metadataResults = await manageMetadataBatch(targetPhotos.map((exportResult) => exportResult.photoInfo), targetPhotos.map((exportResult) => exportResult.path), {
2319
+ exportOptions: resolvedOptions,
2320
+ exportResults: targetPhotos.map((exportResult) => exportResult.results.exportResult),
2321
+ options: metadataOptions
2322
+ });
1977
2323
  for (const exportResult of exportResults) {
1978
2324
  const matchingMetadataResult = metadataResults.find((photoExportResult) => photoExportResult.photoInfo.uuid === exportResult.photoInfo.uuid);
1979
2325
  if (matchingMetadataResult) exportResult.results.metadataResult = cleanMetadataResults(matchingMetadataResult);
1980
2326
  }
1981
2327
  }
2328
+ await deleteStaleFiles(syncResult?.toDelete, exportResults);
1982
2329
  return exportResults;
1983
2330
  }
2331
+ /**
2332
+ * Delete the files a sync plan marked for deletion, now that the export has
2333
+ * gone through.
2334
+ *
2335
+ * A file that a result points to stays, since a new export can take the place
2336
+ * of an old one under the same name. So does an out-of-date export that nothing
2337
+ * took the place of.
2338
+ */
2339
+ async function deleteStaleFiles(toDelete, exportResults) {
2340
+ if (toDelete === void 0 || toDelete.length === 0) return;
2341
+ const keep = /* @__PURE__ */ new Set();
2342
+ for (const { path: resultPath, results } of exportResults) {
2343
+ const identity = resultPath === "" ? void 0 : await getFileIdentity(resultPath);
2344
+ const staleIdentity = identity === void 0 && results.syncResult?.matchFilePath !== void 0 ? await getFileIdentity(results.syncResult.matchFilePath) : void 0;
2345
+ for (const kept of [identity, staleIdentity]) if (kept !== void 0) keep.add(kept);
2346
+ }
2347
+ for (const file of toDelete) {
2348
+ const identity = await getFileIdentity(file);
2349
+ if (identity !== void 0 && !keep.has(identity)) await fse.rm(file, { force: true });
2350
+ }
2351
+ }
2352
+ /**
2353
+ * A string that is the same for every path that leads to one file
2354
+ *
2355
+ * @returns Undefined if there is no file at the path
2356
+ */
2357
+ async function getFileIdentity(filePath) {
2358
+ try {
2359
+ const { dev, ino } = await fse.stat(filePath, { bigint: true });
2360
+ return `${dev}:${ino}`;
2361
+ } catch {
2362
+ return;
2363
+ }
2364
+ }
1984
2365
  function cleanExportResults(result) {
1985
- return { exportEngine: result.exportEngine };
2366
+ return {
2367
+ exportDegraded: result.exportDegraded,
2368
+ exportEngine: result.exportEngine
2369
+ };
1986
2370
  }
1987
2371
  function cleanMetadataResults(result) {
1988
2372
  const { photoInfo: _, ...rest } = result;
@@ -2003,5 +2387,4 @@ function cleanProcessResults(result) {
2003
2387
  output: strippedOutput
2004
2388
  };
2005
2389
  }
2006
- //#endregion
2007
2390
  export { IMAGE_MIME_TYPES, defaultExportOptions, defaultSyncOptions, endExiftool, exportPhoto, exportPhotos, aphexAlbumInfo as getAlbumInfo, aphexPhotoInfo as getPhotoInfo, interactiveSessionStart, interactiveSessionStop, mergeDefaultExportOptions, processImage, setLogger };