@openfairygui/functions 0.2.0-alpha.2 → 0.2.0-alpha.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +48 -6
  2. package/dist/atlas-C6tbl7nn.d.ts +193 -0
  3. package/dist/atlas-CHsu2Y8i.d.cts +193 -0
  4. package/dist/index.cjs +16 -3603
  5. package/dist/index.d.cts +5 -294
  6. package/dist/index.d.ts +5 -294
  7. package/dist/index.js +3 -3594
  8. package/dist/node.cjs +256 -0
  9. package/dist/node.d.cts +36 -0
  10. package/dist/node.d.ts +36 -0
  11. package/dist/node.js +254 -0
  12. package/dist/publish-BJ_eelME.js +3267 -0
  13. package/dist/publish-xFWT9Slz.cjs +3338 -0
  14. package/dist/restore-BW2xacB3.cjs +936 -0
  15. package/dist/restore-BeWaJNjR.d.cts +288 -0
  16. package/dist/restore-Clk62n0O.js +931 -0
  17. package/dist/restore-Dh0-Nvms.d.ts +288 -0
  18. package/dist/uam-transaction.cjs +44 -1
  19. package/dist/uam-transaction.d.cts +16 -1
  20. package/dist/uam-transaction.d.ts +16 -1
  21. package/dist/uam-transaction.js +44 -1
  22. package/dist/web.cjs +274 -0
  23. package/dist/web.d.cts +41 -0
  24. package/dist/web.d.ts +41 -0
  25. package/dist/web.js +273 -0
  26. package/package.json +28 -4
  27. package/src/adapters/node/plugins.ts +82 -0
  28. package/src/adapters/node/publish.ts +130 -0
  29. package/src/adapters/node/restore.ts +187 -0
  30. package/src/adapters/web/publish.ts +159 -0
  31. package/src/adapters/web/raster.ts +251 -0
  32. package/src/atlas/font.ts +95 -0
  33. package/src/atlas/inputs.ts +515 -0
  34. package/src/atlas/jta.ts +211 -0
  35. package/src/atlas/packing.ts +767 -0
  36. package/src/atlas.ts +116 -1221
  37. package/src/codegen.ts +106 -67
  38. package/src/index.ts +43 -3
  39. package/src/node.ts +8 -0
  40. package/src/plugins/types.ts +56 -0
  41. package/src/publish/contracts.ts +80 -0
  42. package/src/publish/external-resources.ts +117 -0
  43. package/src/publish/options.ts +180 -0
  44. package/src/publish/package-context.ts +608 -0
  45. package/src/publish/resource-references.ts +210 -0
  46. package/src/publish.ts +290 -968
  47. package/src/restore-internals/font.ts +100 -0
  48. package/src/restore-internals/movie-clip.ts +104 -0
  49. package/src/restore-internals/output-transaction.ts +164 -0
  50. package/src/restore.ts +112 -311
  51. package/src/shared-types.ts +4 -8
  52. package/src/uam-transaction.ts +68 -0
  53. package/src/utils.ts +28 -0
  54. package/src/web.ts +11 -0
package/src/publish.ts CHANGED
@@ -1,276 +1,93 @@
1
1
  import {
2
- type BinaryWriterOptions,
3
2
  BinaryWriter,
4
- type Component,
5
- type DragonBonesResource,
3
+ type BinaryWriterOptions,
6
4
  type Document,
7
5
  type FileSystem,
8
- type FontResource,
9
- type ImageResource,
10
- type MiscResource,
11
- type MovieClipResource,
12
6
  type Package,
13
- ProjectType,
14
- type SpineResource,
15
- type SoundResource,
16
7
  type Transform,
17
8
  } from '@openfairygui/core';
9
+ import { atlas } from './atlas.js';
10
+ import { publishCodeGeneration, resolveProjectBasePath } from './codegen.js';
11
+ import { formatPluginError, type LoadedPlugin } from './plugins/types.js';
12
+ import type { PublishFileSystem } from './publish/contracts.js';
13
+ import {
14
+ annotatePackagePublishArtifacts,
15
+ } from './publish/package-context.js';
16
+ import {
17
+ exportPackageExternalResources,
18
+ exportPackageSounds,
19
+ } from './publish/external-resources.js';
20
+ import {
21
+ resolvePublishAtlasRuntimeOptions,
22
+ resolvePublishFileName,
23
+ resolvePublishOptions,
24
+ type PublishOptions,
25
+ type ResolvedPublishAtlasOptions,
26
+ type ResolvedPublishOptions,
27
+ } from './publish/options.js';
28
+ import { collectPackageResourceReferences } from './publish/resource-references.js';
29
+ import type { CliPublishSettings, RootProjectSettings } from './shared-types.js';
18
30
  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
