@openfairygui/functions 0.1.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/src/publish.ts ADDED
@@ -0,0 +1,1093 @@
1
+ import {
2
+ type BinaryWriterOptions,
3
+ BinaryWriter,
4
+ type Component,
5
+ type DragonBonesResource,
6
+ type Document,
7
+ type FileSystem,
8
+ type FontResource,
9
+ type ImageResource,
10
+ type MiscResource,
11
+ type MovieClipResource,
12
+ type Package,
13
+ ProjectType,
14
+ type SpineResource,
15
+ type SoundResource,
16
+ type Transform,
17
+ } from '@openfairygui/core';
18
+ import { createTransform } from './utils.js';
19
+ import { atlas, type AtlasOptions } from './atlas.js';
20
+ import { publishCodeGeneration } from './codegen.js';
21
+ import type {
22
+ CliPublishSettings,
23
+ HasOptionalFont,
24
+ PackagePublishArtifactsExtras,
25
+ PublishFileSystem,
26
+ RootProjectSettings,
27
+ } from './shared-types.js';
28
+
29
+ export interface PublishOptions {
30
+ /**
31
+ * Output directory for published files (.fui + atlas PNGs).
32
+ * Required.
33
+ */
34
+ output: string;
35
+
36
+ /**
37
+ * Compress the binary data with zlib raw deflate. Default: false.
38
+ */
39
+ compressed?: boolean;
40
+
41
+ /**
42
+ * File extension for the binary output. Default: 'fui'.
43
+ * Unity projects typically use 'bytes'.
44
+ */
45
+ fileExtension?: string;
46
+
47
+ /**
48
+ * Sharp module instance for atlas image compositing.
49
+ * If not provided, atlas packing only computes layout (no PNGs generated).
50
+ */
51
+ encoder?: unknown;
52
+
53
+ /**
54
+ * Base path for reading source images (project assets root).
55
+ * Required when encoder is provided.
56
+ */
57
+ basePath?: string;
58
+
59
+ /**
60
+ * Atlas packing options.
61
+ */
62
+ atlas?: Omit<AtlasOptions, 'encoder' | 'basePath' | 'outputPath'>;
63
+
64
+ /**
65
+ * Filter which packages to publish by name. If not set, all packages are published.
66
+ */
67
+ packages?: string[];
68
+
69
+ /**
70
+ * FileSystem abstraction for writing output files.
71
+ * Required for actual file output. Without it, only the Document model
72
+ * is updated (atlas layout computed, sprite nodes created).
73
+ */
74
+ fs?: PublishFileSystem;
75
+
76
+ /**
77
+ * Active branch name used when branchProcessing is "主干合并活跃分支".
78
+ * Empty or omitted means publishing the main branch.
79
+ */
80
+ branch?: string;
81
+ }
82
+
83
+ export interface ResolvedPublishAtlasOptions extends Pick<AtlasOptions, 'maxSize' | 'fast' | 'allowRotation' | 'padding' | 'powerOfTwo' | 'square' | 'multiPage' | 'trimImage' | 'extractAlpha'> {}
84
+
85
+ export interface ResolvePublishOptionsOverrides {
86
+ compressed?: boolean;
87
+ fileExtension?: string;
88
+ packages?: string[];
89
+ atlas?: Partial<ResolvedPublishAtlasOptions>;
90
+ }
91
+
92
+ export interface ResolvedPublishOptions {
93
+ compressed: boolean;
94
+ fileExtension: string;
95
+ packages?: string[];
96
+ atlas: ResolvedPublishAtlasOptions;
97
+ }
98
+
99
+ interface ImageResourceExtras extends Record<string, unknown> {
100
+ _fileName?: string;
101
+ }
102
+
103
+ interface PublishFileExtras extends Record<string, unknown> {
104
+ _publishedFile?: string;
105
+ _publishedId?: string;
106
+ }
107
+
108
+ interface BranchAwarePublishedResource {
109
+ getBranch?(): string;
110
+ }
111
+
112
+ interface PackagePublishContext {
113
+ referencedIds: Set<string>;
114
+ publishedResourceIds: Set<string>;
115
+ pixelHitTestImageIds: Set<string>;
116
+ effectiveResourceIds: Map<string, string>;
117
+ includeBranches: boolean;
118
+ }
119
+
120
+ interface ChildReferenceItem {
121
+ icon?: string | null;
122
+ url?: string | null;
123
+ }
124
+
125
+ interface GearWithPublishRefs {
126
+ getValues?(): string;
127
+ getDefaultValue?(): unknown;
128
+ }
129
+
130
+ interface TransitionItemWithPublishRefs {
131
+ getStartValue?(): unknown;
132
+ getEndValue?(): unknown;
133
+ }
134
+
135
+ interface TransitionWithPublishRefs {
136
+ listItems?(): TransitionItemWithPublishRefs[];
137
+ }
138
+
139
+ interface ChildWithPublishRefs extends HasOptionalFont {
140
+ getId?(): string;
141
+ getSrc?(): string;
142
+ getUrl?(): string;
143
+ getDefaultItem?(): string;
144
+ getIcon?(): string;
145
+ getSelectedIcon?(): string;
146
+ getDropdown?(): string;
147
+ getSound?(): string;
148
+ getText?(): string;
149
+ getInstanceIcon?(): string;
150
+ getInstanceSelectedIcon?(): string;
151
+ getVtScrollBarRes?(): string;
152
+ getHzScrollBarRes?(): string;
153
+ getHeaderRes?(): string;
154
+ getFooterRes?(): string;
155
+ getInstanceComboItems?(): Array<{ icon: string | null }>;
156
+ getListItems?(): ChildReferenceItem[];
157
+ listGears?(): GearWithPublishRefs[];
158
+ }
159
+
160
+ interface ComponentWithPublishRefs {
161
+ getId(): string;
162
+ getExported(): boolean;
163
+ listChildren(): ChildWithPublishRefs[];
164
+ getHitTest?(): string;
165
+ getDropdown?(): string;
166
+ getHeaderRes?(): string;
167
+ getFooterRes?(): string;
168
+ getVtScrollBarRes?(): string;
169
+ getHzScrollBarRes?(): string;
170
+ getSound?(): string;
171
+ getFont?(): string | string[] | null | undefined;
172
+ listTransitions?(): TransitionWithPublishRefs[];
173
+ }
174
+
175
+ interface PublishEncoderMetadata {
176
+ width?: number;
177
+ height?: number;
178
+ channels?: number;
179
+ }
180
+
181
+ interface PublishEncoderResolvedBuffer {
182
+ data: Uint8Array;
183
+ info: Required<Pick<PublishEncoderMetadata, 'width' | 'height' | 'channels'>> & PublishEncoderMetadata;
184
+ }
185
+
186
+ interface PublishEncoderPipeline {
187
+ ensureAlpha(): PublishEncoderPipeline;
188
+ resize(options: { width: number; height: number; fit: 'fill' }): PublishEncoderPipeline;
189
+ raw(): PublishEncoderPipeline;
190
+ toBuffer(options: { resolveWithObject: true }): Promise<PublishEncoderResolvedBuffer>;
191
+ metadata(): Promise<PublishEncoderMetadata>;
192
+ }
193
+
194
+ type PublishEncoder = (input: string | Uint8Array) => PublishEncoderPipeline;
195
+
196
+ const UNITY_PROJECT_TYPE = ProjectType.Unity;
197
+ const COCOS_CREATOR_PROJECT_TYPE = ProjectType.CocosCreator;
198
+
199
+ function resolveDefaultPublishFileExtension(projectType: number, publishSettings: CliPublishSettings): string {
200
+ if (projectType === UNITY_PROJECT_TYPE) {
201
+ return 'bytes';
202
+ }
203
+ if (projectType === COCOS_CREATOR_PROJECT_TYPE) {
204
+ return publishSettings.fileExtension || 'bin';
205
+ }
206
+ // publish() is currently a binary forward-publish path. For non-Unity projects,
207
+ // keep the emitted contract driven by the configured extension, falling back to
208
+ // `fui`, which intentionally covers the shared generic binary contract outside
209
+ // Unity and the Creator-specific default-to-bin rule.
210
+ return publishSettings.fileExtension || 'fui';
211
+ }
212
+
213
+ export interface PublishAtlasRuntimeOptions {
214
+ preserveInputOrderOnTie: boolean;
215
+ directSingleImageOutput: boolean;
216
+ }
217
+
218
+ export function resolvePublishAtlasRuntimeOptions(fileExtension: string): PublishAtlasRuntimeOptions {
219
+ return {
220
+ preserveInputOrderOnTie: fileExtension === 'fui',
221
+ directSingleImageOutput: fileExtension === 'bytes',
222
+ };
223
+ }
224
+
225
+ function resolvePublishFileName(publishName: string, fileExtension: string): string {
226
+ if (fileExtension === 'bytes') {
227
+ return `${publishName}_fui.bytes`;
228
+ }
229
+ return `${publishName}.${fileExtension}`;
230
+ }
231
+
232
+ /**
233
+ * Resolve publish defaults from the document's project settings.
234
+ *
235
+ * This keeps the editor-aligned publish rules reusable across environments,
236
+ * while callers still provide environment-specific concerns such as fs/encoder/basePath.
237
+ */
238
+ export function resolvePublishOptions(
239
+ doc: Document,
240
+ overrides: ResolvePublishOptionsOverrides = {},
241
+ ): ResolvedPublishOptions {
242
+ const root = doc.getRoot();
243
+ const settings = (root.getSettings?.() ?? {}) as RootProjectSettings;
244
+ const publishSettings: CliPublishSettings = settings.publish ?? {};
245
+ const atlasSetting = publishSettings.atlasSetting ?? {};
246
+ const projectType = root.getProjectType();
247
+
248
+ const fileExtension = overrides.fileExtension
249
+ ?? resolveDefaultPublishFileExtension(projectType, publishSettings);
250
+
251
+ let compressed = overrides.compressed ?? publishSettings.compressDesc ?? false;
252
+ if (projectType === UNITY_PROJECT_TYPE) {
253
+ compressed = overrides.compressed ?? false;
254
+ }
255
+
256
+ const atlasOptions: ResolvedPublishAtlasOptions = {
257
+ maxSize: overrides.atlas?.maxSize ?? atlasSetting.maxSize ?? 2048,
258
+ fast: overrides.atlas?.fast ?? atlasSetting.fast ?? true,
259
+ allowRotation: overrides.atlas?.allowRotation ?? atlasSetting.allowRotation ?? false,
260
+ padding: overrides.atlas?.padding ?? atlasSetting.padding ?? 2,
261
+ powerOfTwo: overrides.atlas?.powerOfTwo ?? atlasSetting.sizeOption === 'pot',
262
+ square: overrides.atlas?.square ?? atlasSetting.forceSquare ?? false,
263
+ multiPage: overrides.atlas?.multiPage ?? atlasSetting.paging ?? true,
264
+ trimImage: overrides.atlas?.trimImage ?? atlasSetting.trimImage ?? false,
265
+ extractAlpha: overrides.atlas?.extractAlpha ?? atlasSetting.extractAlpha ?? false,
266
+ };
267
+
268
+ return {
269
+ compressed,
270
+ fileExtension,
271
+ packages: overrides.packages,
272
+ atlas: atlasOptions,
273
+ };
274
+ }
275
+
276
+ function dirname(filePath: string): string {
277
+ const trimmed = filePath.replace(/[/\\]+$/, '');
278
+ const match = trimmed.match(/^(.*)[/\\][^/\\]+$/);
279
+ return match?.[1] ?? '';
280
+ }
281
+
282
+ function createUnsupportedFsOperation(name: keyof FileSystem) {
283
+ return async (): Promise<never> => {
284
+ throw new Error(`publish: FileSystem.${name}() is not available in the publish writer adapter.`);
285
+ };
286
+ }
287
+
288
+ function toBinaryWriterFileSystem(fs: PublishFileSystem): FileSystem {
289
+ return {
290
+ readFile: createUnsupportedFsOperation('readFile'),
291
+ readFileRaw: createUnsupportedFsOperation('readFileRaw'),
292
+ writeFile: createUnsupportedFsOperation('writeFile'),
293
+ writeFileRaw: fs.writeFileRaw,
294
+ mkdir: fs.mkdir,
295
+ readdir: createUnsupportedFsOperation('readdir'),
296
+ exists: createUnsupportedFsOperation('exists'),
297
+ join: fs.join,
298
+ dirname,
299
+ };
300
+ }
301
+
302
+ function isComponentResource(resource: ReturnType<Package['listResources']>[number]): resource is Component {
303
+ return resource.propertyType === 'Component';
304
+ }
305
+
306
+ function isImageResource(resource: ReturnType<Package['listResources']>[number]): resource is ImageResource {
307
+ return resource.propertyType === 'ImageResource';
308
+ }
309
+
310
+ function isMovieClipResource(resource: ReturnType<Package['listResources']>[number]): resource is MovieClipResource {
311
+ return resource.propertyType === 'MovieClipResource';
312
+ }
313
+
314
+ function isMiscResource(resource: ReturnType<Package['listResources']>[number]): resource is MiscResource {
315
+ return resource.propertyType === 'MiscResource';
316
+ }
317
+
318
+ function isFontResource(resource: ReturnType<Package['listResources']>[number]): resource is FontResource {
319
+ return resource.propertyType === 'FontResource';
320
+ }
321
+
322
+ function isSoundResource(resource: ReturnType<Package['listResources']>[number]): resource is SoundResource {
323
+ return resource.propertyType === 'SoundResource';
324
+ }
325
+
326
+ function isSpineResource(resource: ReturnType<Package['listResources']>[number]): resource is SpineResource {
327
+ return resource.propertyType === 'SpineResource';
328
+ }
329
+
330
+ function isDragonBonesResource(resource: ReturnType<Package['listResources']>[number]): resource is DragonBonesResource {
331
+ return resource.propertyType === 'DragonBonesResource';
332
+ }
333
+
334
+ function isSkeletonResource(
335
+ resource: ReturnType<Package['listResources']>[number],
336
+ ): resource is SpineResource | DragonBonesResource {
337
+ return isSpineResource(resource) || isDragonBonesResource(resource);
338
+ }
339
+
340
+ function addLocalUiResourceRef(target: Set<string>, pkgId: string, value: string | null | undefined): void {
341
+ if (!value || typeof value !== 'string' || !value.startsWith(`ui://${pkgId}`) || value.length <= 13) return;
342
+ target.add(value.slice(13));
343
+ }
344
+
345
+ function addLocalUiResourceRefsFromText(target: Set<string>, pkgId: string, value: string | null | undefined): void {
346
+ if (!value || typeof value !== 'string') return;
347
+ const prefix = `ui://${pkgId}`;
348
+ let index = value.indexOf(prefix);
349
+ while (index !== -1) {
350
+ const start = index + prefix.length;
351
+ let end = start;
352
+ while (end < value.length && /[0-9a-z]/i.test(value[end] ?? '')) end++;
353
+ if (end > start) target.add(value.slice(start, end));
354
+ index = value.indexOf(prefix, end);
355
+ }
356
+ }
357
+
358
+ function addLocalUiResourceRefsFromUnknown(target: Set<string>, pkgId: string, value: unknown): void {
359
+ if (Array.isArray(value)) {
360
+ for (const entry of value) addLocalUiResourceRefsFromUnknown(target, pkgId, entry);
361
+ return;
362
+ }
363
+ if (typeof value === 'string') {
364
+ addLocalUiResourceRef(target, pkgId, value);
365
+ addLocalUiResourceRefsFromText(target, pkgId, value);
366
+ }
367
+ }
368
+
369
+ function addLocalFontRef(target: Set<string>, pkgId: string, value: string | string[] | null | undefined): void {
370
+ if (Array.isArray(value)) {
371
+ for (const entry of value) addLocalUiResourceRef(target, pkgId, entry);
372
+ return;
373
+ }
374
+ addLocalUiResourceRef(target, pkgId, value ?? undefined);
375
+ }
376
+
377
+ function resolvePackageAssetsBasePath(
378
+ basePath: string,
379
+ resource: BranchAwarePublishedResource | undefined,
380
+ ): string {
381
+ const branchName = resource?.getBranch?.() ?? '';
382
+ if (!branchName) return basePath;
383
+ const normalized = basePath.replace(/[/\\]+$/, '');
384
+ if (/[\\/]assets$/i.test(normalized)) {
385
+ return normalized.replace(/([\\/])assets$/i, `$1assets_${branchName}`);
386
+ }
387
+ return `${normalized}_${branchName}`;
388
+ }
389
+
390
+ function resolveImagePath(resource: ImageResource, pkg: Package, basePath: string): string {
391
+ const fileName = resolveImageFileName(resource);
392
+ const resourcePath = resource.getPath() ?? '/';
393
+ const packageBasePath = resolvePackageAssetsBasePath(basePath, resource);
394
+ return `${packageBasePath}/${pkg.getName()}${resourcePath}${fileName}`;
395
+ }
396
+
397
+ function resolveImageFileName(resource: ImageResource): string {
398
+ const extras = (resource.getExtras() as ImageResourceExtras | undefined) ?? {};
399
+ return resource.getFileName() || extras._fileName || resource.getName();
400
+ }
401
+
402
+ function resolveSoundPath(resource: SoundResource, pkg: Package, basePath: string): string {
403
+ const resourcePath = resource.getPath() ?? '/';
404
+ const packageBasePath = resolvePackageAssetsBasePath(basePath, resource);
405
+ return `${packageBasePath}/${pkg.getName()}${resourcePath}${resource.getFile()}`;
406
+ }
407
+
408
+ function resolveGenericResourcePath(
409
+ resource: { getPath(): string; getFile(): string; getBranch?(): string },
410
+ pkg: Package,
411
+ basePath: string,
412
+ ): string {
413
+ const resourcePath = resource.getPath() ?? '/';
414
+ const packageBasePath = resolvePackageAssetsBasePath(basePath, resource);
415
+ return `${packageBasePath}/${pkg.getName()}${resourcePath}${resource.getFile()}`;
416
+ }
417
+
418
+ function extname(fileName: string): string {
419
+ const normalized = fileName.replace(/\\/g, '/');
420
+ const lastSlash = normalized.lastIndexOf('/');
421
+ const lastDot = normalized.lastIndexOf('.');
422
+ if (lastDot <= lastSlash) return '';
423
+ return normalized.slice(lastDot);
424
+ }
425
+
426
+ function resolvePublishedMiscFileName(resource: MiscResource): string {
427
+ const file = resource.getFile();
428
+ if (file.toLowerCase().endsWith('.atlas')) return `${file}.txt`;
429
+ return file;
430
+ }
431
+
432
+ function resolvePublishedSkeletonFileName(resource: SpineResource | DragonBonesResource): string {
433
+ if (isSpineResource(resource) && resource.getFile().toLowerCase().endsWith('.skel')) {
434
+ return `${resource.getFile()}.bytes`;
435
+ }
436
+ return resource.getFile();
437
+ }
438
+
439
+ function setPublishedFileExtra(
440
+ resource: { getExtras(): Record<string, unknown> | undefined; setExtras(value: Record<string, unknown>): unknown },
441
+ fileName: string,
442
+ ): void {
443
+ const extras = (resource.getExtras() as PublishFileExtras | undefined) ?? {};
444
+ resource.setExtras({
445
+ ...extras,
446
+ _publishedFile: fileName,
447
+ });
448
+ }
449
+
450
+ function setPublishedIdExtra(
451
+ resource: { getId(): string; getExtras(): Record<string, unknown> | undefined; setExtras(value: Record<string, unknown>): unknown },
452
+ effectiveId: string | null,
453
+ ): void {
454
+ const extras = (resource.getExtras() as PublishFileExtras | undefined) ?? {};
455
+ if (!effectiveId || effectiveId === resource.getId()) {
456
+ if (!('_publishedId' in extras)) return;
457
+ const { _publishedId: _ignored, ...rest } = extras;
458
+ resource.setExtras(rest);
459
+ return;
460
+ }
461
+ resource.setExtras({
462
+ ...extras,
463
+ _publishedId: effectiveId,
464
+ });
465
+ }
466
+
467
+ function getPublishedId(resource: { getId(): string; getExtras(): Record<string, unknown> | undefined }): string {
468
+ const extras = (resource.getExtras() as PublishFileExtras | undefined) ?? {};
469
+ return extras._publishedId ?? resource.getId();
470
+ }
471
+
472
+ function getBranchName(resource: BranchAwarePublishedResource | undefined): string {
473
+ return resource?.getBranch?.() ?? '';
474
+ }
475
+
476
+ function buildBranchResourceKey(resource: {
477
+ propertyType: string;
478
+ getPath(): string;
479
+ getName(): string;
480
+ }): string {
481
+ return `${resource.propertyType}|${resource.getPath() ?? ''}|${resource.getName() ?? ''}`;
482
+ }
483
+
484
+ function collectPackagePublishContext(
485
+ pkg: Package,
486
+ options: {
487
+ includeBranches: boolean;
488
+ activeBranch: string;
489
+ },
490
+ ): PackagePublishContext {
491
+ const pkgId = pkg.getId();
492
+ const resources = pkg.listResources();
493
+ const resourceMap = new Map(resources.map((resource) => [resource.getId(), resource]));
494
+ const referencedIds = new Set<string>();
495
+ const pixelHitTestImageIds = new Set<string>();
496
+ const spriteItemIds = new Set<string>();
497
+
498
+ for (const atlas of pkg.listAtlases()) {
499
+ for (const sprite of atlas.listSprites()) {
500
+ spriteItemIds.add(sprite.getItemId());
501
+ }
502
+ }
503
+
504
+ for (const resource of resources) {
505
+ if (!isComponentResource(resource)) continue;
506
+ const component = resource as ComponentWithPublishRefs;
507
+ const children = component.listChildren();
508
+ const childMap = new Map(children.map((child) => [child.getId?.() ?? '', child]));
509
+
510
+ const hitTest = component.getHitTest?.()?.trim();
511
+ if (hitTest && !hitTest.includes(',')) {
512
+ const targetChild = childMap.get(hitTest);
513
+ const sourceId = targetChild?.getSrc?.();
514
+ if (sourceId) {
515
+ const sourceResource = resourceMap.get(sourceId);
516
+ if (sourceResource && isImageResource(sourceResource)) {
517
+ pixelHitTestImageIds.add(sourceId);
518
+ }
519
+ }
520
+ }
521
+
522
+ for (const child of children) {
523
+ const src = child.getSrc?.();
524
+ if (src) referencedIds.add(src);
525
+ addLocalFontRef(referencedIds, pkgId, child.getFont?.());
526
+ addLocalUiResourceRefsFromText(referencedIds, pkgId, child.getText?.());
527
+ for (const ref of [
528
+ child.getUrl?.(),
529
+ child.getDefaultItem?.(),
530
+ child.getIcon?.(),
531
+ child.getSelectedIcon?.(),
532
+ child.getDropdown?.(),
533
+ child.getSound?.(),
534
+ child.getInstanceIcon?.(),
535
+ child.getInstanceSelectedIcon?.(),
536
+ child.getVtScrollBarRes?.(),
537
+ child.getHzScrollBarRes?.(),
538
+ child.getHeaderRes?.(),
539
+ child.getFooterRes?.(),
540
+ ]) {
541
+ addLocalUiResourceRef(referencedIds, pkgId, ref);
542
+ }
543
+ for (const item of child.getInstanceComboItems?.() ?? []) {
544
+ addLocalUiResourceRef(referencedIds, pkgId, item.icon ?? undefined);
545
+ }
546
+ for (const item of child.getListItems?.() ?? []) {
547
+ addLocalUiResourceRef(referencedIds, pkgId, item.icon ?? undefined);
548
+ addLocalUiResourceRef(referencedIds, pkgId, item.url ?? undefined);
549
+ }
550
+ for (const gear of child.listGears?.() ?? []) {
551
+ addLocalUiResourceRefsFromUnknown(referencedIds, pkgId, gear.getValues?.());
552
+ addLocalUiResourceRefsFromUnknown(referencedIds, pkgId, gear.getDefaultValue?.());
553
+ }
554
+ }
555
+
556
+ addLocalFontRef(referencedIds, pkgId, component.getFont?.());
557
+ for (const ref of [
558
+ component.getDropdown?.(),
559
+ component.getHeaderRes?.(),
560
+ component.getFooterRes?.(),
561
+ component.getVtScrollBarRes?.(),
562
+ component.getHzScrollBarRes?.(),
563
+ component.getSound?.(),
564
+ ]) {
565
+ addLocalUiResourceRef(referencedIds, pkgId, ref);
566
+ }
567
+ for (const transition of component.listTransitions?.() ?? []) {
568
+ for (const item of transition.listItems?.() ?? []) {
569
+ addLocalUiResourceRefsFromUnknown(referencedIds, pkgId, item.getStartValue?.());
570
+ addLocalUiResourceRefsFromUnknown(referencedIds, pkgId, item.getEndValue?.());
571
+ }
572
+ }
573
+ }
574
+
575
+ const publishedResourceIds = new Set<string>(spriteItemIds);
576
+ for (const resource of resources) {
577
+ const resourceId = resource.getId();
578
+ if (!resourceId) continue;
579
+ if (isComponentResource(resource)) {
580
+ if (resource.getExported() || referencedIds.has(resourceId)) {
581
+ publishedResourceIds.add(resourceId);
582
+ }
583
+ continue;
584
+ }
585
+ if (isImageResource(resource)) {
586
+ if (resource.getExported() || referencedIds.has(resourceId) || spriteItemIds.has(resourceId) || pixelHitTestImageIds.has(resourceId)) {
587
+ publishedResourceIds.add(resourceId);
588
+ }
589
+ continue;
590
+ }
591
+ if (isMovieClipResource(resource) || isSoundResource(resource)) {
592
+ if (resource.getExported() || referencedIds.has(resourceId)) publishedResourceIds.add(resourceId);
593
+ continue;
594
+ }
595
+ if (isMiscResource(resource) || isSkeletonResource(resource)) {
596
+ if (resource.getExported() || referencedIds.has(resourceId)) publishedResourceIds.add(resourceId);
597
+ continue;
598
+ }
599
+ if (isFontResource(resource)) {
600
+ if (resource.getExported() || referencedIds.has(resourceId)) {
601
+ publishedResourceIds.add(resourceId);
602
+ }
603
+ continue;
604
+ }
605
+ const genericResource = resource as ReturnType<Package['listResources']>[number];
606
+ if (genericResource.getExported() || referencedIds.has(resourceId)) {
607
+ publishedResourceIds.add(resourceId);
608
+ }
609
+ }
610
+
611
+ let changed = true;
612
+ while (changed) {
613
+ changed = false;
614
+ for (const resource of resources) {
615
+ if (!isSkeletonResource(resource)) continue;
616
+ if (!publishedResourceIds.has(resource.getId())) continue;
617
+ for (const requiredId of resource.getRequireIds()) {
618
+ if (!requiredId || publishedResourceIds.has(requiredId)) continue;
619
+ publishedResourceIds.add(requiredId);
620
+ changed = true;
621
+ }
622
+ }
623
+ }
624
+
625
+ if (!options.includeBranches) {
626
+ const mainByKey = new Map<string, ReturnType<Package['listResources']>[number]>();
627
+ const activeBranchByKey = new Map<string, ReturnType<Package['listResources']>[number]>();
628
+ for (const resource of resources) {
629
+ const branchName = getBranchName(resource);
630
+ const key = buildBranchResourceKey(resource);
631
+ if (!branchName) {
632
+ mainByKey.set(key, resource);
633
+ } else if (branchName === options.activeBranch) {
634
+ activeBranchByKey.set(key, resource);
635
+ }
636
+ }
637
+
638
+ const mergedPublishedResourceIds = new Set<string>();
639
+ const effectiveResourceIds = new Map<string, string>();
640
+ for (const resource of resources) {
641
+ const resourceId = resource.getId();
642
+ if (!publishedResourceIds.has(resourceId)) continue;
643
+
644
+ const branchName = getBranchName(resource);
645
+ const key = buildBranchResourceKey(resource);
646
+ if (branchName) {
647
+ if (branchName !== options.activeBranch) continue;
648
+ const mainResource = mainByKey.get(key);
649
+ mergedPublishedResourceIds.add(resourceId);
650
+ effectiveResourceIds.set(resourceId, mainResource?.getId() ?? resourceId);
651
+ continue;
652
+ }
653
+
654
+ const override = activeBranchByKey.get(key);
655
+ if (override) {
656
+ mergedPublishedResourceIds.add(override.getId());
657
+ effectiveResourceIds.set(override.getId(), resourceId);
658
+ continue;
659
+ }
660
+
661
+ mergedPublishedResourceIds.add(resourceId);
662
+ effectiveResourceIds.set(resourceId, resourceId);
663
+ }
664
+
665
+ publishedResourceIds.clear();
666
+ for (const resourceId of mergedPublishedResourceIds) {
667
+ publishedResourceIds.add(resourceId);
668
+ }
669
+
670
+ const mergedPixelHitTestImageIds = new Set<string>();
671
+ for (const resource of resources) {
672
+ if (!isImageResource(resource)) continue;
673
+ const resourceId = resource.getId();
674
+ if (!publishedResourceIds.has(resourceId)) continue;
675
+ const effectiveId = effectiveResourceIds.get(resourceId) ?? resourceId;
676
+ if (pixelHitTestImageIds.has(effectiveId)) {
677
+ mergedPixelHitTestImageIds.add(resourceId);
678
+ }
679
+ }
680
+ pixelHitTestImageIds.clear();
681
+ for (const resourceId of mergedPixelHitTestImageIds) {
682
+ pixelHitTestImageIds.add(resourceId);
683
+ }
684
+
685
+ return {
686
+ referencedIds,
687
+ publishedResourceIds,
688
+ pixelHitTestImageIds,
689
+ effectiveResourceIds,
690
+ includeBranches: false,
691
+ };
692
+ }
693
+
694
+ return {
695
+ referencedIds,
696
+ publishedResourceIds,
697
+ pixelHitTestImageIds,
698
+ effectiveResourceIds: new Map([...publishedResourceIds].map((resourceId) => [resourceId, resourceId])),
699
+ includeBranches: true,
700
+ };
701
+ }
702
+
703
+ async function applyPixelHitTests(
704
+ pkg: Package,
705
+ imageIds: Set<string>,
706
+ basePath: string | undefined,
707
+ encoder: PublishEncoder | undefined,
708
+ ): Promise<void> {
709
+ const images = pkg.listImageResources();
710
+ for (const image of images) {
711
+ image.setPixelHitTestData(null);
712
+ }
713
+ if (!basePath || !encoder || imageIds.size === 0) return;
714
+
715
+ for (const image of images) {
716
+ const imageId = image.getId();
717
+ if (!imageIds.has(imageId)) continue;
718
+ try {
719
+ const sourcePath = resolveImagePath(image, pkg, basePath);
720
+ const metadata = await encoder(sourcePath).metadata();
721
+ if (!metadata.width || !metadata.height) continue;
722
+
723
+ const resizedWidth = Math.max(1, Math.floor(metadata.width / 2));
724
+ const resizedHeight = Math.max(1, Math.floor(metadata.height / 2));
725
+ const { data, info } = await encoder(sourcePath)
726
+ .ensureAlpha()
727
+ .resize({
728
+ width: resizedWidth,
729
+ height: resizedHeight,
730
+ fit: 'fill',
731
+ })
732
+ .raw()
733
+ .toBuffer({ resolveWithObject: true });
734
+
735
+ const pixelCount = info.width * info.height;
736
+ const maskBytes = new Uint8Array(Math.ceil(pixelCount / 8));
737
+ let byteValue = 0;
738
+ let bitIndex = 0;
739
+ let maskIndex = 0;
740
+
741
+ for (let pixel = 0; pixel < pixelCount; pixel++) {
742
+ const alpha = data[pixel * info.channels + 3];
743
+ if (alpha > 10) byteValue |= 1 << bitIndex;
744
+ bitIndex++;
745
+ if (bitIndex === 8) {
746
+ maskBytes[maskIndex++] = byteValue;
747
+ bitIndex = 0;
748
+ byteValue = 0;
749
+ }
750
+ }
751
+ if (bitIndex !== 0) {
752
+ maskBytes[maskIndex] = byteValue;
753
+ }
754
+
755
+ image.setPixelHitTestData({
756
+ pixelWidth: info.width,
757
+ scaleDenominator: 2,
758
+ pixels: maskBytes,
759
+ });
760
+ } catch {
761
+ image.setPixelHitTestData(null);
762
+ }
763
+ }
764
+ }
765
+
766
+ async function annotatePackagePublishArtifacts(
767
+ pkg: Package,
768
+ basePath: string | undefined,
769
+ encoder: PublishEncoder | undefined,
770
+ options: {
771
+ includeBranches: boolean;
772
+ activeBranch: string;
773
+ },
774
+ ): Promise<void> {
775
+ const { publishedResourceIds, pixelHitTestImageIds, effectiveResourceIds, includeBranches } = collectPackagePublishContext(pkg, options);
776
+ for (const resource of pkg.listResources()) {
777
+ setPublishedIdExtra(resource, effectiveResourceIds.get(resource.getId()) ?? null);
778
+ }
779
+ await applyPixelHitTests(pkg, pixelHitTestImageIds, basePath, encoder);
780
+ const extras = (pkg.getExtras() as PackagePublishArtifactsExtras | undefined) ?? {};
781
+ pkg.setExtras({
782
+ ...extras,
783
+ publishedResourceIds: [...publishedResourceIds].sort((a, b) => a.localeCompare(b)),
784
+ publishedIncludeBranches: includeBranches,
785
+ publishedEffectiveResourceIds: Object.fromEntries(effectiveResourceIds),
786
+ });
787
+ for (const resource of pkg.listResources()) {
788
+ if (isMiscResource(resource)) {
789
+ setPublishedFileExtra(resource, resolvePublishedMiscFileName(resource));
790
+ continue;
791
+ }
792
+ if (isSkeletonResource(resource)) {
793
+ setPublishedFileExtra(resource, resolvePublishedSkeletonFileName(resource));
794
+ }
795
+ }
796
+ }
797
+
798
+ function getAnnotatedPublishedResourceIds(pkg: Package): Set<string> {
799
+ const extras = (pkg.getExtras() as PackagePublishArtifactsExtras | undefined) ?? {};
800
+ return new Set(extras.publishedResourceIds ?? []);
801
+ }
802
+
803
+ function getPublishedSkeletonDependencyImageIds(
804
+ pkg: Package,
805
+ publishedResourceIds: Set<string>,
806
+ ): Set<string> {
807
+ const imageIds = new Set<string>();
808
+ const resourcesById = new Map(pkg.listResources().map((resource) => [resource.getId(), resource] as const));
809
+ for (const resource of pkg.listResources()) {
810
+ if (!isSkeletonResource(resource)) continue;
811
+ if (!publishedResourceIds.has(resource.getId())) continue;
812
+ for (const requiredId of resource.getRequireIds()) {
813
+ if (!requiredId) continue;
814
+ const required = resourcesById.get(requiredId);
815
+ if (required && isImageResource(required)) imageIds.add(requiredId);
816
+ }
817
+ }
818
+ return imageIds;
819
+ }
820
+
821
+ async function exportPackageSounds(
822
+ pkg: Package,
823
+ outputDir: string,
824
+ basePath: string | undefined,
825
+ fs: PublishFileSystem,
826
+ readFileRaw: PublishFileSystem['readFileRaw'] | undefined,
827
+ logger: Document['getLogger'] extends () => infer T ? T : never,
828
+ ): Promise<void> {
829
+ const publishedResourceIds = getAnnotatedPublishedResourceIds(pkg);
830
+ if (publishedResourceIds.size === 0) return;
831
+ if (!basePath || !readFileRaw) {
832
+ const hasPublishedSound = pkg.listResources().some((resource) => {
833
+ return isSoundResource(resource) && publishedResourceIds.has(resource.getId());
834
+ });
835
+ if (hasPublishedSound) {
836
+ logger.warn(`publish: Sound resources in package "${pkg.getName()}" were not exported because basePath/readFileRaw is unavailable.`);
837
+ }
838
+ return;
839
+ }
840
+
841
+ for (const resource of pkg.listResources()) {
842
+ if (!isSoundResource(resource)) continue;
843
+ if (!publishedResourceIds.has(resource.getId())) continue;
844
+
845
+ const sourcePath = resolveSoundPath(resource, pkg, basePath);
846
+ const targetName = `${pkg.getPublishName() || pkg.getName()}_${getPublishedId(resource)}${extname(resource.getFile() || '')}`;
847
+ const targetPath = fs.join(outputDir, targetName);
848
+
849
+ try {
850
+ const data = await readFileRaw(sourcePath);
851
+ await fs.writeFileRaw(targetPath, data);
852
+ } catch {
853
+ logger.warn(`publish: Could not export sound "${resource.getId()}" from package "${pkg.getName()}".`);
854
+ }
855
+ }
856
+ }
857
+
858
+ async function exportPackageExternalResources(
859
+ pkg: Package,
860
+ outputDir: string,
861
+ basePath: string | undefined,
862
+ fs: PublishFileSystem,
863
+ readFileRaw: PublishFileSystem['readFileRaw'] | undefined,
864
+ logger: Document['getLogger'] extends () => infer T ? T : never,
865
+ ): Promise<void> {
866
+ const publishedResourceIds = getAnnotatedPublishedResourceIds(pkg);
867
+ const skeletonDependencyImageIds = getPublishedSkeletonDependencyImageIds(pkg, publishedResourceIds);
868
+ if (publishedResourceIds.size === 0) return;
869
+ if (!basePath || !readFileRaw) {
870
+ const hasPublishedExternal = pkg.listResources().some((resource) => {
871
+ return (
872
+ (isMiscResource(resource) || isSkeletonResource(resource))
873
+ && publishedResourceIds.has(resource.getId())
874
+ ) || skeletonDependencyImageIds.has(resource.getId());
875
+ });
876
+ if (hasPublishedExternal) {
877
+ logger.warn(`publish: External resources in package "${pkg.getName()}" were not exported because basePath/readFileRaw is unavailable.`);
878
+ }
879
+ return;
880
+ }
881
+
882
+ for (const resource of pkg.listResources()) {
883
+ const resourceId = resource.getId();
884
+ const isSkeletonExternal = publishedResourceIds.has(resourceId) && (isMiscResource(resource) || isSkeletonResource(resource));
885
+ const isSkeletonImageDependency = skeletonDependencyImageIds.has(resourceId) && isImageResource(resource);
886
+ if (!isSkeletonExternal && !isSkeletonImageDependency) continue;
887
+
888
+ let sourcePath: string;
889
+ let targetName: string;
890
+ if (isSkeletonImageDependency) {
891
+ sourcePath = resolveImagePath(resource, pkg, basePath);
892
+ targetName = resolveImageFileName(resource);
893
+ } else if (isMiscResource(resource) || isSkeletonResource(resource)) {
894
+ sourcePath = resolveGenericResourcePath(resource, pkg, basePath);
895
+ targetName = ((resource.getExtras() as PublishFileExtras | undefined) ?? {})._publishedFile ?? resource.getFile();
896
+ } else {
897
+ continue;
898
+ }
899
+ const targetPath = fs.join(outputDir, targetName);
900
+
901
+ try {
902
+ const data = await readFileRaw(sourcePath);
903
+ await fs.writeFileRaw(targetPath, data);
904
+ } catch {
905
+ logger.warn(`publish: Could not export external resource "${resource.getId()}" from package "${pkg.getName()}".`);
906
+ }
907
+ }
908
+ }
909
+
910
+ /**
911
+ * Publishes a FairyGUI project.
912
+ *
913
+ * Orchestrates:
914
+ * 1. Atlas packing (MaxRects layout + optional sharp compositing)
915
+ * 2. Per-package .fui binary serialization
916
+ * 3. File writing to the output directory
917
+ *
918
+ * ```ts
919
+ * import sharp from 'sharp';
920
+ * const io = new NodeIO();
921
+ * const doc = await io.readProject('./project.fairy');
922
+ *
923
+ * await doc.transform(publish({
924
+ * output: './release/',
925
+ * compressed: true,
926
+ * encoder: sharp,
927
+ * basePath: './assets/',
928
+ * fileExtension: 'bytes',
929
+ * fs: io.createFileSystem(),
930
+ * }));
931
+ * ```
932
+ */
933
+ export function publish(options: PublishOptions): Transform {
934
+ return createTransform('publish', async (doc: Document): Promise<void> => {
935
+ const root = doc.getRoot();
936
+ const logger = doc.getLogger();
937
+ const settings = (root.getSettings?.() ?? {}) as RootProjectSettings;
938
+ const publishSettings: CliPublishSettings = settings.publish ?? {};
939
+ const resolved = resolvePublishOptions(doc, {
940
+ compressed: options.compressed,
941
+ fileExtension: options.fileExtension,
942
+ packages: options.packages,
943
+ atlas: options.atlas,
944
+ });
945
+ const ext = resolved.fileExtension;
946
+
947
+ // Step 1: Determine which packages to publish
948
+ let allPackages = root.listPackages();
949
+ if (resolved.packages && resolved.packages.length > 0) {
950
+ const names = new Set(resolved.packages);
951
+ allPackages = allPackages.filter((p) => names.has(p.getName()));
952
+ }
953
+
954
+ if (allPackages.length === 0) {
955
+ logger.warn('publish: No packages to publish.');
956
+ return;
957
+ }
958
+
959
+ const branchProcessing = publishSettings.branchProcessing ?? 0;
960
+ const includeBranches = branchProcessing === 0;
961
+ const activeBranch = includeBranches ? '' : (options.branch ?? '');
962
+ const atlasRuntimeOptions = resolvePublishAtlasRuntimeOptions(ext);
963
+
964
+ const allDocPackages = root.listPackages();
965
+ // Build a pkgId→name map for dependency resolution
966
+ const pkgMap = new Map<string, Package>();
967
+ for (const p of allDocPackages) {
968
+ pkgMap.set(p.getId(), p);
969
+ }
970
+
971
+ for (const pkg of allPackages) {
972
+ // Compute dependency list and selected publish artifacts before atlas packing,
973
+ // so merged-branch publishes can pack the overridden resources with main IDs.
974
+ _computeDependencies(pkg, pkgMap);
975
+ await annotatePackagePublishArtifacts(
976
+ pkg,
977
+ options.basePath,
978
+ options.encoder as PublishEncoder | undefined,
979
+ {
980
+ includeBranches,
981
+ activeBranch,
982
+ },
983
+ );
984
+ }
985
+
986
+ // Step 2: Atlas packing
987
+ const atlasOpts: AtlasOptions = {
988
+ ...resolved.atlas,
989
+ ...(options.atlas ?? {}),
990
+ separatedAtlasForBranch: includeBranches && publishSettings.seperatedAtlasForBranch === true,
991
+ encoder: options.encoder,
992
+ basePath: options.basePath,
993
+ outputPath: options.fs ? options.output : undefined,
994
+ mkdir: options.fs ? options.fs.mkdir : undefined,
995
+ readFileRaw: options.atlas?.readFileRaw ?? options.fs?.readFileRaw,
996
+ ...atlasRuntimeOptions,
997
+ };
998
+ await atlas(atlasOpts)(doc);
999
+
1000
+ // Step 3: Write .fui binary per package
1001
+ if (!options.fs) {
1002
+ logger.info(`publish: No fs provided — layout computed for ${allPackages.length} package(s), skipping file output.`);
1003
+ return;
1004
+ }
1005
+
1006
+ await options.fs.mkdir(options.output);
1007
+
1008
+ const writerFs = toBinaryWriterFileSystem(options.fs);
1009
+
1010
+ for (const pkg of allPackages) {
1011
+ const pkgIndex = allDocPackages.indexOf(pkg);
1012
+ const publishName = pkg.getPublishName() || pkg.getName();
1013
+ const fileName = resolvePublishFileName(publishName, ext);
1014
+ const filePath = options.fs.join(options.output, fileName);
1015
+
1016
+ const bwOptions: BinaryWriterOptions = {
1017
+ compressed: resolved.compressed,
1018
+ packageIndex: pkgIndex,
1019
+ };
1020
+
1021
+ const bw = new BinaryWriter(writerFs);
1022
+ await bw.write(doc, filePath, bwOptions);
1023
+ await exportPackageSounds(
1024
+ pkg,
1025
+ options.output,
1026
+ options.basePath,
1027
+ options.fs,
1028
+ options.atlas?.readFileRaw ?? options.fs.readFileRaw,
1029
+ logger,
1030
+ );
1031
+ await exportPackageExternalResources(
1032
+ pkg,
1033
+ options.output,
1034
+ options.basePath,
1035
+ options.fs,
1036
+ options.atlas?.readFileRaw ?? options.fs.readFileRaw,
1037
+ logger,
1038
+ );
1039
+
1040
+ logger.info(`publish: Written ${fileName}`);
1041
+ }
1042
+
1043
+ await publishCodeGeneration(doc, {
1044
+ basePath: options.basePath,
1045
+ fs: options.fs,
1046
+ packages: allPackages,
1047
+ });
1048
+
1049
+ logger.info(`publish: Published ${allPackages.length} package(s) to ${options.output}`);
1050
+ });
1051
+ }
1052
+
1053
+ /**
1054
+ * Scan component children for font="ui://..." references to build dependency list.
1055
+ * The editor only adds dependencies for packages referenced via bitmap font URLs.
1056
+ * @internal
1057
+ */
1058
+ function _computeDependencies(pkg: Package, pkgMap: Map<string, Package>): void {
1059
+ const referencedPkgIds = new Set<string>();
1060
+
1061
+ function scanFontUrl(font: string | string[] | null | undefined): void {
1062
+ if (!font) return;
1063
+ const fontStr = Array.isArray(font) ? font[0] : String(font);
1064
+ if (typeof fontStr !== 'string' || !fontStr.startsWith('ui://')) return;
1065
+ const rest = fontStr.slice(5);
1066
+ if (rest.length >= 8) {
1067
+ const depPkgId = rest.slice(0, 8);
1068
+ if (depPkgId !== pkg.getId()) referencedPkgIds.add(depPkgId);
1069
+ }
1070
+ }
1071
+
1072
+ for (const res of pkg.listResources()) {
1073
+ if (res.propertyType !== 'Component') continue;
1074
+ for (const child of res.listChildren?.() ?? []) {
1075
+ // Only font="ui://..." references generate dependencies
1076
+ scanFontUrl((child as HasOptionalFont).getFont?.());
1077
+ }
1078
+ }
1079
+
1080
+ for (const dep of pkg.listDependencies()) {
1081
+ pkg.removeDependency(dep);
1082
+ }
1083
+
1084
+ if (referencedPkgIds.size > 0) {
1085
+ const sortedIds = [...referencedPkgIds].sort((a, b) => a.localeCompare(b));
1086
+ for (const refId of sortedIds) {
1087
+ const depPkg = pkgMap.get(refId);
1088
+ if (depPkg) {
1089
+ pkg.addDependency(depPkg);
1090
+ }
1091
+ }
1092
+ }
1093
+ }