Open History to see the last commit
1#!/usr/bin/env node
2
3import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
4import * as NodeServices from "@effect/platform-node/NodeServices";
5import * as HostProcess from "@t3tools/shared/HostProcess";
6import * as Console from "effect/Console";
7import * as Effect from "effect/Effect";
8import * as FileSystem from "effect/FileSystem";
9import * as Option from "effect/Option";
10import * as Path from "effect/Path";
11import * as Schema from "effect/Schema";
12import * as Stream from "effect/Stream";
13import { Command, Flag } from "effect/cli";
14import { ChildProcess, ChildProcessSpawner } from "effect/process";
15
16import { BRAND_ASSET_PATHS, DEVELOPMENT_PUBLIC_ICON_OVERRIDES } from "./lib/brand-assets.ts";
17import { encodePngIco, readPngDimensions, WINDOWS_ICON_SIZES } from "./lib/icon-export.ts";
18
19const DESIGN_GENERATION = 26;
20const ICON_COMPOSER_EXECUTABLE_PARTS = [
21 "Contents",
22 "Applications",
23 "Icon Composer.app",
24 "Contents",
25 "Executables",
26 "ictool",
27] as const;
28const STANDALONE_ICON_COMPOSER_EXECUTABLE_PARTS = [
29 "Icon Composer.app",
30 "Contents",
31 "Executables",
32 "ictool",
33] as const;
34const NonNegativeInt = Schema.Int.check(Schema.isGreaterThanOrEqualTo(0));
35
36const IconComposerVersion = Schema.Struct({
37 "bundle-version": Schema.NonEmptyString,
38 "short-bundle-version": Schema.NonEmptyString,
39});
40const decodeIconComposerVersion = Schema.decodeUnknownEffect(
41 Schema.fromJsonString(IconComposerVersion),
42);
43
44type IconPlatform = "iOS";
45
46interface VariantOutputs {
47 readonly ios: string;
48 readonly macos: string;
49 readonly universal: string;
50 readonly appleTouch: string;
51 readonly favicon16: string;
52 readonly favicon32: string;
53 readonly faviconIco: string;
54 readonly windowsIco: string;
55}
56
57interface IconVariant {
58 readonly label: string;
59 readonly source: string;
60 readonly outputs: VariantOutputs;
61}
62
63interface IconComposerTool {
64 readonly path: string;
65 readonly version: string;
66 readonly bundleVersion: string;
67 readonly supportsDesignGeneration: boolean;
68}
69
70interface CommandResult {
71 readonly stdout: string;
72 readonly stderr: string;
73 readonly exitCode: number;
74}
75
76export class IconExportFileSystemError extends Schema.TaggedError<IconExportFileSystemError>()(
77 "IconExportFileSystemError",
78 {
79 operation: Schema.Literals([
80 "resolve-repository-root",
81 "check-path",
82 "read-directory",
83 "read-file",
84 "make-directory",
85 "make-temp-directory",
86 "make-temp-file",
87 "write-file",
88 "rename-file",
89 ]),
90 path: Schema.String,
91 cause: Schema.Defect(),
92 },
93) {
94 override get message(): string {
95 return `Icon export file-system operation '${this.operation}' failed for ${this.path}.`;
96 }
97}
98
99export class IconExportProcessError extends Schema.TaggedError<IconExportProcessError>()(
100 "IconExportProcessError",
101 {
102 operation: Schema.Literals(["spawn", "collect-stdout", "collect-stderr", "wait-for-exit"]),
103 command: Schema.String,
104 argumentCount: NonNegativeInt,
105 cause: Schema.Defect(),
106 },
107) {
108 override get message(): string {
109 return `Icon export process operation '${this.operation}' failed for ${this.command}.`;
110 }
111}
112
113export class IconExportCommandFailedError extends Schema.TaggedError<IconExportCommandFailedError>()(
114 "IconExportCommandFailedError",
115 {
116 command: Schema.String,
117 argumentCount: NonNegativeInt,
118 exitCode: Schema.Int,
119 sourcePath: Schema.String,
120 size: Schema.Int,
121 stdout: Schema.optional(Schema.String),
122 stderr: Schema.optional(Schema.String),
123 },
124) {
125 override get message(): string {
126 return `Icon Composer failed to export ${this.sourcePath} at ${this.size}x${this.size}.`;
127 }
128}
129
130export class IconExportToolResolutionError extends Schema.TaggedError<IconExportToolResolutionError>()(
131 "IconExportToolResolutionError",
132 {
133 reason: Schema.Literals(["configured-invalid", "configured-outdated", "not-found"]),
134 designGeneration: Schema.Int,
135 toolPath: Schema.optional(Schema.String),
136 version: Schema.optional(Schema.String),
137 },
138) {
139 override get message(): string {
140 switch (this.reason) {
141 case "configured-invalid":
142 return `ICON_COMPOSER_TOOL does not point to Icon Composer's export-capable ictool: ${this.toolPath}`;
143 case "configured-outdated":
144 return `ICON_COMPOSER_TOOL points to Icon Composer ${this.version}, but version 2 or newer is required for design generation ${this.designGeneration}.`;
145 case "not-found":
146 return `Could not find an Icon Composer 2.x exporter compatible with design generation ${this.designGeneration}. Install a compatible Icon Composer/Xcode or set ICON_COMPOSER_TOOL to Icon Composer.app/Contents/Executables/ictool.`;
147 }
148 }
149}
150
151export class IconExportSourceMissingError extends Schema.TaggedError<IconExportSourceMissingError>()(
152 "IconExportSourceMissingError",
153 {
154 sourcePath: Schema.String,
155 },
156) {
157 override get message(): string {
158 return `Missing Icon Composer source project: ${this.sourcePath}`;
159 }
160}
161
162export class IconExportRenditionError extends Schema.TaggedError<IconExportRenditionError>()(
163 "IconExportRenditionError",
164 {
165 sourcePath: Schema.String,
166 outputPath: Schema.String,
167 expectedSize: Schema.Int,
168 actualWidth: Schema.optional(Schema.Int),
169 actualHeight: Schema.optional(Schema.Int),
170 cause: Schema.optional(Schema.Defect()),
171 },
172) {
173 override get message(): string {
174 const actual =
175 this.actualWidth === undefined || this.actualHeight === undefined
176 ? "an invalid PNG"
177 : `${this.actualWidth}x${this.actualHeight}`;
178 return `Icon Composer produced ${actual}; expected ${this.expectedSize}x${this.expectedSize} for ${this.sourcePath}.`;
179 }
180}
181
182export class IconExportEncodingError extends Schema.TaggedError<IconExportEncodingError>()(
183 "IconExportEncodingError",
184 {
185 variant: Schema.String,
186 cause: Schema.Defect(),
187 },
188) {
189 override get message(): string {
190 return `Failed to encode ICO renditions for the ${this.variant} icon.`;
191 }
192}
193
194export class IconExportAssetsStaleError extends Schema.TaggedError<IconExportAssetsStaleError>()(
195 "IconExportAssetsStaleError",
196 {
197 paths: Schema.Array(Schema.String),
198 },
199) {
200 override get message(): string {
201 return `Generated icon assets are stale:\n${this.paths.map((path) => `- ${path}`).join("\n")}`;
202 }
203}
204
205const ICON_VARIANTS = [
206 {
207 label: "development",
208 source: BRAND_ASSET_PATHS.developmentIconComposerProject,
209 outputs: {
210 ios: BRAND_ASSET_PATHS.developmentIosIconPng,
211 macos: BRAND_ASSET_PATHS.developmentDesktopIconPng,
212 universal: BRAND_ASSET_PATHS.developmentUniversalIconPng,
213 appleTouch: BRAND_ASSET_PATHS.developmentWebAppleTouchIconPng,
214 favicon16: BRAND_ASSET_PATHS.developmentWebFavicon16Png,
215 favicon32: BRAND_ASSET_PATHS.developmentWebFavicon32Png,
216 faviconIco: BRAND_ASSET_PATHS.developmentWebFaviconIco,
217 windowsIco: BRAND_ASSET_PATHS.developmentWindowsIconIco,
218 },
219 },
220 {
221 label: "preview",
222 source: BRAND_ASSET_PATHS.nightlyIconComposerProject,
223 outputs: {
224 ios: BRAND_ASSET_PATHS.nightlyIosIconPng,
225 macos: BRAND_ASSET_PATHS.nightlyMacIconPng,
226 universal: BRAND_ASSET_PATHS.nightlyLinuxIconPng,
227 appleTouch: BRAND_ASSET_PATHS.nightlyWebAppleTouchIconPng,
228 favicon16: BRAND_ASSET_PATHS.nightlyWebFavicon16Png,
229 favicon32: BRAND_ASSET_PATHS.nightlyWebFavicon32Png,
230 faviconIco: BRAND_ASSET_PATHS.nightlyWebFaviconIco,
231 windowsIco: BRAND_ASSET_PATHS.nightlyWindowsIconIco,
232 },
233 },
234 {
235 label: "production",
236 source: BRAND_ASSET_PATHS.productionIconComposerProject,
237 outputs: {
238 ios: BRAND_ASSET_PATHS.productionIosIconPng,
239 macos: BRAND_ASSET_PATHS.productionMacIconPng,
240 universal: BRAND_ASSET_PATHS.productionLinuxIconPng,
241 appleTouch: BRAND_ASSET_PATHS.productionWebAppleTouchIconPng,
242 favicon16: BRAND_ASSET_PATHS.productionWebFavicon16Png,
243 favicon32: BRAND_ASSET_PATHS.productionWebFavicon32Png,
244 faviconIco: BRAND_ASSET_PATHS.productionWebFaviconIco,
245 windowsIco: BRAND_ASSET_PATHS.productionWindowsIconIco,
246 },
247 },
248] as const satisfies ReadonlyArray<IconVariant>;
249
250const RepositoryRoot = Effect.service(Path.Path).pipe(
251 Effect.flatMap((path) => path.fromFileUrl(new URL("..", import.meta.url))),
252 Effect.mapError(
253 (cause) =>
254 new IconExportFileSystemError({
255 operation: "resolve-repository-root",
256 path: new URL("..", import.meta.url).pathname,
257 cause,
258 }),
259 ),
260);
261
262const collectStreamAsString = <E>(stream: Stream.Stream<Uint8Array, E>) =>
263 stream.pipe(
264 Stream.decodeText(),
265 Stream.runFold(
266 () => "",
267 (acc, chunk) => acc + chunk,
268 ),
269 );
270
271const runCommand = Effect.fn("iconExport.runCommand")(function* (
272 command: string,
273 args: ReadonlyArray<string>,
274) {
275 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
276 const child = yield* spawner.spawn(ChildProcess.make(command, args)).pipe(
277 Effect.mapError(
278 (cause) =>
279 new IconExportProcessError({
280 operation: "spawn",
281 command,
282 argumentCount: args.length,
283 cause,
284 }),
285 ),
286 );
287 const [stdout, stderr, exitCode] = yield* Effect.all(
288 [
289 collectStreamAsString(child.stdout).pipe(
290 Effect.mapError(
291 (cause) =>
292 new IconExportProcessError({
293 operation: "collect-stdout",
294 command,
295 argumentCount: args.length,
296 cause,
297 }),
298 ),
299 ),
300 collectStreamAsString(child.stderr).pipe(
301 Effect.mapError(
302 (cause) =>
303 new IconExportProcessError({
304 operation: "collect-stderr",
305 command,
306 argumentCount: args.length,
307 cause,
308 }),
309 ),
310 ),
311 child.exitCode.pipe(
312 Effect.map(Number),
313 Effect.mapError(
314 (cause) =>
315 new IconExportProcessError({
316 operation: "wait-for-exit",
317 command,
318 argumentCount: args.length,
319 cause,
320 }),
321 ),
322 ),
323 ],
324 { concurrency: "unbounded" },
325 );
326
327 return { stdout, stderr, exitCode } satisfies CommandResult;
328});
329
330const iconComposerToolFromDeveloperDirectory = (developerDirectory: string, path: Path.Path) =>
331 path.resolve(developerDirectory, "..", ...ICON_COMPOSER_EXECUTABLE_PARTS.slice(1));
332
333const readSelectedDeveloperDirectory = Effect.fn("iconExport.readSelectedDeveloperDirectory")(
334 function* () {
335 const result = yield* runCommand("xcode-select", ["-p"]).pipe(Effect.option);
336 return Option.flatMap(result, (output) => {
337 const developerDirectory = output.stdout.trim();
338 return output.exitCode === 0 && developerDirectory.length > 0
339 ? Option.some(developerDirectory)
340 : Option.none();
341 });
342 },
343);
344
345const findXcodeAppCandidates = Effect.fn("iconExport.findXcodeAppCandidates")(function* (
346 directory: string,
347) {
348 const fs = yield* FileSystem.FileSystem;
349 const path = yield* Path.Path;
350 const entries = yield* fs.readDirectory(directory).pipe(
351 Effect.mapError(
352 (cause) =>
353 new IconExportFileSystemError({
354 operation: "read-directory",
355 path: directory,
356 cause,
357 }),
358 ),
359 Effect.orElseSucceed(() => []),
360 );
361 return entries
362 .filter((entry) => /^Xcode.*\.app$/.test(entry))
363 .map((entry) => path.join(directory, entry, ...ICON_COMPOSER_EXECUTABLE_PARTS));
364});
365
366const probeIconComposerTool = Effect.fn("iconExport.probeIconComposerTool")(function* (
367 candidate: string,
368) {
369 const fs = yield* FileSystem.FileSystem;
370 const exists = yield* fs.exists(candidate).pipe(
371 Effect.mapError(
372 (cause) =>
373 new IconExportFileSystemError({
374 operation: "check-path",
375 path: candidate,
376 cause,
377 }),
378 ),
379 Effect.orElseSucceed(() => false),
380 );
381 if (!exists) return Option.none<IconComposerTool>();
382
383 const result = yield* runCommand(candidate, ["--version"]).pipe(Effect.option);
384 if (Option.isNone(result) || result.value.exitCode !== 0) {
385 return Option.none<IconComposerTool>();
386 }
387
388 const version = yield* decodeIconComposerVersion(result.value.stdout).pipe(Effect.option);
389 if (Option.isNone(version)) return Option.none<IconComposerTool>();
390
391 const bundleVersion = version.value["bundle-version"];
392 const shortVersion = version.value["short-bundle-version"];
393 return Option.some({
394 path: candidate,
395 version: `${shortVersion} (${bundleVersion})`,
396 bundleVersion,
397 supportsDesignGeneration: Number.parseInt(shortVersion, 10) >= 2,
398 });
399});
400
401const resolveIconComposerTool = Effect.fn("iconExport.resolveIconComposerTool")(function* () {
402 const path = yield* Path.Path;
403 const environment = yield* HostProcess.Environment;
404 const configuredTool = environment.ICON_COMPOSER_TOOL?.trim();
405 if (configuredTool) {
406 const tool = yield* probeIconComposerTool(configuredTool);
407 if (Option.isNone(tool)) {
408 return yield* new IconExportToolResolutionError({
409 reason: "configured-invalid",
410 designGeneration: DESIGN_GENERATION,
411 toolPath: configuredTool,
412 });
413 }
414 if (!tool.value.supportsDesignGeneration) {
415 return yield* new IconExportToolResolutionError({
416 reason: "configured-outdated",
417 designGeneration: DESIGN_GENERATION,
418 toolPath: configuredTool,
419 version: tool.value.version,
420 });
421 }
422 return tool.value;
423 }
424
425 const selectedDeveloperDirectory = yield* readSelectedDeveloperDirectory();
426 const configuredDeveloperDirectory = environment.DEVELOPER_DIR?.trim();
427 const homeDirectory = environment.HOME?.trim();
428 const searchDirectories = [
429 "/Applications",
430 ...(homeDirectory ? [path.join(homeDirectory, "Downloads")] : []),
431 ];
432 const xcodeCandidates = yield* Effect.forEach(searchDirectories, findXcodeAppCandidates, {
433 concurrency: "unbounded",
434 });
435 const candidates = new Set<string>([
436 ...(configuredDeveloperDirectory
437 ? [iconComposerToolFromDeveloperDirectory(configuredDeveloperDirectory, path)]
438 : []),
439 ...Option.match(selectedDeveloperDirectory, {
440 onNone: () => [],
441 onSome: (developerDirectory) => [
442 iconComposerToolFromDeveloperDirectory(developerDirectory, path),
443 ],
444 }),
445 path.join("/Applications", ...STANDALONE_ICON_COMPOSER_EXECUTABLE_PARTS),
446 ...(homeDirectory
447 ? [path.join(homeDirectory, "Applications", ...STANDALONE_ICON_COMPOSER_EXECUTABLE_PARTS)]
448 : []),
449 ...xcodeCandidates.flat(),
450 ]);
451 const probed = yield* Effect.forEach([...candidates], probeIconComposerTool, {
452 concurrency: "unbounded",
453 });
454 const compatibleTools = probed
455 .filter(Option.isSome)
456 .map((tool) => tool.value)
457 .filter((tool) => tool.supportsDesignGeneration)
458 .sort((left, right) =>
459 right.bundleVersion.localeCompare(left.bundleVersion, undefined, { numeric: true }),
460 );
461 const newestTool = compatibleTools[0];
462 if (newestTool) return newestTool;
463
464 return yield* new IconExportToolResolutionError({
465 reason: "not-found",
466 designGeneration: DESIGN_GENERATION,
467 });
468});
469
470const renderIcon = Effect.fn("iconExport.renderIcon")(function* (
471 toolPath: string,
472 sourcePath: string,
473 outputPath: string,
474 platform: IconPlatform,
475 size: number,
476) {
477 const fs = yield* FileSystem.FileSystem;
478 const args = [
479 sourcePath,
480 "--export-image",
481 "--output-file",
482 outputPath,
483 "--platform",
484 platform,
485 "--rendition",
486 "Default",
487 "--width",
488 String(size),
489 "--height",
490 String(size),
491 "--scale",
492 "1",
493 "--design-generation",
494 String(DESIGN_GENERATION),
495 ];
496 const result = yield* runCommand(toolPath, args);
497 if (result.exitCode !== 0) {
498 return yield* new IconExportCommandFailedError({
499 command: toolPath,
500 argumentCount: args.length,
501 exitCode: result.exitCode,
502 sourcePath,
503 size,
504 ...(result.stdout.trim() ? { stdout: result.stdout.trim() } : {}),
505 ...(result.stderr.trim() ? { stderr: result.stderr.trim() } : {}),
506 });
507 }
508
509 const contents = yield* fs.readFile(outputPath).pipe(
510 Effect.mapError(
511 (cause) =>
512 new IconExportFileSystemError({
513 operation: "read-file",
514 path: outputPath,
515 cause,
516 }),
517 ),
518 );
519 const buffer = Buffer.from(contents);
520 const dimensions = yield* Effect.try({
521 try: () => readPngDimensions(buffer),
522 catch: (cause) =>
523 new IconExportRenditionError({
524 sourcePath,
525 outputPath,
526 expectedSize: size,
527 cause,
528 }),
529 });
530 if (dimensions.width !== size || dimensions.height !== size) {
531 return yield* new IconExportRenditionError({
532 sourcePath,
533 outputPath,
534 expectedSize: size,
535 actualWidth: dimensions.width,
536 actualHeight: dimensions.height,
537 });
538 }
539 return buffer;
540});
541
542const renderVariant = Effect.fn("iconExport.renderVariant")(function* (
543 toolPath: string,
544 repositoryRoot: string,
545 temporaryDirectory: string,
546 variant: IconVariant,
547) {
548 const fs = yield* FileSystem.FileSystem;
549 const path = yield* Path.Path;
550 const sourcePath = path.join(repositoryRoot, variant.source);
551 const sourceExists = yield* fs.exists(sourcePath).pipe(
552 Effect.mapError(
553 (cause) =>
554 new IconExportFileSystemError({
555 operation: "check-path",
556 path: sourcePath,
557 cause,
558 }),
559 ),
560 );
561 if (!sourceExists) {
562 return yield* new IconExportSourceMissingError({ sourcePath: variant.source });
563 }
564
565 const renditionCache = new Map<string, Buffer>();
566 const render = Effect.fn("iconExport.renderVariant.rendition")(function* (
567 platform: IconPlatform,
568 size: number,
569 ) {
570 const cacheKey = `${platform}-${size}`;
571 const cached = renditionCache.get(cacheKey);
572 if (cached) return cached;
573
574 const outputPath = path.join(temporaryDirectory, `${variant.label}-${platform}-${size}.png`);
575 const contents = yield* renderIcon(toolPath, sourcePath, outputPath, platform, size);
576 renditionCache.set(cacheKey, contents);
577 return contents;
578 });
579
580 const ios = yield* render("iOS", 1024);
581 const icoRenditions = yield* Effect.forEach(
582 WINDOWS_ICON_SIZES,
583 (size) => render("iOS", size).pipe(Effect.map((contents) => ({ size, contents }))),
584 { concurrency: 1 },
585 );
586 const ico = yield* Effect.try({
587 try: () => encodePngIco(icoRenditions),
588 catch: (cause) => new IconExportEncodingError({ variant: variant.label, cause }),
589 });
590
591 return new Map<string, Buffer>([
592 [variant.outputs.ios, ios],
593 [variant.outputs.universal, ios],
594 [variant.outputs.appleTouch, yield* render("iOS", 180)],
595 [variant.outputs.favicon16, yield* render("iOS", 16)],
596 [variant.outputs.favicon32, yield* render("iOS", 32)],
597 [variant.outputs.faviconIco, ico],
598 [variant.outputs.windowsIco, ico],
599 ]);
600});
601
602const writeAtomically = Effect.fn("iconExport.writeAtomically")(function* (
603 repositoryRoot: string,
604 relativePath: string,
605 contents: Buffer,
606) {
607 const fs = yield* FileSystem.FileSystem;
608 const path = yield* Path.Path;
609 const targetPath = path.join(repositoryRoot, relativePath);
610 const targetDirectory = path.dirname(targetPath);
611 yield* fs.makeDirectory(targetDirectory, { recursive: true }).pipe(
612 Effect.mapError(
613 (cause) =>
614 new IconExportFileSystemError({
615 operation: "make-directory",
616 path: targetDirectory,
617 cause,
618 }),
619 ),
620 );
621 const temporaryPath = yield* fs
622 .makeTempFileScoped({
623 directory: targetDirectory,
624 prefix: ".t3-icon-export-",
625 suffix: ".tmp",
626 })
627 .pipe(
628 Effect.mapError(
629 (cause) =>
630 new IconExportFileSystemError({
631 operation: "make-temp-file",
632 path: targetDirectory,
633 cause,
634 }),
635 ),
636 );
637 yield* fs.writeFile(temporaryPath, contents).pipe(
638 Effect.mapError(
639 (cause) =>
640 new IconExportFileSystemError({
641 operation: "write-file",
642 path: temporaryPath,
643 cause,
644 }),
645 ),
646 );
647 yield* fs.rename(temporaryPath, targetPath).pipe(
648 Effect.mapError(
649 (cause) =>
650 new IconExportFileSystemError({
651 operation: "rename-file",
652 path: targetPath,
653 cause,
654 }),
655 ),
656 );
657});
658
659const isCurrent = Effect.fn("iconExport.isCurrent")(function* (
660 repositoryRoot: string,
661 relativePath: string,
662 expected: Buffer,
663) {
664 const fs = yield* FileSystem.FileSystem;
665 const path = yield* Path.Path;
666 const targetPath = path.join(repositoryRoot, relativePath);
667 const exists = yield* fs.exists(targetPath).pipe(
668 Effect.mapError(
669 (cause) =>
670 new IconExportFileSystemError({
671 operation: "check-path",
672 path: targetPath,
673 cause,
674 }),
675 ),
676 );
677 if (!exists) return false;
678
679 const actual = yield* fs.readFile(targetPath).pipe(
680 Effect.mapError(
681 (cause) =>
682 new IconExportFileSystemError({
683 operation: "read-file",
684 path: targetPath,
685 cause,
686 }),
687 ),
688 );
689 return Buffer.from(actual).equals(expected);
690});
691
692export const exportBrandIcons = Effect.fn("exportBrandIcons")(function* (checkOnly: boolean) {
693 const fs = yield* FileSystem.FileSystem;
694 const repositoryRoot = yield* RepositoryRoot;
695 const tool = yield* resolveIconComposerTool();
696 const temporaryDirectory = yield* fs
697 .makeTempDirectoryScoped({
698 prefix: "t3-icon-export-",
699 })
700 .pipe(
701 Effect.mapError(
702 (cause) =>
703 new IconExportFileSystemError({
704 operation: "make-temp-directory",
705 path: "system temporary directory",
706 cause,
707 }),
708 ),
709 );
710 yield* Console.log(
711 `Exporting icons with Icon Composer ${tool.version}, design generation ${DESIGN_GENERATION}.`,
712 );
713
714 const generated = new Map<string, Buffer>();
715 for (const variant of ICON_VARIANTS) {
716 yield* Console.log(`Rendering ${variant.label} from ${variant.source}...`);
717 const variantAssets = yield* renderVariant(
718 tool.path,
719 repositoryRoot,
720 temporaryDirectory,
721 variant,
722 );
723 for (const [relativePath, contents] of variantAssets) {
724 generated.set(relativePath, contents);
725 }
726 }
727
728 for (const override of DEVELOPMENT_PUBLIC_ICON_OVERRIDES) {
729 const sourceContents = generated.get(override.sourceRelativePath);
730 if (sourceContents === undefined) {
731 return yield* Effect.die(
732 new Error(`Generated development web icon is missing: ${override.sourceRelativePath}`),
733 );
734 }
735 generated.set(override.targetRelativePath, sourceContents);
736 }
737
738 if (checkOnly) {
739 const stale = yield* Effect.filter(
740 [...generated.entries()],
741 ([relativePath, contents]) =>
742 isCurrent(repositoryRoot, relativePath, contents).pipe(Effect.map((current) => !current)),
743 { concurrency: "unbounded" },
744 );
745 if (stale.length > 0) {
746 return yield* new IconExportAssetsStaleError({
747 paths: stale.map(([relativePath]) => relativePath),
748 });
749 }
750 yield* Console.log(`All ${generated.size} generated icon assets are current.`);
751 return;
752 }
753
754 yield* Effect.forEach(
755 generated,
756 ([relativePath, contents]) => writeAtomically(repositoryRoot, relativePath, contents),
757 { concurrency: 1, discard: true },
758 );
759 yield* Console.log(`Updated ${generated.size} generated icon assets.`);
760});
761
762export const exportBrandIconsCommand = Command.make(
763 "export-brand-icons",
764 {
765 check: Flag.Boolean("check").pipe(
766 Flag.withDescription("Verify generated icon assets without modifying files."),
767 Flag.withDefault(false),
768 ),
769 },
770 ({ check }) => exportBrandIcons(check).pipe(Effect.scoped),
771).pipe(
772 Command.withDescription(
773 "Export development, preview, and production assets from Icon Composer projects.",
774 ),
775);
776
777if (import.meta.main) {
778 Command.run(exportBrandIconsCommand, { version: "0.0.0" }).pipe(
779 Effect.provide(NodeServices.layer),
780 NodeRuntime.runMain,
781 );
782}