31
 
59
- /**
60
- * Atlas packing options.
61
- */
62
- atlas?: Omit<AtlasOptions, 'encoder' | 'basePath' | 'outputPath'>;
32
+ export * from './publish/options.js';
63
33
 
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 {
34
+ interface ResolvedProjectPublishConfig extends ResolvedPublishOptions {
35
+ projectType: number;
36
+ includeBranches: boolean;
37
+ activeBranch: string;
38
+ includeHighResolution: number;
39
+ separatedAtlasForBranch: boolean;
40
+ globalOutputPath: string;
41
+ globalBranchOutputPath: string;
42
+ }
43
+
44
+ interface ResolvedPackagePublishPlan {
45
+ pkg: Package;
46
+ outputDir?: string;
47
+ publishName: string;
48
+ fileName: string;
93
49
  compressed: boolean;
94
50
  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
51
  includeBranches: boolean;
52
+ activeBranch: string;
53
+ includeHighResolution: number;
54
+ separatedAtlasForBranch: boolean;
55
+ atlas: ResolvedPublishAtlasOptions;
118
56
  }
119
57
 
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';
58
+ async function runPublishPluginHook(
59
+ plugins: LoadedPlugin[],
60
+ hook: 'onPublishStart' | 'onPublishEnd',
61
+ doc: Document,
62
+ options: PublishOptions,
63
+ ): Promise<void> {
64
+ const logger = doc.getLogger();
65
+ for (const plugin of plugins) {
66
+ const fn = plugin.plugin[hook];
67
+ if (typeof fn !== 'function') continue;
68
+ try {
69
+ await fn(doc, options);
70
+ } catch (error) {
71
+ logger.warn(`publish: Plugin "${plugin.name}" ${hook} failed: ${formatPluginError(error)}`);
72
+ }
205
73
  }
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
74
  }
212
75
 
213
- export interface PublishAtlasRuntimeOptions {
214
- preserveInputOrderOnTie: boolean;
215
- directSingleImageOutput: boolean;
76
+ function trimTrailingSlashes(value: string): string {
77
+ return value.replace(/[/\\]+$/, '');
216
78
  }
217
79
 
218
- export function resolvePublishAtlasRuntimeOptions(fileExtension: string): PublishAtlasRuntimeOptions {
219
- return {
220
- preserveInputOrderOnTie: fileExtension === 'fui',
221
- directSingleImageOutput: fileExtension === 'bytes',
222
- };
80
+ function isAbsolutePathLike(value: string): boolean {
81
+ return /^(?:[a-zA-Z]:[/\\]|[/\\]{1,2})/u.test(value);
223
82
  }
224
83
 
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
- };
84
+ function joinPathSegments(left: string, right: string): string {
85
+ const normalizedLeft = trimTrailingSlashes(left);
86
+ const normalizedRight = right.replace(/^[/\\]+/, '');
87
+ if (!normalizedLeft) return normalizedRight;
88
+ if (!normalizedRight) return normalizedLeft;
89
+ const separator = normalizedLeft.includes('\\') ? '\\' : '/';
90
+ return `${normalizedLeft}${separator}${normalizedRight}`;
274
91
  }
275
92
 
276
93
  function dirname(filePath: string): string {
@@ -299,650 +116,181 @@ function toBinaryWriterFileSystem(fs: PublishFileSystem): FileSystem {
299
116
  };
300
117
  }
301
118
 
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
119
  /**
911
120
  * Publishes a FairyGUI project.
912
121
  *
913
122
  * Orchestrates:
914
- * 1. Atlas packing (MaxRects layout + optional sharp compositing)
123
+ * 1. Atlas packing (MaxRects layout + optional raster compositing)
915
124
  * 2. Per-package .fui binary serialization
916
125
  * 3. File writing to the output directory
917
126
  *
127
+ * This is the capability-injected core. Standard hosts should use
128
+ * `publishNode()` or `publishBrowser()` through their dedicated entries.
129
+ *
918
130
  * ```ts
919
- * import sharp from 'sharp';
920
- * const io = new NodeIO();
921
- * const doc = await io.readProject('./project.fairy');
131
+ * import { NodeIO } from '@openfairygui/core/node';
132
+ * import { publishNode } from '@openfairygui/functions/node';
133
+ * const doc = await new NodeIO().readProject('./project.fairy');
922
134
  *
923
- * await doc.transform(publish({
135
+ * await publishNode({
136
+ * document: doc,
924
137
  * output: './release/',
925
138
  * compressed: true,
926
- * encoder: sharp,
927
- * basePath: './assets/',
139
+ * assetsPath: './assets/',
928
140
  * fileExtension: 'bytes',
929
- * fs: io.createFileSystem(),
930
- * }));
141
+ * });
931
142
  * ```
932
143
  */
933
144
  export function publish(options: PublishOptions): Transform {
934
145
  return createTransform('publish', async (doc: Document): Promise<void> => {
146
+ const resolveConfiguredOutputPath = (value?: string, projectBasePath?: string): string | undefined => {
147
+ const trimmed = value?.trim();
148
+ if (!trimmed) return undefined;
149
+ if (isAbsolutePathLike(trimmed) || !projectBasePath) {
150
+ return trimTrailingSlashes(trimmed);
151
+ }
152
+ return trimTrailingSlashes(
153
+ options.fs ? options.fs.join(projectBasePath, trimmed) : joinPathSegments(projectBasePath, trimmed),
154
+ );
155
+ };
156
+
157
+ const resolveProjectPublishConfig = (): ResolvedProjectPublishConfig => {
158
+ const settings = (doc.getRoot().getSettings?.() ?? {}) as RootProjectSettings;
159
+ const publishSettings: CliPublishSettings = settings.publish ?? {};
160
+ const resolved = resolvePublishOptions(doc, {
161
+ compressed: options.compressed,
162
+ fileExtension: options.fileExtension,
163
+ packages: options.packages,
164
+ atlas: options.atlas,
165
+ });
166
+ const branchProcessing = publishSettings.branchProcessing ?? 0;
167
+ const includeBranches = branchProcessing === 0;
168
+
169
+ return {
170
+ ...resolved,
171
+ projectType: doc.getRoot().getProjectType(),
172
+ includeBranches,
173
+ activeBranch: includeBranches ? '' : (options.branch ?? ''),
174
+ includeHighResolution: publishSettings.includeHighResolution ?? 0,
175
+ separatedAtlasForBranch: includeBranches && publishSettings.seperatedAtlasForBranch === true,
176
+ globalOutputPath: publishSettings.path?.trim() ?? '',
177
+ globalBranchOutputPath: publishSettings.branchPath?.trim() ?? '',
178
+ };
179
+ };
180
+
181
+ const resolvePackagePublishPlan = (
182
+ pkg: Package,
183
+ config: ResolvedProjectPublishConfig,
184
+ projectBasePath?: string,
185
+ ): ResolvedPackagePublishPlan => {
186
+ let outputDir: string | undefined;
187
+
188
+ if (options.output) {
189
+ outputDir = trimTrailingSlashes(options.output);
190
+ } else {
191
+ const candidates: Array<string | undefined> = [];
192
+ if (!config.includeBranches && config.activeBranch) {
193
+ candidates.push(pkg.getPublishBranchPath(), config.globalBranchOutputPath);
194
+ }
195
+ candidates.push(pkg.getPublishPath(), config.globalOutputPath);
196
+
197
+ for (const candidate of candidates) {
198
+ const resolved = resolveConfiguredOutputPath(candidate, projectBasePath);
199
+ if (!resolved) continue;
200
+ outputDir = resolved;
201
+ break;
202
+ }
203
+ }
204
+ const publishName = pkg.getPublishName() || pkg.getName();
205
+
206
+ return {
207
+ pkg,
208
+ outputDir,
209
+ publishName,
210
+ fileName: resolvePublishFileName(publishName, config.fileExtension),
211
+ compressed: config.compressed,
212
+ fileExtension: config.fileExtension,
213
+ includeBranches: config.includeBranches,
214
+ activeBranch: config.activeBranch,
215
+ includeHighResolution: config.includeHighResolution,
216
+ separatedAtlasForBranch: config.separatedAtlasForBranch,
217
+ atlas: config.atlas,
218
+ };
219
+ };
220
+
221
+ const createNoopPublishFs = (): PublishFileSystem => ({
222
+ async writeFileRaw(): Promise<void> {
223
+ // No-op for layout-only publish flows.
224
+ },
225
+ async mkdir(): Promise<void> {
226
+ // No-op for layout-only publish flows.
227
+ },
228
+ join(...paths: string[]): string {
229
+ return paths.join('/');
230
+ },
231
+ });
232
+
233
+ const publishPackage = async (plan: ResolvedPackagePublishPlan, writerFs: FileSystem, packageIndex: number) => {
234
+ if (options.fs && !plan.outputDir) {
235
+ throw new Error(
236
+ 'publish: no output directory resolved. Provide --output, or configure global publish.path / package publishPath.',
237
+ );
238
+ }
239
+
240
+ if (options.fs) {
241
+ await options.fs.mkdir(plan.outputDir!);
242
+ await exportPackageSounds(
243
+ plan.pkg,
244
+ plan.outputDir!,
245
+ options.basePath,
246
+ options.fs,
247
+ options.atlas?.readFileRaw ?? options.fs.readFileRaw,
248
+ );
249
+ await exportPackageExternalResources(
250
+ plan.pkg,
251
+ plan.outputDir!,
252
+ options.basePath,
253
+ options.fs,
254
+ options.atlas?.readFileRaw ?? options.fs.readFileRaw,
255
+ );
256
+ }
257
+
258
+ const atlasRuntimeOptions = resolvePublishAtlasRuntimeOptions(plan.fileExtension);
259
+ await atlas({
260
+ ...plan.atlas,
261
+ ...(options.atlas ?? {}),
262
+ separatedAtlasForBranch: plan.separatedAtlasForBranch,
263
+ encoder: options.encoder,
264
+ basePath: options.basePath,
265
+ outputPath: options.fs ? plan.outputDir : undefined,
266
+ mkdir: options.fs ? options.fs.mkdir : undefined,
267
+ readFileRaw: options.atlas?.readFileRaw ?? options.fs?.readFileRaw,
268
+ strictOutput: options.fs !== undefined,
269
+ packages: [plan.pkg.getName()],
270
+ ...atlasRuntimeOptions,
271
+ })(doc);
272
+
273
+ if (!options.fs) return;
274
+
275
+ const filePath = options.fs.join(plan.outputDir!, plan.fileName);
276
+ const bwOptions: BinaryWriterOptions = {
277
+ compressed: plan.compressed,
278
+ packageIndex,
279
+ };
280
+
281
+ const bw = new BinaryWriter(writerFs);
282
+ await bw.write(doc, filePath, bwOptions);
283
+
284
+ logger.info(`publish: Written ${plan.fileName}`);
285
+ };
286
+
935
287
  const root = doc.getRoot();
936
288
  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;
289
+ const projectBasePath = resolveProjectBasePath(options.basePath) || doc.getProjectDir?.() || '';
290
+ const plugins = options.plugins ?? [];
291
+ await runPublishPluginHook(plugins, 'onPublishStart', doc, options);
292
+
293
+ const resolved = resolveProjectPublishConfig();
946
294
 
947
295
  // Step 1: Determine which packages to publish
948
296
  let allPackages = root.listPackages();
@@ -953,14 +301,10 @@ export function publish(options: PublishOptions): Transform {
953
301
 
954
302
  if (allPackages.length === 0) {
955
303
  logger.warn('publish: No packages to publish.');
304
+ await runPublishPluginHook(plugins, 'onPublishEnd', doc, options);
956
305
  return;
957
306
  }
958
307
 
959
- const branchProcessing = publishSettings.branchProcessing ?? 0;
960
- const includeBranches = branchProcessing === 0;
961
- const activeBranch = includeBranches ? '' : (options.branch ?? '');
962
- const atlasRuntimeOptions = resolvePublishAtlasRuntimeOptions(ext);
963
-
964
308
  const allDocPackages = root.listPackages();
965
309
  // Build a pkgId→name map for dependency resolution
966
310
  const pkgMap = new Map<string, Package>();
@@ -971,82 +315,69 @@ export function publish(options: PublishOptions): Transform {
971
315
  for (const pkg of allPackages) {
972
316
  // Compute dependency list and selected publish artifacts before atlas packing,
973
317
  // 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
- );
318
+ _computeDependencies(doc, pkg, pkgMap);
319
+ await annotatePackagePublishArtifacts(pkg, options.basePath, options.encoder, {
320
+ projectType: resolved.projectType,
321
+ includeBranches: resolved.includeBranches,
322
+ activeBranch: resolved.activeBranch,
323
+ includeHighResolution: resolved.includeHighResolution,
324
+ });
984
325
  }
985
326
 
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);
327
+ const plans = allPackages.map((pkg) => resolvePackagePublishPlan(pkg, resolved, projectBasePath));
999
328
 
1000
- // Step 3: Write .fui binary per package
1001
329
  if (!options.fs) {
1002
- logger.info(`publish: No fs provided — layout computed for ${allPackages.length} package(s), skipping file output.`);
330
+ const outputPlan = plans.find((plan) => !!plan.outputDir);
331
+ if (outputPlan) {
332
+ throw new Error(
333
+ `publish: Output for package "${outputPlan.pkg.getName()}" requires a filesystem. ` +
334
+ 'Omit output and publish paths to run a layout-only transform.',
335
+ );
336
+ }
337
+ logger.info(
338
+ `publish: Layout computed for ${allPackages.length} package(s); no output directory was requested.`,
339
+ );
340
+ const noopWriterFs = toBinaryWriterFileSystem(createNoopPublishFs());
341
+ for (const plan of plans) {
342
+ await publishPackage(plan, noopWriterFs, allDocPackages.indexOf(plan.pkg));
343
+ }
344
+ await runPublishPluginHook(plugins, 'onPublishEnd', doc, options);
1003
345
  return;
1004
346
  }
1005
347
 
1006
- await options.fs.mkdir(options.output);
348
+ const unresolvedPlan = plans.find((plan) => !plan.outputDir);
349
+ if (unresolvedPlan) {
350
+ throw new Error(
351
+ `publish: no output directory resolved for package "${unresolvedPlan.pkg.getName()}". ` +
352
+ 'Provide --output, or configure global publish.path / package publishPath.',
353
+ );
354
+ }
1007
355
 
1008
356
  const writerFs = toBinaryWriterFileSystem(options.fs);
1009
357
 
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}`);
358
+ for (const plan of plans) {
359
+ const pkgIndex = allDocPackages.indexOf(plan.pkg);
360
+ await publishPackage(plan, writerFs, pkgIndex);
1041
361
  }
1042
362
 
1043
- await publishCodeGeneration(doc, {
1044
- basePath: options.basePath,
1045
- fs: options.fs,
1046
- packages: allPackages,
1047
- });
363
+ if (options.codeGeneration !== false) {
364
+ await publishCodeGeneration(doc, {
365
+ basePath: options.basePath,
366
+ fs: options.fs,
367
+ packages: allPackages,
368
+ plugins,
369
+ });
370
+ }
1048
371
 
1049
- logger.info(`publish: Published ${allPackages.length} package(s) to ${options.output}`);
372
+ const publishedTargets = [
373
+ ...new Set(plans.map((plan) => plan.outputDir).filter((value): value is string => Boolean(value))),
374
+ ];
375
+ logger.info(
376
+ publishedTargets.length > 0
377
+ ? `publish: Published ${allPackages.length} package(s) to ${publishedTargets.join(', ')}`
378
+ : `publish: Published ${allPackages.length} package(s)`,
379
+ );
380
+ await runPublishPluginHook(plugins, 'onPublishEnd', doc, options);
1050
381
  });
1051
382
  }
1052
383
 
@@ -1055,34 +386,25 @@ export function publish(options: PublishOptions): Transform {
1055
386
  * The editor only adds dependencies for packages referenced via bitmap font URLs.
1056
387
  * @internal
1057
388
  */
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
-
389
+ function _computeDependencies(doc: Document, pkg: Package, pkgMap: Map<string, Package>): void {
390
+ const referencedPkgIds = collectPackageResourceReferences(pkg).packageIds;
391
+ const packageOrder = new Map(
392
+ doc
393
+ .getRoot()
394
+ .listPackages()
395
+ .map((entry, index) => [entry.getId(), index] as const),
396
+ );
1080
397
  for (const dep of pkg.listDependencies()) {
1081
398
  pkg.removeDependency(dep);
1082
399
  }
1083
400
 
1084
401
  if (referencedPkgIds.size > 0) {
1085
- const sortedIds = [...referencedPkgIds].sort((a, b) => a.localeCompare(b));
402
+ const sortedIds = [...referencedPkgIds].sort((a, b) => {
403
+ const orderA = packageOrder.get(a) ?? Number.MAX_SAFE_INTEGER;
404
+ const orderB = packageOrder.get(b) ?? Number.MAX_SAFE_INTEGER;
405
+ if (orderA !== orderB) return orderA - orderB;
406
+ return a.localeCompare(b);
407
+ });
1086
408
  for (const refId of sortedIds) {
1087
409
  const depPkg = pkgMap.get(refId);
1088
410
  if (depPkg) {