@uniformdev/transformer 1.1.30 → 1.1.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli/index.ts
4
- import { Command as Command15 } from "commander";
4
+ import { Command as Command16 } from "commander";
5
5
 
6
6
  // src/cli/commands/propagate-root-component-property.ts
7
7
  import { Command } from "commander";
@@ -5334,10 +5334,422 @@ function createAddContentTypeFieldCommand() {
5334
5334
  return command;
5335
5335
  }
5336
5336
 
5337
+ // src/cli/commands/flatten-block-field.ts
5338
+ import { Command as Command15 } from "commander";
5339
+
5340
+ // src/core/services/block-field-flattener.service.ts
5341
+ var BlockFieldFlattenerService = class {
5342
+ constructor(fileSystem, componentService, logger) {
5343
+ this.fileSystem = fileSystem;
5344
+ this.componentService = componentService;
5345
+ this.logger = logger;
5346
+ }
5347
+ compareIds(id1, id2, strict) {
5348
+ if (strict) return id1 === id2;
5349
+ return id1.toLowerCase() === id2.toLowerCase();
5350
+ }
5351
+ async loadContentType(contentTypesDir, contentTypeId, strict) {
5352
+ const jsonPath = this.fileSystem.joinPath(contentTypesDir, `${contentTypeId}.json`);
5353
+ const yamlPath = this.fileSystem.joinPath(contentTypesDir, `${contentTypeId}.yaml`);
5354
+ const ymlPath = this.fileSystem.joinPath(contentTypesDir, `${contentTypeId}.yml`);
5355
+ if (await this.fileSystem.fileExists(jsonPath)) {
5356
+ return { contentType: await this.fileSystem.readFile(jsonPath), filePath: jsonPath };
5357
+ }
5358
+ if (await this.fileSystem.fileExists(yamlPath)) {
5359
+ return { contentType: await this.fileSystem.readFile(yamlPath), filePath: yamlPath };
5360
+ }
5361
+ if (await this.fileSystem.fileExists(ymlPath)) {
5362
+ return { contentType: await this.fileSystem.readFile(ymlPath), filePath: ymlPath };
5363
+ }
5364
+ if (!strict) {
5365
+ const files = await this.fileSystem.findFiles(contentTypesDir, "*.{json,yaml,yml}");
5366
+ for (const filePath of files) {
5367
+ const basename2 = this.fileSystem.getBasename(filePath);
5368
+ const nameWithoutExt = basename2.replace(/\.(json|yaml|yml)$/i, "");
5369
+ if (nameWithoutExt.toLowerCase() === contentTypeId.toLowerCase()) {
5370
+ return { contentType: await this.fileSystem.readFile(filePath), filePath };
5371
+ }
5372
+ }
5373
+ }
5374
+ throw new TransformError(`Content type not found: ${contentTypeId} (searched: ${contentTypesDir})`);
5375
+ }
5376
+ async flatten(options) {
5377
+ const {
5378
+ rootDir,
5379
+ componentsDir,
5380
+ compositionsDir,
5381
+ compositionPatternsDir,
5382
+ componentPatternsDir,
5383
+ contentTypesDir,
5384
+ componentId,
5385
+ parameterId,
5386
+ whatIf,
5387
+ strict,
5388
+ excludeFields = []
5389
+ } = options;
5390
+ const findOptions = { strict };
5391
+ const fullComponentsDir = this.fileSystem.resolvePath(rootDir, componentsDir);
5392
+ const fullCompositionsDir = this.fileSystem.resolvePath(rootDir, compositionsDir);
5393
+ const fullCompositionPatternsDir = this.fileSystem.resolvePath(rootDir, compositionPatternsDir);
5394
+ const fullComponentPatternsDir = this.fileSystem.resolvePath(rootDir, componentPatternsDir);
5395
+ const fullContentTypesDir = this.fileSystem.resolvePath(rootDir, contentTypesDir);
5396
+ this.logger.info(`Loading component: ${componentId}`);
5397
+ const { component, filePath: componentFilePath } = await this.componentService.loadComponent(fullComponentsDir, componentId, findOptions);
5398
+ const blockParam = this.componentService.findParameter(component, parameterId, findOptions);
5399
+ if (!blockParam) {
5400
+ throw new PropertyNotFoundError(parameterId, componentId);
5401
+ }
5402
+ const allowedTypes = blockParam.typeConfig?.allowedTypes;
5403
+ if (!allowedTypes || allowedTypes.length === 0) {
5404
+ throw new TransformError(
5405
+ `Parameter "${parameterId}" on component "${componentId}" has no allowedTypes in typeConfig`
5406
+ );
5407
+ }
5408
+ if (allowedTypes.length > 1) {
5409
+ throw new TransformError(
5410
+ `Cannot flatten: parameter "${parameterId}" allows multiple block types: ${allowedTypes.join(", ")}`
5411
+ );
5412
+ }
5413
+ const blockContentTypeId = allowedTypes[0];
5414
+ this.logger.info(`Block content type: ${blockContentTypeId}`);
5415
+ const { contentType: blockContentType } = await this.loadContentType(fullContentTypesDir, blockContentTypeId, strict);
5416
+ const excludeSet = new Set(excludeFields.map((id) => id.toLowerCase()));
5417
+ const blockFields = (blockContentType.fields ?? []).filter(
5418
+ (f) => !excludeSet.has(f.id.toLowerCase())
5419
+ );
5420
+ const blockFieldIds = blockFields.map((f) => f.id);
5421
+ this.logger.info(
5422
+ `Block content type: ${blockContentTypeId} (${blockFields.length} field(s): ${blockFieldIds.join(", ")})`
5423
+ );
5424
+ for (const field of blockFields) {
5425
+ const existingParam = this.componentService.findParameter(component, field.id, findOptions);
5426
+ if (existingParam && !this.compareIds(existingParam.id, parameterId, strict)) {
5427
+ throw new TransformError(
5428
+ `Cannot flatten: field "${field.id}" from block type "${blockContentTypeId}" conflicts with existing parameter "${existingParam.id}" on component "${componentId}"`
5429
+ );
5430
+ }
5431
+ }
5432
+ this.logger.info("Validation pass: scanning compositions...");
5433
+ await this.validateDirectory(fullCompositionsDir, componentId, parameterId, strict, "composition");
5434
+ await this.validateDirectory(fullCompositionPatternsDir, componentId, parameterId, strict, "compositionPattern");
5435
+ await this.validateDirectory(fullComponentPatternsDir, componentId, parameterId, strict, "componentPattern");
5436
+ this.logger.action(
5437
+ whatIf,
5438
+ "REMOVE",
5439
+ `parameter "${parameterId}" from component/${this.fileSystem.getBasename(componentFilePath)}`
5440
+ );
5441
+ this.logger.action(
5442
+ whatIf,
5443
+ "ADD",
5444
+ `parameters "${blockFieldIds.join(", ")}" to component/${this.fileSystem.getBasename(componentFilePath)}`
5445
+ );
5446
+ let updatedComponent = this.componentService.removeParameter(component, parameterId, findOptions);
5447
+ updatedComponent = this.componentService.removeEmptyGroups(updatedComponent);
5448
+ for (const field of blockFields) {
5449
+ updatedComponent = this.componentService.addParameterToComponent(
5450
+ updatedComponent,
5451
+ { id: field.id, name: field.name, type: field.type, ...field.typeConfig ? { typeConfig: field.typeConfig } : {}, ...this.extraFieldProps(field) },
5452
+ findOptions
5453
+ );
5454
+ }
5455
+ if (!whatIf) {
5456
+ await this.componentService.saveComponent(componentFilePath, updatedComponent);
5457
+ }
5458
+ const compositionsResult = await this.flattenInDirectory(
5459
+ fullCompositionsDir,
5460
+ componentId,
5461
+ parameterId,
5462
+ whatIf,
5463
+ strict,
5464
+ "composition"
5465
+ );
5466
+ const compositionPatternsResult = await this.flattenInDirectory(
5467
+ fullCompositionPatternsDir,
5468
+ componentId,
5469
+ parameterId,
5470
+ whatIf,
5471
+ strict,
5472
+ "compositionPattern"
5473
+ );
5474
+ const componentPatternsResult = await this.flattenInDirectory(
5475
+ fullComponentPatternsDir,
5476
+ componentId,
5477
+ parameterId,
5478
+ whatIf,
5479
+ strict,
5480
+ "componentPattern"
5481
+ );
5482
+ const totalFiles = compositionsResult.filesModified + compositionPatternsResult.filesModified + componentPatternsResult.filesModified;
5483
+ const totalInstances = compositionsResult.instancesUpdated + compositionPatternsResult.instancesUpdated + componentPatternsResult.instancesUpdated;
5484
+ this.logger.info("");
5485
+ this.logger.info(
5486
+ `Summary: 1 component definition updated, ${totalFiles} file(s) (${totalInstances} instance(s)) updated.`
5487
+ );
5488
+ return {
5489
+ componentDefinitionUpdated: true,
5490
+ compositionsModified: compositionsResult.filesModified,
5491
+ compositionPatternsModified: compositionPatternsResult.filesModified,
5492
+ componentPatternsModified: componentPatternsResult.filesModified,
5493
+ instancesUpdated: totalInstances
5494
+ };
5495
+ }
5496
+ // Extract extra field props beyond id, name, type, typeConfig
5497
+ extraFieldProps(field) {
5498
+ const { id: _id, name: _name, type: _type, typeConfig: _tc, ...rest } = field;
5499
+ return rest;
5500
+ }
5501
+ async validateDirectory(directory, componentId, parameterId, strict, label) {
5502
+ let files;
5503
+ try {
5504
+ files = await this.fileSystem.findFiles(directory, "**/*.{json,yaml,yml}");
5505
+ } catch {
5506
+ return;
5507
+ }
5508
+ for (const filePath of files) {
5509
+ let composition;
5510
+ try {
5511
+ composition = await this.fileSystem.readFile(filePath);
5512
+ } catch {
5513
+ continue;
5514
+ }
5515
+ if (!composition?.composition) continue;
5516
+ this.validateBlocksInTree(composition.composition, componentId, parameterId, strict, filePath, label);
5517
+ this.validateBlocksInOverrides(composition, componentId, parameterId, strict, filePath, label);
5518
+ }
5519
+ }
5520
+ validateBlocksInTree(node, componentId, parameterId, strict, filePath, label) {
5521
+ if (this.compareIds(node.type, componentId, strict) && node.parameters) {
5522
+ const blockParamValue = this.findKeyInMap(node.parameters, parameterId, strict);
5523
+ if (blockParamValue) {
5524
+ const items = blockParamValue.value;
5525
+ if (Array.isArray(items) && items.length > 1) {
5526
+ throw new TransformError(
5527
+ `Cannot flatten: more than one block item in parameter "${parameterId}" of "${componentId}" instance "${node._id ?? "(root)"}" in file "${label}/${this.fileSystem.getBasename(filePath)}"`
5528
+ );
5529
+ }
5530
+ }
5531
+ }
5532
+ if (node.slots) {
5533
+ for (const slotInstances of Object.values(node.slots)) {
5534
+ if (!Array.isArray(slotInstances)) continue;
5535
+ for (const instance of slotInstances) {
5536
+ this.validateBlocksInTree(instance, componentId, parameterId, strict, filePath, label);
5537
+ }
5538
+ }
5539
+ }
5540
+ }
5541
+ validateBlocksInOverrides(composition, componentId, parameterId, strict, filePath, label) {
5542
+ if (!composition.composition._overrides) return;
5543
+ for (const [overrideId, override] of Object.entries(composition.composition._overrides)) {
5544
+ if (!override.parameters) continue;
5545
+ const blockParamValue = this.findKeyInMap(override.parameters, parameterId, strict);
5546
+ if (blockParamValue) {
5547
+ const items = blockParamValue.value;
5548
+ if (Array.isArray(items) && items.length > 1) {
5549
+ throw new TransformError(
5550
+ `Cannot flatten: more than one block item in _overrides["${overrideId}"] parameter "${parameterId}" in file "${label}/${this.fileSystem.getBasename(filePath)}"`
5551
+ );
5552
+ }
5553
+ }
5554
+ }
5555
+ }
5556
+ async flattenInDirectory(directory, componentId, parameterId, whatIf, strict, label) {
5557
+ let files;
5558
+ try {
5559
+ files = await this.fileSystem.findFiles(directory, "**/*.{json,yaml,yml}");
5560
+ } catch {
5561
+ return { filesModified: 0, instancesUpdated: 0 };
5562
+ }
5563
+ if (files.length === 0) return { filesModified: 0, instancesUpdated: 0 };
5564
+ let filesModified = 0;
5565
+ let instancesUpdated = 0;
5566
+ for (const filePath of files) {
5567
+ let composition;
5568
+ try {
5569
+ composition = await this.fileSystem.readFile(filePath);
5570
+ } catch {
5571
+ continue;
5572
+ }
5573
+ if (!composition?.composition) continue;
5574
+ const treeCount = this.flattenBlocksInTree(composition.composition, componentId, parameterId, strict);
5575
+ const overridesCount = this.flattenBlocksInOverrides(composition, componentId, parameterId, strict);
5576
+ const totalCount = treeCount + overridesCount;
5577
+ if (totalCount > 0) {
5578
+ const relativePath = filePath.replace(directory, "").replace(/^[/\\]/, "");
5579
+ this.logger.action(
5580
+ whatIf,
5581
+ "UPDATE",
5582
+ `${label}/${relativePath} (${totalCount} instance(s) of ${componentId})`
5583
+ );
5584
+ if (!whatIf) {
5585
+ await this.fileSystem.writeFile(filePath, composition);
5586
+ }
5587
+ filesModified++;
5588
+ instancesUpdated += totalCount;
5589
+ }
5590
+ }
5591
+ return { filesModified, instancesUpdated };
5592
+ }
5593
+ flattenBlocksInTree(node, componentId, parameterId, strict) {
5594
+ let count = 0;
5595
+ if (this.compareIds(node.type, componentId, strict) && node.parameters) {
5596
+ const matchingKey = this.findKeyName(node.parameters, parameterId, strict);
5597
+ if (matchingKey !== void 0) {
5598
+ const blockParamValue = node.parameters[matchingKey];
5599
+ const items = blockParamValue.value;
5600
+ if (Array.isArray(items) && items.length === 1) {
5601
+ const blockItem = items[0];
5602
+ for (const [fieldId, fieldValue] of Object.entries(blockItem.fields ?? {})) {
5603
+ node.parameters[fieldId] = fieldValue;
5604
+ }
5605
+ }
5606
+ delete node.parameters[matchingKey];
5607
+ count++;
5608
+ }
5609
+ }
5610
+ if (node.slots) {
5611
+ for (const slotInstances of Object.values(node.slots)) {
5612
+ if (!Array.isArray(slotInstances)) continue;
5613
+ for (const instance of slotInstances) {
5614
+ count += this.flattenBlocksInTree(instance, componentId, parameterId, strict);
5615
+ }
5616
+ }
5617
+ }
5618
+ return count;
5619
+ }
5620
+ flattenBlocksInOverrides(composition, componentId, parameterId, strict) {
5621
+ if (!composition.composition._overrides) return 0;
5622
+ let count = 0;
5623
+ if (this.compareIds(composition.composition.type, componentId, strict)) {
5624
+ count += this.flattenOverrideMap(composition.composition._overrides, parameterId, strict);
5625
+ }
5626
+ count += this.flattenOverridesForMatchingInstances(
5627
+ composition.composition,
5628
+ composition.composition._overrides,
5629
+ componentId,
5630
+ parameterId,
5631
+ strict
5632
+ );
5633
+ return count;
5634
+ }
5635
+ flattenOverrideMap(overrides, parameterId, strict) {
5636
+ let count = 0;
5637
+ for (const override of Object.values(overrides)) {
5638
+ if (!override.parameters) continue;
5639
+ const matchingKey = this.findKeyName(override.parameters, parameterId, strict);
5640
+ if (matchingKey === void 0) continue;
5641
+ const blockParamValue = override.parameters[matchingKey];
5642
+ const items = blockParamValue.value;
5643
+ if (Array.isArray(items) && items.length === 1) {
5644
+ const blockItem = items[0];
5645
+ for (const [fieldId, fieldValue] of Object.entries(blockItem.fields ?? {})) {
5646
+ override.parameters[fieldId] = fieldValue;
5647
+ }
5648
+ }
5649
+ delete override.parameters[matchingKey];
5650
+ count++;
5651
+ }
5652
+ return count;
5653
+ }
5654
+ flattenOverridesForMatchingInstances(node, overrides, componentId, parameterId, strict) {
5655
+ let count = 0;
5656
+ if (node.slots) {
5657
+ for (const slotInstances of Object.values(node.slots)) {
5658
+ if (!Array.isArray(slotInstances)) continue;
5659
+ for (const instance of slotInstances) {
5660
+ if (this.compareIds(instance.type, componentId, strict) && instance._id) {
5661
+ const override = overrides[instance._id];
5662
+ if (override?.parameters) {
5663
+ const matchingKey = this.findKeyName(override.parameters, parameterId, strict);
5664
+ if (matchingKey !== void 0) {
5665
+ const blockParamValue = override.parameters[matchingKey];
5666
+ const items = blockParamValue.value;
5667
+ if (Array.isArray(items) && items.length === 1) {
5668
+ const blockItem = items[0];
5669
+ for (const [fieldId, fieldValue] of Object.entries(blockItem.fields ?? {})) {
5670
+ override.parameters[fieldId] = fieldValue;
5671
+ }
5672
+ }
5673
+ delete override.parameters[matchingKey];
5674
+ count++;
5675
+ }
5676
+ }
5677
+ }
5678
+ count += this.flattenOverridesForMatchingInstances(instance, overrides, componentId, parameterId, strict);
5679
+ }
5680
+ }
5681
+ }
5682
+ return count;
5683
+ }
5684
+ findKeyName(map, key, strict) {
5685
+ return Object.keys(map).find((k) => this.compareIds(k, key, strict));
5686
+ }
5687
+ findKeyInMap(map, key, strict) {
5688
+ const k = this.findKeyName(map, key, strict);
5689
+ return k !== void 0 ? map[k] : void 0;
5690
+ }
5691
+ };
5692
+
5693
+ // src/cli/commands/flatten-block-field.ts
5694
+ function createFlattenBlockFieldCommand() {
5695
+ const command = new Command15("flatten-block-field");
5696
+ command.description(
5697
+ "Dissolves a $block parameter by lifting the block content type fields onto the component and extracting block item values into composition instances directly."
5698
+ ).option("--componentId <id>", "The ID of the component that owns the block parameter").option("--parameterId <id>", "The ID of the $block parameter to flatten").option("--excludeFields <ids>", "Comma-separated list of block content type field IDs to skip when flattening").hook("preAction", (thisCommand) => {
5699
+ const opts = thisCommand.opts();
5700
+ const requiredOptions = [
5701
+ { name: "componentId", flag: "--componentId" },
5702
+ { name: "parameterId", flag: "--parameterId" }
5703
+ ];
5704
+ const missing = requiredOptions.filter((opt) => !opts[opt.name]).map((opt) => opt.flag);
5705
+ if (missing.length > 0) {
5706
+ console.error(`error: missing required options: ${missing.join(", ")}`);
5707
+ process.exit(1);
5708
+ }
5709
+ }).action(async (opts, cmd) => {
5710
+ const globalOpts = cmd.optsWithGlobals();
5711
+ const options = {
5712
+ ...globalOpts,
5713
+ componentId: opts.componentId,
5714
+ parameterId: opts.parameterId,
5715
+ excludeFields: opts.excludeFields
5716
+ };
5717
+ const logger = new Logger();
5718
+ const fileSystem = new FileSystemService();
5719
+ const componentService = new ComponentService(fileSystem);
5720
+ const flattener = new BlockFieldFlattenerService(fileSystem, componentService, logger);
5721
+ try {
5722
+ const result = await flattener.flatten({
5723
+ rootDir: options.rootDir,
5724
+ componentsDir: options.componentsDir,
5725
+ compositionsDir: options.compositionsDir,
5726
+ compositionPatternsDir: options.compositionPatternsDir,
5727
+ componentPatternsDir: options.componentPatternsDir,
5728
+ contentTypesDir: options.contentTypesDir,
5729
+ componentId: options.componentId,
5730
+ parameterId: options.parameterId,
5731
+ whatIf: options.whatIf ?? false,
5732
+ strict: options.strict ?? false,
5733
+ excludeFields: options.excludeFields ? options.excludeFields.split(",").map((s) => s.trim()) : []
5734
+ });
5735
+ logger.success(
5736
+ `Flattened parameter "${options.parameterId}" on component "${options.componentId}": ${result.compositionsModified} composition(s), ${result.compositionPatternsModified} composition pattern(s), ${result.componentPatternsModified} component pattern(s) updated`
5737
+ );
5738
+ } catch (error) {
5739
+ if (error instanceof TransformError) {
5740
+ logger.error(error.message);
5741
+ process.exit(1);
5742
+ }
5743
+ throw error;
5744
+ }
5745
+ });
5746
+ return command;
5747
+ }
5748
+
5337
5749
  // package.json
5338
5750
  var package_default = {
5339
5751
  name: "@uniformdev/transformer",
5340
- version: "1.1.30",
5752
+ version: "1.1.31",
5341
5753
  description: "CLI tool for transforming Uniform.dev serialization files offline",
5342
5754
  type: "module",
5343
5755
  bin: {
@@ -5406,7 +5818,7 @@ var package_default = {
5406
5818
  };
5407
5819
 
5408
5820
  // src/cli/index.ts
5409
- var program = new Command15();
5821
+ var program = new Command16();
5410
5822
  var appVersion = package_default.version;
5411
5823
  console.error(`uniform-transform v${appVersion}`);
5412
5824
  program.name("uniform-transform").description("CLI tool for transforming Uniform.dev serialization files offline").version(appVersion);
@@ -5433,5 +5845,6 @@ program.addCommand(createRemoveParameterCommand());
5433
5845
  program.addCommand(createRemoveFieldCommand());
5434
5846
  program.addCommand(createAddComponentParameterCommand());
5435
5847
  program.addCommand(createAddContentTypeFieldCommand());
5848
+ program.addCommand(createFlattenBlockFieldCommand());
5436
5849
  program.parse();
5437
5850
  //# sourceMappingURL=index.js.map