@camunda8/cli 4.3.0 → 4.4.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.
@@ -892,7 +892,7 @@ var require_truncate = __commonJS({
892
892
  var parse = require_parse();
893
893
  var constants = require_constants();
894
894
  var SemVer = require_semver();
895
- var truncate = (version, truncation, options) => {
895
+ var truncate2 = (version, truncation, options) => {
896
896
  if (!constants.RELEASE_TYPES.includes(truncation)) {
897
897
  return null;
898
898
  }
@@ -922,7 +922,7 @@ var require_truncate = __commonJS({
922
922
  var isPrerelease = (type) => {
923
923
  return type.startsWith("pre");
924
924
  };
925
- module.exports = truncate;
925
+ module.exports = truncate2;
926
926
  }
927
927
  });
928
928
 
@@ -1968,7 +1968,7 @@ var require_semver2 = __commonJS({
1968
1968
  var lte = require_lte();
1969
1969
  var cmp = require_cmp();
1970
1970
  var coerce = require_coerce();
1971
- var truncate = require_truncate();
1971
+ var truncate2 = require_truncate();
1972
1972
  var Comparator = require_comparator();
1973
1973
  var Range = require_range();
1974
1974
  var satisfies = require_satisfies();
@@ -2007,7 +2007,7 @@ var require_semver2 = __commonJS({
2007
2007
  lte,
2008
2008
  cmp,
2009
2009
  coerce,
2010
- truncate,
2010
+ truncate: truncate2,
2011
2011
  Comparator,
2012
2012
  Range,
2013
2013
  satisfies,
@@ -8260,7 +8260,7 @@ var init_dist5 = __esm({
8260
8260
  // default-plugins/element-template/commands/apply.ts
8261
8261
  import { createRequire } from "node:module";
8262
8262
 
8263
- // default-plugins/element-template/moddle.ts
8263
+ // default-plugins/element-template/migration/moddle.ts
8264
8264
  function isModdleElement(value) {
8265
8265
  if (typeof value !== "object" || value === null) {
8266
8266
  return false;
@@ -8349,6 +8349,502 @@ import {
8349
8349
  writeFileSync
8350
8350
  } from "node:fs";
8351
8351
  import { resolve as resolvePath } from "node:path";
8352
+
8353
+ // default-plugins/element-template/migration/binding.ts
8354
+ var BINDING_TYPE_PREFIXES = {
8355
+ input: "zeebe:input",
8356
+ output: "zeebe:output",
8357
+ header: "zeebe:taskHeader",
8358
+ property: "zeebe:property",
8359
+ taskDefinition: "zeebe:taskDefinition",
8360
+ agentDefinition: "zeebe:agentDefinition",
8361
+ adHoc: "zeebe:adHoc"
8362
+ };
8363
+ function splitBindingPrefix(path) {
8364
+ const colon = path.indexOf(":");
8365
+ if (colon !== -1) {
8366
+ const bindingType = BINDING_TYPE_PREFIXES[path.slice(0, colon)];
8367
+ if (bindingType) {
8368
+ return { bindingType, key: path.slice(colon + 1) };
8369
+ }
8370
+ }
8371
+ return { bindingType: null, key: path };
8372
+ }
8373
+ function bindingPath(bindingType, key) {
8374
+ const prefix2 = bindingType === "zeebe:taskHeader" ? "header" : bindingType?.replace("zeebe:", "");
8375
+ return `${prefix2}:${key}`;
8376
+ }
8377
+ function findExtensionByType2(extensionElements, type) {
8378
+ const matches = getModdleList(extensionElements, "values").filter(
8379
+ (v) => v.$type === type
8380
+ );
8381
+ if (matches.length > 1)
8382
+ throw new Error(
8383
+ `Duplicate backing container ${type}; remove duplicate extension containers before migrating.`
8384
+ );
8385
+ return matches[0];
8386
+ }
8387
+ function findExtensionContainers2(extensionElements) {
8388
+ const containers = {
8389
+ ioMapping: findExtensionByType2(extensionElements, "zeebe:IoMapping"),
8390
+ taskHeaders: findExtensionByType2(extensionElements, "zeebe:TaskHeaders"),
8391
+ taskDefinition: findExtensionByType2(
8392
+ extensionElements,
8393
+ "zeebe:TaskDefinition"
8394
+ ),
8395
+ zeebeProperties: findExtensionByType2(extensionElements, "zeebe:Properties"),
8396
+ agentDefinition: findExtensionByType2(
8397
+ extensionElements,
8398
+ "zeebe:AgentDefinition"
8399
+ ),
8400
+ adHoc: findExtensionByType2(extensionElements, "zeebe:AdHoc")
8401
+ };
8402
+ for (const [container, list, key, prefix2] of [
8403
+ [containers.ioMapping, "inputParameters", "target", "input"],
8404
+ [containers.ioMapping, "outputParameters", "source", "output"],
8405
+ [containers.taskHeaders, "values", "key", "header"],
8406
+ [containers.zeebeProperties, "properties", "name", "property"]
8407
+ ]) {
8408
+ const seen = /* @__PURE__ */ new Set();
8409
+ for (const child of getModdleList(container, list)) {
8410
+ const identity2 = child.get(key);
8411
+ if (typeof identity2 !== "string") continue;
8412
+ if (seen.has(identity2))
8413
+ throw new Error(
8414
+ `Duplicate source backing path ${prefix2}:${identity2}; remove duplicate backing entries before migrating.`
8415
+ );
8416
+ seen.add(identity2);
8417
+ }
8418
+ }
8419
+ return containers;
8420
+ }
8421
+ function resolveBindingTarget2(binding, containers) {
8422
+ switch (binding.type) {
8423
+ case "zeebe:input": {
8424
+ const inputs = getModdleList(containers.ioMapping, "inputParameters");
8425
+ const child = inputs.find((p) => p.target === binding.name);
8426
+ return child ? { child, property: "source" } : void 0;
8427
+ }
8428
+ case "zeebe:output": {
8429
+ const outputs = getModdleList(containers.ioMapping, "outputParameters");
8430
+ const child = outputs.find((p) => p.source === binding.source);
8431
+ return child ? { child, property: "target" } : void 0;
8432
+ }
8433
+ case "zeebe:taskHeader": {
8434
+ const headers = getModdleList(containers.taskHeaders, "values");
8435
+ const child = headers.find((h) => h.key === binding.key);
8436
+ return child ? { child, property: "value" } : void 0;
8437
+ }
8438
+ case "zeebe:property": {
8439
+ const props = getModdleList(containers.zeebeProperties, "properties");
8440
+ const child = props.find((p) => p.name === binding.name);
8441
+ return child ? { child, property: "value" } : void 0;
8442
+ }
8443
+ case "zeebe:taskDefinition":
8444
+ return containers.taskDefinition && binding.property ? { child: containers.taskDefinition, property: binding.property } : void 0;
8445
+ case "zeebe:agentDefinition":
8446
+ return containers.agentDefinition && binding.property ? { child: containers.agentDefinition, property: binding.property } : void 0;
8447
+ case "zeebe:adHoc":
8448
+ return containers.adHoc && binding.property ? { child: containers.adHoc, property: binding.property } : void 0;
8449
+ default:
8450
+ return void 0;
8451
+ }
8452
+ }
8453
+ function bindingTargetKey(binding) {
8454
+ if (!binding) {
8455
+ return void 0;
8456
+ }
8457
+ switch (binding.type) {
8458
+ case "zeebe:input":
8459
+ case "zeebe:property":
8460
+ return binding.name;
8461
+ case "zeebe:output":
8462
+ return binding.source;
8463
+ case "zeebe:taskHeader":
8464
+ return binding.key;
8465
+ case "zeebe:taskDefinition":
8466
+ case "zeebe:agentDefinition":
8467
+ case "zeebe:adHoc":
8468
+ return binding.property;
8469
+ default:
8470
+ return void 0;
8471
+ }
8472
+ }
8473
+ function sameTarget(candidate, target) {
8474
+ return candidate.key === target.key && (target.bindingType === null || candidate.bindingType === target.bindingType);
8475
+ }
8476
+ function findPropertiesByTarget(properties, key, bindingType) {
8477
+ return properties.filter(
8478
+ (p) => sameTarget(
8479
+ { key: bindingTargetKey(p.binding), bindingType: p.binding?.type },
8480
+ { key, bindingType }
8481
+ )
8482
+ );
8483
+ }
8484
+ function maybePrependFeel(property, value) {
8485
+ if (property.feel !== "required") {
8486
+ return value;
8487
+ }
8488
+ if (value === "" || value.startsWith("=")) {
8489
+ return value;
8490
+ }
8491
+ return `=${value}`;
8492
+ }
8493
+
8494
+ // default-plugins/element-template/migration/plan.ts
8495
+ var TEMPLATE_REF = /\$\{([^}]+)\}/g;
8496
+ function globToRegex(pattern) {
8497
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
8498
+ return new RegExp(`^${escaped.replace(/\*/g, ".*")}$`, "s");
8499
+ }
8500
+ function lookup(values, path) {
8501
+ const { bindingType, key } = splitBindingPrefix(path);
8502
+ const matches = values.filter((v) => sameTarget(v, { key, bindingType }));
8503
+ if (matches.length > 1) {
8504
+ const types2 = new Set(matches.map((v) => v.bindingType));
8505
+ const qualified = [...types2].map((type) => bindingPath(type, key));
8506
+ throw new Error(
8507
+ `${types2.size > 1 ? "Ambiguous" : "Duplicate"} source path "${path}"; use ${qualified.join(", ")}${types2.size === 1 ? " after removing duplicate backing entries" : ""}`
8508
+ );
8509
+ }
8510
+ return matches[0];
8511
+ }
8512
+ function evalGuard(guard, values) {
8513
+ const value = lookup(values, guard.path)?.value;
8514
+ if (guard.kind === "exists") {
8515
+ return guard.exists ? value !== void 0 : value === void 0;
8516
+ }
8517
+ let result;
8518
+ if (guard.kind === "equals") {
8519
+ result = value === guard.value;
8520
+ } else if (guard.kind === "matches") {
8521
+ result = value !== void 0 && globToRegex(guard.pattern).test(value);
8522
+ } else {
8523
+ result = value !== void 0 && guard.values.includes(value);
8524
+ }
8525
+ return guard.not ? !result : result;
8526
+ }
8527
+ function isPopulated(value) {
8528
+ return value !== void 0 && value !== "";
8529
+ }
8530
+ function effectiveFeel(property) {
8531
+ return property.feel ?? (["zeebe:input", "zeebe:output"].includes(property.binding?.type ?? "") ? "static" : void 0);
8532
+ }
8533
+ function normalizeDestinationValue(property, value) {
8534
+ const feel = effectiveFeel(property);
8535
+ if (value.startsWith("=")) return value;
8536
+ if (feel === "required" || ["optional", "static"].includes(feel ?? "") && ["Number", "Boolean"].includes(property.type ?? "")) {
8537
+ return `=${property.type === "Boolean" ? value !== "false" && value !== "" : value}`;
8538
+ }
8539
+ return value;
8540
+ }
8541
+ var CARRY_OVER_LABEL = "carry-over";
8542
+ function carryOverWrites(writes, sourceValues, template) {
8543
+ return sourceValues.filter(
8544
+ (source) => isPopulated(source.value) && !writes.some(
8545
+ (w) => w.key === source.key && w.bindingType === source.bindingType
8546
+ ) && findPropertiesByTarget(
8547
+ template.properties,
8548
+ source.key,
8549
+ source.bindingType
8550
+ ).some((p) => p.type !== "Hidden")
8551
+ ).map(
8552
+ (source) => ({
8553
+ key: source.key,
8554
+ bindingType: source.bindingType,
8555
+ value: source.value,
8556
+ entry: {
8557
+ kind: "set",
8558
+ to: source.key,
8559
+ value: source.value,
8560
+ when: [],
8561
+ label: CARRY_OVER_LABEL
8562
+ }
8563
+ })
8564
+ );
8565
+ }
8566
+ var DestinationError = class extends Error {
8567
+ /** The value was carried over by key, not written by a recipe or map entry. */
8568
+ carryOver;
8569
+ constructor(message, carryOver) {
8570
+ super(message);
8571
+ this.carryOver = carryOver;
8572
+ }
8573
+ };
8574
+ var ConditionError = class extends Error {
8575
+ kind;
8576
+ constructor(kind) {
8577
+ super(`${kind} destination property condition`);
8578
+ this.kind = kind;
8579
+ }
8580
+ };
8581
+ function validateDestinationValues(writes, sourceValues, template) {
8582
+ const activeProperties = /* @__PURE__ */ new Set();
8583
+ const resolvedValue = (property) => {
8584
+ const key = bindingTargetKey(property.binding);
8585
+ const write = writes.find(
8586
+ (w) => w.key === key && w.bindingType === property.binding?.type
8587
+ );
8588
+ if (write && !(write.entry.label === CARRY_OVER_LABEL && property.type === "Hidden"))
8589
+ return normalizeDestinationValue(property, write.value);
8590
+ if (property.type !== "Hidden" && key !== void 0) {
8591
+ const source = lookup(
8592
+ sourceValues,
8593
+ bindingPath(property.binding?.type, key)
8594
+ );
8595
+ if (source && isPopulated(source.value))
8596
+ return normalizeDestinationValue(property, source.value);
8597
+ }
8598
+ return property.value;
8599
+ };
8600
+ const isActive = (property, visiting = /* @__PURE__ */ new Set()) => {
8601
+ if (!("condition" in property) || !property.condition) return true;
8602
+ if (visiting.has(property)) throw new ConditionError("cyclic");
8603
+ const next = new Set(visiting).add(property);
8604
+ const evaluate = (condition) => {
8605
+ if (typeof condition !== "object" || condition === null)
8606
+ throw new ConditionError("unsupported");
8607
+ if ("allMatch" in condition && Array.isArray(condition.allMatch))
8608
+ return condition.allMatch.every(evaluate);
8609
+ if (!("property" in condition) || typeof condition.property !== "string")
8610
+ throw new ConditionError("unsupported");
8611
+ const related = template.properties.find(
8612
+ (p) => p.id === condition.property
8613
+ );
8614
+ if ("isActive" in condition && typeof condition.isActive === "boolean")
8615
+ return condition.isActive ? !!related && isActive(related, next) : !related || !isActive(related, next);
8616
+ if (!("equals" in condition) && !("oneOf" in condition && Array.isArray(condition.oneOf)) && !("isEmpty" in condition && typeof condition.isEmpty === "boolean"))
8617
+ throw new ConditionError("unsupported");
8618
+ if (!related) return false;
8619
+ const value = resolvedValue(related);
8620
+ if ("isEmpty" in condition)
8621
+ return condition.isEmpty === (value === void 0 || value === null || value === "");
8622
+ const compare = (expected) => {
8623
+ if (value === void 0 || value === null) return false;
8624
+ const literal = (v) => typeof v === "string" && v.startsWith("=") ? v.slice(1) : v;
8625
+ if (related.type === "Number")
8626
+ return Number(literal(value)) === Number(literal(expected));
8627
+ if (related.type === "Boolean")
8628
+ return String(literal(value)) !== "false" === (typeof expected === "string" && expected.startsWith("=") ? literal(expected) !== "false" : expected);
8629
+ return (related.feel === "required" ? literal(value) : value) === literal(expected);
8630
+ };
8631
+ return "equals" in condition ? compare(condition.equals) : "oneOf" in condition && Array.isArray(condition.oneOf) && condition.oneOf.some(compare);
8632
+ };
8633
+ return evaluate(property.condition);
8634
+ };
8635
+ const candidates = [
8636
+ ...writes,
8637
+ ...carryOverWrites(writes, sourceValues, template)
8638
+ ];
8639
+ for (const write of candidates) {
8640
+ const path = bindingPath(write.bindingType, write.key);
8641
+ const at = `${write.entry.label}: destination "${path}"`;
8642
+ const fail = (problem) => new DestinationError(
8643
+ `${at} ${problem}`,
8644
+ write.entry.label === CARRY_OVER_LABEL
8645
+ );
8646
+ for (const property of findPropertiesByTarget(
8647
+ template.properties,
8648
+ write.key,
8649
+ write.bindingType
8650
+ )) {
8651
+ if (write.entry.label === CARRY_OVER_LABEL && property.type === "Hidden")
8652
+ continue;
8653
+ let active;
8654
+ try {
8655
+ active = isActive(property);
8656
+ } catch (error3) {
8657
+ if (!(error3 instanceof ConditionError)) throw error3;
8658
+ throw fail(`has ${error3.kind} condition`);
8659
+ }
8660
+ if (!active) continue;
8661
+ activeProperties.add(property);
8662
+ const constraints = property.constraints;
8663
+ for (const constraint of Object.keys(constraints ?? {})) {
8664
+ if (constraint !== "notEmpty" && constraint !== "pattern")
8665
+ throw fail(`has unsupported constraint ${constraint}`);
8666
+ }
8667
+ const stored = maybePrependFeel(
8668
+ property,
8669
+ effectiveFeel(property) === "static" && ["Number", "Boolean"].includes(property.type ?? "") ? normalizeDestinationValue(property, write.value) : write.value
8670
+ );
8671
+ const isExpression = stored.startsWith("=") && (property.feel === "optional" || property.feel === "required");
8672
+ const literal = effectiveFeel(property) === "static" && ["Number", "Boolean"].includes(property.type ?? "") && stored.startsWith("=") ? stored.slice(1) : stored;
8673
+ if (constraints?.notEmpty && (isExpression ? stored.slice(1) : literal).trim() === "")
8674
+ throw fail("violates notEmpty constraint");
8675
+ if (isExpression) continue;
8676
+ if (property.choices && !property.choices.some((choice) => choice.value === literal))
8677
+ throw fail("violates choice constraint");
8678
+ if (constraints?.pattern) {
8679
+ let pattern;
8680
+ try {
8681
+ pattern = new RegExp(constraints.pattern.value);
8682
+ } catch {
8683
+ throw fail("has invalid pattern constraint");
8684
+ }
8685
+ if (!pattern.test(literal)) throw fail("violates pattern constraint");
8686
+ }
8687
+ }
8688
+ }
8689
+ return activeProperties;
8690
+ }
8691
+ function emptyFacts() {
8692
+ return {
8693
+ moved: [],
8694
+ set: [],
8695
+ notes: [],
8696
+ guardSkipped: [],
8697
+ templateSkipped: [],
8698
+ noMatch: [],
8699
+ feelSkipped: []
8700
+ };
8701
+ }
8702
+ function buildStepPlan(entries, sourceValues, template) {
8703
+ const facts = emptyFacts();
8704
+ const writes = [];
8705
+ const write = (entry, to, value) => {
8706
+ const target = splitBindingPrefix(to);
8707
+ if (template) {
8708
+ validateTargets([entry], template);
8709
+ const properties = findPropertiesByTarget(
8710
+ template.properties,
8711
+ target.key,
8712
+ target.bindingType
8713
+ );
8714
+ target.bindingType = properties[0].binding?.type ?? null;
8715
+ }
8716
+ writes.push({
8717
+ key: target.key,
8718
+ bindingType: target.bindingType,
8719
+ value,
8720
+ entry
8721
+ });
8722
+ if (entry.note) {
8723
+ facts.notes.push(entry.note);
8724
+ }
8725
+ return target;
8726
+ };
8727
+ for (const entry of entries) {
8728
+ const active = entry.when.every((g) => evalGuard(g, sourceValues));
8729
+ if (entry.kind === "set") {
8730
+ if (active) {
8731
+ const target2 = write(entry, entry.to, entry.value);
8732
+ facts.set.push({
8733
+ key: target2.key,
8734
+ bindingType: target2.bindingType,
8735
+ value: entry.value
8736
+ });
8737
+ }
8738
+ continue;
8739
+ }
8740
+ if (entry.kind === "template") {
8741
+ const refs = [...entry.template.matchAll(TEMPLATE_REF)].map((m) => m[1]);
8742
+ const resolved = refs.map((ref) => lookup(sourceValues, ref)?.value);
8743
+ if (!active) {
8744
+ if (resolved.some(isPopulated)) {
8745
+ facts.guardSkipped.push({ from: entry.template, to: entry.to });
8746
+ }
8747
+ continue;
8748
+ }
8749
+ const missing = refs.filter((_, i2) => !isPopulated(resolved[i2]));
8750
+ if (missing.length > 0) {
8751
+ facts.templateSkipped.push({ to: entry.to, missing });
8752
+ continue;
8753
+ }
8754
+ let i = 0;
8755
+ write(
8756
+ entry,
8757
+ entry.to,
8758
+ entry.template.replace(TEMPLATE_REF, () => resolved[i++] ?? "")
8759
+ );
8760
+ continue;
8761
+ }
8762
+ const source = lookup(sourceValues, entry.from);
8763
+ if (!active) {
8764
+ if (source && isPopulated(source.value)) {
8765
+ facts.guardSkipped.push({ from: entry.from, to: entry.to });
8766
+ }
8767
+ continue;
8768
+ }
8769
+ if (!source) {
8770
+ continue;
8771
+ }
8772
+ let value = source.value;
8773
+ let transformed = false;
8774
+ if (entry.valueMap) {
8775
+ if (source.isFeel) {
8776
+ facts.feelSkipped.push({ from: entry.from, to: entry.to });
8777
+ } else {
8778
+ const rule = entry.valueMap.rules.find(
8779
+ (r) => globToRegex(r.match).test(source.value)
8780
+ );
8781
+ const mapped = rule?.value ?? entry.valueMap.default;
8782
+ if (mapped === void 0) {
8783
+ facts.noMatch.push({ from: entry.from, to: entry.to });
8784
+ continue;
8785
+ }
8786
+ value = mapped;
8787
+ transformed = value !== source.value;
8788
+ }
8789
+ }
8790
+ const target = write(entry, entry.to, value);
8791
+ facts.moved.push({
8792
+ from: { key: source.key, bindingType: source.bindingType },
8793
+ to: { key: target.key, bindingType: target.bindingType },
8794
+ transformed
8795
+ });
8796
+ }
8797
+ facts.guardSkipped = facts.guardSkipped.filter(
8798
+ (skip) => !facts.moved.some(
8799
+ (move) => sameTarget(move.from, splitBindingPrefix(skip.from))
8800
+ )
8801
+ );
8802
+ assertNoAmbiguousWrites(writes);
8803
+ const activeProperties = template ? validateDestinationValues(writes, sourceValues, template) : /* @__PURE__ */ new Set();
8804
+ return { writes, facts, activeProperties };
8805
+ }
8806
+ function assertNoAmbiguousWrites(writes) {
8807
+ const seen = /* @__PURE__ */ new Map();
8808
+ for (const w of writes) {
8809
+ const id = `${w.bindingType ?? ""} ${w.key}`;
8810
+ const previous = seen.get(id);
8811
+ if (previous) {
8812
+ throw new Error(
8813
+ `Ambiguous migration: ${previous.entry.label} and ${w.entry.label} both write to "${w.key}"`
8814
+ );
8815
+ }
8816
+ seen.set(id, w);
8817
+ }
8818
+ }
8819
+ function validateTargets(entries, template) {
8820
+ const label = `${template.id}${template.version === void 0 ? "" : `@${template.version}`}`;
8821
+ for (const entry of entries) {
8822
+ const { bindingType, key } = splitBindingPrefix(entry.to);
8823
+ const matches = findPropertiesByTarget(
8824
+ template.properties,
8825
+ key,
8826
+ bindingType
8827
+ );
8828
+ if (matches.length === 0) {
8829
+ throw new Error(
8830
+ `${entry.label}: target path "${entry.to}" is not a binding in template ${label}`
8831
+ );
8832
+ }
8833
+ if (matches.every((m) => m.type === "Hidden" && m.value !== void 0)) {
8834
+ throw new Error(
8835
+ `${entry.label}: target path "${entry.to}" is a Hidden property with a fixed value in template ${label}`
8836
+ );
8837
+ }
8838
+ const types2 = new Set(matches.map((m) => m.binding?.type));
8839
+ if (types2.size > 1) {
8840
+ throw new Error(
8841
+ `${entry.label}: target path "${entry.to}" is bound by several binding types in template ${label}; add a prefix such as input: or header:`
8842
+ );
8843
+ }
8844
+ }
8845
+ }
8846
+
8847
+ // default-plugins/element-template/helpers.ts
8352
8848
  if (!globalThis.c8ctl) throw new Error("c8ctl runtime not initialised");
8353
8849
  var c8ctl = globalThis.c8ctl;
8354
8850
  var USER_AGENT = `c8ctl-plugin-element-template/${c8ctl.version}`;
@@ -8368,19 +8864,23 @@ function installStdoutEpipeHandler() {
8368
8864
  function isRecord(value) {
8369
8865
  return value != null && typeof value === "object" && !Array.isArray(value);
8370
8866
  }
8371
- function atomicOverwriteFile(targetPath, contents) {
8867
+ var CONCURRENT_EDIT_MESSAGE = "BPMN changed while this command ran; refusing to overwrite concurrent edits.";
8868
+ function atomicOverwriteFile(targetPath, contents, expectedContents, directWriteFallback = false) {
8372
8869
  const target = resolvePath(targetPath);
8373
8870
  const tmp = `${target}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
8374
8871
  try {
8375
8872
  writeFileSync(tmp, contents, "utf-8");
8873
+ if (expectedContents !== void 0 && readFileSync(target, "utf-8") !== expectedContents)
8874
+ throw new Error(CONCURRENT_EDIT_MESSAGE);
8376
8875
  renameSync(tmp, target);
8377
8876
  } catch (error3) {
8378
8877
  try {
8379
8878
  unlinkSync(tmp);
8380
8879
  } catch {
8381
8880
  }
8382
- const code = isRecord(error3) && typeof error3.code === "string" ? error3.code : void 0;
8383
- if (code === "EXDEV") {
8881
+ if (directWriteFallback && isRecord(error3) && error3.code === "EXDEV") {
8882
+ if (expectedContents !== void 0 && readFileSync(target, "utf-8") !== expectedContents)
8883
+ throw new Error(CONCURRENT_EDIT_MESSAGE);
8384
8884
  writeFileSync(target, contents, "utf-8");
8385
8885
  return;
8386
8886
  }
@@ -8514,10 +9014,6 @@ function getPropertyDetail(prop, groupLabelMap) {
8514
9014
  }
8515
9015
  return detail;
8516
9016
  }
8517
- function globToRegex(pattern) {
8518
- const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
8519
- return new RegExp(`^${escaped.replace(/\*/g, ".*")}$`);
8520
- }
8521
9017
  function parseSetArg(arg) {
8522
9018
  const eqIndex = arg.indexOf("=");
8523
9019
  if (eqIndex === -1) {
@@ -8545,15 +9041,6 @@ function parseSetArg(arg) {
8545
9041
  }
8546
9042
  return { bindingTypeFilter: null, name: key, value };
8547
9043
  }
8548
- function maybePrependFeel(prop, value) {
8549
- if (prop.feel !== "required") {
8550
- return value;
8551
- }
8552
- if (value === "" || value.startsWith("=")) {
8553
- return value;
8554
- }
8555
- return `=${value}`;
8556
- }
8557
9044
  function findPropertiesByBindingName(properties, name2, bindingTypeFilter) {
8558
9045
  const settable = getSettableProperties(properties);
8559
9046
  const matches = settable.filter((p) => {
@@ -8733,6 +9220,7 @@ function parseTemplateJson(content) {
8733
9220
  }
8734
9221
 
8735
9222
  // default-plugins/element-template/template-ref.ts
9223
+ var import_semver4 = __toESM(require_semver2(), 1);
8736
9224
  import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
8737
9225
  import { resolve as resolvePath2 } from "node:path";
8738
9226
 
@@ -9372,17 +9860,46 @@ Template URLs must use HTTPS to protect credentials and content integrity.`
9372
9860
  version: match[2] !== void 0 ? Number(match[2]) : void 0
9373
9861
  };
9374
9862
  }
9375
- async function getExecutionPlatformVersion(xml2) {
9863
+ async function getExecutionPlatformVersion(xml2, { requireCamunda = false } = {}) {
9376
9864
  const { BpmnModdle: BpmnModdle2 } = await Promise.resolve().then(() => (init_dist5(), dist_exports));
9377
9865
  const moddle = new BpmnModdle2();
9378
9866
  try {
9379
9867
  const { rootElement } = await moddle.fromXML(xml2);
9380
9868
  const version = rootElement.$attrs?.["modeler:executionPlatformVersion"];
9869
+ if (requireCamunda) {
9870
+ const attrs = rootElement.$attrs ?? {};
9871
+ const metadata2 = Object.entries(attrs).filter(([name2]) => {
9872
+ const [prefix2, localName] = name2.split(":");
9873
+ return (localName === "executionPlatform" || localName === "executionPlatformVersion") && attrs[`xmlns:${prefix2}`] === "http://camunda.org/schema/modeler/1.0";
9874
+ });
9875
+ const platforms = metadata2.filter(
9876
+ ([name2]) => name2.endsWith(":executionPlatform")
9877
+ );
9878
+ const versions = metadata2.filter(
9879
+ ([name2]) => name2.endsWith(":executionPlatformVersion")
9880
+ );
9881
+ const engineVersion = versions[0]?.[1];
9882
+ if (platforms.length !== 1 || versions.length !== 1 || platforms[0][1] !== "Camunda Cloud" || typeof engineVersion !== "string" || !/^\d+\.\d+(?:\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?)?$/.test(
9883
+ engineVersion
9884
+ ))
9885
+ return null;
9886
+ return import_semver4.default.valid(
9887
+ /^\d+\.\d+$/.test(engineVersion) ? `${engineVersion}.0` : engineVersion
9888
+ );
9889
+ }
9381
9890
  return typeof version === "string" ? version : null;
9382
9891
  } catch {
9383
9892
  return null;
9384
9893
  }
9385
9894
  }
9895
+ function isEngineCompatible(template, engineVersion) {
9896
+ if (!isRecord(template)) return false;
9897
+ if (!("engines" in template)) return true;
9898
+ if (!isRecord(template.engines)) return false;
9899
+ if (!("camunda" in template.engines)) return true;
9900
+ const range = template.engines.camunda;
9901
+ return typeof range === "string" && range.trim() !== "" && import_semver4.default.validRange(range) !== null && import_semver4.default.satisfies(engineVersion, range);
9902
+ }
9386
9903
  function isTraversable(value) {
9387
9904
  return typeof value === "object" && value !== null;
9388
9905
  }
@@ -9416,20 +9933,25 @@ async function readTemplateFromPathOrUrl(input) {
9416
9933
  return parseTemplateJson(content);
9417
9934
  }
9418
9935
  async function resolveOotbTemplate(ref, {
9419
- executionPlatformVersion
9936
+ executionPlatformVersion,
9937
+ requireEngineCompatibility = false,
9938
+ templates
9420
9939
  } = {}) {
9421
9940
  const logger = c8ctl2.getLogger();
9422
9941
  requireCachePresent();
9423
9942
  nudgeIfStale(logger);
9424
- const candidates = findById(ref.id);
9943
+ const candidates = templates ? templates.filter((t) => t.id === ref.id) : findById(ref.id);
9425
9944
  if (candidates.length === 0) {
9426
9945
  throw new Error(
9427
9946
  `Element template '${ref.id}' not found. Run 'c8ctl element-template sync' to refresh the cache, or use 'c8ctl element-template search <query>' to find an id.`
9428
9947
  );
9429
9948
  }
9430
- const picked = pickVersion(candidates, {
9949
+ const eligible = requireEngineCompatibility && ref.version === void 0 ? candidates.filter(
9950
+ (template) => isEngineCompatible(template, executionPlatformVersion ?? "")
9951
+ ) : candidates;
9952
+ const picked = pickVersion(eligible, {
9431
9953
  version: ref.version,
9432
- executionPlatformVersion
9954
+ executionPlatformVersion: requireEngineCompatibility ? void 0 : executionPlatformVersion
9433
9955
  });
9434
9956
  if (!picked) {
9435
9957
  if (ref.version !== void 0) {
@@ -9690,7 +10212,7 @@ async function applySubcommand(args) {
9690
10212
  warnUnmetConditions(logger, resultXml, setProperties);
9691
10213
  }
9692
10214
  if (parsed.inPlace && bpmnFilePath) {
9693
- atomicOverwriteFile(bpmnFilePath, resultXml);
10215
+ atomicOverwriteFile(bpmnFilePath, resultXml, input.xml, true);
9694
10216
  logger.info(`Updated ${bpmnFilePath}`);
9695
10217
  return;
9696
10218
  }
@@ -9863,7 +10385,7 @@ async function editSubcommand(args) {
9863
10385
  const result = await modeler.saveXML({ format: true });
9864
10386
  const resultXml = result.xml;
9865
10387
  if (parsed.inPlace && bpmnFilePath) {
9866
- atomicOverwriteFile(bpmnFilePath, resultXml);
10388
+ atomicOverwriteFile(bpmnFilePath, resultXml, input.xml, true);
9867
10389
  logger.info(`Updated ${bpmnFilePath}`);
9868
10390
  return;
9869
10391
  }
@@ -10528,65 +11050,2545 @@ async function syncSubcommand(args) {
10528
11050
  }
10529
11051
  }
10530
11052
 
10531
- // default-plugins/element-template/c8ctl-plugin.ts
10532
- if (!globalThis.c8ctl) throw new Error("c8ctl runtime not initialised");
10533
- var c8ctl9 = globalThis.c8ctl;
10534
- function injectFlagsIntoArgs(args, flags) {
10535
- const out = [...args];
10536
- if (!flags) {
10537
- return out;
10538
- }
10539
- for (const [name2, value] of Object.entries(flags)) {
10540
- if (value === void 0 || value === null) {
10541
- continue;
11053
+ // default-plugins/element-template/commands/migrate.ts
11054
+ import {
11055
+ closeSync as closeSync2,
11056
+ existsSync as existsSync5,
11057
+ openSync as openSync2,
11058
+ readFileSync as readFileSync5,
11059
+ unlinkSync as unlinkSync3
11060
+ } from "node:fs";
11061
+ import { createRequire as createRequire3 } from "node:module";
11062
+ import { resolve as resolvePath4 } from "node:path";
11063
+
11064
+ // default-plugins/element-template/migration/element-values.ts
11065
+ var AD_HOC_PROPERTIES = [
11066
+ "activeElementsCollection",
11067
+ "outputCollection",
11068
+ "outputElement"
11069
+ ];
11070
+ function enumerateElementValues(extensionElements) {
11071
+ const containers = findExtensionContainers2(extensionElements);
11072
+ const out = [];
11073
+ const push = (bindingType, key, value) => {
11074
+ if (key === void 0 || value === void 0) {
11075
+ return;
10542
11076
  }
10543
- if (typeof value === "boolean") {
10544
- if (value) {
10545
- out.push(`--${name2}`);
10546
- }
10547
- } else if (Array.isArray(value)) {
10548
- for (const item of value) {
10549
- if (item !== void 0 && item !== null) {
10550
- out.push(`--${name2}`, String(item));
10551
- }
10552
- }
10553
- } else {
10554
- out.push(`--${name2}`, String(value));
11077
+ out.push({ bindingType, key, value, isFeel: value.startsWith("=") });
11078
+ };
11079
+ for (const p of getModdleList(containers.ioMapping, "inputParameters")) {
11080
+ push(
11081
+ "zeebe:input",
11082
+ getModdleString(p, "target"),
11083
+ getModdleString(p, "source")
11084
+ );
11085
+ }
11086
+ for (const p of getModdleList(containers.ioMapping, "outputParameters")) {
11087
+ push(
11088
+ "zeebe:output",
11089
+ getModdleString(p, "source"),
11090
+ getModdleString(p, "target")
11091
+ );
11092
+ }
11093
+ for (const h of getModdleList(containers.taskHeaders, "values")) {
11094
+ push(
11095
+ "zeebe:taskHeader",
11096
+ getModdleString(h, "key"),
11097
+ getModdleString(h, "value")
11098
+ );
11099
+ }
11100
+ for (const p of getModdleList(containers.zeebeProperties, "properties")) {
11101
+ push(
11102
+ "zeebe:property",
11103
+ getModdleString(p, "name"),
11104
+ getModdleString(p, "value")
11105
+ );
11106
+ }
11107
+ if (containers.taskDefinition) {
11108
+ const retries = getModdleString(containers.taskDefinition, "retries") ?? stringifyNumber(getModdleNumber(containers.taskDefinition, "retries"));
11109
+ push("zeebe:taskDefinition", "retries", retries);
11110
+ }
11111
+ if (containers.agentDefinition) {
11112
+ push(
11113
+ "zeebe:agentDefinition",
11114
+ "agentType",
11115
+ getModdleString(containers.agentDefinition, "agentType")
11116
+ );
11117
+ }
11118
+ if (containers.adHoc) {
11119
+ for (const name2 of AD_HOC_PROPERTIES) {
11120
+ push("zeebe:adHoc", name2, getModdleString(containers.adHoc, name2));
10555
11121
  }
10556
11122
  }
10557
11123
  return out;
10558
11124
  }
10559
- var subcommandHandlers = {
10560
- search: searchSubcommand,
10561
- info: infoSubcommand,
10562
- "get-properties": getPropertiesSubcommand,
10563
- apply: applySubcommand,
10564
- edit: editSubcommand,
10565
- get: getSubcommand,
10566
- sync: syncSubcommand
11125
+ var UNREAD_EXTENSIONS = {
11126
+ "zeebe:CalledElement": "zeebe:calledElement",
11127
+ "zeebe:CalledDecision": "zeebe:calledDecision",
11128
+ "zeebe:FormDefinition": "zeebe:formDefinition",
11129
+ "zeebe:Script": "zeebe:script"
10567
11130
  };
10568
- function isSubcommand(name2) {
10569
- return Object.hasOwn(subcommandHandlers, name2);
11131
+ var LINKED_RESOURCE_PROPERTIES = [
11132
+ "resourceId",
11133
+ "resourceType",
11134
+ "bindingType",
11135
+ "versionTag"
11136
+ ];
11137
+ function setAttributes(element) {
11138
+ return Object.keys(element).filter(
11139
+ (name2) => !name2.startsWith("$") && ["string", "boolean", "number"].includes(typeof element[name2])
11140
+ );
10570
11141
  }
10571
- async function elementTemplateHandler(args, flags) {
10572
- const reinjected = injectFlagsIntoArgs(args ?? [], flags);
10573
- const subcommand = reinjected[0];
10574
- const subArgs = reinjected.slice(1);
10575
- if (!subcommand || !isSubcommand(subcommand)) {
10576
- const logger = c8ctl9.getLogger();
10577
- const lead = subcommand ? `Unknown subcommand '${subcommand}'.` : "c8ctl element-template requires a subcommand.";
10578
- const validSubcommands = Object.keys(subcommandHandlers);
10579
- logger.info(`${lead} Available: ${validSubcommands.join(", ")}`);
10580
- logger.info("Run 'c8ctl element-template --help' for full usage.");
10581
- process.exitCode = 1;
10582
- return;
11142
+ function unreadBindings(businessObject) {
11143
+ const bindings = [];
11144
+ for (const extension of getModdleList(
11145
+ getExtensionElements(businessObject),
11146
+ "values"
11147
+ )) {
11148
+ const type = UNREAD_EXTENSIONS[extension.$type];
11149
+ if (type) {
11150
+ for (const property of setAttributes(extension)) {
11151
+ bindings.push({ type, property });
11152
+ }
11153
+ }
11154
+ if (extension.$type === "zeebe:LinkedResources") {
11155
+ for (const resource of getModdleList(extension, "values")) {
11156
+ const linkedResourceId = getModdleString(resource, "linkedResourceId");
11157
+ for (const property of LINKED_RESOURCE_PROPERTIES) {
11158
+ if (getModdleString(resource, property) !== void 0) {
11159
+ bindings.push({
11160
+ type: "zeebe:linkedResource",
11161
+ linkedResourceId,
11162
+ property
11163
+ });
11164
+ }
11165
+ }
11166
+ }
11167
+ }
10583
11168
  }
10584
- try {
10585
- await subcommandHandlers[subcommand](subArgs);
10586
- } catch (error3) {
10587
- const message = error3 instanceof Error ? error3.message : String(error3);
10588
- const logger = c8ctl9.getLogger();
10589
- logger.error(`Failed to element-template ${subcommand}: ${message}`);
11169
+ const definition = getModdleList(businessObject, "eventDefinitions")[0];
11170
+ const reference = businessObject.get("messageRef") ?? definition?.get("messageRef");
11171
+ if (isModdleElement(reference)) {
11172
+ if (getModdleString(reference, "name") !== void 0) {
11173
+ bindings.push({ type: "bpmn:Message#property", name: "name" });
11174
+ }
11175
+ const subscription = getModdleList(
11176
+ getExtensionElements(reference),
11177
+ "values"
11178
+ ).find((v) => v.$type === "zeebe:Subscription");
11179
+ if (subscription && getModdleString(subscription, "correlationKey") !== void 0) {
11180
+ bindings.push({
11181
+ type: "bpmn:Message#zeebe:subscription#property",
11182
+ name: "correlationKey"
11183
+ });
11184
+ }
11185
+ }
11186
+ return bindings;
11187
+ }
11188
+ function stringifyNumber(value) {
11189
+ return value === void 0 ? void 0 : String(value);
11190
+ }
11191
+ function getExtensionElements(businessObject) {
11192
+ return getModdleElement(businessObject, "extensionElements");
11193
+ }
11194
+
11195
+ // default-plugins/element-template/migration/report.ts
11196
+ function templateRef(template) {
11197
+ return {
11198
+ id: template.id,
11199
+ version: template.version ?? 0,
11200
+ name: template.name,
11201
+ deprecated: Boolean(template.deprecated)
11202
+ };
11203
+ }
11204
+ var sameField = (a, b) => a.key === b.key && a.bindingType === b.bindingType;
11205
+ function mergeFacts(all) {
11206
+ let moved = [];
11207
+ let set2 = [];
11208
+ let failedWrites = false;
11209
+ for (const facts of all) {
11210
+ const priorMoved = moved;
11211
+ const priorSet = set2;
11212
+ const overwritten = (field) => facts.moved.some((move) => sameField(move.to, field)) || facts.set.some((write) => sameField(write, field));
11213
+ const forwarded = (field) => facts.moved.some((move) => sameField(move.from, field));
11214
+ failedWrites ||= priorMoved.some(
11215
+ (move) => overwritten(move.to) && !forwarded(move.to)
11216
+ );
11217
+ moved = priorMoved.filter(
11218
+ (move) => !overwritten(move.to) && !forwarded(move.to)
11219
+ );
11220
+ set2 = priorSet.filter((write) => !overwritten(write) && !forwarded(write));
11221
+ for (const move of facts.moved) {
11222
+ const addition = priorSet.find((write) => sameField(write, move.from));
11223
+ if (addition) {
11224
+ set2.push({ ...move.to, value: move.value ?? addition.value });
11225
+ } else {
11226
+ const prior = priorMoved.find((item) => sameField(item.to, move.from));
11227
+ moved.push({
11228
+ ...move,
11229
+ from: prior?.from ?? move.from,
11230
+ transformed: Boolean(prior?.transformed) || move.transformed
11231
+ });
11232
+ }
11233
+ }
11234
+ for (const write of facts.set) {
11235
+ moved = moved.filter((move) => !sameField(move.to, write));
11236
+ set2 = set2.filter((prior) => !sameField(prior, write));
11237
+ set2.push(write);
11238
+ }
11239
+ if (facts.after) {
11240
+ const after = facts.after;
11241
+ const surviving = (field, value) => {
11242
+ const actual = find2(after, field.key, field.bindingType);
11243
+ return actual !== void 0 && (value === void 0 || actual.value === value);
11244
+ };
11245
+ failedWrites ||= moved.some((move) => !surviving(move.to, move.value)) || set2.some((write) => !surviving(write, write.value));
11246
+ moved = moved.filter((move) => surviving(move.to, move.value));
11247
+ set2 = set2.filter((write) => surviving(write, write.value));
11248
+ }
11249
+ failedWrites ||= Boolean(facts.failedWrites);
11250
+ }
11251
+ return {
11252
+ moved,
11253
+ set: set2,
11254
+ failedWrites,
11255
+ notes: all.flatMap((f) => f.notes),
11256
+ guardSkipped: all.flatMap((f) => f.guardSkipped),
11257
+ templateSkipped: all.flatMap((f) => f.templateSkipped),
11258
+ noMatch: all.flatMap((f) => f.noMatch),
11259
+ feelSkipped: all.flatMap((f) => f.feelSkipped)
11260
+ };
11261
+ }
11262
+ function propertyFor(template, key, bindingType) {
11263
+ return findPropertiesByTarget(
11264
+ template?.properties ?? [],
11265
+ key,
11266
+ bindingType
11267
+ )[0];
11268
+ }
11269
+ function fieldOf(template, key, bindingType) {
11270
+ const property = propertyFor(template, key, bindingType);
11271
+ const field = {
11272
+ key,
11273
+ bindingType: bindingType ?? property?.binding?.type ?? null
11274
+ };
11275
+ if (property?.label) {
11276
+ field.label = property.label;
11277
+ }
11278
+ if (property?.group) {
11279
+ field.group = property.group;
11280
+ const groupLabel = template?.groups?.find(
11281
+ (g) => g.id === property.group
11282
+ )?.label;
11283
+ if (groupLabel) {
11284
+ field.groupLabel = groupLabel;
11285
+ }
11286
+ }
11287
+ if (property?.id) {
11288
+ field.propertyId = property.id;
11289
+ }
11290
+ return field;
11291
+ }
11292
+ function inTemplateOrder(template, items, fieldKey) {
11293
+ const groups = template?.groups ?? [];
11294
+ const properties = template?.properties ?? [];
11295
+ const position = (item) => {
11296
+ const { key, bindingType } = fieldKey(item);
11297
+ const property = propertyFor(template, key, bindingType);
11298
+ const group = groups.findIndex((g) => g.id === property?.group);
11299
+ return [
11300
+ group === -1 ? groups.length : group,
11301
+ property ? properties.indexOf(property) : properties.length
11302
+ ];
11303
+ };
11304
+ return items.map((item) => ({ item, position: position(item) })).sort(
11305
+ (a, b) => a.position[0] - b.position[0] || a.position[1] - b.position[1]
11306
+ ).map(({ item }) => item);
11307
+ }
11308
+ function choiceName(template, field, value) {
11309
+ const property = propertyFor(template, field.key, field.bindingType);
11310
+ return property?.choices?.find((c) => c.value === value)?.name;
11311
+ }
11312
+ function find2(values, key, bindingType) {
11313
+ return values.find((v) => sameTarget(v, { key, bindingType }));
11314
+ }
11315
+ function isHidden(template, key, bindingType) {
11316
+ return propertyFor(template, key, bindingType)?.type === "Hidden";
11317
+ }
11318
+ function withNames(template, field, value) {
11319
+ const name2 = choiceName(template, field, value);
11320
+ return name2 ? { valueName: name2 } : {};
11321
+ }
11322
+ function buildReport({
11323
+ fromTemplate,
11324
+ toTemplate,
11325
+ before,
11326
+ after,
11327
+ facts,
11328
+ usedRecipe,
11329
+ refusal
11330
+ }) {
11331
+ const survivingMoves = facts.moved.filter((m) => {
11332
+ const source = find2(before, m.from.key, m.from.bindingType);
11333
+ const target = find2(after, m.to.key, m.to.bindingType);
11334
+ return source !== void 0 && target !== void 0 && (m.value !== void 0 ? target.value === m.value : m.transformed ? source.value === "" || target.value !== "" : target.value === source.value);
11335
+ });
11336
+ const survivingSets = facts.set.filter(
11337
+ (s) => find2(after, s.key, s.bindingType)?.value === s.value
11338
+ );
11339
+ const addedSets = survivingSets.filter(
11340
+ (s) => !find2(before, s.key, s.bindingType)
11341
+ );
11342
+ const claimedFrom = (v) => survivingMoves.some((m) => sameTarget(v, m.from));
11343
+ const claimedTo = (v) => survivingMoves.some((m) => sameTarget(v, m.to)) || addedSets.some((s) => sameTarget(v, s));
11344
+ const moved = survivingMoves.map((m) => {
11345
+ const from = fieldOf(fromTemplate, m.from.key, m.from.bindingType);
11346
+ const to = fieldOf(toTemplate, m.to.key, m.to.bindingType);
11347
+ const fromValue = find2(before, m.from.key, m.from.bindingType)?.value;
11348
+ const toValue = find2(after, m.to.key, m.to.bindingType)?.value ?? "";
11349
+ const item = {
11350
+ from,
11351
+ to,
11352
+ value: toValue,
11353
+ ...withNames(toTemplate, to, toValue),
11354
+ source: m.map ? "map" : "recipe"
11355
+ };
11356
+ if ((m.transformed || fromValue !== toValue) && fromValue !== void 0) {
11357
+ item.valueChange = {
11358
+ from: fromValue,
11359
+ to: toValue,
11360
+ ...nameOf("fromName", choiceName(fromTemplate, from, fromValue)),
11361
+ ...nameOf("toName", choiceName(toTemplate, to, toValue))
11362
+ };
11363
+ }
11364
+ return item;
11365
+ });
11366
+ const lostBySource = (v) => facts.moved.some(
11367
+ (m) => !survivingMoves.includes(m) && sameTarget(v, m.from) && find2(after, m.to.key, m.to.bindingType) === void 0
11368
+ );
11369
+ const dropped = before.filter(
11370
+ (v) => v.value !== "" && (!claimedFrom(v) && !find2(after, v.key, v.bindingType) || lostBySource(v))
11371
+ ).map((v) => {
11372
+ const field = fieldOf(fromTemplate, v.key, v.bindingType);
11373
+ return {
11374
+ ...field,
11375
+ value: v.value,
11376
+ ...withNames(fromTemplate, field, v.value)
11377
+ };
11378
+ });
11379
+ const added = after.filter(
11380
+ (v) => v.value !== "" && !find2(before, v.key, v.bindingType) && !isHidden(toTemplate, v.key, v.bindingType) && !claimedTo(v)
11381
+ ).map((v) => {
11382
+ const field = fieldOf(toTemplate, v.key, v.bindingType);
11383
+ return {
11384
+ ...field,
11385
+ value: v.value,
11386
+ ...withNames(toTemplate, field, v.value),
11387
+ source: "default"
11388
+ };
11389
+ });
11390
+ for (const s of addedSets) {
11391
+ const field = fieldOf(toTemplate, s.key, s.bindingType);
11392
+ const actual = find2(after, s.key, s.bindingType)?.value ?? "";
11393
+ added.push({
11394
+ ...field,
11395
+ value: actual,
11396
+ ...withNames(toTemplate, field, actual),
11397
+ source: "recipe"
11398
+ });
11399
+ }
11400
+ const changed = after.filter((v) => {
11401
+ const prior = find2(before, v.key, v.bindingType);
11402
+ return prior !== void 0 && prior.value !== v.value && !claimedTo(v) && !isHidden(toTemplate, v.key, v.bindingType);
11403
+ }).map((v) => {
11404
+ const prior = find2(before, v.key, v.bindingType);
11405
+ const field = fieldOf(toTemplate, v.key, v.bindingType);
11406
+ const fromValue = prior?.value ?? "";
11407
+ return {
11408
+ ...field,
11409
+ valueChange: {
11410
+ from: fromValue,
11411
+ to: v.value,
11412
+ ...nameOf("fromName", choiceName(fromTemplate, field, fromValue)),
11413
+ ...nameOf("toName", choiceName(toTemplate, field, v.value))
11414
+ },
11415
+ source: survivingSets.some((s) => sameTarget(v, s)) ? "recipe" : "default"
11416
+ };
11417
+ });
11418
+ const kept = after.filter(
11419
+ (v) => v.value !== "" && find2(before, v.key, v.bindingType)?.value === v.value && !claimedTo(v) && !isHidden(toTemplate, v.key, v.bindingType)
11420
+ ).map((v) => fieldOf(toTemplate, v.key, v.bindingType));
11421
+ const skipped = {
11422
+ guard: facts.guardSkipped,
11423
+ template: facts.templateSkipped,
11424
+ noMatch: facts.noMatch,
11425
+ feel: facts.feelSkipped,
11426
+ unchecked: uncheckedFields(fromTemplate, toTemplate)
11427
+ };
11428
+ return {
11429
+ from: templateRef(fromTemplate),
11430
+ to: templateRef(toTemplate),
11431
+ usedRecipe,
11432
+ refusal,
11433
+ dropped: inTemplateOrder(fromTemplate, dropped, (item) => item),
11434
+ added: inTemplateOrder(toTemplate, added, (item) => item),
11435
+ changed: inTemplateOrder(toTemplate, changed, (item) => item),
11436
+ moved: inTemplateOrder(toTemplate, moved, (item) => item.to),
11437
+ kept: inTemplateOrder(toTemplate, kept, (item) => item),
11438
+ notes: facts.notes,
11439
+ skipped,
11440
+ lossless: !facts.failedWrites && survivingMoves.length === facts.moved.filter(
11441
+ (move) => find2(before, move.from.key, move.from.bindingType)
11442
+ ).length && survivingSets.length === facts.set.length && dropped.length === 0 && skipped.guard.length === 0 && skipped.template.length === 0 && skipped.noMatch.length === 0 && skipped.unchecked.length === 0
11443
+ };
11444
+ }
11445
+ function uncheckedFields(fromTemplate, toTemplate) {
11446
+ return fromTemplate.properties.filter(
11447
+ (p) => p.binding && p.type !== "Hidden" && bindingTargetKey(p.binding) === void 0 && !toTemplate.properties.some(
11448
+ (t) => t.type !== "Hidden" && sameBinding(t.binding, p.binding)
11449
+ )
11450
+ ).map((p) => {
11451
+ const binding = { ...p.binding };
11452
+ const field = {
11453
+ key: String(binding.name ?? binding.property ?? p.id ?? ""),
11454
+ bindingType: p.binding?.type ?? null
11455
+ };
11456
+ if (p.label) field.label = p.label;
11457
+ if (p.id) field.propertyId = p.id;
11458
+ return field;
11459
+ });
11460
+ }
11461
+ function sameBinding(a, b) {
11462
+ if (!a || !b) return false;
11463
+ const x = { ...a };
11464
+ const y = { ...b };
11465
+ const keys = Object.keys(x);
11466
+ return keys.length === Object.keys(y).length && keys.every((k) => x[k] === y[k]);
11467
+ }
11468
+ function nameOf(field, name2) {
11469
+ return name2 === void 0 ? {} : { [field]: name2 };
11470
+ }
11471
+
11472
+ // default-plugins/element-template/migration/steps.ts
11473
+ import { isDeepStrictEqual } from "node:util";
11474
+
11475
+ // default-plugins/element-template/migration/recipe.ts
11476
+ var SUPPORTED_SCHEMA_VERSION = 1;
11477
+ var RecipeError = class extends Error {
11478
+ constructor(message) {
11479
+ super(`Invalid migration recipe: ${message}`);
11480
+ this.name = "RecipeError";
11481
+ }
11482
+ };
11483
+ function isRecord2(value) {
11484
+ return typeof value === "object" && value !== null && !Array.isArray(value);
11485
+ }
11486
+ function isScalar(value) {
11487
+ return typeof value === "string" || typeof value === "number" && Number.isFinite(value) || typeof value === "boolean";
11488
+ }
11489
+ function requireRecord(value, at) {
11490
+ if (!isRecord2(value)) {
11491
+ throw new RecipeError(`${at} must be an object`);
11492
+ }
11493
+ return value;
11494
+ }
11495
+ function rejectUnknownKeys(raw, allowed, at) {
11496
+ for (const key of Object.keys(raw)) {
11497
+ if (!allowed.includes(key)) {
11498
+ throw new RecipeError(`${at} has unknown property \`${key}\``);
11499
+ }
11500
+ }
11501
+ }
11502
+ function requireString(value, at) {
11503
+ if (typeof value !== "string" || value.trim() === "") {
11504
+ throw new RecipeError(`${at} must be a non-empty string`);
11505
+ }
11506
+ return value;
11507
+ }
11508
+ function requireScalar(value, at) {
11509
+ if (!isScalar(value)) {
11510
+ throw new RecipeError(`${at} must be a string, finite number or boolean`);
11511
+ }
11512
+ return String(value);
11513
+ }
11514
+ function parseNote(raw, at) {
11515
+ if (typeof raw === "string") {
11516
+ return { level: "info", message: requireString(raw, at) };
11517
+ }
11518
+ const obj = requireRecord(raw, at);
11519
+ rejectUnknownKeys(obj, ["level", "message"], at);
11520
+ const level = obj.level === void 0 ? "info" : obj.level;
11521
+ if (level !== "info" && level !== "warning") {
11522
+ throw new RecipeError(`${at}.level must be "info" or "warning"`);
11523
+ }
11524
+ return { level, message: requireString(obj.message, `${at}.message`) };
11525
+ }
11526
+ function parseValueMap(raw, at) {
11527
+ const obj = requireRecord(raw, at);
11528
+ rejectUnknownKeys(obj, ["rules", "default"], at);
11529
+ if (!Array.isArray(obj.rules) || obj.rules.length === 0) {
11530
+ throw new RecipeError(`${at}.rules must be a non-empty list`);
11531
+ }
11532
+ const rules = obj.rules.map((item, i) => {
11533
+ const rule = requireRecord(item, `${at}.rules[${i}]`);
11534
+ rejectUnknownKeys(rule, ["match", "value"], `${at}.rules[${i}]`);
11535
+ return {
11536
+ match: requireString(rule.match, `${at}.rules[${i}].match`),
11537
+ value: requireScalar(rule.value, `${at}.rules[${i}].value`)
11538
+ };
11539
+ });
11540
+ if (obj.default === void 0) {
11541
+ return { rules };
11542
+ }
11543
+ return { rules, default: requireScalar(obj.default, `${at}.default`) };
11544
+ }
11545
+ var GUARD_OPERATORS = [
11546
+ "equals",
11547
+ "matches",
11548
+ "in",
11549
+ "exists"
11550
+ ];
11551
+ function parseGuard(raw, at) {
11552
+ const obj = requireRecord(raw, at);
11553
+ rejectUnknownKeys(obj, ["path", ...GUARD_OPERATORS, "not"], at);
11554
+ const path = requireString(obj.path, `${at}.path`);
11555
+ const present = GUARD_OPERATORS.filter((op) => obj[op] !== void 0);
11556
+ if (present.length !== 1) {
11557
+ throw new RecipeError(
11558
+ `${at} must have exactly one of ${GUARD_OPERATORS.join(", ")}`
11559
+ );
11560
+ }
11561
+ const operator = present[0];
11562
+ if (operator === "exists") {
11563
+ if (obj.not !== void 0) {
11564
+ throw new RecipeError(
11565
+ `${at}.not is not allowed with \`exists\`; use \`exists: false\``
11566
+ );
11567
+ }
11568
+ if (typeof obj.exists !== "boolean") {
11569
+ throw new RecipeError(`${at}.exists must be a boolean`);
11570
+ }
11571
+ return { kind: "exists", path, exists: obj.exists };
11572
+ }
11573
+ if (obj.not !== void 0 && typeof obj.not !== "boolean") {
11574
+ throw new RecipeError(`${at}.not must be a boolean`);
11575
+ }
11576
+ const not = obj.not === true;
11577
+ if (operator === "equals") {
11578
+ return {
11579
+ kind: "equals",
11580
+ path,
11581
+ value: requireScalar(obj.equals, `${at}.equals`),
11582
+ not
11583
+ };
11584
+ }
11585
+ if (operator === "matches") {
11586
+ return {
11587
+ kind: "matches",
11588
+ path,
11589
+ pattern: requireString(obj.matches, `${at}.matches`),
11590
+ not
11591
+ };
11592
+ }
11593
+ if (!Array.isArray(obj.in)) {
11594
+ throw new RecipeError(`${at}.in must be a list`);
11595
+ }
11596
+ return {
11597
+ kind: "in",
11598
+ path,
11599
+ values: obj.in.map((v, i) => requireScalar(v, `${at}.in[${i}]`)),
11600
+ not
11601
+ };
11602
+ }
11603
+ function parseWhen(raw, at) {
11604
+ if (Array.isArray(raw)) {
11605
+ if (raw.length === 0) {
11606
+ throw new RecipeError(`${at}.when must not be an empty list`);
11607
+ }
11608
+ return raw.map((g, i) => parseGuard(g, `${at}.when[${i}]`));
11609
+ }
11610
+ return [parseGuard(raw, `${at}.when`)];
11611
+ }
11612
+ function parseLeaf(obj, at, inherited) {
11613
+ const hasFrom = obj.from !== void 0;
11614
+ const hasSet = obj.set !== void 0;
11615
+ const hasTemplate = obj.template !== void 0;
11616
+ if (Number(hasFrom) + Number(hasSet) + Number(hasTemplate) !== 1) {
11617
+ throw new RecipeError(
11618
+ `${at} must have exactly one of \`from\`, \`set\`, \`template\` (or \`rules\` for a group)`
11619
+ );
11620
+ }
11621
+ const base = {
11622
+ when: [
11623
+ ...inherited,
11624
+ ...obj.when === void 0 ? [] : parseWhen(obj.when, at)
11625
+ ],
11626
+ label: at,
11627
+ ...obj.note === void 0 ? {} : { note: parseNote(obj.note, `${at}.note`) }
11628
+ };
11629
+ const to = requireString(obj.to, `${at}.to`);
11630
+ if (hasFrom) {
11631
+ rejectUnknownKeys(obj, ["from", "to", "valueMap", "when", "note"], at);
11632
+ const entry = {
11633
+ ...base,
11634
+ kind: "rename",
11635
+ from: requireString(obj.from, `${at}.from`),
11636
+ to
11637
+ };
11638
+ if (obj.valueMap !== void 0) {
11639
+ entry.valueMap = parseValueMap(obj.valueMap, `${at}.valueMap`);
11640
+ }
11641
+ return entry;
11642
+ }
11643
+ if (hasSet) {
11644
+ rejectUnknownKeys(obj, ["set", "to", "when", "note"], at);
11645
+ return { ...base, kind: "set", to, value: requireScalar(obj.set, at) };
11646
+ }
11647
+ rejectUnknownKeys(obj, ["template", "to", "when", "note"], at);
11648
+ return {
11649
+ ...base,
11650
+ kind: "template",
11651
+ to,
11652
+ template: requireString(obj.template, `${at}.template`)
11653
+ };
11654
+ }
11655
+ function flattenNode(raw, at, inherited) {
11656
+ const obj = requireRecord(raw, at);
11657
+ if (obj.rules === void 0) {
11658
+ return [parseLeaf(obj, at, inherited)];
11659
+ }
11660
+ rejectUnknownKeys(obj, ["when", "rules"], at);
11661
+ if (obj.when === void 0) {
11662
+ throw new RecipeError(`${at} has \`rules\` but no \`when\``);
11663
+ }
11664
+ if (!Array.isArray(obj.rules) || obj.rules.length === 0) {
11665
+ throw new RecipeError(`${at}.rules must be a non-empty list`);
11666
+ }
11667
+ const guards = [...inherited, ...parseWhen(obj.when, at)];
11668
+ return obj.rules.flatMap(
11669
+ (child, i) => flattenNode(child, `${at}.rules[${i}]`, guards)
11670
+ );
11671
+ }
11672
+ function parseSource(raw, at) {
11673
+ const obj = requireRecord(raw, at);
11674
+ if (obj.kind !== "upgrade" && obj.kind !== "change") {
11675
+ throw new RecipeError(`${at}.kind must be "upgrade" or "change"`);
11676
+ }
11677
+ rejectUnknownKeys(
11678
+ obj,
11679
+ [
11680
+ "kind",
11681
+ "sourceTemplateId",
11682
+ obj.kind === "upgrade" ? "toVersion" : "minSourceVersion",
11683
+ "paths"
11684
+ ],
11685
+ at
11686
+ );
11687
+ const base = {
11688
+ sourceTemplateId: requireString(
11689
+ obj.sourceTemplateId,
11690
+ `${at}.sourceTemplateId`
11691
+ ),
11692
+ entries: []
11693
+ };
11694
+ const field = obj.kind === "upgrade" ? "toVersion" : "minSourceVersion";
11695
+ const version = obj[field];
11696
+ if ((obj.kind === "upgrade" || version !== void 0) && (typeof version !== "number" || !Number.isSafeInteger(version) || version < 0)) {
11697
+ throw new RecipeError(`${at}.${field} must be a non-negative safe integer`);
11698
+ }
11699
+ if (obj.paths !== void 0) {
11700
+ if (!Array.isArray(obj.paths)) {
11701
+ throw new RecipeError(`${at}.paths must be a list`);
11702
+ }
11703
+ base.entries = obj.paths.flatMap(
11704
+ (node, i) => flattenNode(node, `${at}.paths[${i}]`, [])
11705
+ );
11706
+ }
11707
+ if (obj.kind === "upgrade" && typeof version === "number") {
11708
+ return { ...base, kind: "upgrade", toVersion: version };
11709
+ }
11710
+ return {
11711
+ ...base,
11712
+ kind: "change",
11713
+ ...typeof version === "number" ? { minSourceVersion: version } : {}
11714
+ };
11715
+ }
11716
+ function parseRecipe(raw) {
11717
+ const obj = requireRecord(raw, "recipe");
11718
+ rejectUnknownKeys(obj, ["$schema", "schemaVersion", "sources"], "recipe");
11719
+ if (obj.$schema !== void 0 && typeof obj.$schema !== "string") {
11720
+ throw new RecipeError("recipe.$schema must be a string");
11721
+ }
11722
+ if (obj.schemaVersion !== SUPPORTED_SCHEMA_VERSION) {
11723
+ if (Number.isInteger(obj.schemaVersion) && Number(obj.schemaVersion) > SUPPORTED_SCHEMA_VERSION) {
11724
+ throw new RecipeError(
11725
+ `schemaVersion ${obj.schemaVersion} is newer than this c8ctl supports (${SUPPORTED_SCHEMA_VERSION}). Update c8ctl to use this recipe`
11726
+ );
11727
+ }
11728
+ throw new RecipeError(`schemaVersion must be ${SUPPORTED_SCHEMA_VERSION}`);
11729
+ }
11730
+ if (!Array.isArray(obj.sources) || obj.sources.length === 0) {
11731
+ throw new RecipeError("sources must be a non-empty list");
11732
+ }
11733
+ const sources = obj.sources.map(
11734
+ (item, i) => parseSource(item, `sources[${i}]`)
11735
+ );
11736
+ const seen = /* @__PURE__ */ new Set();
11737
+ for (const source of sources) {
11738
+ const version = source.kind === "upgrade" ? source.toVersion : source.minSourceVersion;
11739
+ const key = JSON.stringify([
11740
+ source.kind,
11741
+ source.sourceTemplateId,
11742
+ version ?? null
11743
+ ]);
11744
+ if (seen.has(key)) {
11745
+ throw new RecipeError(
11746
+ `source "${source.sourceTemplateId}" is declared twice for ${source.kind} at version ${version ?? "(unset)"}`
11747
+ );
11748
+ }
11749
+ seen.add(key);
11750
+ }
11751
+ return { schemaVersion: SUPPORTED_SCHEMA_VERSION, sources };
11752
+ }
11753
+ function validateRecipeOwner(recipe, owner) {
11754
+ for (const source of recipe.sources) {
11755
+ if (source.kind === "upgrade") {
11756
+ if (source.sourceTemplateId !== owner.id) {
11757
+ throw new RecipeError(
11758
+ `upgrade source must equal recipe owner "${owner.id}"`
11759
+ );
11760
+ }
11761
+ if (owner.version === void 0 || source.toVersion > owner.version) {
11762
+ throw new RecipeError(
11763
+ `upgrade version ${source.toVersion} exceeds owner version ${owner.version ?? "(unset)"}`
11764
+ );
11765
+ }
11766
+ } else if (source.sourceTemplateId === owner.id) {
11767
+ throw new RecipeError(
11768
+ `change source must differ from recipe owner "${owner.id}"`
11769
+ );
11770
+ }
11771
+ }
11772
+ }
11773
+ function readEmbeddedRecipe(template) {
11774
+ if (!isRecord2(template.metadata)) {
11775
+ return void 0;
11776
+ }
11777
+ const raw = template.metadata.migratesFrom;
11778
+ return raw === void 0 ? void 0 : parseRecipe(raw);
11779
+ }
11780
+
11781
+ // default-plugins/element-template/migration/steps.ts
11782
+ function versionOf(template) {
11783
+ return typeof template.version === "number" ? template.version : void 0;
11784
+ }
11785
+ function resolveCatalog(templates, authoritative = []) {
11786
+ const identity2 = (template) => JSON.stringify([template.id, versionOf(template) ?? 0]);
11787
+ const overrides = new Map(authoritative.map((t) => [identity2(t), t]));
11788
+ const catalog = /* @__PURE__ */ new Map();
11789
+ const conflicts = /* @__PURE__ */ new Set();
11790
+ for (const candidate of [...authoritative, ...templates]) {
11791
+ const key = identity2(candidate);
11792
+ const template = overrides.get(key) ?? candidate;
11793
+ const existing = catalog.get(key);
11794
+ if (existing && !isDeepStrictEqual(existing, template)) conflicts.add(key);
11795
+ else if (!existing) catalog.set(key, template);
11796
+ }
11797
+ const conflict = [...conflicts].sort()[0];
11798
+ if (conflict) {
11799
+ const template = catalog.get(conflict);
11800
+ throw new Error(
11801
+ `Conflicting definitions for template "${template?.id}" version ${template?.version}; supply one definition per identity.`
11802
+ );
11803
+ }
11804
+ return [...catalog.values()];
11805
+ }
11806
+ function latestOf(templates, id) {
11807
+ let best;
11808
+ for (const t of resolveCatalog(templates)) {
11809
+ const v = versionOf(t) ?? 0;
11810
+ if (t.id === id && (!best || v > (versionOf(best) ?? 0))) {
11811
+ best = t;
11812
+ }
11813
+ }
11814
+ return best;
11815
+ }
11816
+ function recipeSourcesFor(recipe, sourceId) {
11817
+ return (recipe?.sources ?? []).filter((s) => s.sourceTemplateId === sourceId);
11818
+ }
11819
+ function readPaths(entry) {
11820
+ const paths = [];
11821
+ if (entry.kind === "rename") {
11822
+ paths.push(entry.from);
11823
+ }
11824
+ if (entry.kind === "template") {
11825
+ paths.push(...[...entry.template.matchAll(TEMPLATE_REF)].map((m) => m[1]));
11826
+ }
11827
+ for (const guard of entry.when) {
11828
+ paths.push(guard.path);
11829
+ }
11830
+ return paths;
11831
+ }
11832
+ function findCoverageGap(steps, appliedId, appliedVersion, templates, hop) {
11833
+ let shape = templates.find(
11834
+ (t) => t.id === appliedId && (versionOf(t) ?? 0) === appliedVersion
11835
+ );
11836
+ for (const step of steps) {
11837
+ for (const entry of step.entries) {
11838
+ for (const path of readPaths(entry)) {
11839
+ const { bindingType, key } = splitBindingPrefix(path);
11840
+ if (!shape) {
11841
+ continue;
11842
+ }
11843
+ if (findPropertiesByTarget(shape.properties, key, bindingType).length === 0) {
11844
+ return `the recipe for ${appliedId} is incomplete: the step at version ${step.toVersion} reads "${path}", which reached version ${shape.version} does not define`;
11845
+ }
11846
+ }
11847
+ }
11848
+ shape = templates.find(
11849
+ (t) => t.id === appliedId && (versionOf(t) ?? 0) === step.toVersion
11850
+ );
11851
+ }
11852
+ for (const entry of hop?.entries ?? []) {
11853
+ for (const path of readPaths(entry)) {
11854
+ const { bindingType, key } = splitBindingPrefix(path);
11855
+ if (shape && findPropertiesByTarget(shape.properties, key, bindingType).length === 0) {
11856
+ return `the recipe for ${hop?.targetId} is incomplete: the change from ${appliedId} reads "${path}", which reached version ${shape.version} does not define`;
11857
+ }
11858
+ }
11859
+ }
11860
+ return null;
11861
+ }
11862
+ function reachableHop(recipe, sourceId, drainedVersion) {
11863
+ let best;
11864
+ for (const s of recipeSourcesFor(recipe, sourceId)) {
11865
+ if (s.kind !== "change" || s.minSourceVersion !== void 0 && s.minSourceVersion > drainedVersion) {
11866
+ continue;
11867
+ }
11868
+ if (!best || (s.minSourceVersion ?? -1) > (best.kind === "change" ? best.minSourceVersion ?? -1 : -1)) {
11869
+ best = s;
11870
+ }
11871
+ }
11872
+ return best;
11873
+ }
11874
+ function resolveSteps({
11875
+ appliedId,
11876
+ appliedVersion,
11877
+ target,
11878
+ templates,
11879
+ recipe
11880
+ }) {
11881
+ templates = resolveCatalog(templates, [target]);
11882
+ const sameId = target.id === appliedId;
11883
+ const targetVersion = versionOf(target) ?? 0;
11884
+ const targetRecipe = recipe ?? readEmbeddedRecipe(target);
11885
+ if (targetRecipe) validateRecipeOwner(targetRecipe, target);
11886
+ const sourceLatest = latestOf(templates, appliedId);
11887
+ const sourceRecipe = sameId ? targetRecipe : sourceLatest ? readEmbeddedRecipe(sourceLatest) : void 0;
11888
+ if (!sameId && sourceRecipe && sourceLatest)
11889
+ validateRecipeOwner(sourceRecipe, sourceLatest);
11890
+ const limit = sameId ? targetVersion : sourceLatest ? versionOf(sourceLatest) ?? appliedVersion : appliedVersion;
11891
+ const rungs = recipeSourcesFor(sourceRecipe, appliedId).flatMap(
11892
+ (s) => s.kind === "upgrade" && s.toVersion > appliedVersion && s.toVersion <= limit ? [{ toVersion: s.toVersion, entries: s.entries }] : []
11893
+ ).sort((a, b) => a.toVersion - b.toVersion);
11894
+ for (const rung of rungs) {
11895
+ if (!sameId || rung.toVersion !== targetVersion)
11896
+ loaded(templates, appliedId, rung.toVersion);
11897
+ }
11898
+ const reachedVersion = rungs.at(-1)?.toVersion ?? appliedVersion;
11899
+ const hop = sameId ? void 0 : reachableHop(targetRecipe, appliedId, reachedVersion);
11900
+ const refusal = findCoverageGap(
11901
+ rungs,
11902
+ appliedId,
11903
+ appliedVersion,
11904
+ templates,
11905
+ hop && { targetId: target.id, entries: hop.entries }
11906
+ );
11907
+ if (refusal) {
11908
+ return { steps: [], refusal };
11909
+ }
11910
+ const steps = rungs.map((rung) => ({
11911
+ kind: "version",
11912
+ templateId: appliedId,
11913
+ version: rung.toVersion,
11914
+ entries: rung.entries
11915
+ }));
11916
+ if (!sameId) {
11917
+ if (hop) {
11918
+ steps.push({
11919
+ kind: "hop",
11920
+ templateId: target.id,
11921
+ version: targetVersion,
11922
+ entries: hop.entries
11923
+ });
11924
+ } else if (targetRecipe) {
11925
+ const sources = recipeSourcesFor(targetRecipe, appliedId).filter(
11926
+ (source) => source.kind === "change"
11927
+ );
11928
+ const floor = Math.min(
11929
+ ...sources.map((source) => source.minSourceVersion ?? 0)
11930
+ );
11931
+ return {
11932
+ steps: [],
11933
+ refusal: sources.length === 0 ? `wrong source ID: the recipe has no change entry for "${appliedId}"` : `unmet source floor: the recipe requires source version ${floor}, but reached version is ${reachedVersion}; update the element to version ${floor} or later first`
11934
+ };
11935
+ }
11936
+ } else if (targetRecipe && steps.length === 0 && targetVersion !== appliedVersion) {
11937
+ return {
11938
+ steps: [],
11939
+ refusal: recipeSourcesFor(targetRecipe, appliedId).length === 0 ? `wrong source ID: the recipe has no upgrade entry for "${appliedId}"` : `no applicable upgrade: the recipe has no upgrade above applied version ${appliedVersion} through target version ${targetVersion}`
11940
+ };
11941
+ }
11942
+ return { steps, refusal: null };
11943
+ }
11944
+ function findSuccessors(candidates, appliedId, appliedVersion, templates) {
11945
+ candidates = resolveCatalog(candidates);
11946
+ templates = resolveCatalog([...templates, ...candidates]);
11947
+ const ids = new Set(candidates.map((c) => c.id));
11948
+ const found = [];
11949
+ for (const id of ids) {
11950
+ const latest = latestOf(
11951
+ candidates.filter((c) => !c.deprecated),
11952
+ id
11953
+ );
11954
+ if (latest && latest.id !== appliedId) {
11955
+ try {
11956
+ const result = resolveSteps({
11957
+ appliedId,
11958
+ appliedVersion,
11959
+ target: latest,
11960
+ templates: [...templates, latest]
11961
+ });
11962
+ if (!result.refusal && result.steps.some((s) => s.kind === "hop"))
11963
+ found.push(latest);
11964
+ } catch {
11965
+ }
11966
+ }
11967
+ }
11968
+ return found;
11969
+ }
11970
+ function loaded(templates, id, version) {
11971
+ const template = templates.find(
11972
+ (t) => t.id === id && (versionOf(t) ?? 0) === version
11973
+ );
11974
+ if (!template) {
11975
+ throw new Error(`Template "${id}" version ${version} is not available`);
11976
+ }
11977
+ return template;
11978
+ }
11979
+ function resolveApplications(templates, steps, target) {
11980
+ templates = resolveCatalog(templates, [target]);
11981
+ const applications = steps.map((step) => ({
11982
+ step,
11983
+ template: loaded(templates, step.templateId, step.version)
11984
+ }));
11985
+ const last = applications[applications.length - 1];
11986
+ if (!last || last.template.id !== target.id || versionOf(last.template) !== versionOf(target)) {
11987
+ applications.push({ step: null, template: target });
11988
+ }
11989
+ return applications;
11990
+ }
11991
+
11992
+ // default-plugins/element-template/migration/apply.ts
11993
+ function readAppliedTemplate(businessObject) {
11994
+ const id = getModdleString(businessObject, "modelerTemplate");
11995
+ if (id === void 0) {
11996
+ return void 0;
11997
+ }
11998
+ const asString = getModdleString(businessObject, "modelerTemplateVersion");
11999
+ const version = asString !== void 0 ? Number.parseInt(asString, 10) : getModdleNumber(businessObject, "modelerTemplateVersion") ?? 0;
12000
+ return !Number.isSafeInteger(version) || version < 0 ? void 0 : { id, version };
12001
+ }
12002
+ function availableNames(template) {
12003
+ return [
12004
+ ...new Set(
12005
+ template.properties.filter((p) => p.type !== "Hidden" && p.binding).map(
12006
+ (p) => bindingPath(p.binding?.type, bindingTargetKey(p.binding) ?? "")
12007
+ )
12008
+ )
12009
+ ].join(", ");
12010
+ }
12011
+ function resolveMapWrites(maps, before, fromTemplate, target) {
12012
+ const result = { writes: [], moved: [] };
12013
+ for (const map of maps) {
12014
+ const fromPath = bindingPath(map.from.bindingType, map.from.key);
12015
+ const toPath = bindingPath(map.to.bindingType, map.to.key);
12016
+ const label = `--map ${map.from.bindingType ? fromPath : map.from.key}=${map.to.bindingType ? toPath : map.to.key}`;
12017
+ if (fromTemplate.properties.length > 0 && findPropertiesByTarget(
12018
+ fromTemplate.properties,
12019
+ map.from.key,
12020
+ map.from.bindingType
12021
+ ).length === 0) {
12022
+ throw new Error(
12023
+ `${label}: source "${map.from.key}" is not a binding in template ${fromTemplate.id}@${fromTemplate.version}. Available: ${availableNames(fromTemplate)}`
12024
+ );
12025
+ }
12026
+ const entry = {
12027
+ kind: "set",
12028
+ to: map.to.bindingType ? toPath : map.to.key,
12029
+ value: "",
12030
+ when: [],
12031
+ label
12032
+ };
12033
+ const destinations = findPropertiesByTarget(
12034
+ target.properties,
12035
+ map.to.key,
12036
+ map.to.bindingType
12037
+ ).filter((p) => p.type !== "Hidden");
12038
+ if (destinations.length === 0) {
12039
+ throw new Error(
12040
+ `${label}: destination "${map.to.key}" is not a settable binding in template ${target.id}@${target.version}. Available: ${availableNames(target)}`
12041
+ );
12042
+ }
12043
+ validateTargets([entry], target);
12044
+ const sources = before.filter((v) => sameTarget(v, map.from));
12045
+ if (new Set(sources.map((v) => v.bindingType)).size > 1) {
12046
+ throw new Error(
12047
+ `${label}: source "${map.from.key}" is bound by several binding types; add a prefix such as input: or header:`
12048
+ );
12049
+ }
12050
+ const source = sources[0];
12051
+ if (!source || source.value === "") continue;
12052
+ const bindingType = destinations[0].binding?.type ?? null;
12053
+ result.writes.push({
12054
+ key: map.to.key,
12055
+ bindingType,
12056
+ value: source.value,
12057
+ entry: { ...entry, value: source.value }
12058
+ });
12059
+ result.moved.push({
12060
+ from: { key: source.key, bindingType: source.bindingType },
12061
+ to: { key: map.to.key, bindingType },
12062
+ transformed: false,
12063
+ map: true
12064
+ });
12065
+ }
12066
+ return result;
12067
+ }
12068
+ function valuesOf(element) {
12069
+ return enumerateElementValues(getExtensionElements(element.businessObject));
12070
+ }
12071
+ function applyApplication(modeler, catalog, element, application, mapWrites = []) {
12072
+ const { template, step } = application;
12073
+ const applied = readAppliedTemplate(element.businessObject);
12074
+ if (applied?.id === template.id && applied.version === (template.version ?? 0)) {
12075
+ return null;
12076
+ }
12077
+ const values = valuesOf(element);
12078
+ const clone = structuredClone(template);
12079
+ const {
12080
+ writes: recipeWrites,
12081
+ facts,
12082
+ activeProperties
12083
+ } = buildStepPlan(step?.entries ?? [], values, clone);
12084
+ assertNoAmbiguousWrites([...recipeWrites, ...mapWrites]);
12085
+ const stepWrites = [...recipeWrites, ...mapWrites];
12086
+ const writes = [
12087
+ ...stepWrites,
12088
+ ...carryOverWrites(stepWrites, values, template)
12089
+ ];
12090
+ const active = mapWrites.length > 0 ? validateDestinationValues(stepWrites, values, clone) : activeProperties;
12091
+ for (const w of writes) {
12092
+ for (const property of findPropertiesByTarget(
12093
+ clone.properties,
12094
+ w.key,
12095
+ w.bindingType
12096
+ )) {
12097
+ if (!active.has(property)) continue;
12098
+ property.value = normalizeDestinationValue(property, w.value);
12099
+ }
12100
+ }
12101
+ modeler.elementTemplates.set(
12102
+ catalog.map(
12103
+ (t) => t.id === clone.id && t.version === clone.version ? clone : t
12104
+ )
12105
+ );
12106
+ let current = modeler.elementTemplates.applyTemplate(element, clone) ?? element;
12107
+ const containers = findExtensionContainers2(
12108
+ getExtensionElements(current.businessObject)
12109
+ );
12110
+ for (const w of writes) {
12111
+ for (const property of findPropertiesByTarget(
12112
+ clone.properties,
12113
+ w.key,
12114
+ w.bindingType
12115
+ )) {
12116
+ if (!active.has(property)) continue;
12117
+ if (!property.binding) {
12118
+ continue;
12119
+ }
12120
+ const target = resolveBindingTarget2(property.binding, containers);
12121
+ if (target) {
12122
+ modeler.modeling.updateModdleProperties(current, target.child, {
12123
+ [target.property]: normalizeDestinationValue(property, w.value)
12124
+ });
12125
+ }
12126
+ }
12127
+ }
12128
+ current = modeler.elementTemplates.applyTemplate(current, clone) ?? current;
12129
+ const resolvedValue = (key, bindingType) => {
12130
+ const write = writes.find(
12131
+ (w) => w.key === key && w.bindingType === bindingType
12132
+ );
12133
+ const property = findPropertiesByTarget(
12134
+ clone.properties,
12135
+ key,
12136
+ bindingType
12137
+ ).find((property2) => active.has(property2));
12138
+ return write && property ? normalizeDestinationValue(property, write.value) : void 0;
12139
+ };
12140
+ return {
12141
+ element: current,
12142
+ facts: {
12143
+ ...facts,
12144
+ after: valuesOf(current),
12145
+ moved: facts.moved.map((move) => ({
12146
+ ...move,
12147
+ value: resolvedValue(move.to.key, move.to.bindingType)
12148
+ })),
12149
+ set: recipeWrites.filter(
12150
+ (write) => write.entry.kind === "set" || write.entry.kind === "template"
12151
+ ).map((write) => ({
12152
+ key: write.key,
12153
+ bindingType: write.bindingType,
12154
+ value: resolvedValue(write.key, write.bindingType) ?? write.value
12155
+ }))
12156
+ }
12157
+ };
12158
+ }
12159
+ function migrateElement({
12160
+ modeler,
12161
+ element,
12162
+ fromTemplate,
12163
+ target,
12164
+ templates,
12165
+ recipe,
12166
+ maps = []
12167
+ }) {
12168
+ const applied = readAppliedTemplate(element.businessObject);
12169
+ if (!applied || applied.id !== fromTemplate.id || applied.version !== (fromTemplate.version ?? 0)) {
12170
+ throw new Error(
12171
+ "Migration context does not match the element's applied template."
12172
+ );
12173
+ }
12174
+ templates = resolveCatalog(templates, [fromTemplate, target]);
12175
+ const { steps, refusal } = resolveSteps({
12176
+ appliedId: fromTemplate.id,
12177
+ appliedVersion: fromTemplate.version ?? 0,
12178
+ target,
12179
+ templates,
12180
+ recipe
12181
+ });
12182
+ const applications = resolveApplications(templates, steps, target);
12183
+ for (const { step, template } of applications) {
12184
+ if (step) {
12185
+ validateTargets(step.entries, template);
12186
+ }
12187
+ }
12188
+ const catalog = resolveCatalog(
12189
+ [fromTemplate, ...applications.map((a) => a.template)],
12190
+ [fromTemplate, target]
12191
+ );
12192
+ const before = valuesOf(element);
12193
+ const reportSource = fromTemplate.properties.length > 0 ? fromTemplate : {
12194
+ ...fromTemplate,
12195
+ properties: unreadBindings(element.businessObject).map((binding) => ({
12196
+ binding
12197
+ }))
12198
+ };
12199
+ const mapPlan = resolveMapWrites(maps, before, fromTemplate, target);
12200
+ const allFacts = [];
12201
+ let current = element;
12202
+ let mapsApplied = false;
12203
+ for (const [index, application] of applications.entries()) {
12204
+ const isFinal = index === applications.length - 1;
12205
+ const result = applyApplication(
12206
+ modeler,
12207
+ catalog,
12208
+ current,
12209
+ application,
12210
+ isFinal ? mapPlan.writes : []
12211
+ );
12212
+ if (result) {
12213
+ current = result.element;
12214
+ allFacts.push(result.facts);
12215
+ mapsApplied ||= isFinal;
12216
+ }
12217
+ }
12218
+ const finalApplied = readAppliedTemplate(current.businessObject);
12219
+ if (!finalApplied || finalApplied.id !== target.id || finalApplied.version !== (target.version ?? 0)) {
12220
+ throw new Error("Migration did not apply the target template identity.");
12221
+ }
12222
+ const facts = mergeFacts(allFacts);
12223
+ if (mapsApplied) {
12224
+ facts.moved.push(
12225
+ ...mapPlan.moved.map((move) => {
12226
+ const property = findPropertiesByTarget(
12227
+ target.properties,
12228
+ move.to.key,
12229
+ move.to.bindingType
12230
+ )[0];
12231
+ const write = mapPlan.writes.find((w) => sameTarget(w, move.to));
12232
+ return {
12233
+ ...move,
12234
+ value: property && write ? normalizeDestinationValue(property, write.value) : void 0
12235
+ };
12236
+ })
12237
+ );
12238
+ }
12239
+ const report = buildReport({
12240
+ fromTemplate: reportSource,
12241
+ toTemplate: target,
12242
+ before,
12243
+ after: allFacts.at(-1)?.after ?? before,
12244
+ facts,
12245
+ usedRecipe: steps.length > 0,
12246
+ refusal
12247
+ });
12248
+ return { element: current, report };
12249
+ }
12250
+
12251
+ // src/core/config.ts
12252
+ import { homedir, platform } from "node:os";
12253
+
12254
+ // src/core/runtime.ts
12255
+ import { readFileSync as readFileSync4 } from "node:fs";
12256
+ import { dirname as dirname2, join as join2 } from "node:path";
12257
+ import { fileURLToPath as fileURLToPath2 } from "node:url";
12258
+ var __filename = fileURLToPath2(import.meta.url);
12259
+ var __dirname2 = dirname2(__filename);
12260
+ var UNVERSIONED_DEV_BUILD = "0.0.0-semantically-released";
12261
+ function getVersion() {
12262
+ try {
12263
+ const packageJsonPath = join2(__dirname2, "..", "..", "package.json");
12264
+ const packageJson = JSON.parse(readFileSync4(packageJsonPath, "utf-8"));
12265
+ return packageJson.version || UNVERSIONED_DEV_BUILD;
12266
+ } catch {
12267
+ return UNVERSIONED_DEV_BUILD;
12268
+ }
12269
+ }
12270
+ var C8ctl = class {
12271
+ _activeProfile;
12272
+ _activeTenant;
12273
+ _outputMode = "text";
12274
+ _fields;
12275
+ _dryRun;
12276
+ _verbose;
12277
+ _resolvedBaseUrl;
12278
+ _deps;
12279
+ env = {
12280
+ version: getVersion(),
12281
+ nodeVersion: process.version,
12282
+ platform: process.platform,
12283
+ arch: process.arch,
12284
+ cwd: process.cwd(),
12285
+ rootDir: join2(__dirname2, "..", "..")
12286
+ };
12287
+ /**
12288
+ * Inject dependencies that cannot be imported at module level
12289
+ * due to circular imports. Must be called once during startup,
12290
+ * before any plugin or command accesses createClient/resolveTenantId/getLogger.
12291
+ */
12292
+ init(deps) {
12293
+ if (this._deps) {
12294
+ throw new Error("c8ctl.init() must only be called once");
12295
+ }
12296
+ this._deps = deps;
12297
+ }
12298
+ createClient(profileFlag, additionalSdkConfig) {
12299
+ if (!this._deps) {
12300
+ throw new Error("c8ctl.init() must be called before createClient()");
12301
+ }
12302
+ return this._deps.createClient(profileFlag, additionalSdkConfig);
12303
+ }
12304
+ resolveTenantId(profileFlag) {
12305
+ if (!this._deps) {
12306
+ throw new Error("c8ctl.init() must be called before resolveTenantId()");
12307
+ }
12308
+ return this._deps.resolveTenantId(profileFlag);
12309
+ }
12310
+ getLogger(mode) {
12311
+ if (!this._deps) {
12312
+ throw new Error("c8ctl.init() must be called before getLogger()");
12313
+ }
12314
+ return this._deps.getLogger(mode);
12315
+ }
12316
+ getUserDataDir() {
12317
+ if (!this._deps) {
12318
+ throw new Error("c8ctl.init() must be called before getUserDataDir()");
12319
+ }
12320
+ return this._deps.getUserDataDir();
12321
+ }
12322
+ npm(options) {
12323
+ if (!this._deps) {
12324
+ throw new Error("c8ctl.init() must be called before npm()");
12325
+ }
12326
+ return options.stdout === true ? this._deps.npm(options) : this._deps.npm(options);
12327
+ }
12328
+ // Expose env properties directly for plugin compatibility
12329
+ get version() {
12330
+ return this.env.version;
12331
+ }
12332
+ get nodeVersion() {
12333
+ return this.env.nodeVersion;
12334
+ }
12335
+ get platform() {
12336
+ return this.env.platform;
12337
+ }
12338
+ get arch() {
12339
+ return this.env.arch;
12340
+ }
12341
+ get cwd() {
12342
+ return this.env.cwd;
12343
+ }
12344
+ get activeProfile() {
12345
+ return this._activeProfile;
12346
+ }
12347
+ set activeProfile(value) {
12348
+ this._activeProfile = value;
12349
+ }
12350
+ get activeTenant() {
12351
+ return this._activeTenant;
12352
+ }
12353
+ set activeTenant(value) {
12354
+ this._activeTenant = value;
12355
+ }
12356
+ get outputMode() {
12357
+ return this._outputMode;
12358
+ }
12359
+ set outputMode(value) {
12360
+ this._outputMode = value;
12361
+ }
12362
+ get fields() {
12363
+ return this._fields;
12364
+ }
12365
+ set fields(value) {
12366
+ this._fields = value;
12367
+ }
12368
+ get dryRun() {
12369
+ return this._dryRun;
12370
+ }
12371
+ set dryRun(value) {
12372
+ this._dryRun = value;
12373
+ }
12374
+ get verbose() {
12375
+ return this._verbose;
12376
+ }
12377
+ set verbose(value) {
12378
+ this._verbose = value;
12379
+ }
12380
+ get resolvedBaseUrl() {
12381
+ return this._resolvedBaseUrl;
12382
+ }
12383
+ set resolvedBaseUrl(value) {
12384
+ this._resolvedBaseUrl = value;
12385
+ }
12386
+ };
12387
+ var c8ctl9 = new C8ctl();
12388
+
12389
+ // src/core/logger.ts
12390
+ function isRecord3(value) {
12391
+ return value != null && typeof value === "object" && !Array.isArray(value);
12392
+ }
12393
+
12394
+ // src/core/config.ts
12395
+ var VALIDATION_PATTERNS = {
12396
+ URL: /^https?:\/\//,
12397
+ CAMUNDA_CLOUD_REST_URL: /^https:\/\/[a-z]+-\d+\.zeebe\.camunda\.io(:443|)\/[a-z\d-]+\/?$/
12398
+ };
12399
+ var CAMUNDA_CLOUD_URL_PATTERN = VALIDATION_PATTERNS.CAMUNDA_CLOUD_REST_URL;
12400
+ var isWindows = platform() === "win32";
12401
+
12402
+ // src/core/update-check.ts
12403
+ var CHECK_INTERVAL_MS = 60 * 60 * 1e3;
12404
+
12405
+ // default-plugins/element-template/migration-output.ts
12406
+ var sensitiveName = (identity2) => {
12407
+ const name2 = identity2.replace(
12408
+ /(?:max(?:imum)?|budget)[ ._-]?(?:[a-z]+[ ._-]?)?tokens/gi,
12409
+ ""
12410
+ );
12411
+ return /password|passwd|secret|token|credential|api[._ -]?key|private[._ -]?key|authorization/i.test(
12412
+ name2
12413
+ );
12414
+ };
12415
+ var isSensitiveTarget = (targets, field) => {
12416
+ const types2 = targets.get(field.key);
12417
+ return types2 !== void 0 && [...types2].some(
12418
+ (bindingType) => sameTarget({ key: field.key, bindingType }, field)
12419
+ );
12420
+ };
12421
+ var templateSecretsOf = /* @__PURE__ */ new WeakMap();
12422
+ function templateSecrets(templates) {
12423
+ const cached = templateSecretsOf.get(templates);
12424
+ if (cached) return cached;
12425
+ const targets = /* @__PURE__ */ new Map();
12426
+ for (const template of templates) {
12427
+ for (const property of template.properties) {
12428
+ const key = bindingTargetKey(property.binding);
12429
+ if (key !== void 0 && (property.secret === true || sensitiveName(
12430
+ `${property.id ?? ""} ${property.label ?? ""} ${property.group ?? ""} ${template.groups?.find((group) => group.id === property.group)?.label ?? ""}`
12431
+ ))) {
12432
+ const types2 = targets.get(key) ?? /* @__PURE__ */ new Set();
12433
+ types2.add(property.binding?.type);
12434
+ targets.set(key, types2);
12435
+ }
12436
+ }
12437
+ }
12438
+ const defaults = [];
12439
+ for (const template of templates) {
12440
+ for (const property of template.properties) {
12441
+ const key = bindingTargetKey(property.binding);
12442
+ if (key !== void 0 && typeof property.value === "string" && (sensitiveName(key) || isSensitiveTarget(targets, {
12443
+ key,
12444
+ bindingType: property.binding?.type ?? null
12445
+ })))
12446
+ defaults.push(property.value);
12447
+ }
12448
+ }
12449
+ const result = { targets, defaults };
12450
+ templateSecretsOf.set(templates, result);
12451
+ return result;
12452
+ }
12453
+ function migrationRedactor(context) {
12454
+ const { targets, defaults } = templateSecrets(context.templates ?? []);
12455
+ const sensitive = (field) => sensitiveName(
12456
+ `${field.key} ${field.label ?? ""} ${field.group ?? ""} ${field.groupLabel ?? ""}`
12457
+ ) || isSensitiveTarget(targets, field);
12458
+ const secrets = /* @__PURE__ */ new Set();
12459
+ const remember = (...values) => {
12460
+ for (const value of values) {
12461
+ if (value) {
12462
+ secrets.add(value);
12463
+ secrets.add(JSON.stringify(value).slice(1, -1));
12464
+ }
12465
+ }
12466
+ };
12467
+ for (const value of context.values ?? []) {
12468
+ if (sensitive(value)) remember(value.value);
12469
+ }
12470
+ remember(...defaults);
12471
+ if (context.report) {
12472
+ for (const item of [...context.report.dropped, ...context.report.added]) {
12473
+ if (sensitive(item)) remember(item.value, item.valueName);
12474
+ }
12475
+ for (const item of context.report.changed) {
12476
+ if (sensitive(item))
12477
+ remember(
12478
+ item.valueChange.from,
12479
+ item.valueChange.to,
12480
+ item.valueChange.fromName,
12481
+ item.valueChange.toName
12482
+ );
12483
+ }
12484
+ for (const item of context.report.moved) {
12485
+ if (sensitive(item.from) || sensitive(item.to))
12486
+ remember(
12487
+ item.value,
12488
+ item.valueName,
12489
+ item.valueChange?.from,
12490
+ item.valueChange?.to,
12491
+ item.valueChange?.fromName,
12492
+ item.valueChange?.toName
12493
+ );
12494
+ }
12495
+ }
12496
+ const pattern = [...secrets].sort((a, b) => b.length - a.length).map((value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
12497
+ const matcher = pattern ? new RegExp(pattern, "g") : void 0;
12498
+ const text = (message) => matcher ? message.replace(matcher, "[REDACTED]") : message;
12499
+ return { sensitive, text };
12500
+ }
12501
+ function redactMigrationDiagnostic(message, context = {}) {
12502
+ return migrationRedactor(context).text(message);
12503
+ }
12504
+ function redactReport(report, redactor) {
12505
+ const { sensitive, text } = redactor;
12506
+ const change = { from: "[REDACTED]", to: "[REDACTED]" };
12507
+ const redacted = structuredClone(report);
12508
+ const scrub = (value) => {
12509
+ if (Array.isArray(value) || isRecord3(value)) {
12510
+ for (const [key, child] of Object.entries(value)) {
12511
+ if (typeof child === "string") {
12512
+ if (Array.isArray(value)) value[Number(key)] = text(child);
12513
+ else value[key] = text(child);
12514
+ } else scrub(child);
12515
+ }
12516
+ }
12517
+ };
12518
+ scrub(redacted);
12519
+ return {
12520
+ ...redacted,
12521
+ dropped: redacted.dropped.map(
12522
+ (item, index) => sensitive(report.dropped[index]) ? { ...item, value: "[REDACTED]", valueName: void 0 } : item
12523
+ ),
12524
+ added: redacted.added.map(
12525
+ (item, index) => sensitive(report.added[index]) ? { ...item, value: "[REDACTED]", valueName: void 0 } : item
12526
+ ),
12527
+ changed: redacted.changed.map(
12528
+ (item, index) => sensitive(report.changed[index]) ? { ...item, valueChange: change } : item
12529
+ ),
12530
+ moved: redacted.moved.map(
12531
+ (item, index) => sensitive(report.moved[index].from) || sensitive(report.moved[index].to) ? {
12532
+ ...item,
12533
+ value: "[REDACTED]",
12534
+ valueName: void 0,
12535
+ ...item.valueChange ? { valueChange: change } : {}
12536
+ } : item
12537
+ )
12538
+ };
12539
+ }
12540
+ function styles(color) {
12541
+ const wrap = (open, close) => (text) => color ? `\x1B[${open}m${text}\x1B[${close}m` : text;
12542
+ return {
12543
+ bold: wrap(1, 22),
12544
+ dim: wrap(2, 22),
12545
+ red: wrap(31, 39),
12546
+ green: wrap(32, 39),
12547
+ yellow: wrap(33, 39),
12548
+ blue: wrap(34, 39),
12549
+ cyan: wrap(36, 39)
12550
+ };
12551
+ }
12552
+ function templateName(ref) {
12553
+ const name2 = (ref.name ?? ref.id).replace(/\s*\(deprecated\)/i, "");
12554
+ return `${name2}${ref.deprecated ? " (deprecated)" : ""} v${ref.version}`;
12555
+ }
12556
+ function valueText(value, name2) {
12557
+ return name2 && name2 !== value ? name2 : value;
12558
+ }
12559
+ function shouldUseColor(stream) {
12560
+ if (process.env.NO_COLOR !== void 0 && process.env.NO_COLOR !== "") {
12561
+ return false;
12562
+ }
12563
+ if (process.env.FORCE_COLOR !== void 0 && process.env.FORCE_COLOR !== "0") {
12564
+ return true;
12565
+ }
12566
+ return stream.isTTY === true;
12567
+ }
12568
+ var MAX_LABEL_WIDTH = 28;
12569
+ var MAX_VALUE_WIDTH = 40;
12570
+ var NARROW_COLUMNS = 100;
12571
+ function truncate(text) {
12572
+ return text.length > MAX_VALUE_WIDTH ? `${text.slice(0, MAX_VALUE_WIDTH - 1)}\u2026` : text;
12573
+ }
12574
+ function plain(segments) {
12575
+ return segments.map(([text]) => text).join("");
12576
+ }
12577
+ function pad(text, width) {
12578
+ return text.length >= width ? text : text + " ".repeat(width - text.length);
12579
+ }
12580
+ function fieldLabel(field) {
12581
+ return field.label ?? field.key;
12582
+ }
12583
+ function groupName(field) {
12584
+ return field.groupLabel ?? field.group;
12585
+ }
12586
+ function sourceText(source) {
12587
+ switch (source) {
12588
+ case "recipe":
12589
+ return "set by recipe";
12590
+ case "map":
12591
+ return "--map";
12592
+ case "default":
12593
+ return "template default";
12594
+ case "fixed":
12595
+ return "fixed by template";
12596
+ }
12597
+ }
12598
+ function wasText(from, to) {
12599
+ const label = fieldLabel(from);
12600
+ if (groupName(from) !== groupName(to)) {
12601
+ const group = groupName(from);
12602
+ return `was ${group ? `${group} \u203A ` : ""}${label}`;
12603
+ }
12604
+ return label !== fieldLabel(to) ? `was ${label}` : "";
12605
+ }
12606
+ function rankOf(template, field) {
12607
+ const groups = template?.groups ?? [];
12608
+ const properties = template?.properties ?? [];
12609
+ const property = properties.findIndex(
12610
+ (p) => field.propertyId !== void 0 && p.id === field.propertyId || sameTarget(
12611
+ { key: bindingTargetKey(p.binding), bindingType: p.binding?.type },
12612
+ field
12613
+ )
12614
+ );
12615
+ const declared = groups.findIndex((g) => g.id === field.group);
12616
+ const group = field.group === void 0 ? groups.length + properties.length + 1 : declared !== -1 ? declared : groups.length + Math.max(
12617
+ 0,
12618
+ properties.findIndex((p) => p.group === field.group)
12619
+ );
12620
+ return [group, property === -1 ? properties.length : property];
12621
+ }
12622
+ function renameLines(renames) {
12623
+ const dir = (key) => key.slice(0, key.lastIndexOf(".") + 1);
12624
+ const base = (key) => key.slice(key.lastIndexOf(".") + 1);
12625
+ const buckets = /* @__PURE__ */ new Map();
12626
+ for (const rename of renames) {
12627
+ const same = base(rename.from) === base(rename.to);
12628
+ const bucket = same ? `${dir(rename.from)}\0${dir(rename.to)}` : "";
12629
+ const list = buckets.get(bucket || `${rename.from}`) ?? [];
12630
+ list.push(rename);
12631
+ buckets.set(bucket || `${rename.from}`, list);
12632
+ }
12633
+ const lines = [];
12634
+ for (const [bucket, list] of buckets) {
12635
+ if (list.length > 1 && !bucket.startsWith("")) {
12636
+ const [from, to] = bucket.split("\0");
12637
+ lines.push(`${from}* \u2192 ${to}* (${list.length})`);
12638
+ } else {
12639
+ for (const r of list) lines.push(`${r.from} \u2192 ${r.to}`);
12640
+ }
12641
+ }
12642
+ return lines;
12643
+ }
12644
+ function rowsOf(report, targetTemplate, s) {
12645
+ const shown = (value, name2, stored) => {
12646
+ const text = valueText(value, name2);
12647
+ return truncate(stored && text !== value ? `${text} [${value}]` : text);
12648
+ };
12649
+ const base = (field) => ({
12650
+ group: field.group,
12651
+ groupLabel: groupName(field),
12652
+ label: fieldLabel(field),
12653
+ identity: `${groupName(field) ?? ""}\0${fieldLabel(field)}`,
12654
+ key: field.key,
12655
+ rank: rankOf(targetTemplate, field)
12656
+ });
12657
+ const change = (c) => [
12658
+ [shown(c.from, c.fromName, false), s.red],
12659
+ [" \u2192 ", s.dim],
12660
+ [shown(c.to, c.toName, true), s.green]
12661
+ ];
12662
+ const rows = [];
12663
+ for (const a of report.added) {
12664
+ rows.push({
12665
+ ...base(a),
12666
+ marker: "+",
12667
+ value: [[shown(a.value, a.valueName, true), s.green]],
12668
+ source: sourceText(a.source)
12669
+ });
12670
+ }
12671
+ for (const c of report.changed) {
12672
+ rows.push({
12673
+ ...base(c),
12674
+ marker: "~",
12675
+ value: change(c.valueChange),
12676
+ source: sourceText(c.source)
12677
+ });
12678
+ }
12679
+ for (const m of report.moved) {
12680
+ const common = base(m.to);
12681
+ if (m.valueChange) {
12682
+ rows.push({
12683
+ ...common,
12684
+ marker: "~",
12685
+ value: change(m.valueChange),
12686
+ source: sourceText(m.source)
12687
+ });
12688
+ continue;
12689
+ }
12690
+ const was = wasText(m.from, m.to);
12691
+ rows.push({
12692
+ ...common,
12693
+ marker: ">",
12694
+ value: [[shown(m.value, m.valueName, false)]],
12695
+ source: was,
12696
+ ...!was && m.from.key !== m.to.key ? { rename: { from: m.from.key, to: m.to.key } } : {}
12697
+ });
12698
+ }
12699
+ rows.sort((a, b) => a.rank[0] - b.rank[0] || a.rank[1] - b.rank[1]);
12700
+ const dropped = report.dropped.map((d) => {
12701
+ const group = groupName(d);
12702
+ return {
12703
+ ...base(d),
12704
+ marker: "-",
12705
+ label: `${group ? `${group} \u203A ` : ""}${fieldLabel(d)}`,
12706
+ value: [[shown(d.value, d.valueName, false), s.red]],
12707
+ source: ""
12708
+ };
12709
+ });
12710
+ return { rows, dropped };
12711
+ }
12712
+ function renderReportText(report, {
12713
+ elementId,
12714
+ elementName,
12715
+ color,
12716
+ recipe,
12717
+ recipePath,
12718
+ recipeOwner,
12719
+ targetTemplate,
12720
+ authorization,
12721
+ columns,
12722
+ redaction
12723
+ }) {
12724
+ const redactor = migrationRedactor({ ...redaction, report });
12725
+ elementId = redactor.text(elementId);
12726
+ elementName = elementName ? redactor.text(elementName) : void 0;
12727
+ report = redactReport(report, redactor);
12728
+ const s = styles(color);
12729
+ const lines = [];
12730
+ lines.push(
12731
+ s.bold(elementName ? `${elementName} (${elementId})` : elementId),
12732
+ ` ${s.dim(templateName(report.from))} ${s.dim("\u2192")} ${s.bold(templateName(report.to))}`,
12733
+ s.dim(
12734
+ ` ${report.from.id}@${report.from.version} \u2192 ${report.to.id}@${report.to.version}`
12735
+ )
12736
+ );
12737
+ if (report.refusal) {
12738
+ lines.push(s.yellow(` recipe not used: ${redactor.text(report.refusal)}`));
12739
+ } else if (recipe === "file") {
12740
+ lines.push(
12741
+ s.dim(` recipe: ${recipePath ? redactor.text(recipePath) : "file"}`)
12742
+ );
12743
+ } else if (recipe === "embedded") {
12744
+ lines.push(s.dim(` recipe: embedded in ${recipeOwner ?? report.to.id}`));
12745
+ } else {
12746
+ lines.push(s.dim(" no recipe: values carried over by key"));
12747
+ }
12748
+ const { rows, dropped } = rowsOf(report, targetTemplate, s);
12749
+ const all = [...rows, ...dropped];
12750
+ const labelWidth = Math.min(
12751
+ MAX_LABEL_WIDTH,
12752
+ Math.max(0, ...all.map((r) => r.label.length))
12753
+ );
12754
+ const valueWidth = Math.max(0, ...all.map((r) => plain(r.value).length));
12755
+ const narrow = columns !== void 0 && columns < NARROW_COLUMNS;
12756
+ const valueColumn = 2 + 2 + labelWidth + 2;
12757
+ const colorOf = (marker) => marker === "+" ? s.green : marker === "-" ? s.red : marker === "~" ? s.yellow : s.cyan;
12758
+ const collides = /* @__PURE__ */ new Set();
12759
+ const seen = /* @__PURE__ */ new Map();
12760
+ for (const r of all) {
12761
+ const first = seen.get(r.identity);
12762
+ if (first === void 0) seen.set(r.identity, r.key);
12763
+ else if (first !== r.key) collides.add(r.identity);
12764
+ }
12765
+ const emit = (r) => {
12766
+ const paint = r.marker === "+" || r.marker === "-" ? colorOf(r.marker) : void 0;
12767
+ const label = pad(r.label, labelWidth);
12768
+ const value = r.value.map(([text, style]) => style ? style(text) : text).join("");
12769
+ const gap = " ".repeat(Math.max(0, valueWidth - plain(r.value).length));
12770
+ const markerText = s.bold(colorOf(r.marker)(r.marker));
12771
+ const labelText = paint ? paint(label) : label;
12772
+ if (r.source && !narrow) {
12773
+ lines.push(
12774
+ ` ${markerText} ${labelText} ${value}${gap} ${s.dim(r.source)}`
12775
+ );
12776
+ } else {
12777
+ lines.push(` ${markerText} ${labelText} ${value}`.trimEnd());
12778
+ if (r.source) lines.push(`${" ".repeat(valueColumn)}${s.dim(r.source)}`);
12779
+ }
12780
+ if (collides.has(r.identity)) {
12781
+ lines.push(`${" ".repeat(valueColumn)}${s.dim(r.key)}`);
12782
+ }
12783
+ };
12784
+ let current = null;
12785
+ let groupRenames = [];
12786
+ const flushRenames = () => {
12787
+ const out = renameLines(groupRenames);
12788
+ out.forEach((text, i) => {
12789
+ const lead = i === 0 ? "keys renamed: " : " ".repeat("keys renamed: ".length);
12790
+ lines.push(s.dim(` ${lead}${text}`));
12791
+ });
12792
+ groupRenames = [];
12793
+ };
12794
+ for (const r of rows) {
12795
+ if (current !== r.group) {
12796
+ if (current !== null) flushRenames();
12797
+ current = r.group;
12798
+ lines.push("", ` ${s.bold(r.groupLabel ?? "(no group)")}`);
12799
+ }
12800
+ emit(r);
12801
+ if (r.rename) groupRenames.push(r.rename);
12802
+ }
12803
+ if (current !== null) flushRenames();
12804
+ if (dropped.length > 0) {
12805
+ lines.push("", ` ${s.bold("Dropped")}`);
12806
+ for (const r of dropped) emit(r);
12807
+ }
12808
+ if (report.notes.length > 0) {
12809
+ lines.push("", ` ${s.bold("Notes")}`);
12810
+ for (const note of report.notes) {
12811
+ lines.push(
12812
+ note.level === "warning" ? s.yellow(` \u26A0\uFE0F ${note.message}`) : s.blue(` \u2139\uFE0F ${note.message}`)
12813
+ );
12814
+ }
12815
+ }
12816
+ const { guard, template, noMatch, feel, unchecked } = report.skipped;
12817
+ if (guard.length + template.length + noMatch.length + feel.length + unchecked.length > 0) {
12818
+ lines.push("", ` ${s.bold("Needs attention")}`);
12819
+ for (const g of guard) {
12820
+ lines.push(` Condition not met, not moved: ${g.from} \u2192 ${g.to}`);
12821
+ }
12822
+ for (const t of template) {
12823
+ lines.push(` Not composed, missing ${t.missing.join(", ")}: ${t.to}`);
12824
+ }
12825
+ for (const n of noMatch) {
12826
+ lines.push(
12827
+ ` No value rule matched, target default kept: ${n.from} \u2192 ${n.to}`
12828
+ );
12829
+ }
12830
+ for (const f of feel) {
12831
+ lines.push(
12832
+ ` FEEL expression moved as-is, value rules not applied: ${f.from} \u2192 ${f.to}`
12833
+ );
12834
+ }
12835
+ for (const u of unchecked) {
12836
+ lines.push(
12837
+ ` Not checked, ${u.bindingType} binding not kept by the target: ${u.label ?? u.key}`
12838
+ );
12839
+ }
12840
+ }
12841
+ const updated = report.added.length + report.changed.length + report.moved.length;
12842
+ const lost = report.dropped.length + guard.length + template.length + noMatch.length + unchecked.length;
12843
+ const tail = authorization === "required" ? ". Requires --allow-lossy before writing." : authorization === "authorized" ? ". Authorized with --allow-lossy." : "";
12844
+ const counts = `${updated} updated, ${report.kept.length} kept unchanged, ${lost} lost${tail}`;
12845
+ lines.push(
12846
+ "",
12847
+ report.lossless ? s.green(` \u2705 ${counts}`) : s.yellow(` \u26A0\uFE0F ${counts}`)
12848
+ );
12849
+ return `${lines.join("\n")}
12850
+ `;
12851
+ }
12852
+ function renderLegend(color) {
12853
+ const s = styles(color);
12854
+ return [
12855
+ s.green("+ new"),
12856
+ s.yellow("~ changed"),
12857
+ s.cyan("> moved"),
12858
+ s.red("- dropped")
12859
+ ].join(" ");
12860
+ }
12861
+ function reportToJson(report, {
12862
+ elementId,
12863
+ elementName,
12864
+ recipe,
12865
+ recipePath,
12866
+ recipeOwner,
12867
+ dryRun,
12868
+ file,
12869
+ redaction
12870
+ }) {
12871
+ const redactor = migrationRedactor({ ...redaction, report });
12872
+ const { text } = redactor;
12873
+ report = redactReport(report, redactor);
12874
+ return {
12875
+ elementId: text(elementId),
12876
+ ...elementName ? { elementName: text(elementName) } : {},
12877
+ dryRun,
12878
+ ...file ? { file: text(file) } : {},
12879
+ from: report.from,
12880
+ to: report.to,
12881
+ recipe: {
12882
+ source: recipe,
12883
+ ...recipe === "file" && recipePath ? { path: text(recipePath) } : {},
12884
+ ...recipe === "embedded" ? { owner: recipeOwner ?? report.to.id } : {},
12885
+ used: report.usedRecipe,
12886
+ refusal: report.refusal
12887
+ },
12888
+ lossless: report.lossless,
12889
+ counts: {
12890
+ moved: report.moved.length,
12891
+ added: report.added.length,
12892
+ changed: report.changed.length,
12893
+ dropped: report.dropped.length,
12894
+ kept: report.kept.length
12895
+ },
12896
+ report: {
12897
+ moved: report.moved,
12898
+ added: report.added,
12899
+ changed: report.changed,
12900
+ dropped: report.dropped,
12901
+ kept: report.kept,
12902
+ notes: report.notes,
12903
+ skipped: report.skipped
12904
+ }
12905
+ };
12906
+ }
12907
+
12908
+ // default-plugins/element-template/commands/migrate.ts
12909
+ if (!globalThis.c8ctl) throw new Error("c8ctl runtime not initialised");
12910
+ var c8ctl10 = globalThis.c8ctl;
12911
+ var require4 = createRequire3(import.meta.url);
12912
+ var COMMAND = "element-template update";
12913
+ var USAGE = "c8ctl element-template update <template-id> [<element-id>] [<file.bpmn>] [--to <template>[@<n>]] [--recipe <file>] [--map <from>=<to>]... [--in-place]";
12914
+ function readFlagValue(args, index, flag) {
12915
+ const arg = args[index];
12916
+ if (arg.startsWith(`${flag}=`)) {
12917
+ return { value: arg.slice(flag.length + 1), skip: 0 };
12918
+ }
12919
+ const next = args[index + 1];
12920
+ if (next === void 0 || next.startsWith("-")) {
12921
+ throw new Error(`${flag} requires a value`);
12922
+ }
12923
+ return { value: next, skip: 1 };
12924
+ }
12925
+ function parseMigrateArgs(args) {
12926
+ const parsed = {
12927
+ inPlace: false,
12928
+ allowLossy: false,
12929
+ to: void 0,
12930
+ recipePath: void 0,
12931
+ maps: [],
12932
+ positionals: []
12933
+ };
12934
+ const valueFlag = (arg, flag) => arg === flag || arg.startsWith(`${flag}=`);
12935
+ for (let i = 0; i < args.length; i++) {
12936
+ const arg = args[i];
12937
+ if (arg === "--") {
12938
+ parsed.positionals.push(...args.slice(i + 1));
12939
+ break;
12940
+ }
12941
+ if (arg === "--in-place" || arg === "-i") {
12942
+ parsed.inPlace = true;
12943
+ } else if (arg === "--allow-lossy") {
12944
+ parsed.allowLossy = true;
12945
+ } else if (valueFlag(arg, "--recipe")) {
12946
+ const { value, skip } = readFlagValue(args, i, "--recipe");
12947
+ if (value === "") throw new Error("--recipe requires a value");
12948
+ parsed.recipePath = value;
12949
+ i += skip;
12950
+ } else if (valueFlag(arg, "--to")) {
12951
+ const { value, skip } = readFlagValue(args, i, "--to");
12952
+ if (value === "") throw new Error("--to requires a value");
12953
+ parsed.to = value;
12954
+ i += skip;
12955
+ } else if (valueFlag(arg, "--map")) {
12956
+ const { value, skip } = readFlagValue(args, i, "--map");
12957
+ parsed.maps.push(value);
12958
+ i += skip;
12959
+ } else if (arg.startsWith("-")) {
12960
+ throw new Error(`Unknown flag: ${arg}`);
12961
+ } else {
12962
+ parsed.positionals.push(arg);
12963
+ }
12964
+ }
12965
+ return parsed;
12966
+ }
12967
+ function resolveMigrateArgs(args) {
12968
+ const parsed = parseMigrateArgs(args);
12969
+ const [templateId, ...rest] = parsed.positionals;
12970
+ if (!templateId) {
12971
+ throw new Error(`Missing template-id argument. Usage: ${USAGE}`);
12972
+ }
12973
+ if (templateId.toLowerCase().endsWith(".bpmn")) {
12974
+ throw new Error(
12975
+ `"${templateId}" is a BPMN file; the first argument is the applied template ID. Usage: ${USAGE}`
12976
+ );
12977
+ }
12978
+ if (templateId.includes("@")) {
12979
+ throw new Error(
12980
+ `The template selector does not take a version ("${templateId}"). To pick the target version, use --to <template-id>@<n>.`
12981
+ );
12982
+ }
12983
+ if (rest.length > 2) {
12984
+ throw new Error(`Unexpected argument: ${rest[2]}. Usage: ${USAGE}`);
12985
+ }
12986
+ let elementId;
12987
+ let bpmnFilePath;
12988
+ if (rest.length === 2) {
12989
+ [elementId, bpmnFilePath] = rest;
12990
+ } else if (rest.length === 1) {
12991
+ if (rest[0].toLowerCase().endsWith(".bpmn") || existsSync5(rest[0])) {
12992
+ bpmnFilePath = rest[0];
12993
+ } else {
12994
+ elementId = rest[0];
12995
+ }
12996
+ }
12997
+ return { parsed, templateId, elementId, bpmnFilePath };
12998
+ }
12999
+ function parseMapArg(arg) {
13000
+ const eq = arg.indexOf("=");
13001
+ if (eq <= 0 || eq === arg.length - 1) {
13002
+ throw new Error(
13003
+ `Invalid --map format: "${arg}". Expected <from>=<to> (e.g. --map maxTokens=limit)`
13004
+ );
13005
+ }
13006
+ const side = (text) => {
13007
+ const colon = text.indexOf(":");
13008
+ if (colon === -1) return { key: text, bindingType: null };
13009
+ const prefix2 = text.slice(0, colon);
13010
+ const bindingType = BINDING_TYPE_SHORTHANDS[prefix2];
13011
+ if (!bindingType) {
13012
+ const valid = Object.keys(BINDING_TYPE_SHORTHANDS).join(", ");
13013
+ throw new Error(
13014
+ `Unknown binding type prefix "${prefix2}" in --map "${arg}". Valid prefixes: ${valid}`
13015
+ );
13016
+ }
13017
+ return { key: text.slice(colon + 1), bindingType };
13018
+ };
13019
+ return { from: side(arg.slice(0, eq)), to: side(arg.slice(eq + 1)) };
13020
+ }
13021
+ function isMigrationTemplate(template) {
13022
+ return typeof template.id === "string";
13023
+ }
13024
+ function migrationTemplates(templates) {
13025
+ return templates.filter(isMigrationTemplate);
13026
+ }
13027
+ function compatibleTemplates(templates, engineVersion) {
13028
+ return migrationTemplates(
13029
+ templates.filter((template) => isEngineCompatible(template, engineVersion))
13030
+ );
13031
+ }
13032
+ function loadRecipeFile(path) {
13033
+ let raw;
13034
+ try {
13035
+ raw = JSON.parse(readFileSync5(resolvePath4(path), "utf-8"));
13036
+ } catch (error3) {
13037
+ const message = error3 instanceof Error ? error3.message : String(error3);
13038
+ throw new Error(`Cannot read recipe ${path}: ${message}`);
13039
+ }
13040
+ return parseRecipe(raw);
13041
+ }
13042
+ function embeddedRecipe(template) {
13043
+ try {
13044
+ return readEmbeddedRecipe(template);
13045
+ } catch (error3) {
13046
+ if (error3 instanceof RecipeError) {
13047
+ throw new Error(
13048
+ `Template ${template.id}@${template.version} carries an unusable recipe. ${error3.message}`
13049
+ );
13050
+ }
13051
+ throw error3;
13052
+ }
13053
+ }
13054
+ function createModeler() {
13055
+ const vendor = require4(resolveVendorBundle());
13056
+ return new vendor.Modeler({
13057
+ additionalModules: [
13058
+ vendor.HeadlessTextRendererModule,
13059
+ vendor.CloudElementTemplatesCoreModule
13060
+ ],
13061
+ moddleExtensions: { zeebe: vendor.ZeebeModdleExtension }
13062
+ });
13063
+ }
13064
+ async function resolveTarget({
13065
+ templateId,
13066
+ to,
13067
+ executionPlatformVersion,
13068
+ cachedTemplates
13069
+ }) {
13070
+ const arg = to ?? templateId;
13071
+ const ref = parseTemplateRef(arg);
13072
+ if (ref?.kind === "id") {
13073
+ requireCachePresent();
13074
+ resolveCatalog(
13075
+ migrationTemplates(cachedTemplates.filter((t) => t.id === ref.id))
13076
+ );
13077
+ }
13078
+ const target = ref?.kind === "id" ? await resolveOotbTemplate(ref, {
13079
+ executionPlatformVersion,
13080
+ requireEngineCompatibility: true,
13081
+ templates: cachedTemplates
13082
+ }) : await readTemplateFromPathOrUrl(arg);
13083
+ if (!isMigrationTemplate(target)) {
13084
+ throw new Error("The target template has no id.");
13085
+ }
13086
+ return target;
13087
+ }
13088
+ var selected = (element, id) => ({
13089
+ element,
13090
+ id,
13091
+ name: getModdleString(element.businessObject, "name") || void 0
13092
+ });
13093
+ function selectElements(modeler, templateId, elementId) {
13094
+ const registry = modeler.get("elementRegistry");
13095
+ if (elementId !== void 0) {
13096
+ const element = registry.get(elementId);
13097
+ if (!element) {
13098
+ throw new Error(`Element "${elementId}" not found in the BPMN diagram`);
13099
+ }
13100
+ const applied = readAppliedTemplate(element.businessObject);
13101
+ if (!applied) {
13102
+ throw new Error(
13103
+ `Element "${elementId}" has no element template applied. Use 'apply' first.`
13104
+ );
13105
+ }
13106
+ if (applied.id !== templateId) {
13107
+ throw new Error(
13108
+ `Element "${elementId}" uses template '${applied.id}', not '${templateId}'.`
13109
+ );
13110
+ }
13111
+ return [selected(element, elementId)];
13112
+ }
13113
+ const seen = /* @__PURE__ */ new Set();
13114
+ const result = [];
13115
+ for (const candidate of registry.getAll()) {
13116
+ const id = candidate.businessObject.id;
13117
+ if (typeof id !== "string" || seen.has(id)) continue;
13118
+ const element = registry.get(id);
13119
+ if (element && readAppliedTemplate(element.businessObject)?.id === templateId) {
13120
+ seen.add(id);
13121
+ result.push(selected(element, id));
13122
+ }
13123
+ }
13124
+ if (result.length === 0) {
13125
+ throw new Error(
13126
+ `No element in the BPMN diagram uses template '${templateId}'.`
13127
+ );
13128
+ }
13129
+ return result;
13130
+ }
13131
+ var CARRY_OVER_HINT = "Pass --recipe <file> to migrate with a recipe, or --map <from>=<to> to move the value to another binding.";
13132
+ function deprecationOf(templateId, templates, cache) {
13133
+ const latest = templates.filter((t) => t.id === templateId).sort((a, b) => (b.version ?? 0) - (a.version ?? 0))[0];
13134
+ if (!latest?.deprecated) return null;
13135
+ let successors = [];
13136
+ try {
13137
+ successors = findSuccessors(
13138
+ cache,
13139
+ templateId,
13140
+ latest.version ?? 0,
13141
+ templates
13142
+ );
13143
+ } catch {
13144
+ }
13145
+ return { templateId, successors: successors.map((t) => t.id) };
13146
+ }
13147
+ function describeDropped(report) {
13148
+ const names = report.dropped.map((d) => d.key);
13149
+ const unchecked = report.skipped.unchecked.map((u) => u.key);
13150
+ return names.length > 0 ? `${names.length} dropped (${names.join(", ")})` : unchecked.length > 0 ? `${unchecked.length} unchecked (${unchecked.join(", ")})` : report.refusal ? `recipe not used: ${report.refusal}` : "values not migrated";
13151
+ }
13152
+ async function runMigrateInternal({ parsed, templateId, elementId, bpmnFilePath }, redaction) {
13153
+ const logger = c8ctl10.getLogger();
13154
+ installStdoutEpipeHandler();
13155
+ const dryRun = c8ctl10.dryRun === true;
13156
+ const json = c8ctl10.outputMode === "json";
13157
+ if (parsed.inPlace && !bpmnFilePath) {
13158
+ throw new Error("--in-place cannot be used with stdin input");
13159
+ }
13160
+ const writesXmlToStdout = !parsed.inPlace && !dryRun;
13161
+ if (json && writesXmlToStdout) {
13162
+ throw new Error(
13163
+ "--json needs --in-place or --dry-run, because stdout carries the BPMN otherwise"
13164
+ );
13165
+ }
13166
+ const maps = parsed.maps.map(parseMapArg);
13167
+ const input = await readBpmnInput(bpmnFilePath);
13168
+ if (!input) {
13169
+ throw new Error(
13170
+ "No BPMN input provided. Pass a file path or pipe BPMN XML via stdin."
13171
+ );
13172
+ }
13173
+ const engineVersion = await getExecutionPlatformVersion(input.xml, {
13174
+ requireCamunda: true
13175
+ });
13176
+ if (!engineVersion) {
13177
+ throw new Error(
13178
+ 'Cannot verify template compatibility: set modeler:executionPlatform="Camunda Cloud" and a valid modeler:executionPlatformVersion (major.minor or semantic version) on the BPMN document.'
13179
+ );
13180
+ }
13181
+ const modeler = createModeler();
13182
+ await modeler.importXML(input.xml);
13183
+ const selected2 = selectElements(modeler, templateId, elementId);
13184
+ const valuesOf2 = (element) => enumerateElementValues(getExtensionElements(element.businessObject));
13185
+ redaction.values = selected2.flatMap(({ element }) => valuesOf2(element));
13186
+ const cachedTemplates = loadCache() ?? [];
13187
+ const lineages = (ids) => migrationTemplates(cachedTemplates).filter((t) => ids.includes(t.id));
13188
+ redaction.templates = lineages([templateId, parsed.to]);
13189
+ const cache = compatibleTemplates(cachedTemplates, engineVersion);
13190
+ const recipe = parsed.recipePath ? loadRecipeFile(parsed.recipePath) : void 0;
13191
+ if (recipe && !recipe.sources.some((s) => s.sourceTemplateId === templateId)) {
13192
+ throw new Error(
13193
+ `Recipe ${parsed.recipePath} has no source entry for template '${templateId}'.`
13194
+ );
13195
+ }
13196
+ const target = await resolveTarget({
13197
+ templateId,
13198
+ to: parsed.to,
13199
+ executionPlatformVersion: engineVersion,
13200
+ cachedTemplates
13201
+ });
13202
+ const templates = resolveCatalog(
13203
+ cache.filter((t) => t.id === templateId || t.id === target.id),
13204
+ [target]
13205
+ );
13206
+ redaction.templates = [...lineages([templateId, target.id]), target];
13207
+ const targetRecipe = recipe ?? embeddedRecipe(target);
13208
+ if (targetRecipe) validateRecipeOwner(targetRecipe, target);
13209
+ if (!isEngineCompatible(target, engineVersion)) {
13210
+ throw new Error(
13211
+ `Template '${target.id}' is not compatible with Camunda ${engineVersion}.`
13212
+ );
13213
+ }
13214
+ const recipeSource = recipe ? "file" : targetRecipe ? "embedded" : "none";
13215
+ const sourceLineageRecipe = (report) => recipeSource === "none" && report.usedRecipe;
13216
+ const originOf = (report) => sourceLineageRecipe(report) ? "embedded" : recipeSource;
13217
+ const ownerOf = (report) => sourceLineageRecipe(report) ? templateId : target.id;
13218
+ const service = modeler.get("elementTemplates");
13219
+ const migrationModeler = {
13220
+ elementTemplates: service,
13221
+ modeling: modeler.get("modeling")
13222
+ };
13223
+ const outcomes = [];
13224
+ for (const { element, id, name: name2 } of selected2) {
13225
+ const applied = readAppliedTemplate(element.businessObject);
13226
+ if (!applied) continue;
13227
+ if (target.id === applied.id && (target.version ?? 0) === applied.version) {
13228
+ if (maps.length > 0 && !json) {
13229
+ process.stderr.write(
13230
+ `Warning: ${id} is already on the target template, so --map was not applied.
13231
+ `
13232
+ );
13233
+ }
13234
+ outcomes.push({
13235
+ status: "unchanged",
13236
+ id,
13237
+ name: name2,
13238
+ version: applied.version
13239
+ });
13240
+ continue;
13241
+ }
13242
+ if (target.id === applied.id && (target.version ?? 0) < applied.version) {
13243
+ outcomes.push({
13244
+ status: "skipped",
13245
+ id,
13246
+ name: name2,
13247
+ from: applied.version,
13248
+ to: target.version ?? 0
13249
+ });
13250
+ continue;
13251
+ }
13252
+ const isApplied = (t) => t.id === applied.id && (t.version ?? 0) === applied.version;
13253
+ const fromTemplate = templates.find(isApplied) ?? lineages([applied.id]).find(isApplied) ?? {
13254
+ id: applied.id,
13255
+ version: applied.version,
13256
+ properties: []
13257
+ };
13258
+ try {
13259
+ const result = migrateElement({
13260
+ modeler: migrationModeler,
13261
+ element,
13262
+ fromTemplate,
13263
+ target,
13264
+ templates,
13265
+ recipe,
13266
+ maps
13267
+ });
13268
+ redaction.values = [
13269
+ ...redaction.values ?? [],
13270
+ ...valuesOf2(result.element)
13271
+ ];
13272
+ const { report } = result;
13273
+ if (recipe && (!report.usedRecipe || report.refusal)) {
13274
+ throw new Error(
13275
+ `Explicit recipe cannot be used: ${report.refusal ?? "no applicable source entry"}.`
13276
+ );
13277
+ }
13278
+ outcomes.push({
13279
+ status: "updated",
13280
+ id,
13281
+ name: name2,
13282
+ report,
13283
+ requiresAuthorization: (parsed.inPlace || dryRun) && !report.lossless || report.refusal !== null
13284
+ });
13285
+ } catch (error3) {
13286
+ const message = error3 instanceof Error ? error3.message : String(error3);
13287
+ const carryOver = error3 instanceof DestinationError && error3.carryOver && !targetRecipe;
13288
+ outcomes.push({
13289
+ status: "failed",
13290
+ id,
13291
+ name: name2,
13292
+ error: `Cannot migrate ${id}: ${message}`,
13293
+ ...carryOver ? { hint: CARRY_OVER_HINT } : {}
13294
+ });
13295
+ }
13296
+ }
13297
+ const updated = outcomes.filter((o) => o.status === "updated");
13298
+ const failed = outcomes.filter((o) => o.status === "failed");
13299
+ const blocked = updated.filter(
13300
+ (o) => o.requiresAuthorization && !parsed.allowLossy
13301
+ );
13302
+ const droppedCount = updated.reduce(
13303
+ (sum, o) => sum + o.report.dropped.length,
13304
+ 0
13305
+ );
13306
+ const wouldBlock = blocked.length > 0;
13307
+ if (wouldBlock && !dryRun && failed.length === 0) {
13308
+ throw new Error(
13309
+ `Migration may lose values or discard its recipe; preview with --dry-run and pass --allow-lossy to authorize it. Blocked: ${blocked.map((o) => `${o.id} (${describeDropped(o.report)})`).join("; ")}`
13310
+ );
13311
+ }
13312
+ const canWrite = !dryRun && failed.length === 0 && !wouldBlock;
13313
+ const saved = canWrite && updated.length > 0 ? await modeler.saveXML({ format: true }) : void 0;
13314
+ if (saved && parsed.inPlace && bpmnFilePath) {
13315
+ if (readFileSync5(bpmnFilePath, "utf-8") !== input.xml)
13316
+ throw new Error(CONCURRENT_EDIT_MESSAGE);
13317
+ atomicOverwriteFile(bpmnFilePath, saved.xml, input.xml);
13318
+ }
13319
+ const summary = {
13320
+ updated: updated.length,
13321
+ skipped: outcomes.filter((o) => o.status === "skipped").length,
13322
+ unchanged: outcomes.filter((o) => o.status === "unchanged").length,
13323
+ failed: failed.length,
13324
+ dropped: droppedCount,
13325
+ blocked: blocked.length
13326
+ };
13327
+ const deprecation = deprecationOf(templateId, templates, cache);
13328
+ if (json) {
13329
+ const file = parsed.inPlace ? bpmnFilePath : void 0;
13330
+ const elementName = (o) => o.name ? { elementName: redactMigrationDiagnostic(o.name, redaction) } : {};
13331
+ const emptyReport = (version) => buildReport({
13332
+ fromTemplate: { ...target, version },
13333
+ toTemplate: target,
13334
+ before: [],
13335
+ after: [],
13336
+ facts: emptyFacts(),
13337
+ usedRecipe: false,
13338
+ refusal: null
13339
+ });
13340
+ logger.json({
13341
+ dryRun,
13342
+ command: COMMAND,
13343
+ results: outcomes.map((o) => {
13344
+ switch (o.status) {
13345
+ case "updated":
13346
+ return {
13347
+ status: o.status,
13348
+ ...reportToJson(o.report, {
13349
+ elementId: o.id,
13350
+ elementName: o.name,
13351
+ recipe: originOf(o.report),
13352
+ recipePath: parsed.recipePath,
13353
+ recipeOwner: ownerOf(o.report),
13354
+ dryRun,
13355
+ file,
13356
+ redaction
13357
+ }),
13358
+ requiresAuthorization: o.requiresAuthorization,
13359
+ authorized: parsed.allowLossy
13360
+ };
13361
+ case "unchanged":
13362
+ return {
13363
+ status: o.status,
13364
+ ...reportToJson(emptyReport(o.version), {
13365
+ elementId: o.id,
13366
+ elementName: o.name,
13367
+ recipe: "none",
13368
+ dryRun,
13369
+ file,
13370
+ redaction
13371
+ }),
13372
+ noop: true
13373
+ };
13374
+ case "skipped":
13375
+ return {
13376
+ status: o.status,
13377
+ elementId: redactMigrationDiagnostic(o.id, redaction),
13378
+ ...elementName(o),
13379
+ from: { id: templateId, version: o.from },
13380
+ to: { id: target.id, version: o.to }
13381
+ };
13382
+ default:
13383
+ return {
13384
+ status: o.status,
13385
+ elementId: redactMigrationDiagnostic(o.id, redaction),
13386
+ ...elementName(o),
13387
+ error: redactMigrationDiagnostic(o.error, redaction),
13388
+ ...o.hint ? { hint: o.hint } : {}
13389
+ };
13390
+ }
13391
+ }),
13392
+ summary,
13393
+ deprecation
13394
+ });
13395
+ } else {
13396
+ const stream = writesXmlToStdout ? process.stderr : process.stdout;
13397
+ const color = shouldUseColor(stream);
13398
+ const s = {
13399
+ red: (text) => color ? `\x1B[31m${text}\x1B[39m` : text
13400
+ };
13401
+ const lines = [];
13402
+ const errorLines = [];
13403
+ const columns = stream.isTTY ? stream.columns : void 0;
13404
+ for (const o of outcomes) {
13405
+ if (o.status === "updated") {
13406
+ lines.push(
13407
+ renderReportText(o.report, {
13408
+ elementId: o.id,
13409
+ elementName: o.name,
13410
+ color,
13411
+ recipe: originOf(o.report),
13412
+ recipePath: parsed.recipePath,
13413
+ recipeOwner: ownerOf(o.report),
13414
+ targetTemplate: target,
13415
+ authorization: o.requiresAuthorization ? parsed.allowLossy ? "authorized" : "required" : void 0,
13416
+ columns,
13417
+ redaction
13418
+ })
13419
+ );
13420
+ } else if (o.status === "unchanged") {
13421
+ lines.push(
13422
+ `${o.id} is already on ${target.name ?? target.id} v${o.version}; nothing to do.
13423
+ `
13424
+ );
13425
+ } else if (o.status === "skipped") {
13426
+ lines.push(`${o.id} is on v${o.from}, newer than v${o.to}; skipped.
13427
+ `);
13428
+ } else {
13429
+ const reason = o.error.replace(`Cannot migrate ${o.id}: `, "");
13430
+ errorLines.push(
13431
+ `${s.red(`\u2717 Cannot migrate ${o.name ? `${o.name} (${o.id})` : o.id}: ${reason}`)}
13432
+ `
13433
+ );
13434
+ if (o.hint) errorLines.push(`${o.hint}
13435
+ `);
13436
+ }
13437
+ }
13438
+ const counts = [
13439
+ [summary.updated, "updated"],
13440
+ [summary.skipped, "skipped"],
13441
+ [summary.unchanged, "unchanged"],
13442
+ [summary.failed, "failed"]
13443
+ ].filter(([n]) => n > 0).map(
13444
+ ([n, label], i) => i === 0 ? `${n} element${n === 1 ? "" : "s"} ${label}` : `${n} ${label}`
13445
+ );
13446
+ const destination = dryRun ? "Dry run: nothing was written." : failed.length > 0 ? "" : saved && parsed.inPlace && bpmnFilePath ? `Updated ${bpmnFilePath}.` : writesXmlToStdout ? "BPMN written to stdout." : "";
13447
+ lines.push(
13448
+ `${[counts.join(", ") && `${counts.join(", ")}.`, destination].filter(Boolean).join(" ")}
13449
+ `
13450
+ );
13451
+ if (failed.length > 0) {
13452
+ errorLines.push("Nothing was written because an element failed.\n");
13453
+ } else if (wouldBlock && dryRun) {
13454
+ lines.push(
13455
+ "A write would be blocked: pass --allow-lossy to authorize it.\n"
13456
+ );
13457
+ }
13458
+ if (deprecation && (!parsed.to || parsed.to === templateId)) {
13459
+ const { successors } = deprecation;
13460
+ lines.push(
13461
+ `Template '${templateId}' is deprecated.${successors.length > 0 ? ` Templates that declare a migration from it: ${successors.join(", ")}. Use --to <template>.` : ""}
13462
+ `
13463
+ );
13464
+ }
13465
+ lines.push(`${renderLegend(color)}
13466
+ `);
13467
+ stream.write(redactMigrationDiagnostic(lines.join("\n"), redaction));
13468
+ if (errorLines.length > 0) {
13469
+ process.stderr.write(
13470
+ redactMigrationDiagnostic(errorLines.join("\n"), redaction)
13471
+ );
13472
+ }
13473
+ }
13474
+ if (failed.length > 0 || wouldBlock && dryRun) {
13475
+ process.exitCode = 1;
13476
+ }
13477
+ if (saved && parsed.inPlace && bpmnFilePath) {
13478
+ return;
13479
+ }
13480
+ if (writesXmlToStdout && failed.length === 0) {
13481
+ process.stdout.write(saved ? saved.xml : input.xml);
13482
+ }
13483
+ }
13484
+ async function runLockedMigrate(args, redaction) {
13485
+ const resolved = resolveMigrateArgs(args);
13486
+ const file = resolved.bpmnFilePath;
13487
+ if (!resolved.parsed.inPlace || !file || c8ctl10.dryRun)
13488
+ return runMigrateInternal(resolved, redaction);
13489
+ if (!existsSync5(resolvePath4(file)))
13490
+ throw new Error(`File not found: ${file}`);
13491
+ const lock = `${resolvePath4(file)}.migration.lock`;
13492
+ let descriptor;
13493
+ try {
13494
+ descriptor = openSync2(lock, "wx");
13495
+ } catch (error3) {
13496
+ if (!isRecord(error3) || error3.code !== "EEXIST") throw error3;
13497
+ throw new Error(
13498
+ `Cannot acquire migration lock ${lock}. Another writer may be active; remove a stale lock only after checking that no migration is running.`
13499
+ );
13500
+ }
13501
+ let cleanupFailure;
13502
+ try {
13503
+ await runMigrateInternal(resolved, redaction);
13504
+ } finally {
13505
+ try {
13506
+ try {
13507
+ closeSync2(descriptor);
13508
+ } finally {
13509
+ unlinkSync3(lock);
13510
+ }
13511
+ } catch (error3) {
13512
+ cleanupFailure = { error: error3 };
13513
+ }
13514
+ }
13515
+ if (cleanupFailure) throw cleanupFailure.error;
13516
+ }
13517
+ async function runMigrate(args) {
13518
+ const redaction = {};
13519
+ try {
13520
+ await runLockedMigrate(args, redaction);
13521
+ } catch (error3) {
13522
+ const message = error3 instanceof Error ? error3.message : String(error3);
13523
+ throw new Error(redactMigrationDiagnostic(message, redaction));
13524
+ }
13525
+ }
13526
+
13527
+ // default-plugins/element-template/commands/update.ts
13528
+ function updateSubcommand(args) {
13529
+ return runMigrate(args);
13530
+ }
13531
+
13532
+ // default-plugins/element-template/c8ctl-plugin.ts
13533
+ if (!globalThis.c8ctl) throw new Error("c8ctl runtime not initialised");
13534
+ var c8ctl11 = globalThis.c8ctl;
13535
+ function injectFlagsIntoArgs(args, flags) {
13536
+ const out = [...args];
13537
+ if (!flags) {
13538
+ return out;
13539
+ }
13540
+ for (const [name2, value] of Object.entries(flags)) {
13541
+ if (value === void 0 || value === null) {
13542
+ continue;
13543
+ }
13544
+ if (typeof value === "boolean") {
13545
+ if (value) {
13546
+ out.push(`--${name2}`);
13547
+ }
13548
+ } else if (Array.isArray(value)) {
13549
+ for (const item of value) {
13550
+ if (item !== void 0 && item !== null) {
13551
+ out.push(`--${name2}`, String(item));
13552
+ }
13553
+ }
13554
+ } else {
13555
+ out.push(`--${name2}`, String(value));
13556
+ }
13557
+ }
13558
+ return out;
13559
+ }
13560
+ var subcommandHandlers = {
13561
+ search: searchSubcommand,
13562
+ info: infoSubcommand,
13563
+ "get-properties": getPropertiesSubcommand,
13564
+ apply: applySubcommand,
13565
+ edit: editSubcommand,
13566
+ update: updateSubcommand,
13567
+ get: getSubcommand,
13568
+ sync: syncSubcommand
13569
+ };
13570
+ function isSubcommand(name2) {
13571
+ return Object.hasOwn(subcommandHandlers, name2);
13572
+ }
13573
+ async function elementTemplateHandler(args, flags) {
13574
+ const reinjected = injectFlagsIntoArgs(args ?? [], flags);
13575
+ const subcommand = reinjected[0];
13576
+ const subArgs = reinjected.slice(1);
13577
+ if (!subcommand || !isSubcommand(subcommand)) {
13578
+ const logger = c8ctl11.getLogger();
13579
+ const lead = subcommand ? `Unknown subcommand '${subcommand}'.` : "c8ctl element-template requires a subcommand.";
13580
+ const validSubcommands = Object.keys(subcommandHandlers);
13581
+ logger.error(`${lead} Available: ${validSubcommands.join(", ")}`);
13582
+ logger.error("Run 'c8ctl element-template --help' for full usage.");
13583
+ process.exitCode = 1;
13584
+ return;
13585
+ }
13586
+ try {
13587
+ await subcommandHandlers[subcommand](subArgs);
13588
+ } catch (error3) {
13589
+ const message = error3 instanceof Error ? error3.message : String(error3);
13590
+ const logger = c8ctl11.getLogger();
13591
+ logger.error(`Failed to element-template ${subcommand}: ${message}`);
10590
13592
  process.exitCode = 1;
10591
13593
  }
10592
13594
  }
@@ -10596,7 +13598,7 @@ var metadata = {
10596
13598
  commands: {
10597
13599
  "element-template": {
10598
13600
  description: "Apply, inspect, and export Camunda element templates",
10599
- helpDescription: "Apply Camunda element templates to BPMN elements, inspect template metadata and properties, search the out-of-the-box template catalogue, export raw template JSON, and manage the local template cache.\n\n<template> is a local path, an https:// URL, or an OOTB template id (optionally @<version>).\n\napply --set name=value targets a property by binding name (run `get-properties` to discover names). Pass --set multiple times to set multiple properties. Prefix with a binding type (input | output | header | property | taskDefinition) when the same name is bound across multiple types \u2014 e.g. --set input:correlationKey=order-42.\n\nedit --set name=value updates a property on an element that already has a template applied, without re-running template application \u2014 it never resets other template-owned content (including hand-customized extension values a template doesn't fully control) and doesn't need a <template> argument (it reads zeebe:modelerTemplate/-Version off the element). The tradeoff: edit can only change bindings that already have a value; a property whose gating condition was never met has nothing to edit \u2014 use apply --set to materialize it first.\n\nFEEL values: properties with feel=required always store a FEEL expression (prefixed with `=`). For those properties, c8ctl auto-prepends `=` when it is missing, so `--set key=orderId` writes `=orderId` to the BPMN \u2014 equivalent to `--set key==orderId`. Properties with feel=optional keep the value verbatim; you must supply the `=` prefix yourself when you want to write a FEEL expression for those. Three forms for feel=required properties:\n --set key='=value' canonical: single-quoted FEEL value (explicit =)\n --set 'key==value' compact: whole argument single-quoted (explicit =)\n --set key=value shorthand: = auto-prepended (feel=required only)\nLeading/trailing whitespace is stripped from values, and whitespace immediately after a FEEL `=` prefix is also stripped, so `--set 'key== value'` is equivalent to `--set 'key==value'`.",
13601
+ helpDescription: "Apply Camunda element templates to BPMN elements, inspect template metadata and properties, search the out-of-the-box template catalogue, export raw template JSON, and manage the local template cache.\n\n<template> is a local path, an https:// URL, or an OOTB template id (optionally @<version>).\n\napply --set name=value targets a property by binding name (run `get-properties` to discover names). Pass --set multiple times to set multiple properties. Prefix with a binding type (input | output | header | property | taskDefinition) when the same name is bound across multiple types \u2014 e.g. --set input:correlationKey=order-42.\n\nedit --set name=value updates a property on an element that already has a template applied, without re-running template application \u2014 it never resets other template-owned content (including hand-customized extension values a template doesn't fully control) and doesn't need a <template> argument (it reads zeebe:modelerTemplate/-Version off the element). The tradeoff: edit can only change bindings that already have a value; a property whose gating condition was never met has nothing to edit \u2014 use apply --set to materialize it first.\n\nupdate <template-id> moves every element that uses that template to its latest compatible version, or to the template given with --to <template>[@<n>] (an id, path or URL); pass an element id to update only that element. Values the target binds under another key are moved when it carries a migration recipe (metadata.migratesFrom) or one is passed with --recipe <file>; --map <from>=<to> moves a value per element when no recipe covers it; the rest carry over by key. A report lists what was dropped, added, moved and changed. --dry-run previews the migration and writes nothing; it exits 1 when an element would fail to migrate or the write would need --allow-lossy. The file is written once, and only if every element migrates.\n\nFEEL values: properties with feel=required always store a FEEL expression (prefixed with `=`). For those properties, c8ctl auto-prepends `=` when it is missing, so `--set key=orderId` writes `=orderId` to the BPMN \u2014 equivalent to `--set key==orderId`. Properties with feel=optional keep the value verbatim; you must supply the `=` prefix yourself when you want to write a FEEL expression for those. Three forms for feel=required properties:\n --set key='=value' canonical: single-quoted FEEL value (explicit =)\n --set 'key==value' compact: whole argument single-quoted (explicit =)\n --set key=value shorthand: = auto-prepended (feel=required only)\nLeading/trailing whitespace is stripped from values, and whitespace immediately after a FEEL `=` prefix is also stripped, so `--set 'key== value'` is equivalent to `--set 'key==value'`.",
10600
13602
  subcommands: [
10601
13603
  {
10602
13604
  name: "search",
@@ -10618,6 +13620,10 @@ var metadata = {
10618
13620
  name: "edit",
10619
13621
  description: "Update a property on an element that already has a template applied, without re-applying it"
10620
13622
  },
13623
+ {
13624
+ name: "update",
13625
+ description: "Move all elements of a template to its latest version, or to another template, migrating their values"
13626
+ },
10621
13627
  {
10622
13628
  name: "get",
10623
13629
  description: "Print the raw template JSON to stdout (pipe-friendly)"
@@ -10684,6 +13690,26 @@ var metadata = {
10684
13690
  command: "c8ctl element-template edit Task_1 process.bpmn --set method=PUT",
10685
13691
  description: "Update a single property on an already-templated element in place, without touching anything else the template governs"
10686
13692
  },
13693
+ {
13694
+ command: "c8ctl element-template update io.camunda.connectors.HttpJson.v2 process.bpmn --dry-run",
13695
+ description: "Preview moving all elements of a template to its latest compatible version, with a report of what changes"
13696
+ },
13697
+ {
13698
+ command: "c8ctl element-template update io.camunda.connectors.HttpJson.v2 Task_1 process.bpmn --to io.camunda.connectors.HttpJson.v2@15 --in-place",
13699
+ description: "Update one element to a pinned version"
13700
+ },
13701
+ {
13702
+ command: "c8ctl element-template update io.camunda.connectors.agenticai.aiagent.v1 process.bpmn --to io.camunda.connectors.agenticai.ai-agent-task.v2 --in-place",
13703
+ description: "Move all elements to another template; its embedded recipe moves renamed values"
13704
+ },
13705
+ {
13706
+ command: "c8ctl element-template update old.id process.bpmn --to new-template.json --recipe recipe.json --in-place",
13707
+ description: "Migrate with a recipe from a file instead of the one embedded in the template"
13708
+ },
13709
+ {
13710
+ command: "c8ctl element-template update old.id process.bpmn --to new-template.json --map maxTokens=limit --in-place",
13711
+ description: "Move a value to a key the target binds differently; each element keeps its own value"
13712
+ },
10687
13713
  {
10688
13714
  command: "c8ctl element-template get io.camunda.connectors.HttpJson.v2 > template.json",
10689
13715
  description: "Print the raw template JSON to stdout (redirect to save a copy)"
@@ -10703,10 +13729,14 @@ var metadata = {
10703
13729
  var commands = {
10704
13730
  "element-template": {
10705
13731
  flags: {
13732
+ "allow-lossy": {
13733
+ type: "boolean",
13734
+ description: "Authorize lossy in-place migration or embedded-recipe fallback [update]"
13735
+ },
10706
13736
  "in-place": {
10707
13737
  type: "boolean",
10708
13738
  short: "i",
10709
- description: "Modify the BPMN file in place [apply|edit]"
13739
+ description: "Modify the BPMN file in place [apply|edit|update]"
10710
13740
  },
10711
13741
  set: {
10712
13742
  type: "string",
@@ -10723,6 +13753,19 @@ var commands = {
10723
13753
  multiple: true,
10724
13754
  description: "Filter to one or more group ids (repeatable) [get-properties]"
10725
13755
  },
13756
+ recipe: {
13757
+ type: "string",
13758
+ description: "Migration recipe file, used instead of the one embedded in the target template [update]"
13759
+ },
13760
+ to: {
13761
+ type: "string",
13762
+ description: "Target template: id[@n], path or URL; default is the latest compatible version of the selected template [update]"
13763
+ },
13764
+ map: {
13765
+ type: "string",
13766
+ multiple: true,
13767
+ description: "Move the original value of binding <from> to binding <to> on every selected element: from=to (repeatable) [update]"
13768
+ },
10726
13769
  prune: {
10727
13770
  type: "boolean",
10728
13771
  description: "Drop cached entries no longer in a selected release [sync]"