@backstage/plugin-scaffolder-backend 1.22.8-next.2 → 1.22.8

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.
@@ -164,6 +164,7 @@ function createCatalogRegisterAction(options) {
164
164
  }
165
165
  },
166
166
  async handler(ctx) {
167
+ var _a, _b;
167
168
  const { input } = ctx;
168
169
  let catalogInfoUrl;
169
170
  if ("catalogInfoUrl" in input) {
@@ -182,10 +183,10 @@ function createCatalogRegisterAction(options) {
182
183
  });
183
184
  }
184
185
  ctx.logger.info(`Registering ${catalogInfoUrl} in the catalog`);
185
- const { token } = await auth?.getPluginRequestToken({
186
+ const { token } = (_b = await (auth == null ? void 0 : auth.getPluginRequestToken({
186
187
  onBehalfOf: await ctx.getInitiatorCredentials(),
187
188
  targetPluginId: "catalog"
188
- }) ?? { token: ctx.secrets?.backstageToken };
189
+ }))) != null ? _b : { token: (_a = ctx.secrets) == null ? void 0 : _a.backstageToken };
189
190
  try {
190
191
  await catalogClient.addLocation(
191
192
  {
@@ -281,10 +282,11 @@ function createCatalogWriteAction() {
281
282
  examples: examples$8,
282
283
  supportsDryRun: true,
283
284
  async handler(ctx) {
285
+ var _a;
284
286
  ctx.logger.info(`Writing catalog-info.yaml`);
285
287
  const { filePath, entity } = ctx.input;
286
- const entityRef = ctx.templateInfo?.entityRef;
287
- const path = filePath ?? "catalog-info.yaml";
288
+ const entityRef = (_a = ctx.templateInfo) == null ? void 0 : _a.entityRef;
289
+ const path = filePath != null ? filePath : "catalog-info.yaml";
288
290
  await fs__default.default.writeFile(
289
291
  backendPluginApi.resolveSafeChildPath(ctx.workspacePath, path),
290
292
  yaml__namespace.stringify({
@@ -371,6 +373,7 @@ function createFetchCatalogEntityAction(options) {
371
373
  })
372
374
  },
373
375
  async handler(ctx) {
376
+ var _a, _b;
374
377
  const { entityRef, entityRefs, optional, defaultKind, defaultNamespace } = ctx.input;
375
378
  if (!entityRef && !entityRefs) {
376
379
  if (optional) {
@@ -378,10 +381,10 @@ function createFetchCatalogEntityAction(options) {
378
381
  }
379
382
  throw new Error("Missing entity reference or references");
380
383
  }
381
- const { token } = await auth?.getPluginRequestToken({
384
+ const { token } = (_b = await (auth == null ? void 0 : auth.getPluginRequestToken({
382
385
  onBehalfOf: await ctx.getInitiatorCredentials(),
383
386
  targetPluginId: "catalog"
384
- }) ?? { token: ctx.secrets?.backstageToken };
387
+ }))) != null ? _b : { token: (_a = ctx.secrets) == null ? void 0 : _a.backstageToken };
385
388
  if (entityRef) {
386
389
  const entity = await catalogClient.getEntityByRef(
387
390
  catalogModel.stringifyEntityRef(
@@ -394,7 +397,7 @@ function createFetchCatalogEntityAction(options) {
394
397
  if (!entity && !optional) {
395
398
  throw new Error(`Entity ${entityRef} not found`);
396
399
  }
397
- ctx.output("entity", entity ?? null);
400
+ ctx.output("entity", entity != null ? entity : null);
398
401
  }
399
402
  if (entityRefs) {
400
403
  const entities = await catalogClient.getEntitiesByRefs(
@@ -413,7 +416,7 @@ function createFetchCatalogEntityAction(options) {
413
416
  if (!e && !optional) {
414
417
  throw new Error(`Entity ${entityRefs[i]} not found`);
415
418
  }
416
- return e ?? null;
419
+ return e != null ? e : null;
417
420
  });
418
421
  ctx.output("entities", finalEntities);
419
422
  }
@@ -480,11 +483,12 @@ function createDebugLogAction() {
480
483
  },
481
484
  supportsDryRun: true,
482
485
  async handler(ctx) {
486
+ var _a, _b;
483
487
  ctx.logger.info(JSON.stringify(ctx.input, null, 2));
484
- if (ctx.input?.message) {
488
+ if ((_a = ctx.input) == null ? void 0 : _a.message) {
485
489
  ctx.logger.info(ctx.input.message);
486
490
  }
487
- if (ctx.input?.listWorkspace) {
491
+ if ((_b = ctx.input) == null ? void 0 : _b.listWorkspace) {
488
492
  const files = await recursiveReadDir(ctx.workspacePath);
489
493
  ctx.logger.info(
490
494
  `Workspace:
@@ -590,18 +594,20 @@ function createWaitAction(options) {
590
594
  },
591
595
  async handler(ctx) {
592
596
  const delayTime = luxon.Duration.fromObject(ctx.input);
593
- const maxWait = toDuration(options?.maxWaitTime);
597
+ const maxWait = toDuration(options == null ? void 0 : options.maxWaitTime);
594
598
  if (delayTime.minus(maxWait).toMillis() > 0) {
595
599
  throw new Error(
596
600
  `Waiting duration is longer than the maximum threshold of ${maxWait.toHuman()}`
597
601
  );
598
602
  }
599
603
  await new Promise((resolve) => {
604
+ var _a;
600
605
  const controller = new AbortController();
601
606
  const timeoutHandle = setTimeout(abort, delayTime.toMillis());
602
- ctx.signal?.addEventListener("abort", abort);
607
+ (_a = ctx.signal) == null ? void 0 : _a.addEventListener("abort", abort);
603
608
  function abort() {
604
- ctx.signal?.removeEventListener("abort", abort);
609
+ var _a2;
610
+ (_a2 = ctx.signal) == null ? void 0 : _a2.removeEventListener("abort", abort);
605
611
  clearTimeout(timeoutHandle);
606
612
  controller.abort();
607
613
  resolve("finished");
@@ -677,13 +683,14 @@ function createFetchPlainAction(options) {
677
683
  },
678
684
  supportsDryRun: true,
679
685
  async handler(ctx) {
686
+ var _a, _b;
680
687
  ctx.logger.info("Fetching plain content from remote URL");
681
- const targetPath = ctx.input.targetPath ?? "./";
688
+ const targetPath = (_a = ctx.input.targetPath) != null ? _a : "./";
682
689
  const outputPath = backendPluginApi.resolveSafeChildPath(ctx.workspacePath, targetPath);
683
690
  await pluginScaffolderNode.fetchContents({
684
691
  reader,
685
692
  integrations,
686
- baseUrl: ctx.templateInfo?.baseUrl,
693
+ baseUrl: (_b = ctx.templateInfo) == null ? void 0 : _b.baseUrl,
687
694
  fetchUrl: ctx.input.url,
688
695
  outputPath,
689
696
  token: ctx.input.token
@@ -742,6 +749,7 @@ function createFetchPlainFileAction(options) {
742
749
  },
743
750
  supportsDryRun: true,
744
751
  async handler(ctx) {
752
+ var _a;
745
753
  ctx.logger.info("Fetching plain content from remote URL");
746
754
  const outputPath = backendPluginApi.resolveSafeChildPath(
747
755
  ctx.workspacePath,
@@ -750,7 +758,7 @@ function createFetchPlainFileAction(options) {
750
758
  await pluginScaffolderNode.fetchFile({
751
759
  reader,
752
760
  integrations,
753
- baseUrl: ctx.templateInfo?.baseUrl,
761
+ baseUrl: (_a = ctx.templateInfo) == null ? void 0 : _a.baseUrl,
754
762
  fetchUrl: ctx.input.url,
755
763
  outputPath,
756
764
  token: ctx.input.token
@@ -760,7 +768,8 @@ function createFetchPlainFileAction(options) {
760
768
  }
761
769
 
762
770
  function isNoNodeSnapshotOptionProvided() {
763
- return process.env.NODE_OPTIONS?.includes("--no-node-snapshot") || process.argv.includes("--no-node-snapshot");
771
+ var _a;
772
+ return ((_a = process.env.NODE_OPTIONS) == null ? void 0 : _a.includes("--no-node-snapshot")) || process.argv.includes("--no-node-snapshot");
764
773
  }
765
774
  function getMajorNodeVersion() {
766
775
  const version = process.versions.node;
@@ -1035,10 +1044,11 @@ function createFetchTemplateAction(options) {
1035
1044
  },
1036
1045
  supportsDryRun: true,
1037
1046
  async handler(ctx) {
1047
+ var _a, _b;
1038
1048
  ctx.logger.info("Fetching template content from remote URL");
1039
1049
  const workDir = await ctx.createTemporaryDirectory();
1040
1050
  const templateDir = backendPluginApi.resolveSafeChildPath(workDir, "template");
1041
- const targetPath = ctx.input.targetPath ?? "./";
1051
+ const targetPath = (_a = ctx.input.targetPath) != null ? _a : "./";
1042
1052
  const outputDir = backendPluginApi.resolveSafeChildPath(ctx.workspacePath, targetPath);
1043
1053
  if (ctx.input.copyWithoutRender && ctx.input.copyWithoutTemplating) {
1044
1054
  throw new errors.InputError(
@@ -1077,7 +1087,7 @@ function createFetchTemplateAction(options) {
1077
1087
  await pluginScaffolderNode.fetchContents({
1078
1088
  reader,
1079
1089
  integrations,
1080
- baseUrl: ctx.templateInfo?.baseUrl,
1090
+ baseUrl: (_b = ctx.templateInfo) == null ? void 0 : _b.baseUrl,
1081
1091
  fetchUrl: ctx.input.url,
1082
1092
  outputPath: templateDir,
1083
1093
  token: ctx.input.token
@@ -1224,7 +1234,8 @@ const createFilesystemDeleteAction = () => {
1224
1234
  },
1225
1235
  supportsDryRun: true,
1226
1236
  async handler(ctx) {
1227
- if (!Array.isArray(ctx.input?.files)) {
1237
+ var _a;
1238
+ if (!Array.isArray((_a = ctx.input) == null ? void 0 : _a.files)) {
1228
1239
  throw new errors.InputError("files must be an Array");
1229
1240
  }
1230
1241
  for (const file of ctx.input.files) {
@@ -1301,7 +1312,8 @@ const createFilesystemRenameAction = () => {
1301
1312
  },
1302
1313
  supportsDryRun: true,
1303
1314
  async handler(ctx) {
1304
- if (!Array.isArray(ctx.input?.files)) {
1315
+ var _a, _b;
1316
+ if (!Array.isArray((_a = ctx.input) == null ? void 0 : _a.files)) {
1305
1317
  throw new errors.InputError("files must be an Array");
1306
1318
  }
1307
1319
  for (const file of ctx.input.files) {
@@ -1315,7 +1327,7 @@ const createFilesystemRenameAction = () => {
1315
1327
  const destFilepath = backendPluginApi.resolveSafeChildPath(ctx.workspacePath, file.to);
1316
1328
  try {
1317
1329
  await fs__default.default.move(sourceFilepath, destFilepath, {
1318
- overwrite: file.overwrite ?? false
1330
+ overwrite: (_b = file.overwrite) != null ? _b : false
1319
1331
  });
1320
1332
  ctx.logger.info(
1321
1333
  `File ${sourceFilepath} renamed to ${destFilepath} successfully`
@@ -1455,8 +1467,16 @@ const createBuiltinActions = (options) => {
1455
1467
  return actions;
1456
1468
  };
1457
1469
 
1470
+ var __defProp$4 = Object.defineProperty;
1471
+ var __defNormalProp$4 = (obj, key, value) => key in obj ? __defProp$4(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1472
+ var __publicField$4 = (obj, key, value) => {
1473
+ __defNormalProp$4(obj, key + "" , value);
1474
+ return value;
1475
+ };
1458
1476
  class TemplateActionRegistry {
1459
- actions = /* @__PURE__ */ new Map();
1477
+ constructor() {
1478
+ __publicField$4(this, "actions", /* @__PURE__ */ new Map());
1479
+ }
1460
1480
  register(action) {
1461
1481
  if (this.actions.has(action.id)) {
1462
1482
  throw new errors.ConflictError(
@@ -1526,6 +1546,12 @@ const restoreWorkspace = async (path, buffer) => {
1526
1546
  }
1527
1547
  };
1528
1548
 
1549
+ var __defProp$3 = Object.defineProperty;
1550
+ var __defNormalProp$3 = (obj, key, value) => key in obj ? __defProp$3(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1551
+ var __publicField$3 = (obj, key, value) => {
1552
+ __defNormalProp$3(obj, key + "" , value);
1553
+ return value;
1554
+ };
1529
1555
  const migrationsDir = backendPluginApi.resolvePackagePath(
1530
1556
  "@backstage/plugin-scaffolder-backend",
1531
1557
  "migrations"
@@ -1546,7 +1572,10 @@ const parseSqlDateToIsoString = (input) => {
1546
1572
  return input;
1547
1573
  };
1548
1574
  class DatabaseTaskStore {
1549
- db;
1575
+ constructor(client) {
1576
+ __publicField$3(this, "db");
1577
+ this.db = client;
1578
+ }
1550
1579
  static async create(options) {
1551
1580
  const { database } = options;
1552
1581
  const client = await this.getClient(database);
@@ -1554,8 +1583,9 @@ class DatabaseTaskStore {
1554
1583
  return new DatabaseTaskStore(client);
1555
1584
  }
1556
1585
  isRecoverableTask(spec) {
1586
+ var _a, _b;
1557
1587
  return ["startOver"].includes(
1558
- spec.EXPERIMENTAL_recovery?.EXPERIMENTAL_strategy ?? "none"
1588
+ (_b = (_a = spec.EXPERIMENTAL_recovery) == null ? void 0 : _a.EXPERIMENTAL_strategy) != null ? _b : "none"
1559
1589
  );
1560
1590
  }
1561
1591
  parseSpec({ spec, id }) {
@@ -1581,21 +1611,19 @@ class DatabaseTaskStore {
1581
1611
  return database;
1582
1612
  }
1583
1613
  static async runMigrations(database, client) {
1614
+ var _a;
1584
1615
  if (!isPluginDatabaseManager(database)) {
1585
1616
  await client.migrate.latest({
1586
1617
  directory: migrationsDir
1587
1618
  });
1588
1619
  return;
1589
1620
  }
1590
- if (!database.migrations?.skip) {
1621
+ if (!((_a = database.migrations) == null ? void 0 : _a.skip)) {
1591
1622
  await client.migrate.latest({
1592
1623
  directory: migrationsDir
1593
1624
  });
1594
1625
  }
1595
1626
  }
1596
- constructor(client) {
1597
- this.db = client;
1598
- }
1599
1627
  async list(options) {
1600
1628
  const queryBuilder = this.db("tasks");
1601
1629
  if (options.createdBy) {
@@ -1604,17 +1632,21 @@ class DatabaseTaskStore {
1604
1632
  });
1605
1633
  }
1606
1634
  const results = await queryBuilder.orderBy("created_at", "desc").select();
1607
- const tasks = results.map((result) => ({
1608
- id: result.id,
1609
- spec: JSON.parse(result.spec),
1610
- status: result.status,
1611
- createdBy: result.created_by ?? void 0,
1612
- lastHeartbeatAt: parseSqlDateToIsoString(result.last_heartbeat_at),
1613
- createdAt: parseSqlDateToIsoString(result.created_at)
1614
- }));
1635
+ const tasks = results.map((result) => {
1636
+ var _a;
1637
+ return {
1638
+ id: result.id,
1639
+ spec: JSON.parse(result.spec),
1640
+ status: result.status,
1641
+ createdBy: (_a = result.created_by) != null ? _a : void 0,
1642
+ lastHeartbeatAt: parseSqlDateToIsoString(result.last_heartbeat_at),
1643
+ createdAt: parseSqlDateToIsoString(result.created_at)
1644
+ };
1645
+ });
1615
1646
  return { tasks };
1616
1647
  }
1617
1648
  async getTask(taskId) {
1649
+ var _a;
1618
1650
  const [result] = await this.db("tasks").where({ id: taskId }).select();
1619
1651
  if (!result) {
1620
1652
  throw new errors.NotFoundError(`No task with id '${taskId}' found`);
@@ -1629,7 +1661,7 @@ class DatabaseTaskStore {
1629
1661
  status: result.status,
1630
1662
  lastHeartbeatAt: parseSqlDateToIsoString(result.last_heartbeat_at),
1631
1663
  createdAt: parseSqlDateToIsoString(result.created_at),
1632
- createdBy: result.created_by ?? void 0,
1664
+ createdBy: (_a = result.created_by) != null ? _a : void 0,
1633
1665
  secrets,
1634
1666
  state
1635
1667
  };
@@ -1638,18 +1670,20 @@ class DatabaseTaskStore {
1638
1670
  }
1639
1671
  }
1640
1672
  async createTask(options) {
1673
+ var _a;
1641
1674
  const taskId = uuid.v4();
1642
1675
  await this.db("tasks").insert({
1643
1676
  id: taskId,
1644
1677
  spec: JSON.stringify(options.spec),
1645
1678
  secrets: options.secrets ? JSON.stringify(options.secrets) : void 0,
1646
- created_by: options.createdBy ?? null,
1679
+ created_by: (_a = options.createdBy) != null ? _a : null,
1647
1680
  status: "open"
1648
1681
  });
1649
1682
  return { taskId };
1650
1683
  }
1651
1684
  async claimTask() {
1652
1685
  return this.db.transaction(async (tx) => {
1686
+ var _a;
1653
1687
  const [task] = await tx("tasks").where({
1654
1688
  status: "open"
1655
1689
  }).limit(1).select();
@@ -1682,7 +1716,7 @@ class DatabaseTaskStore {
1682
1716
  status: "processing",
1683
1717
  lastHeartbeatAt: task.last_heartbeat_at,
1684
1718
  createdAt: task.created_at,
1685
- createdBy: task.created_by ?? void 0,
1719
+ createdBy: (_a = task.created_by) != null ? _a : void 0,
1686
1720
  secrets,
1687
1721
  state: getState()
1688
1722
  };
@@ -1811,7 +1845,7 @@ class DatabaseTaskStore {
1811
1845
  const { taskId } = options;
1812
1846
  const message = `This task was marked as stale as it exceeded its timeout`;
1813
1847
  const statusStepEvents = (await this.listEvents({ taskId })).events.filter(
1814
- ({ body }) => body?.stepId
1848
+ ({ body }) => body == null ? void 0 : body.stepId
1815
1849
  );
1816
1850
  const completedSteps = statusStepEvents.filter(
1817
1851
  ({ body: { status } }) => status === "failed" || status === "completed"
@@ -1864,6 +1898,7 @@ class DatabaseTaskStore {
1864
1898
  const taskIdsToRecover = [];
1865
1899
  const timeoutS = luxon.Duration.fromObject(options.timeout).as("seconds");
1866
1900
  await this.db.transaction(async (tx) => {
1901
+ var _a, _b;
1867
1902
  const heartbeatInterval = intervalFromNowTill(timeoutS, this.db);
1868
1903
  const result = await tx("tasks").where("status", "processing").andWhere("last_heartbeat_at", "<=", heartbeatInterval).update(
1869
1904
  {
@@ -1879,7 +1914,7 @@ class DatabaseTaskStore {
1879
1914
  task_id: id,
1880
1915
  event_type: "recovered",
1881
1916
  body: JSON.stringify({
1882
- recoverStrategy: taskSpec.EXPERIMENTAL_recovery?.EXPERIMENTAL_strategy ?? "none"
1917
+ recoverStrategy: (_b = (_a = taskSpec.EXPERIMENTAL_recovery) == null ? void 0 : _a.EXPERIMENTAL_strategy) != null ? _b : "none"
1883
1918
  })
1884
1919
  });
1885
1920
  }
@@ -1892,19 +1927,20 @@ function isTruthy(value) {
1892
1927
  return lodash.isArray(value) ? value.length > 0 : !!value;
1893
1928
  }
1894
1929
  function generateExampleOutput(schema) {
1930
+ var _a, _b;
1895
1931
  const { examples } = schema;
1896
1932
  if (examples && Array.isArray(examples)) {
1897
1933
  return examples[0];
1898
1934
  }
1899
1935
  if (schema.type === "object") {
1900
1936
  return Object.fromEntries(
1901
- Object.entries(schema.properties ?? {}).map(([key, value]) => [
1937
+ Object.entries((_a = schema.properties) != null ? _a : {}).map(([key, value]) => [
1902
1938
  key,
1903
1939
  generateExampleOutput(value)
1904
1940
  ])
1905
1941
  );
1906
1942
  } else if (schema.type === "array") {
1907
- const [firstSchema] = [schema.items]?.flat();
1943
+ const [firstSchema] = (_b = [schema.items]) == null ? void 0 : _b.flat();
1908
1944
  if (firstSchema) {
1909
1945
  return [generateExampleOutput(firstSchema)];
1910
1946
  }
@@ -1919,12 +1955,18 @@ function generateExampleOutput(schema) {
1919
1955
  return "<unknown>";
1920
1956
  }
1921
1957
  const readDuration$1 = (config$1, key, defaultValue) => {
1922
- if (config$1?.has(key)) {
1958
+ if (config$1 == null ? void 0 : config$1.has(key)) {
1923
1959
  return config.readDurationFromConfig(config$1, { key });
1924
1960
  }
1925
1961
  return defaultValue;
1926
1962
  };
1927
1963
 
1964
+ var __defProp$2 = Object.defineProperty;
1965
+ var __defNormalProp$2 = (obj, key, value) => key in obj ? __defProp$2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
1966
+ var __publicField$2 = (obj, key, value) => {
1967
+ __defNormalProp$2(obj, typeof key !== "symbol" ? key + "" : key, value);
1968
+ return value;
1969
+ };
1928
1970
  class TaskManager {
1929
1971
  // Runs heartbeat internally
1930
1972
  constructor(task, storage, signal, logger, auth, config) {
@@ -1934,9 +1976,9 @@ class TaskManager {
1934
1976
  this.logger = logger;
1935
1977
  this.auth = auth;
1936
1978
  this.config = config;
1979
+ __publicField$2(this, "isDone", false);
1980
+ __publicField$2(this, "heartbeatTimeoutId");
1937
1981
  }
1938
- isDone = false;
1939
- heartbeatTimeoutId;
1940
1982
  static create(task, storage, abortSignal, logger, auth, config) {
1941
1983
  const agent = new TaskManager(
1942
1984
  task,
@@ -1965,8 +2007,9 @@ class TaskManager {
1965
2007
  return this.task.taskId;
1966
2008
  }
1967
2009
  async rehydrateWorkspace(options) {
2010
+ var _a, _b;
1968
2011
  if (this.isWorkspaceSerializationEnabled()) {
1969
- this.storage.rehydrateWorkspace?.(options);
2012
+ (_b = (_a = this.storage).rehydrateWorkspace) == null ? void 0 : _b.call(_a, options);
1970
2013
  }
1971
2014
  }
1972
2015
  get done() {
@@ -1979,31 +2022,35 @@ class TaskManager {
1979
2022
  });
1980
2023
  }
1981
2024
  async getTaskState() {
1982
- return this.storage.getTaskState?.({ taskId: this.task.taskId });
2025
+ var _a, _b;
2026
+ return (_b = (_a = this.storage).getTaskState) == null ? void 0 : _b.call(_a, { taskId: this.task.taskId });
1983
2027
  }
1984
2028
  async updateCheckpoint(options) {
2029
+ var _a, _b;
1985
2030
  const { key, ...value } = options;
1986
2031
  if (this.task.state) {
1987
2032
  this.task.state.checkpoints[key] = value;
1988
2033
  } else {
1989
2034
  this.task.state = { checkpoints: { [key]: value } };
1990
2035
  }
1991
- await this.storage.saveTaskState?.({
2036
+ await ((_b = (_a = this.storage).saveTaskState) == null ? void 0 : _b.call(_a, {
1992
2037
  taskId: this.task.taskId,
1993
2038
  state: this.task.state
1994
- });
2039
+ }));
1995
2040
  }
1996
2041
  async serializeWorkspace(options) {
2042
+ var _a, _b;
1997
2043
  if (this.isWorkspaceSerializationEnabled()) {
1998
- await this.storage.serializeWorkspace?.({
2044
+ await ((_b = (_a = this.storage).serializeWorkspace) == null ? void 0 : _b.call(_a, {
1999
2045
  path: options.path,
2000
2046
  taskId: this.task.taskId
2001
- });
2047
+ }));
2002
2048
  }
2003
2049
  }
2004
2050
  async cleanWorkspace() {
2051
+ var _a, _b;
2005
2052
  if (this.isWorkspaceSerializationEnabled()) {
2006
- await this.storage.cleanWorkspace?.({ taskId: this.task.taskId });
2053
+ await ((_b = (_a = this.storage).cleanWorkspace) == null ? void 0 : _b.call(_a, { taskId: this.task.taskId }));
2007
2054
  }
2008
2055
  }
2009
2056
  async complete(result, metadata) {
@@ -2035,9 +2082,10 @@ class TaskManager {
2035
2082
  }, 1e3);
2036
2083
  }
2037
2084
  isWorkspaceSerializationEnabled() {
2038
- return this.config?.getOptionalBoolean(
2085
+ var _a, _b;
2086
+ return (_b = (_a = this.config) == null ? void 0 : _a.getOptionalBoolean(
2039
2087
  "scaffolder.EXPERIMENTAL_workspaceSerialization"
2040
- ) ?? false;
2088
+ )) != null ? _b : false;
2041
2089
  }
2042
2090
  async getInitiatorCredentials() {
2043
2091
  const secrets = this.task.secrets;
@@ -2066,6 +2114,7 @@ class StorageTaskBroker {
2066
2114
  this.logger = logger;
2067
2115
  this.config = config;
2068
2116
  this.auth = auth;
2117
+ __publicField$2(this, "deferredDispatch", defer());
2069
2118
  }
2070
2119
  async list(options) {
2071
2120
  if (!this.storage.list) {
@@ -2073,9 +2122,8 @@ class StorageTaskBroker {
2073
2122
  "TaskStore does not implement the list method. Please implement the list method to be able to list tasks"
2074
2123
  );
2075
2124
  }
2076
- return await this.storage.list({ createdBy: options?.createdBy });
2125
+ return await this.storage.list({ createdBy: options == null ? void 0 : options.createdBy });
2077
2126
  }
2078
- deferredDispatch = defer();
2079
2127
  async registerCancellable(taskId, abortController) {
2080
2128
  let shouldUnsubscribe = false;
2081
2129
  const subscription = this.event$({ taskId, after: void 0 }).subscribe({
@@ -2099,9 +2147,10 @@ class StorageTaskBroker {
2099
2147
  });
2100
2148
  }
2101
2149
  async recoverTasks() {
2102
- const enabled = (this.config && this.config.getOptionalBoolean(
2150
+ var _a, _b, _c, _d;
2151
+ const enabled = (_a = this.config && this.config.getOptionalBoolean(
2103
2152
  "scaffolder.EXPERIMENTAL_recoverTasks"
2104
- )) ?? false;
2153
+ )) != null ? _a : false;
2105
2154
  if (enabled) {
2106
2155
  const defaultTimeout = { seconds: 30 };
2107
2156
  const timeout = readDuration$1(
@@ -2109,9 +2158,9 @@ class StorageTaskBroker {
2109
2158
  "scaffolder.EXPERIMENTAL_recoverTasksTimeout",
2110
2159
  defaultTimeout
2111
2160
  );
2112
- const { ids: recoveredTaskIds } = await this.storage.recoverTasks?.({
2161
+ const { ids: recoveredTaskIds } = (_d = await ((_c = (_b = this.storage).recoverTasks) == null ? void 0 : _c.call(_b, {
2113
2162
  timeout
2114
- }) ?? { ids: [] };
2163
+ }))) != null ? _d : { ids: [] };
2115
2164
  if (recoveredTaskIds.length > 0) {
2116
2165
  this.signalDispatch();
2117
2166
  }
@@ -2213,16 +2262,17 @@ class StorageTaskBroker {
2213
2262
  this.deferredDispatch = defer();
2214
2263
  }
2215
2264
  async cancel(taskId) {
2265
+ var _a, _b;
2216
2266
  const { events } = await this.storage.listEvents({ taskId });
2217
- const currentStepId = events.length > 0 ? events.filter(({ body }) => body?.stepId).reduce((prev, curr) => prev.id > curr.id ? prev : curr).body.stepId : 0;
2218
- await this.storage.cancelTask?.({
2267
+ const currentStepId = events.length > 0 ? events.filter(({ body }) => body == null ? void 0 : body.stepId).reduce((prev, curr) => prev.id > curr.id ? prev : curr).body.stepId : 0;
2268
+ await ((_b = (_a = this.storage).cancelTask) == null ? void 0 : _b.call(_a, {
2219
2269
  taskId,
2220
2270
  body: {
2221
2271
  message: `Step ${currentStepId} has been cancelled.`,
2222
2272
  stepId: currentStepId,
2223
2273
  status: "cancelled"
2224
2274
  }
2225
- });
2275
+ }));
2226
2276
  }
2227
2277
  }
2228
2278
 
@@ -2252,7 +2302,8 @@ const hasTag = createTemplatePermissionRule({
2252
2302
  tag: zod.z.string().describe("Name of the tag to match on")
2253
2303
  }),
2254
2304
  apply: (resource, { tag }) => {
2255
- return resource["backstage:permissions"]?.tags?.includes(tag) ?? false;
2305
+ var _a, _b, _c;
2306
+ return (_c = (_b = (_a = resource["backstage:permissions"]) == null ? void 0 : _a.tags) == null ? void 0 : _b.includes(tag)) != null ? _c : false;
2256
2307
  },
2257
2308
  toQuery: () => ({})
2258
2309
  });
@@ -2323,56 +2374,85 @@ const scaffolderActionRules = {
2323
2374
  hasStringProperty
2324
2375
  };
2325
2376
 
2377
+ var __accessCheck = (obj, member, msg) => {
2378
+ if (!member.has(obj))
2379
+ throw TypeError("Cannot " + msg);
2380
+ };
2381
+ var __privateGet = (obj, member, getter) => {
2382
+ __accessCheck(obj, member, "read from private field");
2383
+ return member.get(obj);
2384
+ };
2385
+ var __privateAdd = (obj, member, value) => {
2386
+ if (member.has(obj))
2387
+ throw TypeError("Cannot add the same private member more than once");
2388
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
2389
+ };
2390
+ var __privateSet = (obj, member, value, setter) => {
2391
+ __accessCheck(obj, member, "write to private field");
2392
+ member.set(obj, value);
2393
+ return value;
2394
+ };
2395
+ var _winston, _addRedactions;
2326
2396
  const escapeRegExp = (text) => {
2327
2397
  return text.replace(/[.*+?^${}(\)|[\]\\]/g, "\\$&");
2328
2398
  };
2329
2399
  class BackstageLoggerTransport extends Transport__default.default {
2330
- constructor(backstageLogger, opts) {
2400
+ constructor(backstageLogger, taskContext, stepId, opts) {
2331
2401
  super(opts);
2332
2402
  this.backstageLogger = backstageLogger;
2403
+ this.taskContext = taskContext;
2404
+ this.stepId = stepId;
2333
2405
  }
2334
2406
  log(info, callback) {
2335
2407
  if (typeof info !== "object" || info === null) {
2336
2408
  callback();
2337
2409
  return;
2338
2410
  }
2339
- const { level, message, ...meta } = info;
2411
+ const message = info[tripleBeam.MESSAGE];
2412
+ const level = info[tripleBeam.LEVEL];
2413
+ const splat = info[tripleBeam.SPLAT];
2340
2414
  switch (level) {
2341
2415
  case "error":
2342
- this.backstageLogger.error(String(message), meta);
2416
+ this.backstageLogger.error(String(message), ...splat);
2343
2417
  break;
2344
2418
  case "warn":
2345
- this.backstageLogger.warn(String(message), meta);
2419
+ this.backstageLogger.warn(String(message), ...splat);
2346
2420
  break;
2347
2421
  case "info":
2348
- this.backstageLogger.info(String(message), meta);
2422
+ this.backstageLogger.info(String(message), ...splat);
2349
2423
  break;
2350
2424
  case "debug":
2351
- this.backstageLogger.debug(String(message), meta);
2425
+ this.backstageLogger.debug(String(message), ...splat);
2352
2426
  break;
2353
2427
  default:
2354
- this.backstageLogger.info(String(message), meta);
2428
+ this.backstageLogger.info(String(message), ...splat);
2355
2429
  }
2430
+ this.taskContext.emitLog(message, { stepId: this.stepId });
2356
2431
  callback();
2357
2432
  }
2358
2433
  }
2359
- class WinstonLogger {
2360
- #winston;
2361
- #addRedactions;
2434
+ const _WinstonLogger = class _WinstonLogger {
2435
+ constructor(winston, addRedactions) {
2436
+ __privateAdd(this, _winston, void 0);
2437
+ __privateAdd(this, _addRedactions, void 0);
2438
+ __privateSet(this, _winston, winston);
2439
+ __privateSet(this, _addRedactions, addRedactions);
2440
+ }
2362
2441
  /**
2363
2442
  * Creates a {@link WinstonLogger} instance.
2364
2443
  */
2365
2444
  static create(options) {
2366
- const redacter = WinstonLogger.redacter();
2445
+ var _a;
2446
+ const redacter = _WinstonLogger.redacter();
2367
2447
  let logger = winston.createLogger({
2368
2448
  level: options.level,
2369
- format: winston.format.combine(redacter.format, options.format),
2370
- transports: options.transports ?? new winston.transports.Console()
2449
+ format: winston.format.combine(options.format, redacter.format),
2450
+ transports: (_a = options.transports) != null ? _a : new winston.transports.Console()
2371
2451
  });
2372
2452
  if (options.meta) {
2373
2453
  logger = logger.child(options.meta);
2374
2454
  }
2375
- return new WinstonLogger(logger, redacter.add);
2455
+ return new _WinstonLogger(logger, redacter.add);
2376
2456
  }
2377
2457
  /**
2378
2458
  * Creates a winston log formatter for redacting secrets.
@@ -2382,10 +2462,11 @@ class WinstonLogger {
2382
2462
  let redactionPattern = void 0;
2383
2463
  return {
2384
2464
  format: winston.format((obj) => {
2465
+ var _a, _b;
2385
2466
  if (!redactionPattern || !obj) {
2386
2467
  return obj;
2387
2468
  }
2388
- obj[tripleBeam.MESSAGE] = obj[tripleBeam.MESSAGE]?.replace?.(redactionPattern, "***");
2469
+ obj[tripleBeam.MESSAGE] = (_b = (_a = obj[tripleBeam.MESSAGE]) == null ? void 0 : _a.replace) == null ? void 0 : _b.call(_a, redactionPattern, "[REDACTED]");
2389
2470
  return obj;
2390
2471
  })(),
2391
2472
  add(newRedactions) {
@@ -2423,7 +2504,10 @@ class WinstonLogger {
2423
2504
  }
2424
2505
  }),
2425
2506
  winston.format.printf((info) => {
2426
- const { timestamp, level, message, plugin, service, ...fields } = info;
2507
+ const { timestamp, plugin, service } = info;
2508
+ const message = info[tripleBeam.MESSAGE];
2509
+ const level = info[tripleBeam.LEVEL];
2510
+ const fields = info[tripleBeam.SPLAT];
2427
2511
  const prefix = plugin || service;
2428
2512
  const timestampColor = colorizer.colorize("timestamp", timestamp);
2429
2513
  const prefixColor = colorizer.colorize("prefix", prefix);
@@ -2434,30 +2518,36 @@ class WinstonLogger {
2434
2518
  })
2435
2519
  );
2436
2520
  }
2437
- constructor(winston, addRedactions) {
2438
- this.#winston = winston;
2439
- this.#addRedactions = addRedactions;
2440
- }
2441
2521
  error(message, meta) {
2442
- this.#winston.error(message, meta);
2522
+ __privateGet(this, _winston).error(message, meta);
2443
2523
  }
2444
2524
  warn(message, meta) {
2445
- this.#winston.warn(message, meta);
2525
+ __privateGet(this, _winston).warn(message, meta);
2446
2526
  }
2447
2527
  info(message, meta) {
2448
- this.#winston.info(message, meta);
2528
+ __privateGet(this, _winston).info(message, meta);
2449
2529
  }
2450
2530
  debug(message, meta) {
2451
- this.#winston.debug(message, meta);
2531
+ __privateGet(this, _winston).debug(message, meta);
2452
2532
  }
2453
2533
  child(meta) {
2454
- return new WinstonLogger(this.#winston.child(meta));
2534
+ return new _WinstonLogger(__privateGet(this, _winston).child(meta));
2455
2535
  }
2456
2536
  addRedactions(redactions) {
2457
- this.#addRedactions?.(redactions);
2537
+ var _a;
2538
+ (_a = __privateGet(this, _addRedactions)) == null ? void 0 : _a.call(this, redactions);
2458
2539
  }
2459
- }
2540
+ };
2541
+ _winston = new WeakMap();
2542
+ _addRedactions = new WeakMap();
2543
+ let WinstonLogger = _WinstonLogger;
2460
2544
 
2545
+ var __defProp$1 = Object.defineProperty;
2546
+ var __defNormalProp$1 = (obj, key, value) => key in obj ? __defProp$1(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
2547
+ var __publicField$1 = (obj, key, value) => {
2548
+ __defNormalProp$1(obj, typeof key !== "symbol" ? key + "" : key, value);
2549
+ return value;
2550
+ };
2461
2551
  const isValidTaskSpec = (taskSpec) => {
2462
2552
  return taskSpec.apiVersion === "scaffolder.backstage.io/v1beta3";
2463
2553
  };
@@ -2466,29 +2556,20 @@ const createStepLogger = ({
2466
2556
  step,
2467
2557
  rootLogger
2468
2558
  }) => {
2469
- const stepLogStream = new stream.PassThrough();
2470
- stepLogStream.on("data", async (data) => {
2471
- const message = data.toString().trim();
2472
- if (message?.length > 1) {
2473
- await task.emitLog(message, { stepId: step.id });
2474
- }
2475
- });
2559
+ var _a;
2476
2560
  const taskLogger = WinstonLogger.create({
2477
2561
  level: process.env.LOG_LEVEL || "info",
2478
2562
  format: winston__namespace.format.combine(
2479
2563
  winston__namespace.format.colorize(),
2480
2564
  winston__namespace.format.simple()
2481
2565
  ),
2482
- transports: [
2483
- new winston__namespace.transports.Stream({ stream: stepLogStream }),
2484
- new BackstageLoggerTransport(rootLogger)
2485
- ]
2566
+ transports: [new BackstageLoggerTransport(rootLogger, task, step.id)]
2486
2567
  });
2487
- taskLogger.addRedactions(Object.values(task.secrets ?? {}));
2568
+ taskLogger.addRedactions(Object.values((_a = task.secrets) != null ? _a : {}));
2488
2569
  const streamLogger = new stream.PassThrough();
2489
2570
  streamLogger.on("data", async (data) => {
2490
2571
  const message = data.toString().trim();
2491
- if (message?.length > 1) {
2572
+ if ((message == null ? void 0 : message.length) > 1) {
2492
2573
  taskLogger.info(message);
2493
2574
  }
2494
2575
  });
@@ -2500,13 +2581,14 @@ const isActionAuthorized = pluginPermissionNode.createConditionAuthorizer(
2500
2581
  class NunjucksWorkflowRunner {
2501
2582
  constructor(options) {
2502
2583
  this.options = options;
2584
+ __publicField$1(this, "defaultTemplateFilters");
2585
+ __publicField$1(this, "tracker", scaffoldingTracker());
2503
2586
  this.defaultTemplateFilters = createDefaultFilters({
2504
2587
  integrations: this.options.integrations
2505
2588
  });
2506
2589
  }
2507
- defaultTemplateFilters;
2508
- tracker = scaffoldingTracker();
2509
2590
  isSingleTemplateString(input) {
2591
+ var _a, _b;
2510
2592
  const { parser, nodes } = nunjucks__default.default;
2511
2593
  const parsed = parser.parse(
2512
2594
  input,
@@ -2519,7 +2601,7 @@ class NunjucksWorkflowRunner {
2519
2601
  }
2520
2602
  }
2521
2603
  );
2522
- return parsed.children.length === 1 && !(parsed.children[0]?.children?.[0] instanceof nodes.TemplateData);
2604
+ return parsed.children.length === 1 && !(((_b = (_a = parsed.children[0]) == null ? void 0 : _a.children) == null ? void 0 : _b[0]) instanceof nodes.TemplateData);
2523
2605
  }
2524
2606
  render(input, context, renderTemplate) {
2525
2607
  return JSON.parse(JSON.stringify(input), (_key, value) => {
@@ -2555,6 +2637,7 @@ class NunjucksWorkflowRunner {
2555
2637
  });
2556
2638
  }
2557
2639
  async executeStep(task, step, context, renderTemplate, taskTrack, workspacePath, decision) {
2640
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2558
2641
  const stepTrack = await this.tracker.stepStart(task, step);
2559
2642
  if (task.cancelSignal.aborted) {
2560
2643
  throw new Error(`Step ${step.name} has been cancelled.`);
@@ -2575,16 +2658,19 @@ class NunjucksWorkflowRunner {
2575
2658
  });
2576
2659
  if (task.isDryRun) {
2577
2660
  const redactedSecrets = Object.fromEntries(
2578
- Object.entries(task.secrets ?? {}).map((secret) => [secret[0], "***"])
2661
+ Object.entries((_a = task.secrets) != null ? _a : {}).map((secret) => [
2662
+ secret[0],
2663
+ "[REDACTED]"
2664
+ ])
2579
2665
  );
2580
- const debugInput = (step.input && this.render(
2666
+ const debugInput = (_b = step.input && this.render(
2581
2667
  step.input,
2582
2668
  {
2583
2669
  ...context,
2584
2670
  secrets: redactedSecrets
2585
2671
  },
2586
2672
  renderTemplate
2587
- )) ?? {};
2673
+ )) != null ? _b : {};
2588
2674
  taskLogger.info(
2589
2675
  `Running ${action.id} in dry-run mode with inputs (secrets redacted): ${JSON.stringify(
2590
2676
  debugInput,
@@ -2594,7 +2680,7 @@ class NunjucksWorkflowRunner {
2594
2680
  );
2595
2681
  if (!action.supportsDryRun) {
2596
2682
  await taskTrack.skipDryRun(step, action);
2597
- const outputSchema = action.schema?.output;
2683
+ const outputSchema = (_c = action.schema) == null ? void 0 : _c.output;
2598
2684
  if (outputSchema) {
2599
2685
  context.steps[step.id] = {
2600
2686
  output: generateExampleOutput(outputSchema)
@@ -2609,18 +2695,21 @@ class NunjucksWorkflowRunner {
2609
2695
  ([key, value]) => ({
2610
2696
  each: { key, value }
2611
2697
  })
2612
- ) : [{}]).map((i) => ({
2613
- ...i,
2614
- // Secrets are only passed when templating the input to actions for security reasons
2615
- input: step.input ? this.render(
2616
- step.input,
2617
- { ...context, secrets: task.secrets ?? {}, ...i },
2618
- renderTemplate
2619
- ) : {}
2620
- }));
2698
+ ) : [{}]).map((i) => {
2699
+ var _a2;
2700
+ return {
2701
+ ...i,
2702
+ // Secrets are only passed when templating the input to actions for security reasons
2703
+ input: step.input ? this.render(
2704
+ step.input,
2705
+ { ...context, secrets: (_a2 = task.secrets) != null ? _a2 : {}, ...i },
2706
+ renderTemplate
2707
+ ) : {}
2708
+ };
2709
+ });
2621
2710
  for (const iteration of iterations) {
2622
2711
  const actionId = `${action.id}${iteration.each ? `[${iteration.each.key}]` : ""}`;
2623
- if (action.schema?.input) {
2712
+ if ((_d = action.schema) == null ? void 0 : _d.input) {
2624
2713
  const validateResult = jsonschema.validate(
2625
2714
  iteration.input,
2626
2715
  action.schema.input
@@ -2647,7 +2736,7 @@ class NunjucksWorkflowRunner {
2647
2736
  }
2648
2737
  const tmpDirs = new Array();
2649
2738
  const stepOutput = {};
2650
- const prevTaskState = await task.getTaskState?.();
2739
+ const prevTaskState = await ((_e = task.getTaskState) == null ? void 0 : _e.call(task));
2651
2740
  for (const iteration of iterations) {
2652
2741
  if (iteration.each) {
2653
2742
  taskLogger.info(
@@ -2660,24 +2749,25 @@ class NunjucksWorkflowRunner {
2660
2749
  }
2661
2750
  await action.handler({
2662
2751
  input: iteration.input,
2663
- secrets: task.secrets ?? {},
2752
+ secrets: (_f = task.secrets) != null ? _f : {},
2664
2753
  // TODO(blam): move to LoggerService and away from Winston
2665
2754
  logger: backendCommon.loggerToWinstonLogger(taskLogger),
2666
2755
  logStream: streamLogger,
2667
2756
  workspacePath,
2668
2757
  async checkpoint(keySuffix, fn) {
2758
+ var _a2, _b2, _c2, _d2, _e2;
2669
2759
  const key = `v1.task.checkpoint.${keySuffix}`;
2670
2760
  try {
2671
2761
  let prevValue;
2672
2762
  if (prevTaskState) {
2673
- const prevState = prevTaskState.state?.checkpoints?.[key];
2763
+ const prevState = (_b2 = (_a2 = prevTaskState.state) == null ? void 0 : _a2.checkpoints) == null ? void 0 : _b2[key];
2674
2764
  if (prevState && prevState.status === "success") {
2675
2765
  prevValue = prevState.value;
2676
2766
  }
2677
2767
  }
2678
2768
  const value = prevValue ? prevValue : await fn();
2679
2769
  if (!prevValue) {
2680
- task.updateCheckpoint?.({
2770
+ (_c2 = task.updateCheckpoint) == null ? void 0 : _c2.call(task, {
2681
2771
  key,
2682
2772
  status: "success",
2683
2773
  value
@@ -2685,14 +2775,14 @@ class NunjucksWorkflowRunner {
2685
2775
  }
2686
2776
  return value;
2687
2777
  } catch (err) {
2688
- task.updateCheckpoint?.({
2778
+ (_d2 = task.updateCheckpoint) == null ? void 0 : _d2.call(task, {
2689
2779
  key,
2690
2780
  status: "failed",
2691
2781
  reason: errors.stringifyError(err)
2692
2782
  });
2693
2783
  throw err;
2694
2784
  } finally {
2695
- await task.serializeWorkspace?.({ path: workspacePath });
2785
+ await ((_e2 = task.serializeWorkspace) == null ? void 0 : _e2.call(task, { path: workspacePath }));
2696
2786
  }
2697
2787
  },
2698
2788
  createTemporaryDirectory: async () => {
@@ -2724,17 +2814,18 @@ class NunjucksWorkflowRunner {
2724
2814
  if (task.cancelSignal.aborted) {
2725
2815
  throw new Error(`Step ${step.name} has been cancelled.`);
2726
2816
  }
2727
- await task.cleanWorkspace?.();
2817
+ await ((_g = task.cleanWorkspace) == null ? void 0 : _g.call(task));
2728
2818
  await stepTrack.markSuccessful();
2729
2819
  } catch (err) {
2730
2820
  await taskTrack.markFailed(step, err);
2731
2821
  await stepTrack.markFailed();
2732
2822
  throw err;
2733
2823
  } finally {
2734
- await task.serializeWorkspace?.({ path: workspacePath });
2824
+ await ((_h = task.serializeWorkspace) == null ? void 0 : _h.call(task, { path: workspacePath }));
2735
2825
  }
2736
2826
  }
2737
2827
  async execute(task) {
2828
+ var _a;
2738
2829
  if (!isValidTaskSpec(task.spec)) {
2739
2830
  throw new errors.InputError(
2740
2831
  "Wrong template version executed with the workflow engine"
@@ -2751,7 +2842,7 @@ class NunjucksWorkflowRunner {
2751
2842
  templateGlobals: additionalTemplateGlobals
2752
2843
  });
2753
2844
  try {
2754
- await task.rehydrateWorkspace?.({ taskId, targetPath: workspacePath });
2845
+ await ((_a = task.rehydrateWorkspace) == null ? void 0 : _a.call(task, { taskId, targetPath: workspacePath }));
2755
2846
  const taskTrack = await this.tracker.taskStart(task);
2756
2847
  await fs__default.default.ensureDir(workspacePath);
2757
2848
  const context = {
@@ -2806,9 +2897,10 @@ function scaffoldingTracker() {
2806
2897
  labelNames: ["template", "step", "result"]
2807
2898
  });
2808
2899
  async function taskStart(task) {
2900
+ var _a, _b;
2809
2901
  await task.emitLog(`Starting up task with ${task.spec.steps.length} steps`);
2810
- const template = task.spec.templateInfo?.entityRef || "";
2811
- const user = task.spec.user?.ref || "";
2902
+ const template = ((_a = task.spec.templateInfo) == null ? void 0 : _a.entityRef) || "";
2903
+ const user = ((_b = task.spec.user) == null ? void 0 : _b.ref) || "";
2812
2904
  const taskTimer = taskDuration.startTimer({
2813
2905
  template
2814
2906
  });
@@ -2858,11 +2950,12 @@ function scaffoldingTracker() {
2858
2950
  };
2859
2951
  }
2860
2952
  async function stepStart(task, step) {
2953
+ var _a;
2861
2954
  await task.emitLog(`Beginning step ${step.name}`, {
2862
2955
  stepId: step.id,
2863
2956
  status: "processing"
2864
2957
  });
2865
- const template = task.spec.templateInfo?.entityRef || "";
2958
+ const template = ((_a = task.spec.templateInfo) == null ? void 0 : _a.entityRef) || "";
2866
2959
  const stepTimer = stepDuration.startTimer({
2867
2960
  template,
2868
2961
  step: step.name
@@ -2915,18 +3008,24 @@ function scaffoldingTracker() {
2915
3008
  };
2916
3009
  }
2917
3010
 
3011
+ var __defProp = Object.defineProperty;
3012
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3013
+ var __publicField = (obj, key, value) => {
3014
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
3015
+ return value;
3016
+ };
2918
3017
  class TaskWorker {
2919
3018
  constructor(options) {
2920
3019
  this.options = options;
3020
+ __publicField(this, "taskQueue");
3021
+ __publicField(this, "logger");
3022
+ __publicField(this, "stopWorkers");
2921
3023
  this.stopWorkers = false;
2922
3024
  this.logger = options.logger;
2923
3025
  this.taskQueue = new PQueue__default.default({
2924
3026
  concurrency: options.concurrentTasksLimit
2925
3027
  });
2926
3028
  }
2927
- taskQueue;
2928
- logger;
2929
- stopWorkers;
2930
3029
  static async create(options) {
2931
3030
  const {
2932
3031
  taskBroker,
@@ -2957,10 +3056,11 @@ class TaskWorker {
2957
3056
  });
2958
3057
  }
2959
3058
  async recoverTasks() {
3059
+ var _a, _b, _c;
2960
3060
  try {
2961
- await this.options.taskBroker.recoverTasks?.();
3061
+ await ((_b = (_a = this.options.taskBroker).recoverTasks) == null ? void 0 : _b.call(_a));
2962
3062
  } catch (err) {
2963
- this.logger?.error(errors.stringifyError(err));
3063
+ (_c = this.logger) == null ? void 0 : _c.error(errors.stringifyError(err));
2964
3064
  }
2965
3065
  }
2966
3066
  start() {
@@ -3082,7 +3182,7 @@ function createDryRunner(options) {
3082
3182
  getWorkspaceName: async () => `dry-run-${dryRunId}`,
3083
3183
  cancelSignal: abortSignal,
3084
3184
  async emitLog(message, logMetadata) {
3085
- if (logMetadata?.stepId === dryRunId) {
3185
+ if ((logMetadata == null ? void 0 : logMetadata.stepId) === dryRunId) {
3086
3186
  return;
3087
3187
  }
3088
3188
  log.push({
@@ -3129,9 +3229,10 @@ async function getWorkingDirectory(config, logger) {
3129
3229
  return workingDirectory;
3130
3230
  }
3131
3231
  function getEntityBaseUrl(entity) {
3132
- let location = entity.metadata.annotations?.[catalogModel.ANNOTATION_SOURCE_LOCATION];
3232
+ var _a, _b;
3233
+ let location = (_a = entity.metadata.annotations) == null ? void 0 : _a[catalogModel.ANNOTATION_SOURCE_LOCATION];
3133
3234
  if (!location) {
3134
- location = entity.metadata.annotations?.[catalogModel.ANNOTATION_LOCATION];
3235
+ location = (_b = entity.metadata.annotations) == null ? void 0 : _b[catalogModel.ANNOTATION_LOCATION];
3135
3236
  }
3136
3237
  if (!location) {
3137
3238
  return void 0;
@@ -3158,24 +3259,6 @@ async function findTemplate(options) {
3158
3259
  return template;
3159
3260
  }
3160
3261
 
3161
- async function checkPermission(options) {
3162
- const { permissions, permissionService, credentials } = options;
3163
- if (permissionService) {
3164
- const permissionRequest = permissions.map((permission) => ({
3165
- permission
3166
- }));
3167
- const authorizationResponses = await permissionService.authorize(
3168
- permissionRequest,
3169
- { credentials }
3170
- );
3171
- for (const response of authorizationResponses) {
3172
- if (response.result === pluginPermissionCommon.AuthorizeResult.DENY) {
3173
- throw new errors.NotAllowedError();
3174
- }
3175
- }
3176
- }
3177
- }
3178
-
3179
3262
  function isTemplatePermissionRuleInput(permissionRule) {
3180
3263
  return permissionRule.resourceType === alpha.RESOURCE_TYPE_SCAFFOLDER_TEMPLATE;
3181
3264
  }
@@ -3188,13 +3271,14 @@ function isSupportedTemplate(entity) {
3188
3271
  function buildDefaultIdentityClient(options) {
3189
3272
  return {
3190
3273
  getIdentity: async ({ request }) => {
3274
+ var _a;
3191
3275
  const header = request.headers.authorization;
3192
3276
  const { logger } = options;
3193
3277
  if (!header) {
3194
3278
  return void 0;
3195
3279
  }
3196
3280
  try {
3197
- const token = header.match(/^Bearer\s(\S+\.\S+\.\S+)$/i)?.[1];
3281
+ const token = (_a = header.match(/^Bearer\s(\S+\.\S+\.\S+)$/i)) == null ? void 0 : _a[1];
3198
3282
  if (!token) {
3199
3283
  throw new TypeError("Expected Bearer with JWT");
3200
3284
  }
@@ -3235,6 +3319,7 @@ const readDuration = (config$1, key, defaultValue) => {
3235
3319
  return defaultValue;
3236
3320
  };
3237
3321
  async function createRouter(options) {
3322
+ var _a;
3238
3323
  const router = Router__default.default();
3239
3324
  router.use(express__default.default.json({ limit: "10MB" }));
3240
3325
  const {
@@ -3258,7 +3343,7 @@ async function createRouter(options) {
3258
3343
  identity,
3259
3344
  discovery
3260
3345
  });
3261
- const concurrentTasksLimit = options.concurrentTasksLimit ?? options.config.getOptionalNumber("scaffolder.concurrentTasksLimit");
3346
+ const concurrentTasksLimit = (_a = options.concurrentTasksLimit) != null ? _a : options.config.getOptionalNumber("scaffolder.concurrentTasksLimit");
3262
3347
  const logger = parentLogger.child({ plugin: "scaffolder" });
3263
3348
  const workingDirectory = await getWorkingDirectory(config, logger);
3264
3349
  const integrations = integration.ScmIntegrations.fromConfig(config);
@@ -3367,13 +3452,13 @@ async function createRouter(options) {
3367
3452
  permissions: alpha.scaffolderActionPermissions,
3368
3453
  rules: actionRules
3369
3454
  }
3370
- ],
3371
- permissions: alpha.scaffolderTaskPermissions
3455
+ ]
3372
3456
  });
3373
3457
  router.use(permissionIntegrationRouter);
3374
3458
  router.get(
3375
3459
  "/v2/templates/:namespace/:kind/:name/parameter-schema",
3376
3460
  async (req, res) => {
3461
+ var _a2, _b;
3377
3462
  const credentials = await httpAuth.credentials(req);
3378
3463
  const { token } = await auth.getPluginRequestToken({
3379
3464
  onBehalfOf: credentials,
@@ -3384,18 +3469,21 @@ async function createRouter(options) {
3384
3469
  token,
3385
3470
  credentials
3386
3471
  );
3387
- const parameters = [template.spec.parameters ?? []].flat();
3472
+ const parameters = [(_a2 = template.spec.parameters) != null ? _a2 : []].flat();
3388
3473
  const presentation = template.spec.presentation;
3389
3474
  res.json({
3390
- title: template.metadata.title ?? template.metadata.name,
3475
+ title: (_b = template.metadata.title) != null ? _b : template.metadata.name,
3391
3476
  ...presentation ? { presentation } : {},
3392
3477
  description: template.metadata.description,
3393
3478
  "ui:options": template.metadata["ui:options"],
3394
- steps: parameters.map((schema) => ({
3395
- title: schema.title ?? "Please enter the following information",
3396
- description: schema.description,
3397
- schema
3398
- }))
3479
+ steps: parameters.map((schema) => {
3480
+ var _a3;
3481
+ return {
3482
+ title: (_a3 = schema.title) != null ? _a3 : "Please enter the following information",
3483
+ description: schema.description,
3484
+ schema
3485
+ };
3486
+ })
3399
3487
  });
3400
3488
  }
3401
3489
  ).get("/v2/actions", async (_req, res) => {
@@ -3409,16 +3497,12 @@ async function createRouter(options) {
3409
3497
  });
3410
3498
  res.json(actionsList);
3411
3499
  }).post("/v2/tasks", async (req, res) => {
3500
+ var _a2, _b;
3412
3501
  const templateRef = req.body.templateRef;
3413
3502
  const { kind, namespace, name } = catalogModel.parseEntityRef(templateRef, {
3414
3503
  defaultKind: "template"
3415
3504
  });
3416
3505
  const credentials = await httpAuth.credentials(req);
3417
- await checkPermission({
3418
- credentials,
3419
- permissions: [alpha.taskCreatePermission],
3420
- permissionService: permissions
3421
- });
3422
3506
  const { token } = await auth.getPluginRequestToken({
3423
3507
  onBehalfOf: credentials,
3424
3508
  targetPluginId: "catalog"
@@ -3436,7 +3520,7 @@ async function createRouter(options) {
3436
3520
  token,
3437
3521
  credentials
3438
3522
  );
3439
- for (const parameters of [template.spec.parameters ?? []].flat()) {
3523
+ for (const parameters of [(_a2 = template.spec.parameters) != null ? _a2 : []].flat()) {
3440
3524
  const result2 = jsonschema.validate(values, parameters);
3441
3525
  if (!result2.valid) {
3442
3526
  res.status(400).json({ errors: result2.errors });
@@ -3446,13 +3530,16 @@ async function createRouter(options) {
3446
3530
  const baseUrl = getEntityBaseUrl(template);
3447
3531
  const taskSpec = {
3448
3532
  apiVersion: template.apiVersion,
3449
- steps: template.spec.steps.map((step, index) => ({
3450
- ...step,
3451
- id: step.id ?? `step-${index + 1}`,
3452
- name: step.name ?? step.action
3453
- })),
3533
+ steps: template.spec.steps.map((step, index) => {
3534
+ var _a3, _b2;
3535
+ return {
3536
+ ...step,
3537
+ id: (_a3 = step.id) != null ? _a3 : `step-${index + 1}`,
3538
+ name: (_b2 = step.name) != null ? _b2 : step.action
3539
+ };
3540
+ }),
3454
3541
  EXPERIMENTAL_recovery: template.spec.EXPERIMENTAL_recovery,
3455
- output: template.spec.output ?? {},
3542
+ output: (_b = template.spec.output) != null ? _b : {},
3456
3543
  parameters: values,
3457
3544
  user: {
3458
3545
  entity: userEntity,
@@ -3478,12 +3565,6 @@ async function createRouter(options) {
3478
3565
  });
3479
3566
  res.status(201).json({ id: result.taskId });
3480
3567
  }).get("/v2/tasks", async (req, res) => {
3481
- const credentials = await httpAuth.credentials(req);
3482
- await checkPermission({
3483
- credentials,
3484
- permissions: [alpha.taskReadPermission],
3485
- permissionService: permissions
3486
- });
3487
3568
  const [userEntityRef] = [req.query.createdBy].flat();
3488
3569
  if (typeof userEntityRef !== "string" && typeof userEntityRef !== "undefined") {
3489
3570
  throw new errors.InputError("createdBy query parameter must be a string");
@@ -3498,12 +3579,6 @@ async function createRouter(options) {
3498
3579
  });
3499
3580
  res.status(200).json(tasks);
3500
3581
  }).get("/v2/tasks/:taskId", async (req, res) => {
3501
- const credentials = await httpAuth.credentials(req);
3502
- await checkPermission({
3503
- credentials,
3504
- permissions: [alpha.taskReadPermission],
3505
- permissionService: permissions
3506
- });
3507
3582
  const { taskId } = req.params;
3508
3583
  const task = await taskBroker.get(taskId);
3509
3584
  if (!task) {
@@ -3512,22 +3587,11 @@ async function createRouter(options) {
3512
3587
  delete task.secrets;
3513
3588
  res.status(200).json(task);
3514
3589
  }).post("/v2/tasks/:taskId/cancel", async (req, res) => {
3515
- const credentials = await httpAuth.credentials(req);
3516
- await checkPermission({
3517
- credentials,
3518
- permissions: [alpha.taskCancelPermission, alpha.taskReadPermission],
3519
- permissionService: permissions
3520
- });
3590
+ var _a2;
3521
3591
  const { taskId } = req.params;
3522
- await taskBroker.cancel?.(taskId);
3592
+ await ((_a2 = taskBroker.cancel) == null ? void 0 : _a2.call(taskBroker, taskId));
3523
3593
  res.status(200).json({ status: "cancelled" });
3524
3594
  }).get("/v2/tasks/:taskId/eventstream", async (req, res) => {
3525
- const credentials = await httpAuth.credentials(req);
3526
- await checkPermission({
3527
- credentials,
3528
- permissions: [alpha.taskReadPermission],
3529
- permissionService: permissions
3530
- });
3531
3595
  const { taskId } = req.params;
3532
3596
  const after = req.query.after !== void 0 ? Number(req.query.after) : void 0;
3533
3597
  logger.debug(`Event stream observing taskId '${taskId}' opened`);
@@ -3544,6 +3608,7 @@ async function createRouter(options) {
3544
3608
  res.end();
3545
3609
  },
3546
3610
  next: ({ events }) => {
3611
+ var _a2;
3547
3612
  let shouldUnsubscribe = false;
3548
3613
  for (const event of events) {
3549
3614
  res.write(
@@ -3556,7 +3621,7 @@ data: ${JSON.stringify(event)}
3556
3621
  shouldUnsubscribe = true;
3557
3622
  }
3558
3623
  }
3559
- res.flush?.();
3624
+ (_a2 = res.flush) == null ? void 0 : _a2.call(res);
3560
3625
  if (shouldUnsubscribe) {
3561
3626
  subscription.unsubscribe();
3562
3627
  res.end();
@@ -3568,12 +3633,6 @@ data: ${JSON.stringify(event)}
3568
3633
  logger.debug(`Event stream observing taskId '${taskId}' closed`);
3569
3634
  });
3570
3635
  }).get("/v2/tasks/:taskId/events", async (req, res) => {
3571
- const credentials = await httpAuth.credentials(req);
3572
- await checkPermission({
3573
- credentials,
3574
- permissions: [alpha.taskReadPermission],
3575
- permissionService: permissions
3576
- });
3577
3636
  const { taskId } = req.params;
3578
3637
  const after = Number(req.query.after) || void 0;
3579
3638
  const timeout = setTimeout(() => {
@@ -3596,12 +3655,7 @@ data: ${JSON.stringify(event)}
3596
3655
  clearTimeout(timeout);
3597
3656
  });
3598
3657
  }).post("/v2/dry-run", async (req, res) => {
3599
- const credentials = await httpAuth.credentials(req);
3600
- await checkPermission({
3601
- credentials,
3602
- permissions: [alpha.taskCreatePermission],
3603
- permissionService: permissions
3604
- });
3658
+ var _a2, _b, _c;
3605
3659
  const bodySchema = zod.z.object({
3606
3660
  template: zod.z.unknown(),
3607
3661
  values: zod.z.record(zod.z.unknown()),
@@ -3617,30 +3671,34 @@ data: ${JSON.stringify(event)}
3617
3671
  if (!await pluginScaffolderCommon.templateEntityV1beta3Validator.check(template)) {
3618
3672
  throw new errors.InputError("Input template is not a template");
3619
3673
  }
3674
+ const credentials = await httpAuth.credentials(req);
3620
3675
  const { token } = await auth.getPluginRequestToken({
3621
3676
  onBehalfOf: credentials,
3622
3677
  targetPluginId: "catalog"
3623
3678
  });
3624
- for (const parameters of [template.spec.parameters ?? []].flat()) {
3679
+ for (const parameters of [(_a2 = template.spec.parameters) != null ? _a2 : []].flat()) {
3625
3680
  const result2 = jsonschema.validate(body.values, parameters);
3626
3681
  if (!result2.valid) {
3627
3682
  res.status(400).json({ errors: result2.errors });
3628
3683
  return;
3629
3684
  }
3630
3685
  }
3631
- const steps = template.spec.steps.map((step, index) => ({
3632
- ...step,
3633
- id: step.id ?? `step-${index + 1}`,
3634
- name: step.name ?? step.action
3635
- }));
3686
+ const steps = template.spec.steps.map((step, index) => {
3687
+ var _a3, _b2;
3688
+ return {
3689
+ ...step,
3690
+ id: (_a3 = step.id) != null ? _a3 : `step-${index + 1}`,
3691
+ name: (_b2 = step.name) != null ? _b2 : step.action
3692
+ };
3693
+ });
3636
3694
  const result = await dryRunner({
3637
3695
  spec: {
3638
3696
  apiVersion: template.apiVersion,
3639
3697
  steps,
3640
- output: template.spec.output ?? {},
3698
+ output: (_b = template.spec.output) != null ? _b : {},
3641
3699
  parameters: body.values
3642
3700
  },
3643
- directoryContents: (body.directoryContents ?? []).map((file) => ({
3701
+ directoryContents: ((_c = body.directoryContents) != null ? _c : []).map((file) => ({
3644
3702
  path: file.path,
3645
3703
  content: Buffer.from(file.base64Content, "base64")
3646
3704
  })),
@@ -3717,4 +3775,4 @@ exports.createRouter = createRouter;
3717
3775
  exports.createWaitAction = createWaitAction;
3718
3776
  exports.scaffolderActionRules = scaffolderActionRules;
3719
3777
  exports.scaffolderTemplateRules = scaffolderTemplateRules;
3720
- //# sourceMappingURL=router-Czj3wQrV.cjs.js.map
3778
+ //# sourceMappingURL=router-Bj9ovbjU.cjs.js.map