@backstage/plugin-scaffolder 1.2.0-next.3 → 1.3.0-next.1

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.
@@ -0,0 +1,2131 @@
1
+ import React, { useState, useContext, useCallback, createContext, useEffect, useRef, useMemo, Children, Component } from 'react';
2
+ import { useNavigate, Navigate, useOutlet, Routes, Route } from 'react-router';
3
+ import { ItemCardHeader, MarkdownContent, Button, ContentHeader, Progress, WarningPanel, Link as Link$1, Content, ItemCardGrid, Page, Header, CreateButton, SupportButton, StructuredMetadataTable, InfoCard, ErrorPage, ErrorPanel, LogViewer } from '@backstage/core-components';
4
+ import { useRouteRef, useApi, errorApiRef, featureFlagsApiRef, useApiHolder, alertApiRef, useElementFilter } from '@backstage/core-plugin-api';
5
+ import { getEntityRelations, getEntitySourceLocation, FavoriteEntity, EntityRefLinks, useEntityList, EntityListProvider, CatalogFilterLayout, EntitySearchBar, EntityKindPicker, UserListPicker, EntityTagPicker, catalogApiRef, humanizeEntityRef } from '@backstage/plugin-catalog-react';
6
+ import { s as selectedTemplateRouteRef, r as rootRouteRef, a as registerComponentRouteRef, T as TemplateTypePicker, S as SecretsContext, b as scaffolderApiRef, c as scaffolderTaskRouteRef, d as TaskStatusStepper, e as TaskPageLinks, F as FIELD_EXTENSION_WRAPPER_KEY, f as FIELD_EXTENSION_KEY, g as SecretsContextProvider, h as actionsRouteRef, i as editRouteRef, j as TaskPage } from './index-6a2f3be9.esm.js';
7
+ import { RELATION_OWNED_BY, stringifyEntityRef } from '@backstage/catalog-model';
8
+ import { makeStyles, useTheme, Card, CardMedia, CardContent, Box, Typography, Chip, CardActions, IconButton, Tooltip, Link, Stepper, Step, StepLabel, StepContent, Button as Button$1, Paper, LinearProgress, TableContainer, Table, TableHead, TableRow, TableCell, TableBody, Divider as Divider$1, FormControl, InputLabel, Select, MenuItem as MenuItem$1 } from '@material-ui/core';
9
+ import { scmIntegrationsApiRef, ScmIntegrationIcon } from '@backstage/integration-react';
10
+ import WarningIcon from '@material-ui/icons/Warning';
11
+ import { catalogEntityCreatePermission } from '@backstage/plugin-catalog-common';
12
+ import { usePermission } from '@backstage/plugin-permission-react';
13
+ import IconButton$1 from '@material-ui/core/IconButton';
14
+ import ListItemIcon from '@material-ui/core/ListItemIcon';
15
+ import ListItemText from '@material-ui/core/ListItemText';
16
+ import MenuItem from '@material-ui/core/MenuItem';
17
+ import MenuList from '@material-ui/core/MenuList';
18
+ import Popover from '@material-ui/core/Popover';
19
+ import { makeStyles as makeStyles$1 } from '@material-ui/core/styles';
20
+ import Description from '@material-ui/icons/Description';
21
+ import Edit from '@material-ui/icons/Edit';
22
+ import MoreVert from '@material-ui/icons/MoreVert';
23
+ import qs from 'qs';
24
+ import { useParams } from 'react-router-dom';
25
+ import useAsync from 'react-use/lib/useAsync';
26
+ import { withTheme } from '@rjsf/core';
27
+ import { Theme } from '@rjsf/material-ui';
28
+ import cloneDeep from 'lodash/cloneDeep';
29
+ import classNames from 'classnames';
30
+ import Card$1 from '@material-ui/core/Card';
31
+ import CardActionArea from '@material-ui/core/CardActionArea';
32
+ import CardContent$1 from '@material-ui/core/CardContent';
33
+ import Tooltip$1 from '@material-ui/core/Tooltip';
34
+ import Typography$1 from '@material-ui/core/Typography';
35
+ import InfoOutlinedIcon from '@material-ui/icons/InfoOutlined';
36
+ import { useAsync as useAsync$1, useRerender, usePrevious, useKeyboardEvent } from '@react-hookz/web';
37
+ import yaml from 'yaml';
38
+ import Accordion from '@material-ui/core/Accordion';
39
+ import AccordionDetails from '@material-ui/core/AccordionDetails';
40
+ import AccordionSummary from '@material-ui/core/AccordionSummary';
41
+ import Divider from '@material-ui/core/Divider';
42
+ import ExpandMoreIcon$1 from '@material-ui/icons/ExpandLess';
43
+ import List from '@material-ui/core/List';
44
+ import ListItem from '@material-ui/core/ListItem';
45
+ import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
46
+ import Cancel from '@material-ui/icons/Cancel';
47
+ import Check from '@material-ui/icons/Check';
48
+ import DeleteIcon from '@material-ui/icons/Delete';
49
+ import { StreamLanguage } from '@codemirror/language';
50
+ import { yaml as yaml$1 } from '@codemirror/legacy-modes/mode/yaml';
51
+ import Box$1 from '@material-ui/core/Box';
52
+ import Tab from '@material-ui/core/Tab';
53
+ import Tabs from '@material-ui/core/Tabs';
54
+ import CodeMirror from '@uiw/react-codemirror';
55
+ import TreeView from '@material-ui/lab/TreeView';
56
+ import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
57
+ import ChevronRightIcon from '@material-ui/icons/ChevronRight';
58
+ import TreeItem from '@material-ui/lab/TreeItem';
59
+ import CloseIcon from '@material-ui/icons/Close';
60
+ import RefreshIcon from '@material-ui/icons/Refresh';
61
+ import SaveIcon from '@material-ui/icons/Save';
62
+ import useDebounce from 'react-use/lib/useDebounce';
63
+ import { showPanel } from '@codemirror/view';
64
+ import { D as DEFAULT_SCAFFOLDER_FIELD_EXTENSIONS } from './default-bff55719.esm.js';
65
+ import '@backstage/errors';
66
+ import 'zen-observable';
67
+ import '@material-ui/core/FormControl';
68
+ import '@material-ui/lab/Autocomplete';
69
+ import 'react-use/lib/useEffectOnce';
70
+ import '@material-ui/lab';
71
+ import '@material-ui/core/FormHelperText';
72
+ import '@material-ui/core/Input';
73
+ import '@material-ui/core/InputLabel';
74
+ import 'lodash/capitalize';
75
+ import '@material-ui/icons/CheckBox';
76
+ import '@material-ui/icons/CheckBoxOutlineBlank';
77
+ import '@material-ui/core/Grid';
78
+ import '@material-ui/core/Step';
79
+ import '@material-ui/core/StepLabel';
80
+ import '@material-ui/core/Stepper';
81
+ import '@material-ui/icons/FiberManualRecord';
82
+ import 'luxon';
83
+ import 'react-use/lib/useInterval';
84
+ import 'use-immer';
85
+ import '@material-ui/icons/Language';
86
+
87
+ const useStyles$d = makeStyles((theme) => ({
88
+ cardHeader: {
89
+ position: "relative"
90
+ },
91
+ title: {
92
+ backgroundImage: ({ backgroundImage }) => backgroundImage
93
+ },
94
+ box: {
95
+ overflow: "hidden",
96
+ textOverflow: "ellipsis",
97
+ display: "-webkit-box",
98
+ "-webkit-line-clamp": 10,
99
+ "-webkit-box-orient": "vertical",
100
+ paddingBottom: "0.8em"
101
+ },
102
+ label: {
103
+ color: theme.palette.text.secondary,
104
+ textTransform: "uppercase",
105
+ fontSize: "0.65rem",
106
+ fontWeight: "bold",
107
+ letterSpacing: 0.5,
108
+ lineHeight: 1,
109
+ paddingBottom: "0.2rem"
110
+ },
111
+ leftButton: {
112
+ marginRight: "auto"
113
+ },
114
+ starButton: {
115
+ position: "absolute",
116
+ top: theme.spacing(0.5),
117
+ right: theme.spacing(0.5),
118
+ padding: "0.25rem",
119
+ color: "#fff"
120
+ }
121
+ }));
122
+ const useDeprecationStyles = makeStyles((theme) => ({
123
+ deprecationIcon: {
124
+ position: "absolute",
125
+ top: theme.spacing(0.5),
126
+ right: theme.spacing(3.5),
127
+ padding: "0.25rem"
128
+ },
129
+ link: {
130
+ color: theme.palette.warning.light
131
+ }
132
+ }));
133
+ const getTemplateCardProps = (template) => {
134
+ var _a, _b, _c, _d, _e;
135
+ return {
136
+ key: template.metadata.uid,
137
+ name: template.metadata.name,
138
+ title: `${(_a = template.metadata.title || template.metadata.name) != null ? _a : ""}`,
139
+ type: (_b = template.spec.type) != null ? _b : "",
140
+ description: (_c = template.metadata.description) != null ? _c : "-",
141
+ tags: (_e = (_d = template.metadata) == null ? void 0 : _d.tags) != null ? _e : []
142
+ };
143
+ };
144
+ const DeprecationWarning = () => {
145
+ const styles = useDeprecationStyles();
146
+ const Title = /* @__PURE__ */ React.createElement(Typography, {
147
+ style: { padding: 10, maxWidth: 300 }
148
+ }, "This template uses a syntax that has been deprecated, and should be migrated to a newer syntax. Click for more info.");
149
+ return /* @__PURE__ */ React.createElement("div", {
150
+ className: styles.deprecationIcon
151
+ }, /* @__PURE__ */ React.createElement(Tooltip, {
152
+ title: Title
153
+ }, /* @__PURE__ */ React.createElement(Link, {
154
+ href: "https://backstage.io/docs/features/software-templates/migrating-from-v1beta2-to-v1beta3",
155
+ className: styles.link
156
+ }, /* @__PURE__ */ React.createElement(WarningIcon, null))));
157
+ };
158
+ const TemplateCard = ({ template, deprecated }) => {
159
+ var _a;
160
+ const backstageTheme = useTheme();
161
+ const templateRoute = useRouteRef(selectedTemplateRouteRef);
162
+ const templateProps = getTemplateCardProps(template);
163
+ const ownedByRelations = getEntityRelations(template, RELATION_OWNED_BY);
164
+ const themeId = backstageTheme.getPageTheme({ themeId: templateProps.type }) ? templateProps.type : "other";
165
+ const theme = backstageTheme.getPageTheme({ themeId });
166
+ const classes = useStyles$d({ backgroundImage: theme.backgroundImage });
167
+ const href = templateRoute({ templateName: templateProps.name });
168
+ const scmIntegrationsApi = useApi(scmIntegrationsApiRef);
169
+ const sourceLocation = getEntitySourceLocation(template, scmIntegrationsApi);
170
+ return /* @__PURE__ */ React.createElement(Card, null, /* @__PURE__ */ React.createElement(CardMedia, {
171
+ className: classes.cardHeader
172
+ }, /* @__PURE__ */ React.createElement(FavoriteEntity, {
173
+ className: classes.starButton,
174
+ entity: template
175
+ }), deprecated && /* @__PURE__ */ React.createElement(DeprecationWarning, null), /* @__PURE__ */ React.createElement(ItemCardHeader, {
176
+ title: templateProps.title,
177
+ subtitle: templateProps.type,
178
+ classes: { root: classes.title }
179
+ })), /* @__PURE__ */ React.createElement(CardContent, {
180
+ style: { display: "grid" }
181
+ }, /* @__PURE__ */ React.createElement(Box, {
182
+ className: classes.box
183
+ }, /* @__PURE__ */ React.createElement(Typography, {
184
+ variant: "body2",
185
+ className: classes.label
186
+ }, "Description"), /* @__PURE__ */ React.createElement(MarkdownContent, {
187
+ content: templateProps.description
188
+ })), /* @__PURE__ */ React.createElement(Box, {
189
+ className: classes.box
190
+ }, /* @__PURE__ */ React.createElement(Typography, {
191
+ variant: "body2",
192
+ className: classes.label
193
+ }, "Owner"), /* @__PURE__ */ React.createElement(EntityRefLinks, {
194
+ entityRefs: ownedByRelations,
195
+ defaultKind: "Group"
196
+ })), /* @__PURE__ */ React.createElement(Box, null, /* @__PURE__ */ React.createElement(Typography, {
197
+ variant: "body2",
198
+ className: classes.label
199
+ }, "Tags"), (_a = templateProps.tags) == null ? void 0 : _a.map((tag) => /* @__PURE__ */ React.createElement(Chip, {
200
+ size: "small",
201
+ label: tag,
202
+ key: tag
203
+ })))), /* @__PURE__ */ React.createElement(CardActions, null, sourceLocation && /* @__PURE__ */ React.createElement(IconButton, {
204
+ className: classes.leftButton,
205
+ href: sourceLocation.locationTargetUrl
206
+ }, /* @__PURE__ */ React.createElement(ScmIntegrationIcon, {
207
+ type: sourceLocation.integrationType
208
+ })), /* @__PURE__ */ React.createElement(Button, {
209
+ color: "primary",
210
+ to: href,
211
+ "aria-label": `Choose ${templateProps.title}`
212
+ }, "Choose")));
213
+ };
214
+
215
+ const TemplateList = ({
216
+ TemplateCardComponent,
217
+ group
218
+ }) => {
219
+ const { loading, error, entities } = useEntityList();
220
+ const Card = TemplateCardComponent || TemplateCard;
221
+ const maybeFilteredEntities = group ? entities.filter((e) => group.filter(e)) : entities;
222
+ const titleComponent = (() => {
223
+ if (group && group.title) {
224
+ if (typeof group.title === "string") {
225
+ return /* @__PURE__ */ React.createElement(ContentHeader, {
226
+ title: group.title
227
+ });
228
+ }
229
+ return group.title;
230
+ }
231
+ return /* @__PURE__ */ React.createElement(ContentHeader, {
232
+ title: "Other Templates"
233
+ });
234
+ })();
235
+ if (group && maybeFilteredEntities.length === 0) {
236
+ return null;
237
+ }
238
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, loading && /* @__PURE__ */ React.createElement(Progress, null), error && /* @__PURE__ */ React.createElement(WarningPanel, {
239
+ title: "Oops! Something went wrong loading the templates"
240
+ }, error.message), !error && !loading && !entities.length && /* @__PURE__ */ React.createElement(Typography, {
241
+ variant: "body2"
242
+ }, "No templates found that match your filter. Learn more about", " ", /* @__PURE__ */ React.createElement(Link$1, {
243
+ to: "https://backstage.io/docs/features/software-templates/adding-templates"
244
+ }, "adding templates"), "."), /* @__PURE__ */ React.createElement(Content, null, titleComponent, /* @__PURE__ */ React.createElement(ItemCardGrid, null, maybeFilteredEntities && (maybeFilteredEntities == null ? void 0 : maybeFilteredEntities.length) > 0 && maybeFilteredEntities.map((template) => /* @__PURE__ */ React.createElement(Card, {
245
+ key: stringifyEntityRef(template),
246
+ template,
247
+ deprecated: template.apiVersion === "backstage.io/v1beta2"
248
+ })))));
249
+ };
250
+
251
+ const useStyles$c = makeStyles$1({
252
+ button: {
253
+ color: "white"
254
+ }
255
+ });
256
+ function ScaffolderPageContextMenu(props) {
257
+ const classes = useStyles$c();
258
+ const [anchorEl, setAnchorEl] = useState();
259
+ const pageLink = useRouteRef(rootRouteRef);
260
+ const navigate = useNavigate();
261
+ const showEditor = props.editor !== false;
262
+ const showActions = props.actions !== false;
263
+ if (!showEditor && !showActions) {
264
+ return null;
265
+ }
266
+ const onOpen = (event) => {
267
+ setAnchorEl(event.currentTarget);
268
+ };
269
+ const onClose = () => {
270
+ setAnchorEl(void 0);
271
+ };
272
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(IconButton$1, {
273
+ "aria-label": "more",
274
+ "aria-controls": "long-menu",
275
+ "aria-haspopup": "true",
276
+ onClick: onOpen,
277
+ "data-testid": "menu-button",
278
+ color: "inherit",
279
+ className: classes.button
280
+ }, /* @__PURE__ */ React.createElement(MoreVert, null)), /* @__PURE__ */ React.createElement(Popover, {
281
+ open: Boolean(anchorEl),
282
+ onClose,
283
+ anchorEl,
284
+ anchorOrigin: { vertical: "bottom", horizontal: "right" },
285
+ transformOrigin: { vertical: "top", horizontal: "right" }
286
+ }, /* @__PURE__ */ React.createElement(MenuList, null, showEditor && /* @__PURE__ */ React.createElement(MenuItem, {
287
+ onClick: () => navigate(`${pageLink()}/edit`)
288
+ }, /* @__PURE__ */ React.createElement(ListItemIcon, null, /* @__PURE__ */ React.createElement(Edit, {
289
+ fontSize: "small"
290
+ })), /* @__PURE__ */ React.createElement(ListItemText, {
291
+ primary: "Template Editor"
292
+ })), showActions && /* @__PURE__ */ React.createElement(MenuItem, {
293
+ onClick: () => navigate(`${pageLink()}/actions`)
294
+ }, /* @__PURE__ */ React.createElement(ListItemIcon, null, /* @__PURE__ */ React.createElement(Description, {
295
+ fontSize: "small"
296
+ })), /* @__PURE__ */ React.createElement(ListItemText, {
297
+ primary: "Installed Actions"
298
+ })))));
299
+ }
300
+
301
+ const ScaffolderPageContents = ({
302
+ TemplateCardComponent,
303
+ groups,
304
+ contextMenu
305
+ }) => {
306
+ const registerComponentLink = useRouteRef(registerComponentRouteRef);
307
+ const otherTemplatesGroup = {
308
+ title: groups ? "Other Templates" : "Templates",
309
+ filter: (entity) => {
310
+ const filtered = (groups != null ? groups : []).map((group) => group.filter(entity));
311
+ return !filtered.some((result) => result === true);
312
+ }
313
+ };
314
+ const { allowed } = usePermission({
315
+ permission: catalogEntityCreatePermission
316
+ });
317
+ return /* @__PURE__ */ React.createElement(Page, {
318
+ themeId: "home"
319
+ }, /* @__PURE__ */ React.createElement(Header, {
320
+ pageTitleOverride: "Create a New Component",
321
+ title: "Create a New Component",
322
+ subtitle: "Create new software components using standard templates"
323
+ }, /* @__PURE__ */ React.createElement(ScaffolderPageContextMenu, {
324
+ ...contextMenu
325
+ })), /* @__PURE__ */ React.createElement(Content, null, /* @__PURE__ */ React.createElement(ContentHeader, {
326
+ title: "Available Templates"
327
+ }, allowed && /* @__PURE__ */ React.createElement(CreateButton, {
328
+ title: "Register Existing Component",
329
+ to: registerComponentLink && registerComponentLink()
330
+ }), /* @__PURE__ */ React.createElement(SupportButton, null, "Create new software components using standard templates. Different templates create different kinds of components (services, websites, documentation, ...).")), /* @__PURE__ */ React.createElement(CatalogFilterLayout, null, /* @__PURE__ */ React.createElement(CatalogFilterLayout.Filters, null, /* @__PURE__ */ React.createElement(EntitySearchBar, null), /* @__PURE__ */ React.createElement(EntityKindPicker, {
331
+ initialFilter: "template",
332
+ hidden: true
333
+ }), /* @__PURE__ */ React.createElement(UserListPicker, {
334
+ initialFilter: "all",
335
+ availableFilters: ["all", "starred"]
336
+ }), /* @__PURE__ */ React.createElement(TemplateTypePicker, null), /* @__PURE__ */ React.createElement(EntityTagPicker, null)), /* @__PURE__ */ React.createElement(CatalogFilterLayout.Content, null, groups && groups.map((group, index) => /* @__PURE__ */ React.createElement(TemplateList, {
337
+ key: index,
338
+ TemplateCardComponent,
339
+ group
340
+ })), /* @__PURE__ */ React.createElement(TemplateList, {
341
+ key: "other",
342
+ TemplateCardComponent,
343
+ group: otherTemplatesGroup
344
+ })))));
345
+ };
346
+ const ScaffolderPage = ({
347
+ TemplateCardComponent,
348
+ groups
349
+ }) => /* @__PURE__ */ React.createElement(EntityListProvider, null, /* @__PURE__ */ React.createElement(ScaffolderPageContents, {
350
+ TemplateCardComponent,
351
+ groups
352
+ }));
353
+
354
+ function isObject$1(value) {
355
+ return typeof value === "object" && value !== null && !Array.isArray(value);
356
+ }
357
+ function extractUiSchema(schema, uiSchema) {
358
+ if (!isObject$1(schema)) {
359
+ return;
360
+ }
361
+ const { properties, items, anyOf, oneOf, allOf, dependencies } = schema;
362
+ for (const propName in schema) {
363
+ if (!schema.hasOwnProperty(propName)) {
364
+ continue;
365
+ }
366
+ if (propName.startsWith("ui:")) {
367
+ uiSchema[propName] = schema[propName];
368
+ delete schema[propName];
369
+ }
370
+ }
371
+ if (isObject$1(properties)) {
372
+ for (const propName in properties) {
373
+ if (!properties.hasOwnProperty(propName)) {
374
+ continue;
375
+ }
376
+ const schemaNode = properties[propName];
377
+ if (!isObject$1(schemaNode)) {
378
+ continue;
379
+ }
380
+ const innerUiSchema = {};
381
+ uiSchema[propName] = innerUiSchema;
382
+ extractUiSchema(schemaNode, innerUiSchema);
383
+ }
384
+ }
385
+ if (isObject$1(items)) {
386
+ const innerUiSchema = {};
387
+ uiSchema.items = innerUiSchema;
388
+ extractUiSchema(items, innerUiSchema);
389
+ }
390
+ if (Array.isArray(anyOf)) {
391
+ for (const schemaNode of anyOf) {
392
+ if (!isObject$1(schemaNode)) {
393
+ continue;
394
+ }
395
+ extractUiSchema(schemaNode, uiSchema);
396
+ }
397
+ }
398
+ if (Array.isArray(oneOf)) {
399
+ for (const schemaNode of oneOf) {
400
+ if (!isObject$1(schemaNode)) {
401
+ continue;
402
+ }
403
+ extractUiSchema(schemaNode, uiSchema);
404
+ }
405
+ }
406
+ if (Array.isArray(allOf)) {
407
+ for (const schemaNode of allOf) {
408
+ if (!isObject$1(schemaNode)) {
409
+ continue;
410
+ }
411
+ extractUiSchema(schemaNode, uiSchema);
412
+ }
413
+ }
414
+ if (isObject$1(dependencies)) {
415
+ for (const depName of Object.keys(dependencies)) {
416
+ const schemaNode = dependencies[depName];
417
+ if (!isObject$1(schemaNode)) {
418
+ continue;
419
+ }
420
+ extractUiSchema(schemaNode, uiSchema);
421
+ }
422
+ }
423
+ }
424
+ function transformSchemaToProps(inputSchema) {
425
+ inputSchema.type = inputSchema.type || "object";
426
+ const schema = JSON.parse(JSON.stringify(inputSchema));
427
+ delete schema.title;
428
+ const uiSchema = {};
429
+ extractUiSchema(schema, uiSchema);
430
+ return { schema, uiSchema };
431
+ }
432
+
433
+ const DescriptionField = ({ description }) => description && /* @__PURE__ */ React.createElement(MarkdownContent, {
434
+ content: description,
435
+ linkTarget: "_blank"
436
+ });
437
+
438
+ var fieldOverrides = /*#__PURE__*/Object.freeze({
439
+ __proto__: null,
440
+ DescriptionField: DescriptionField
441
+ });
442
+
443
+ const Form = withTheme(Theme);
444
+ function getUiSchemasFromSteps(steps) {
445
+ const uiSchemas = [];
446
+ steps.forEach((step) => {
447
+ const schemaProps = step.schema.properties;
448
+ for (const key in schemaProps) {
449
+ if (schemaProps.hasOwnProperty(key)) {
450
+ const uiSchema = schemaProps[key];
451
+ uiSchema.name = key;
452
+ uiSchemas.push(uiSchema);
453
+ }
454
+ }
455
+ });
456
+ return uiSchemas;
457
+ }
458
+ function getReviewData(formData, steps) {
459
+ const uiSchemas = getUiSchemasFromSteps(steps);
460
+ const reviewData = {};
461
+ for (const key in formData) {
462
+ if (formData.hasOwnProperty(key)) {
463
+ const uiSchema = uiSchemas.find((us) => us.name === key);
464
+ if (!uiSchema) {
465
+ reviewData[key] = formData[key];
466
+ continue;
467
+ }
468
+ if (uiSchema["ui:widget"] === "password") {
469
+ reviewData[key] = "******";
470
+ continue;
471
+ }
472
+ if (!uiSchema["ui:backstage"] || !uiSchema["ui:backstage"].review) {
473
+ reviewData[key] = formData[key];
474
+ continue;
475
+ }
476
+ const review = uiSchema["ui:backstage"].review;
477
+ if (!review.show) {
478
+ continue;
479
+ }
480
+ if (review.mask) {
481
+ reviewData[key] = review.mask;
482
+ continue;
483
+ }
484
+ reviewData[key] = formData[key];
485
+ }
486
+ }
487
+ return reviewData;
488
+ }
489
+ const MultistepJsonForm = (props) => {
490
+ const {
491
+ formData,
492
+ onChange,
493
+ onReset,
494
+ onFinish,
495
+ fields,
496
+ widgets,
497
+ finishButtonLabel
498
+ } = props;
499
+ const [activeStep, setActiveStep] = useState(0);
500
+ const [disableButtons, setDisableButtons] = useState(false);
501
+ const errorApi = useApi(errorApiRef);
502
+ const featureFlagApi = useApi(featureFlagsApiRef);
503
+ const featureFlagKey = "backstage:featureFlag";
504
+ const filterOutProperties = (step) => {
505
+ var _a;
506
+ const filteredStep = cloneDeep(step);
507
+ const removedPropertyKeys = [];
508
+ if (filteredStep.schema.properties) {
509
+ filteredStep.schema.properties = Object.fromEntries(Object.entries(filteredStep.schema.properties).filter(([key, value]) => {
510
+ if (value[featureFlagKey]) {
511
+ if (featureFlagApi.isActive(value[featureFlagKey])) {
512
+ return true;
513
+ }
514
+ removedPropertyKeys.push(key);
515
+ return false;
516
+ }
517
+ return true;
518
+ }));
519
+ filteredStep.schema.required = Array.isArray(filteredStep.schema.required) ? (_a = filteredStep.schema.required) == null ? void 0 : _a.filter((r) => !removedPropertyKeys.includes(r)) : filteredStep.schema.required;
520
+ }
521
+ return filteredStep;
522
+ };
523
+ const steps = props.steps.filter((step) => {
524
+ const featureFlag = step.schema[featureFlagKey];
525
+ return typeof featureFlag !== "string" || featureFlagApi.isActive(featureFlag);
526
+ }).map(filterOutProperties);
527
+ const handleReset = () => {
528
+ setActiveStep(0);
529
+ onReset();
530
+ };
531
+ const handleNext = () => {
532
+ setActiveStep(Math.min(activeStep + 1, steps.length));
533
+ };
534
+ const handleBack = () => setActiveStep(Math.max(activeStep - 1, 0));
535
+ const handleCreate = async () => {
536
+ if (!onFinish) {
537
+ return;
538
+ }
539
+ setDisableButtons(true);
540
+ try {
541
+ await onFinish();
542
+ } catch (err) {
543
+ errorApi.post(err);
544
+ } finally {
545
+ setDisableButtons(false);
546
+ }
547
+ };
548
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Stepper, {
549
+ activeStep,
550
+ orientation: "vertical"
551
+ }, steps.map(({ title, schema, ...formProps }, index) => {
552
+ return /* @__PURE__ */ React.createElement(Step, {
553
+ key: title
554
+ }, /* @__PURE__ */ React.createElement(StepLabel, {
555
+ "aria-label": `Step ${index + 1} ${title}`,
556
+ "aria-disabled": "false",
557
+ tabIndex: 0
558
+ }, /* @__PURE__ */ React.createElement(Typography, {
559
+ variant: "h6",
560
+ component: "h3"
561
+ }, title)), /* @__PURE__ */ React.createElement(StepContent, {
562
+ key: title
563
+ }, /* @__PURE__ */ React.createElement(Form, {
564
+ showErrorList: false,
565
+ fields: { ...fieldOverrides, ...fields },
566
+ widgets,
567
+ noHtml5Validate: true,
568
+ formData,
569
+ formContext: { formData },
570
+ onChange,
571
+ onSubmit: (e) => {
572
+ if (e.errors.length === 0)
573
+ handleNext();
574
+ },
575
+ ...formProps,
576
+ ...transformSchemaToProps(schema)
577
+ }, /* @__PURE__ */ React.createElement(Button$1, {
578
+ disabled: activeStep === 0,
579
+ onClick: handleBack
580
+ }, "Back"), /* @__PURE__ */ React.createElement(Button$1, {
581
+ variant: "contained",
582
+ color: "primary",
583
+ type: "submit"
584
+ }, "Next step"))));
585
+ })), activeStep === steps.length && /* @__PURE__ */ React.createElement(Content, null, /* @__PURE__ */ React.createElement(Paper, {
586
+ square: true,
587
+ elevation: 0
588
+ }, /* @__PURE__ */ React.createElement(Typography, {
589
+ variant: "h6"
590
+ }, "Review and create"), /* @__PURE__ */ React.createElement(StructuredMetadataTable, {
591
+ dense: true,
592
+ metadata: getReviewData(formData, steps)
593
+ }), /* @__PURE__ */ React.createElement(Box, {
594
+ mb: 4
595
+ }), /* @__PURE__ */ React.createElement(Button$1, {
596
+ onClick: handleBack,
597
+ disabled: disableButtons
598
+ }, "Back"), /* @__PURE__ */ React.createElement(Button$1, {
599
+ onClick: handleReset,
600
+ disabled: disableButtons
601
+ }, "Reset"), /* @__PURE__ */ React.createElement(Button$1, {
602
+ variant: "contained",
603
+ color: "primary",
604
+ onClick: handleCreate,
605
+ disabled: !onFinish || disableButtons
606
+ }, finishButtonLabel != null ? finishButtonLabel : "Create"))));
607
+ };
608
+
609
+ function isObject(obj) {
610
+ return typeof obj === "object" && obj !== null && !Array.isArray(obj);
611
+ }
612
+ const createValidator = (rootSchema, validators, context) => {
613
+ function validate(schema, formData, errors) {
614
+ const schemaProps = schema.properties;
615
+ const customObject = schema.type === "object" && schemaProps === void 0;
616
+ if (!isObject(schemaProps) && !customObject) {
617
+ return;
618
+ }
619
+ if (schemaProps) {
620
+ for (const [key, propData] of Object.entries(formData)) {
621
+ const propValidation = errors[key];
622
+ if (isObject(propData)) {
623
+ const propSchemaProps = schemaProps[key];
624
+ if (isObject(propSchemaProps)) {
625
+ validate(propSchemaProps, propData, propValidation);
626
+ }
627
+ } else {
628
+ const propSchema = schemaProps[key];
629
+ const fieldName = isObject(propSchema) && propSchema["ui:field"];
630
+ if (fieldName && typeof validators[fieldName] === "function") {
631
+ validators[fieldName](propData, propValidation, context);
632
+ }
633
+ }
634
+ }
635
+ } else if (customObject) {
636
+ const fieldName = schema["ui:field"];
637
+ if (fieldName && typeof validators[fieldName] === "function") {
638
+ validators[fieldName](formData, errors, context);
639
+ }
640
+ }
641
+ }
642
+ return (formData, errors) => {
643
+ validate(rootSchema, formData, errors);
644
+ return errors;
645
+ };
646
+ };
647
+
648
+ const useTemplateParameterSchema = (templateRef) => {
649
+ const scaffolderApi = useApi(scaffolderApiRef);
650
+ const { value, loading, error } = useAsync(() => scaffolderApi.getTemplateParameterSchema(templateRef), [scaffolderApi, templateRef]);
651
+ return { schema: value, loading, error };
652
+ };
653
+ const TemplatePage = ({
654
+ customFieldExtensions = []
655
+ }) => {
656
+ const apiHolder = useApiHolder();
657
+ const secretsContext = useContext(SecretsContext);
658
+ const errorApi = useApi(errorApiRef);
659
+ const scaffolderApi = useApi(scaffolderApiRef);
660
+ const { templateName } = useParams();
661
+ const navigate = useNavigate();
662
+ const scaffolderTaskRoute = useRouteRef(scaffolderTaskRouteRef);
663
+ const rootRoute = useRouteRef(rootRouteRef);
664
+ const { schema, loading, error } = useTemplateParameterSchema(templateName);
665
+ const [formState, setFormState] = useState(() => {
666
+ var _a;
667
+ const query = qs.parse(window.location.search, {
668
+ ignoreQueryPrefix: true
669
+ });
670
+ try {
671
+ return JSON.parse(query.formData);
672
+ } catch (e) {
673
+ return (_a = query.formData) != null ? _a : {};
674
+ }
675
+ });
676
+ const handleFormReset = () => setFormState({});
677
+ const handleChange = useCallback((e) => setFormState(e.formData), [setFormState]);
678
+ const handleCreate = async () => {
679
+ var _a;
680
+ const { taskId } = await scaffolderApi.scaffold({
681
+ templateRef: stringifyEntityRef({
682
+ name: templateName,
683
+ kind: "template",
684
+ namespace: "default"
685
+ }),
686
+ values: formState,
687
+ secrets: secretsContext == null ? void 0 : secretsContext.secrets
688
+ });
689
+ const formParams = qs.stringify({ formData: formState }, { addQueryPrefix: true });
690
+ const newUrl = `${window.location.pathname}${formParams}`;
691
+ (_a = window.history) == null ? void 0 : _a.replaceState(null, document.title, newUrl);
692
+ navigate(scaffolderTaskRoute({ taskId }));
693
+ };
694
+ if (error) {
695
+ errorApi.post(new Error(`Failed to load template, ${error}`));
696
+ return /* @__PURE__ */ React.createElement(Navigate, {
697
+ to: rootRoute()
698
+ });
699
+ }
700
+ if (!loading && !schema) {
701
+ errorApi.post(new Error("Template was not found."));
702
+ return /* @__PURE__ */ React.createElement(Navigate, {
703
+ to: rootRoute()
704
+ });
705
+ }
706
+ const customFieldComponents = Object.fromEntries(customFieldExtensions.map(({ name, component }) => [name, component]));
707
+ const customFieldValidators = Object.fromEntries(customFieldExtensions.map(({ name, validation }) => [name, validation]));
708
+ return /* @__PURE__ */ React.createElement(Page, {
709
+ themeId: "home"
710
+ }, /* @__PURE__ */ React.createElement(Header, {
711
+ pageTitleOverride: "Create a New Component",
712
+ title: "Create a New Component",
713
+ subtitle: "Create new software components using standard templates"
714
+ }), /* @__PURE__ */ React.createElement(Content, null, loading && /* @__PURE__ */ React.createElement(LinearProgress, {
715
+ "data-testid": "loading-progress"
716
+ }), schema && /* @__PURE__ */ React.createElement(InfoCard, {
717
+ title: schema.title,
718
+ noPadding: true,
719
+ titleTypographyProps: { component: "h2" }
720
+ }, /* @__PURE__ */ React.createElement(MultistepJsonForm, {
721
+ formData: formState,
722
+ fields: customFieldComponents,
723
+ onChange: handleChange,
724
+ onReset: handleFormReset,
725
+ onFinish: handleCreate,
726
+ steps: schema.steps.map((step) => {
727
+ return {
728
+ ...step,
729
+ validate: createValidator(step.schema, customFieldValidators, { apiHolder })
730
+ };
731
+ })
732
+ }))));
733
+ };
734
+
735
+ const useStyles$b = makeStyles((theme) => ({
736
+ code: {
737
+ fontFamily: "Menlo, monospace",
738
+ padding: theme.spacing(1),
739
+ backgroundColor: theme.palette.type === "dark" ? theme.palette.grey[700] : theme.palette.grey[300],
740
+ display: "inline-block",
741
+ borderRadius: 5,
742
+ border: `1px solid ${theme.palette.grey[500]}`,
743
+ position: "relative"
744
+ },
745
+ codeRequired: {
746
+ "&::after": {
747
+ position: "absolute",
748
+ content: '"*"',
749
+ top: 0,
750
+ right: theme.spacing(0.5),
751
+ fontWeight: "bolder",
752
+ color: theme.palette.error.light
753
+ }
754
+ }
755
+ }));
756
+ const ActionsPage = () => {
757
+ const api = useApi(scaffolderApiRef);
758
+ const classes = useStyles$b();
759
+ const { loading, value, error } = useAsync(async () => {
760
+ return api.listActions();
761
+ });
762
+ if (loading) {
763
+ return /* @__PURE__ */ React.createElement(Progress, null);
764
+ }
765
+ if (error) {
766
+ return /* @__PURE__ */ React.createElement(ErrorPage, {
767
+ statusMessage: "Failed to load installed actions",
768
+ status: "500"
769
+ });
770
+ }
771
+ const formatRows = (input) => {
772
+ const properties = input.properties;
773
+ if (!properties) {
774
+ return void 0;
775
+ }
776
+ return Object.entries(properties).map((entry) => {
777
+ var _a;
778
+ const [key] = entry;
779
+ const props = entry[1];
780
+ const codeClassname = classNames(classes.code, {
781
+ [classes.codeRequired]: (_a = input.required) == null ? void 0 : _a.includes(key)
782
+ });
783
+ return /* @__PURE__ */ React.createElement(TableRow, {
784
+ key
785
+ }, /* @__PURE__ */ React.createElement(TableCell, null, /* @__PURE__ */ React.createElement("div", {
786
+ className: codeClassname
787
+ }, key)), /* @__PURE__ */ React.createElement(TableCell, null, props.title), /* @__PURE__ */ React.createElement(TableCell, null, props.description), /* @__PURE__ */ React.createElement(TableCell, null, /* @__PURE__ */ React.createElement("span", {
788
+ className: classes.code
789
+ }, props.type)));
790
+ });
791
+ };
792
+ const renderTable = (input) => {
793
+ if (!input.properties) {
794
+ return void 0;
795
+ }
796
+ return /* @__PURE__ */ React.createElement(TableContainer, {
797
+ component: Paper
798
+ }, /* @__PURE__ */ React.createElement(Table, {
799
+ size: "small"
800
+ }, /* @__PURE__ */ React.createElement(TableHead, null, /* @__PURE__ */ React.createElement(TableRow, null, /* @__PURE__ */ React.createElement(TableCell, null, "Name"), /* @__PURE__ */ React.createElement(TableCell, null, "Title"), /* @__PURE__ */ React.createElement(TableCell, null, "Description"), /* @__PURE__ */ React.createElement(TableCell, null, "Type"))), /* @__PURE__ */ React.createElement(TableBody, null, formatRows(input))));
801
+ };
802
+ const renderTables = (name, input) => {
803
+ if (!input) {
804
+ return void 0;
805
+ }
806
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Typography, {
807
+ variant: "h6"
808
+ }, name), input.map((i, index) => /* @__PURE__ */ React.createElement("div", {
809
+ key: index
810
+ }, renderTable(i))));
811
+ };
812
+ const items = value == null ? void 0 : value.map((action) => {
813
+ var _a, _b, _c, _d;
814
+ if (action.id.startsWith("legacy:")) {
815
+ return void 0;
816
+ }
817
+ const oneOf = renderTables("oneOf", (_b = (_a = action.schema) == null ? void 0 : _a.input) == null ? void 0 : _b.oneOf);
818
+ return /* @__PURE__ */ React.createElement(Box, {
819
+ pb: 4,
820
+ key: action.id
821
+ }, /* @__PURE__ */ React.createElement(Typography, {
822
+ variant: "h4",
823
+ className: classes.code
824
+ }, action.id), /* @__PURE__ */ React.createElement(Typography, null, action.description), ((_c = action.schema) == null ? void 0 : _c.input) && /* @__PURE__ */ React.createElement(Box, {
825
+ pb: 2
826
+ }, /* @__PURE__ */ React.createElement(Typography, {
827
+ variant: "h5"
828
+ }, "Input"), renderTable(action.schema.input), oneOf), ((_d = action.schema) == null ? void 0 : _d.output) && /* @__PURE__ */ React.createElement(Box, {
829
+ pb: 2
830
+ }, /* @__PURE__ */ React.createElement(Typography, {
831
+ variant: "h5"
832
+ }, "Output"), renderTable(action.schema.output)));
833
+ });
834
+ return /* @__PURE__ */ React.createElement(Page, {
835
+ themeId: "home"
836
+ }, /* @__PURE__ */ React.createElement(Header, {
837
+ pageTitleOverride: "Create a New Component",
838
+ title: "Installed actions",
839
+ subtitle: "This is the collection of all installed actions"
840
+ }), /* @__PURE__ */ React.createElement(Content, null, items));
841
+ };
842
+
843
+ const showDirectoryPicker = window.showDirectoryPicker;
844
+ class WebFileAccess {
845
+ constructor(path, handle) {
846
+ this.path = path;
847
+ this.handle = handle;
848
+ }
849
+ file() {
850
+ return this.handle.getFile();
851
+ }
852
+ async save(data) {
853
+ const writable = await this.handle.createWritable();
854
+ await writable.write(data);
855
+ await writable.close();
856
+ }
857
+ }
858
+ class WebDirectoryAccess {
859
+ constructor(handle) {
860
+ this.handle = handle;
861
+ }
862
+ async listFiles() {
863
+ const content = [];
864
+ for await (const entry of this.listDirectoryContents(this.handle)) {
865
+ content.push(entry);
866
+ }
867
+ return content;
868
+ }
869
+ async *listDirectoryContents(dirHandle, basePath = []) {
870
+ for await (const handle of dirHandle.values()) {
871
+ if (handle.kind === "file") {
872
+ yield new WebFileAccess([...basePath, handle.name].join("/"), handle);
873
+ } else if (handle.kind === "directory") {
874
+ yield* this.listDirectoryContents(handle, [...basePath, handle.name]);
875
+ }
876
+ }
877
+ }
878
+ }
879
+ class WebFileSystemAccess {
880
+ static isSupported() {
881
+ return Boolean(showDirectoryPicker);
882
+ }
883
+ static async requestDirectoryAccess() {
884
+ if (!showDirectoryPicker) {
885
+ throw new Error("File system access is not supported");
886
+ }
887
+ const handle = await showDirectoryPicker();
888
+ return new WebDirectoryAccess(handle);
889
+ }
890
+ constructor() {
891
+ }
892
+ }
893
+
894
+ const useStyles$a = makeStyles$1((theme) => ({
895
+ introText: {
896
+ textAlign: "center",
897
+ marginTop: theme.spacing(2)
898
+ },
899
+ card: {
900
+ position: "relative",
901
+ maxWidth: 340,
902
+ marginTop: theme.spacing(4),
903
+ margin: theme.spacing(0, 2)
904
+ },
905
+ infoIcon: {
906
+ position: "absolute",
907
+ top: theme.spacing(1),
908
+ right: theme.spacing(1)
909
+ }
910
+ }));
911
+ function TemplateEditorIntro(props) {
912
+ const classes = useStyles$a();
913
+ const supportsLoad = WebFileSystemAccess.isSupported();
914
+ const cardLoadLocal = /* @__PURE__ */ React.createElement(Card$1, {
915
+ className: classes.card,
916
+ elevation: 4
917
+ }, /* @__PURE__ */ React.createElement(CardActionArea, {
918
+ disabled: !supportsLoad,
919
+ onClick: () => {
920
+ var _a;
921
+ return (_a = props.onSelect) == null ? void 0 : _a.call(props, "local");
922
+ }
923
+ }, /* @__PURE__ */ React.createElement(CardContent$1, null, /* @__PURE__ */ React.createElement(Typography$1, {
924
+ variant: "h5",
925
+ gutterBottom: true,
926
+ color: supportsLoad ? void 0 : "textSecondary",
927
+ style: { display: "flex", flexFlow: "row nowrap" }
928
+ }, "Load Template Directory"), /* @__PURE__ */ React.createElement(Typography$1, {
929
+ variant: "body1",
930
+ color: supportsLoad ? void 0 : "textSecondary"
931
+ }, "Load a local template directory, allowing you to both edit and try executing your own template."))), !supportsLoad && /* @__PURE__ */ React.createElement("div", {
932
+ className: classes.infoIcon
933
+ }, /* @__PURE__ */ React.createElement(Tooltip$1, {
934
+ placement: "top",
935
+ title: "Only supported in some Chromium-based browsers"
936
+ }, /* @__PURE__ */ React.createElement(InfoOutlinedIcon, null))));
937
+ const cardFormEditor = /* @__PURE__ */ React.createElement(Card$1, {
938
+ className: classes.card,
939
+ elevation: 4
940
+ }, /* @__PURE__ */ React.createElement(CardActionArea, {
941
+ onClick: () => {
942
+ var _a;
943
+ return (_a = props.onSelect) == null ? void 0 : _a.call(props, "form");
944
+ }
945
+ }, /* @__PURE__ */ React.createElement(CardContent$1, null, /* @__PURE__ */ React.createElement(Typography$1, {
946
+ variant: "h5",
947
+ gutterBottom: true
948
+ }, "Edit Template Form"), /* @__PURE__ */ React.createElement(Typography$1, {
949
+ variant: "body1"
950
+ }, "Preview and edit a template form, either using a sample template or by loading a template from the catalog."))));
951
+ return /* @__PURE__ */ React.createElement("div", {
952
+ style: props.style
953
+ }, /* @__PURE__ */ React.createElement(Typography$1, {
954
+ variant: "h6",
955
+ className: classes.introText
956
+ }, "Get started by choosing one of the options below"), /* @__PURE__ */ React.createElement("div", {
957
+ style: {
958
+ display: "flex",
959
+ flexFlow: "row wrap",
960
+ alignItems: "flex-start",
961
+ justifyContent: "center",
962
+ alignContent: "flex-start"
963
+ }
964
+ }, supportsLoad && cardLoadLocal, cardFormEditor, !supportsLoad && cardLoadLocal));
965
+ }
966
+
967
+ var __accessCheck = (obj, member, msg) => {
968
+ if (!member.has(obj))
969
+ throw TypeError("Cannot " + msg);
970
+ };
971
+ var __privateGet = (obj, member, getter) => {
972
+ __accessCheck(obj, member, "read from private field");
973
+ return getter ? getter.call(obj) : member.get(obj);
974
+ };
975
+ var __privateAdd = (obj, member, value) => {
976
+ if (member.has(obj))
977
+ throw TypeError("Cannot add the same private member more than once");
978
+ member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
979
+ };
980
+ var __privateSet = (obj, member, value, setter) => {
981
+ __accessCheck(obj, member, "write to private field");
982
+ setter ? setter.call(obj, value) : member.set(obj, value);
983
+ return value;
984
+ };
985
+ var _access, _signalUpdate, _content, _savedContent, _access2, _listeners, _files, _selectedFile, _signalUpdate2;
986
+ const MAX_SIZE = 1024 * 1024;
987
+ const MAX_SIZE_MESSAGE = "This file is too large to be displayed";
988
+ class DirectoryEditorFileManager {
989
+ constructor(access, signalUpdate) {
990
+ __privateAdd(this, _access, void 0);
991
+ __privateAdd(this, _signalUpdate, void 0);
992
+ __privateAdd(this, _content, void 0);
993
+ __privateAdd(this, _savedContent, void 0);
994
+ __privateSet(this, _access, access);
995
+ __privateSet(this, _signalUpdate, signalUpdate);
996
+ }
997
+ get path() {
998
+ return __privateGet(this, _access).path;
999
+ }
1000
+ get content() {
1001
+ var _a;
1002
+ return (_a = __privateGet(this, _content)) != null ? _a : MAX_SIZE_MESSAGE;
1003
+ }
1004
+ updateContent(content) {
1005
+ if (__privateGet(this, _content) === void 0) {
1006
+ return;
1007
+ }
1008
+ __privateSet(this, _content, content);
1009
+ __privateGet(this, _signalUpdate).call(this);
1010
+ }
1011
+ get dirty() {
1012
+ return __privateGet(this, _content) !== __privateGet(this, _savedContent);
1013
+ }
1014
+ async save() {
1015
+ if (__privateGet(this, _content) !== void 0) {
1016
+ await __privateGet(this, _access).save(__privateGet(this, _content));
1017
+ __privateSet(this, _savedContent, __privateGet(this, _content));
1018
+ __privateGet(this, _signalUpdate).call(this);
1019
+ }
1020
+ }
1021
+ async reload() {
1022
+ const file = await __privateGet(this, _access).file();
1023
+ if (file.size > MAX_SIZE) {
1024
+ if (__privateGet(this, _content) !== void 0) {
1025
+ __privateSet(this, _content, void 0);
1026
+ __privateSet(this, _savedContent, void 0);
1027
+ __privateGet(this, _signalUpdate).call(this);
1028
+ }
1029
+ return;
1030
+ }
1031
+ const content = await file.text();
1032
+ if (__privateGet(this, _content) !== content) {
1033
+ __privateSet(this, _content, content);
1034
+ __privateSet(this, _savedContent, content);
1035
+ __privateGet(this, _signalUpdate).call(this);
1036
+ }
1037
+ }
1038
+ }
1039
+ _access = new WeakMap();
1040
+ _signalUpdate = new WeakMap();
1041
+ _content = new WeakMap();
1042
+ _savedContent = new WeakMap();
1043
+ class DirectoryEditorManager {
1044
+ constructor(access) {
1045
+ __privateAdd(this, _access2, void 0);
1046
+ __privateAdd(this, _listeners, /* @__PURE__ */ new Set());
1047
+ __privateAdd(this, _files, []);
1048
+ __privateAdd(this, _selectedFile, void 0);
1049
+ this.setSelectedFile = (path) => {
1050
+ const prev = __privateGet(this, _selectedFile);
1051
+ const next = __privateGet(this, _files).find((file) => file.path === path);
1052
+ if (prev !== next) {
1053
+ __privateSet(this, _selectedFile, next);
1054
+ __privateGet(this, _signalUpdate2).call(this);
1055
+ }
1056
+ };
1057
+ __privateAdd(this, _signalUpdate2, () => {
1058
+ __privateGet(this, _listeners).forEach((listener) => listener());
1059
+ });
1060
+ __privateSet(this, _access2, access);
1061
+ }
1062
+ get files() {
1063
+ return __privateGet(this, _files);
1064
+ }
1065
+ get selectedFile() {
1066
+ return __privateGet(this, _selectedFile);
1067
+ }
1068
+ get dirty() {
1069
+ return __privateGet(this, _files).some((file) => file.dirty);
1070
+ }
1071
+ async save() {
1072
+ await Promise.all(__privateGet(this, _files).map((file) => file.save()));
1073
+ }
1074
+ async reload() {
1075
+ var _a;
1076
+ const selectedPath = (_a = __privateGet(this, _selectedFile)) == null ? void 0 : _a.path;
1077
+ const files = await __privateGet(this, _access2).listFiles();
1078
+ const fileManagers = await Promise.all(files.map(async (file) => {
1079
+ const manager = new DirectoryEditorFileManager(file, __privateGet(this, _signalUpdate2));
1080
+ await manager.reload();
1081
+ return manager;
1082
+ }));
1083
+ __privateGet(this, _files).length = 0;
1084
+ __privateGet(this, _files).push(...fileManagers);
1085
+ this.setSelectedFile(selectedPath);
1086
+ __privateGet(this, _signalUpdate2).call(this);
1087
+ }
1088
+ subscribe(listener) {
1089
+ __privateGet(this, _listeners).add(listener);
1090
+ return () => {
1091
+ __privateGet(this, _listeners).delete(listener);
1092
+ };
1093
+ }
1094
+ }
1095
+ _access2 = new WeakMap();
1096
+ _listeners = new WeakMap();
1097
+ _files = new WeakMap();
1098
+ _selectedFile = new WeakMap();
1099
+ _signalUpdate2 = new WeakMap();
1100
+ const DirectoryEditorContext = createContext(void 0);
1101
+ function useDirectoryEditor() {
1102
+ const value = useContext(DirectoryEditorContext);
1103
+ const rerender = useRerender();
1104
+ useEffect(() => value == null ? void 0 : value.subscribe(rerender), [value, rerender]);
1105
+ if (!value) {
1106
+ throw new Error("must be used within a DirectoryEditorProvider");
1107
+ }
1108
+ return value;
1109
+ }
1110
+ function DirectoryEditorProvider(props) {
1111
+ const { directory } = props;
1112
+ const [{ result, error }, { execute }] = useAsync$1(async (dir) => {
1113
+ const manager = new DirectoryEditorManager(dir);
1114
+ await manager.reload();
1115
+ const firstYaml = manager.files.find((file) => file.path.match(/\.ya?ml$/));
1116
+ if (firstYaml) {
1117
+ manager.setSelectedFile(firstYaml.path);
1118
+ }
1119
+ return manager;
1120
+ });
1121
+ useEffect(() => {
1122
+ execute(directory);
1123
+ }, [execute, directory]);
1124
+ if (error) {
1125
+ return /* @__PURE__ */ React.createElement(ErrorPanel, {
1126
+ error
1127
+ });
1128
+ } else if (!result) {
1129
+ return /* @__PURE__ */ React.createElement(Progress, null);
1130
+ }
1131
+ return /* @__PURE__ */ React.createElement(DirectoryEditorContext.Provider, {
1132
+ value: result
1133
+ }, props.children);
1134
+ }
1135
+
1136
+ const DryRunContext = createContext(void 0);
1137
+ function DryRunProvider(props) {
1138
+ const scaffolderApi = useApi(scaffolderApiRef);
1139
+ const [state, setState] = useState({
1140
+ results: [],
1141
+ selectedResult: void 0
1142
+ });
1143
+ const idRef = useRef(1);
1144
+ const selectResult = useCallback((id) => {
1145
+ setState((prevState) => {
1146
+ const result = prevState.results.find((r) => r.id === id);
1147
+ if (result === prevState.selectedResult) {
1148
+ return prevState;
1149
+ }
1150
+ return {
1151
+ results: prevState.results,
1152
+ selectedResult: result
1153
+ };
1154
+ });
1155
+ }, []);
1156
+ const deleteResult = useCallback((id) => {
1157
+ setState((prevState) => {
1158
+ var _a;
1159
+ const index = prevState.results.findIndex((r) => r.id === id);
1160
+ if (index === -1) {
1161
+ return prevState;
1162
+ }
1163
+ const newResults = prevState.results.slice();
1164
+ const [deleted] = newResults.splice(index, 1);
1165
+ return {
1166
+ results: newResults,
1167
+ selectedResult: ((_a = prevState.selectedResult) == null ? void 0 : _a.id) === deleted.id ? newResults[0] : prevState.selectedResult
1168
+ };
1169
+ });
1170
+ }, []);
1171
+ const execute = useCallback(async (options) => {
1172
+ if (!scaffolderApi.dryRun) {
1173
+ throw new Error("Scaffolder API does not support dry-run");
1174
+ }
1175
+ const parsed = yaml.parse(options.templateContent);
1176
+ const response = await scaffolderApi.dryRun({
1177
+ template: parsed,
1178
+ values: options.values,
1179
+ secrets: {},
1180
+ directoryContents: options.files.map((file) => ({
1181
+ path: file.path,
1182
+ base64Content: btoa(file.content)
1183
+ }))
1184
+ });
1185
+ const result = {
1186
+ ...response,
1187
+ id: idRef.current++
1188
+ };
1189
+ setState((prevState) => {
1190
+ var _a;
1191
+ return {
1192
+ results: [...prevState.results, result],
1193
+ selectedResult: (_a = prevState.selectedResult) != null ? _a : result
1194
+ };
1195
+ });
1196
+ }, [scaffolderApi]);
1197
+ const dryRun = useMemo(() => ({
1198
+ ...state,
1199
+ selectResult,
1200
+ deleteResult,
1201
+ execute
1202
+ }), [state, selectResult, deleteResult, execute]);
1203
+ return /* @__PURE__ */ React.createElement(DryRunContext.Provider, {
1204
+ value: dryRun
1205
+ }, props.children);
1206
+ }
1207
+ function useDryRun() {
1208
+ const value = useContext(DryRunContext);
1209
+ if (!value) {
1210
+ throw new Error("must be used within a DryRunProvider");
1211
+ }
1212
+ return value;
1213
+ }
1214
+
1215
+ const useStyles$9 = makeStyles$1((theme) => ({
1216
+ root: {
1217
+ overflowY: "auto",
1218
+ background: theme.palette.background.default
1219
+ },
1220
+ iconSuccess: {
1221
+ minWidth: 0,
1222
+ marginRight: theme.spacing(1),
1223
+ color: theme.palette.status.ok
1224
+ },
1225
+ iconFailure: {
1226
+ minWidth: 0,
1227
+ marginRight: theme.spacing(1),
1228
+ color: theme.palette.status.error
1229
+ }
1230
+ }));
1231
+ function DryRunResultsList() {
1232
+ const classes = useStyles$9();
1233
+ const dryRun = useDryRun();
1234
+ return /* @__PURE__ */ React.createElement(List, {
1235
+ className: classes.root,
1236
+ dense: true
1237
+ }, dryRun.results.map((result) => {
1238
+ var _a;
1239
+ const failed = result.log.some((l) => l.body.status === "failed");
1240
+ return /* @__PURE__ */ React.createElement(ListItem, {
1241
+ button: true,
1242
+ key: result.id,
1243
+ selected: ((_a = dryRun.selectedResult) == null ? void 0 : _a.id) === result.id,
1244
+ onClick: () => dryRun.selectResult(result.id)
1245
+ }, /* @__PURE__ */ React.createElement(ListItemIcon, {
1246
+ className: failed ? classes.iconFailure : classes.iconSuccess
1247
+ }, failed ? /* @__PURE__ */ React.createElement(Cancel, null) : /* @__PURE__ */ React.createElement(Check, null)), /* @__PURE__ */ React.createElement(ListItemText, {
1248
+ primary: `Result ${result.id}`
1249
+ }), /* @__PURE__ */ React.createElement(ListItemSecondaryAction, null, /* @__PURE__ */ React.createElement(IconButton$1, {
1250
+ edge: "end",
1251
+ "aria-label": "delete",
1252
+ onClick: () => dryRun.deleteResult(result.id)
1253
+ }, /* @__PURE__ */ React.createElement(DeleteIcon, null))));
1254
+ }));
1255
+ }
1256
+
1257
+ const useStyles$8 = makeStyles$1({
1258
+ root: {
1259
+ whiteSpace: "nowrap",
1260
+ overflowY: "auto"
1261
+ }
1262
+ });
1263
+ function parseFileEntires(paths) {
1264
+ const root = {
1265
+ type: "directory",
1266
+ name: "",
1267
+ path: "",
1268
+ children: []
1269
+ };
1270
+ for (const path of paths.slice().sort()) {
1271
+ const parts = path.split("/");
1272
+ let current = root;
1273
+ for (let i = 0; i < parts.length; i++) {
1274
+ const part = parts[i];
1275
+ if (part === "") {
1276
+ throw new Error(`Invalid path part: ''`);
1277
+ }
1278
+ const entryPath = parts.slice(0, i + 1).join("/");
1279
+ const existing = current.children.find((child) => child.name === part);
1280
+ if ((existing == null ? void 0 : existing.type) === "file") {
1281
+ throw new Error(`Duplicate filename at '${entryPath}'`);
1282
+ } else if (existing) {
1283
+ current = existing;
1284
+ } else {
1285
+ if (i < parts.length - 1) {
1286
+ const newEntry = {
1287
+ type: "directory",
1288
+ name: part,
1289
+ path: entryPath,
1290
+ children: []
1291
+ };
1292
+ const firstFileIndex = current.children.findIndex((child) => child.type === "file");
1293
+ current.children.splice(firstFileIndex, 0, newEntry);
1294
+ current = newEntry;
1295
+ } else {
1296
+ current.children.push({
1297
+ type: "file",
1298
+ name: part,
1299
+ path: entryPath
1300
+ });
1301
+ }
1302
+ }
1303
+ }
1304
+ }
1305
+ return root.children;
1306
+ }
1307
+ function FileTreeItem({ entry }) {
1308
+ if (entry.type === "file") {
1309
+ return /* @__PURE__ */ React.createElement(TreeItem, {
1310
+ nodeId: entry.path,
1311
+ label: entry.name
1312
+ });
1313
+ }
1314
+ return /* @__PURE__ */ React.createElement(TreeItem, {
1315
+ nodeId: entry.path,
1316
+ label: entry.name
1317
+ }, entry.children.map((child) => /* @__PURE__ */ React.createElement(FileTreeItem, {
1318
+ key: child.path,
1319
+ entry: child
1320
+ })));
1321
+ }
1322
+ function FileBrowser(props) {
1323
+ const classes = useStyles$8();
1324
+ const fileTree = useMemo(() => parseFileEntires(props.filePaths), [props.filePaths]);
1325
+ return /* @__PURE__ */ React.createElement(TreeView, {
1326
+ selected: props.selected,
1327
+ className: classes.root,
1328
+ defaultCollapseIcon: /* @__PURE__ */ React.createElement(ExpandMoreIcon, null),
1329
+ defaultExpandIcon: /* @__PURE__ */ React.createElement(ChevronRightIcon, null),
1330
+ onNodeSelect: (_e, nodeId) => {
1331
+ if (props.onSelect && props.filePaths.includes(nodeId)) {
1332
+ props.onSelect(nodeId);
1333
+ }
1334
+ }
1335
+ }, fileTree.map((entry) => /* @__PURE__ */ React.createElement(FileTreeItem, {
1336
+ key: entry.path,
1337
+ entry
1338
+ })));
1339
+ }
1340
+
1341
+ const useStyles$7 = makeStyles$1((theme) => ({
1342
+ root: {
1343
+ display: "grid",
1344
+ gridTemplateColumns: "280px auto 3fr",
1345
+ gridTemplateRows: "1fr"
1346
+ },
1347
+ child: {
1348
+ overflowY: "auto",
1349
+ height: "100%",
1350
+ minHeight: 0
1351
+ },
1352
+ firstChild: {
1353
+ background: theme.palette.background.paper
1354
+ }
1355
+ }));
1356
+ function DryRunResultsSplitView(props) {
1357
+ const classes = useStyles$7();
1358
+ const childArray = Children.toArray(props.children);
1359
+ if (childArray.length !== 2) {
1360
+ throw new Error("must have exactly 2 children");
1361
+ }
1362
+ return /* @__PURE__ */ React.createElement("div", {
1363
+ className: classes.root
1364
+ }, /* @__PURE__ */ React.createElement("div", {
1365
+ className: classNames(classes.child, classes.firstChild)
1366
+ }, childArray[0]), /* @__PURE__ */ React.createElement(Divider, {
1367
+ orientation: "horizontal"
1368
+ }), /* @__PURE__ */ React.createElement("div", {
1369
+ className: classes.child
1370
+ }, childArray[1]));
1371
+ }
1372
+
1373
+ const useStyles$6 = makeStyles$1({
1374
+ root: {
1375
+ display: "flex",
1376
+ flexFlow: "column nowrap"
1377
+ },
1378
+ contentWrapper: {
1379
+ flex: 1,
1380
+ position: "relative"
1381
+ },
1382
+ content: {
1383
+ position: "absolute",
1384
+ top: 0,
1385
+ left: 0,
1386
+ right: 0,
1387
+ bottom: 0,
1388
+ display: "flex",
1389
+ "& > *": {
1390
+ flex: 1
1391
+ }
1392
+ },
1393
+ codeMirror: {
1394
+ height: "100%",
1395
+ overflowY: "auto"
1396
+ }
1397
+ });
1398
+ function FilesContent() {
1399
+ const classes = useStyles$6();
1400
+ const { selectedResult } = useDryRun();
1401
+ const [selectedPath, setSelectedPath] = useState("");
1402
+ const selectedFile = selectedResult == null ? void 0 : selectedResult.directoryContents.find((f) => f.path === selectedPath);
1403
+ useEffect(() => {
1404
+ if (selectedResult) {
1405
+ const [firstFile] = selectedResult.directoryContents;
1406
+ if (firstFile) {
1407
+ setSelectedPath(firstFile.path);
1408
+ } else {
1409
+ setSelectedPath("");
1410
+ }
1411
+ }
1412
+ return void 0;
1413
+ }, [selectedResult]);
1414
+ if (!selectedResult) {
1415
+ return null;
1416
+ }
1417
+ return /* @__PURE__ */ React.createElement(DryRunResultsSplitView, null, /* @__PURE__ */ React.createElement(FileBrowser, {
1418
+ selected: selectedPath,
1419
+ onSelect: setSelectedPath,
1420
+ filePaths: selectedResult.directoryContents.map((file) => file.path)
1421
+ }), /* @__PURE__ */ React.createElement(CodeMirror, {
1422
+ className: classes.codeMirror,
1423
+ theme: "dark",
1424
+ height: "100%",
1425
+ extensions: [StreamLanguage.define(yaml$1)],
1426
+ readOnly: true,
1427
+ value: (selectedFile == null ? void 0 : selectedFile.base64Content) ? atob(selectedFile.base64Content) : ""
1428
+ }));
1429
+ }
1430
+ function LogContent() {
1431
+ var _a, _b;
1432
+ const { selectedResult } = useDryRun();
1433
+ const [currentStepId, setUserSelectedStepId] = useState();
1434
+ const steps = useMemo(() => {
1435
+ var _a2;
1436
+ if (!selectedResult) {
1437
+ return [];
1438
+ }
1439
+ return (_a2 = selectedResult.steps.map((step) => {
1440
+ var _a3, _b2;
1441
+ const stepLog = selectedResult.log.filter((l) => l.body.stepId === step.id);
1442
+ return {
1443
+ id: step.id,
1444
+ name: step.name,
1445
+ logString: stepLog.map((l) => l.body.message).join("\n"),
1446
+ status: (_b2 = (_a3 = stepLog[stepLog.length - 1]) == null ? void 0 : _a3.body.status) != null ? _b2 : "completed"
1447
+ };
1448
+ })) != null ? _a2 : [];
1449
+ }, [selectedResult]);
1450
+ if (!selectedResult) {
1451
+ return null;
1452
+ }
1453
+ const selectedStep = (_a = steps.find((s) => s.id === currentStepId)) != null ? _a : steps[0];
1454
+ return /* @__PURE__ */ React.createElement(DryRunResultsSplitView, null, /* @__PURE__ */ React.createElement(TaskStatusStepper, {
1455
+ steps,
1456
+ currentStepId: selectedStep.id,
1457
+ onUserStepChange: setUserSelectedStepId
1458
+ }), /* @__PURE__ */ React.createElement(LogViewer, {
1459
+ text: (_b = selectedStep == null ? void 0 : selectedStep.logString) != null ? _b : ""
1460
+ }));
1461
+ }
1462
+ function OutputContent() {
1463
+ var _a, _b;
1464
+ const classes = useStyles$6();
1465
+ const { selectedResult } = useDryRun();
1466
+ if (!selectedResult) {
1467
+ return null;
1468
+ }
1469
+ return /* @__PURE__ */ React.createElement(DryRunResultsSplitView, null, /* @__PURE__ */ React.createElement(Box$1, {
1470
+ pt: 2
1471
+ }, ((_b = (_a = selectedResult.output) == null ? void 0 : _a.links) == null ? void 0 : _b.length) && /* @__PURE__ */ React.createElement(TaskPageLinks, {
1472
+ output: selectedResult.output
1473
+ })), /* @__PURE__ */ React.createElement(CodeMirror, {
1474
+ className: classes.codeMirror,
1475
+ theme: "dark",
1476
+ height: "100%",
1477
+ extensions: [StreamLanguage.define(yaml$1)],
1478
+ readOnly: true,
1479
+ value: JSON.stringify(selectedResult.output, null, 2)
1480
+ }));
1481
+ }
1482
+ function DryRunResultsView() {
1483
+ const classes = useStyles$6();
1484
+ const [selectedTab, setSelectedTab] = useState("files");
1485
+ return /* @__PURE__ */ React.createElement("div", {
1486
+ className: classes.root
1487
+ }, /* @__PURE__ */ React.createElement(Tabs, {
1488
+ value: selectedTab,
1489
+ onChange: (_, v) => setSelectedTab(v)
1490
+ }, /* @__PURE__ */ React.createElement(Tab, {
1491
+ value: "files",
1492
+ label: "Files"
1493
+ }), /* @__PURE__ */ React.createElement(Tab, {
1494
+ value: "log",
1495
+ label: "Log"
1496
+ }), /* @__PURE__ */ React.createElement(Tab, {
1497
+ value: "output",
1498
+ label: "Output"
1499
+ })), /* @__PURE__ */ React.createElement(Divider, null), /* @__PURE__ */ React.createElement("div", {
1500
+ className: classes.contentWrapper
1501
+ }, /* @__PURE__ */ React.createElement("div", {
1502
+ className: classes.content
1503
+ }, selectedTab === "files" && /* @__PURE__ */ React.createElement(FilesContent, null), selectedTab === "log" && /* @__PURE__ */ React.createElement(LogContent, null), selectedTab === "output" && /* @__PURE__ */ React.createElement(OutputContent, null))));
1504
+ }
1505
+
1506
+ const useStyles$5 = makeStyles$1((theme) => ({
1507
+ header: {
1508
+ height: 48,
1509
+ minHeight: 0,
1510
+ "&.Mui-expanded": {
1511
+ height: 48,
1512
+ minHeight: 0
1513
+ }
1514
+ },
1515
+ content: {
1516
+ display: "grid",
1517
+ background: theme.palette.background.default,
1518
+ gridTemplateColumns: "180px auto 1fr",
1519
+ gridTemplateRows: "1fr",
1520
+ padding: 0,
1521
+ height: 400
1522
+ }
1523
+ }));
1524
+ function DryRunResults() {
1525
+ const classes = useStyles$5();
1526
+ const dryRun = useDryRun();
1527
+ const [expanded, setExpanded] = useState(false);
1528
+ const [hidden, setHidden] = useState(true);
1529
+ const resultsLength = dryRun.results.length;
1530
+ const prevResultsLength = usePrevious(resultsLength);
1531
+ useEffect(() => {
1532
+ if (prevResultsLength === 0 && resultsLength === 1) {
1533
+ setHidden(false);
1534
+ setExpanded(true);
1535
+ } else if (prevResultsLength === 1 && resultsLength === 0) {
1536
+ setExpanded(false);
1537
+ }
1538
+ }, [prevResultsLength, resultsLength]);
1539
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Accordion, {
1540
+ variant: "outlined",
1541
+ expanded,
1542
+ hidden: resultsLength === 0 && hidden,
1543
+ onChange: (_, exp) => setExpanded(exp),
1544
+ onTransitionEnd: () => resultsLength === 0 && setHidden(true)
1545
+ }, /* @__PURE__ */ React.createElement(AccordionSummary, {
1546
+ className: classes.header,
1547
+ expandIcon: /* @__PURE__ */ React.createElement(ExpandMoreIcon$1, null)
1548
+ }, /* @__PURE__ */ React.createElement(Typography$1, null, "Dry-run results")), /* @__PURE__ */ React.createElement(Divider, {
1549
+ orientation: "horizontal"
1550
+ }), /* @__PURE__ */ React.createElement(AccordionDetails, {
1551
+ className: classes.content
1552
+ }, /* @__PURE__ */ React.createElement(DryRunResultsList, null), /* @__PURE__ */ React.createElement(Divider, {
1553
+ orientation: "horizontal"
1554
+ }), /* @__PURE__ */ React.createElement(DryRunResultsView, null))));
1555
+ }
1556
+
1557
+ const useStyles$4 = makeStyles((theme) => ({
1558
+ button: {
1559
+ padding: theme.spacing(1)
1560
+ },
1561
+ buttons: {
1562
+ display: "flex",
1563
+ flexFlow: "row nowrap",
1564
+ alignItems: "center",
1565
+ justifyContent: "flex-start"
1566
+ },
1567
+ buttonsGap: {
1568
+ flex: "1 1 auto"
1569
+ },
1570
+ buttonsDivider: {
1571
+ marginBottom: theme.spacing(1)
1572
+ }
1573
+ }));
1574
+ function TemplateEditorBrowser(props) {
1575
+ var _a, _b;
1576
+ const classes = useStyles$4();
1577
+ const directoryEditor = useDirectoryEditor();
1578
+ const changedFiles = directoryEditor.files.filter((file) => file.dirty);
1579
+ const handleClose = () => {
1580
+ if (!props.onClose) {
1581
+ return;
1582
+ }
1583
+ if (changedFiles.length > 0) {
1584
+ const accepted = window.confirm("Are you sure? Unsaved changes will be lost");
1585
+ if (!accepted) {
1586
+ return;
1587
+ }
1588
+ }
1589
+ props.onClose();
1590
+ };
1591
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
1592
+ className: classes.buttons
1593
+ }, /* @__PURE__ */ React.createElement(Tooltip, {
1594
+ title: "Save all files"
1595
+ }, /* @__PURE__ */ React.createElement(IconButton, {
1596
+ className: classes.button,
1597
+ disabled: directoryEditor.files.every((file) => !file.dirty),
1598
+ onClick: () => directoryEditor.save()
1599
+ }, /* @__PURE__ */ React.createElement(SaveIcon, null))), /* @__PURE__ */ React.createElement(Tooltip, {
1600
+ title: "Reload directory"
1601
+ }, /* @__PURE__ */ React.createElement(IconButton, {
1602
+ className: classes.button,
1603
+ onClick: () => directoryEditor.reload()
1604
+ }, /* @__PURE__ */ React.createElement(RefreshIcon, null))), /* @__PURE__ */ React.createElement("div", {
1605
+ className: classes.buttonsGap
1606
+ }), /* @__PURE__ */ React.createElement(Tooltip, {
1607
+ title: "Close directory"
1608
+ }, /* @__PURE__ */ React.createElement(IconButton, {
1609
+ className: classes.button,
1610
+ onClick: handleClose
1611
+ }, /* @__PURE__ */ React.createElement(CloseIcon, null)))), /* @__PURE__ */ React.createElement(Divider$1, {
1612
+ className: classes.buttonsDivider
1613
+ }), /* @__PURE__ */ React.createElement(FileBrowser, {
1614
+ selected: (_b = (_a = directoryEditor.selectedFile) == null ? void 0 : _a.path) != null ? _b : "",
1615
+ onSelect: directoryEditor.setSelectedFile,
1616
+ filePaths: directoryEditor.files.map((file) => file.path)
1617
+ }));
1618
+ }
1619
+
1620
+ const useStyles$3 = makeStyles$1({
1621
+ containerWrapper: {
1622
+ position: "relative",
1623
+ width: "100%",
1624
+ height: "100%"
1625
+ },
1626
+ container: {
1627
+ position: "absolute",
1628
+ top: 0,
1629
+ bottom: 0,
1630
+ left: 0,
1631
+ right: 0,
1632
+ overflow: "auto"
1633
+ }
1634
+ });
1635
+ class ErrorBoundary extends Component {
1636
+ constructor() {
1637
+ super(...arguments);
1638
+ this.state = {
1639
+ shouldRender: true
1640
+ };
1641
+ }
1642
+ componentDidUpdate(prevProps) {
1643
+ if (prevProps.invalidator !== this.props.invalidator) {
1644
+ this.setState({ shouldRender: true });
1645
+ }
1646
+ }
1647
+ componentDidCatch(error) {
1648
+ this.props.setErrorText(error.message);
1649
+ this.setState({ shouldRender: false });
1650
+ }
1651
+ render() {
1652
+ return this.state.shouldRender ? this.props.children : null;
1653
+ }
1654
+ }
1655
+ function isJsonObject(value) {
1656
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1657
+ }
1658
+ function TemplateEditorForm(props) {
1659
+ const {
1660
+ content,
1661
+ contentIsSpec,
1662
+ data,
1663
+ onUpdate,
1664
+ onDryRun,
1665
+ setErrorText,
1666
+ fieldExtensions = []
1667
+ } = props;
1668
+ const classes = useStyles$3();
1669
+ const apiHolder = useApiHolder();
1670
+ const [steps, setSteps] = useState();
1671
+ const fields = useMemo(() => {
1672
+ return Object.fromEntries(fieldExtensions.map(({ name, component }) => [name, component]));
1673
+ }, [fieldExtensions]);
1674
+ useDebounce(() => {
1675
+ try {
1676
+ if (!content) {
1677
+ setSteps(void 0);
1678
+ return;
1679
+ }
1680
+ const parsed = yaml.parse(content);
1681
+ if (!isJsonObject(parsed)) {
1682
+ setSteps(void 0);
1683
+ return;
1684
+ }
1685
+ let rootObj = parsed;
1686
+ if (!contentIsSpec) {
1687
+ const isTemplate = String(parsed.kind).toLocaleLowerCase("en-US") === "template";
1688
+ if (!isTemplate) {
1689
+ setSteps(void 0);
1690
+ return;
1691
+ }
1692
+ rootObj = isJsonObject(parsed.spec) ? parsed.spec : {};
1693
+ }
1694
+ const { parameters } = rootObj;
1695
+ if (!Array.isArray(parameters)) {
1696
+ setErrorText("Template parameters must be an array");
1697
+ setSteps(void 0);
1698
+ return;
1699
+ }
1700
+ const fieldValidators = Object.fromEntries(fieldExtensions.map(({ name, validation }) => [name, validation]));
1701
+ setErrorText();
1702
+ setSteps(parameters.flatMap((param) => isJsonObject(param) ? [
1703
+ {
1704
+ title: String(param.title),
1705
+ schema: param,
1706
+ validate: createValidator(param, fieldValidators, {
1707
+ apiHolder
1708
+ })
1709
+ }
1710
+ ] : []));
1711
+ } catch (e) {
1712
+ setErrorText(e.message);
1713
+ }
1714
+ }, 250, [contentIsSpec, content, apiHolder]);
1715
+ if (!steps) {
1716
+ return null;
1717
+ }
1718
+ return /* @__PURE__ */ React.createElement("div", {
1719
+ className: classes.containerWrapper
1720
+ }, /* @__PURE__ */ React.createElement("div", {
1721
+ className: classes.container
1722
+ }, /* @__PURE__ */ React.createElement(ErrorBoundary, {
1723
+ invalidator: steps,
1724
+ setErrorText
1725
+ }, /* @__PURE__ */ React.createElement(MultistepJsonForm, {
1726
+ steps,
1727
+ fields,
1728
+ formData: data,
1729
+ onChange: (e) => onUpdate(e.formData),
1730
+ onReset: () => onUpdate({}),
1731
+ finishButtonLabel: onDryRun && "Try It",
1732
+ onFinish: onDryRun && (() => onDryRun(data))
1733
+ }))));
1734
+ }
1735
+ function TemplateEditorFormDirectoryEditorDryRun(props) {
1736
+ const { setErrorText, fieldExtensions = [] } = props;
1737
+ const dryRun = useDryRun();
1738
+ const directoryEditor = useDirectoryEditor();
1739
+ const { selectedFile } = directoryEditor;
1740
+ const [data, setData] = useState({});
1741
+ const handleDryRun = async () => {
1742
+ if (!selectedFile) {
1743
+ return;
1744
+ }
1745
+ await dryRun.execute({
1746
+ templateContent: selectedFile.content,
1747
+ values: data,
1748
+ files: directoryEditor.files
1749
+ });
1750
+ };
1751
+ const content = selectedFile && selectedFile.path.match(/\.ya?ml$/) ? selectedFile.content : void 0;
1752
+ return /* @__PURE__ */ React.createElement(TemplateEditorForm, {
1753
+ onDryRun: handleDryRun,
1754
+ fieldExtensions,
1755
+ setErrorText,
1756
+ content,
1757
+ data,
1758
+ onUpdate: setData
1759
+ });
1760
+ }
1761
+ TemplateEditorForm.DirectoryEditorDryRun = TemplateEditorFormDirectoryEditorDryRun;
1762
+
1763
+ const useStyles$2 = makeStyles((theme) => ({
1764
+ container: {
1765
+ position: "relative",
1766
+ width: "100%",
1767
+ height: "100%"
1768
+ },
1769
+ codeMirror: {
1770
+ position: "absolute",
1771
+ top: 0,
1772
+ bottom: 0,
1773
+ left: 0,
1774
+ right: 0
1775
+ },
1776
+ errorPanel: {
1777
+ color: theme.palette.error.main,
1778
+ lineHeight: 2,
1779
+ margin: theme.spacing(0, 1)
1780
+ },
1781
+ floatingButtons: {
1782
+ position: "absolute",
1783
+ top: theme.spacing(1),
1784
+ right: theme.spacing(3)
1785
+ },
1786
+ floatingButton: {
1787
+ padding: theme.spacing(1)
1788
+ }
1789
+ }));
1790
+ function TemplateEditorTextArea(props) {
1791
+ const { errorText } = props;
1792
+ const classes = useStyles$2();
1793
+ const panelExtension = useMemo(() => {
1794
+ if (!errorText) {
1795
+ return showPanel.of(null);
1796
+ }
1797
+ const dom = document.createElement("div");
1798
+ dom.classList.add(classes.errorPanel);
1799
+ dom.textContent = errorText;
1800
+ return showPanel.of(() => ({ dom, bottom: true }));
1801
+ }, [classes, errorText]);
1802
+ useKeyboardEvent((e) => e.key === "s" && (e.ctrlKey || e.metaKey), (e) => {
1803
+ e.preventDefault();
1804
+ if (props.onSave) {
1805
+ props.onSave();
1806
+ }
1807
+ });
1808
+ return /* @__PURE__ */ React.createElement("div", {
1809
+ className: classes.container
1810
+ }, /* @__PURE__ */ React.createElement(CodeMirror, {
1811
+ className: classes.codeMirror,
1812
+ theme: "dark",
1813
+ height: "100%",
1814
+ extensions: [StreamLanguage.define(yaml$1), panelExtension],
1815
+ value: props.content,
1816
+ onChange: props.onUpdate
1817
+ }), (props.onSave || props.onReload) && /* @__PURE__ */ React.createElement("div", {
1818
+ className: classes.floatingButtons
1819
+ }, /* @__PURE__ */ React.createElement(Paper, null, props.onSave && /* @__PURE__ */ React.createElement(Tooltip, {
1820
+ title: "Save file"
1821
+ }, /* @__PURE__ */ React.createElement(IconButton, {
1822
+ className: classes.floatingButton,
1823
+ onClick: () => {
1824
+ var _a;
1825
+ return (_a = props.onSave) == null ? void 0 : _a.call(props);
1826
+ }
1827
+ }, /* @__PURE__ */ React.createElement(SaveIcon, null))), props.onReload && /* @__PURE__ */ React.createElement(Tooltip, {
1828
+ title: "Reload file"
1829
+ }, /* @__PURE__ */ React.createElement(IconButton, {
1830
+ className: classes.floatingButton,
1831
+ onClick: () => {
1832
+ var _a;
1833
+ return (_a = props.onReload) == null ? void 0 : _a.call(props);
1834
+ }
1835
+ }, /* @__PURE__ */ React.createElement(RefreshIcon, null))))));
1836
+ }
1837
+ function TemplateEditorDirectoryEditorTextArea(props) {
1838
+ var _a, _b;
1839
+ const directoryEditor = useDirectoryEditor();
1840
+ const actions = ((_a = directoryEditor.selectedFile) == null ? void 0 : _a.dirty) ? {
1841
+ onSave: () => directoryEditor.save(),
1842
+ onReload: () => directoryEditor.reload()
1843
+ } : {
1844
+ onReload: () => directoryEditor.reload()
1845
+ };
1846
+ return /* @__PURE__ */ React.createElement(TemplateEditorTextArea, {
1847
+ errorText: props.errorText,
1848
+ content: (_b = directoryEditor.selectedFile) == null ? void 0 : _b.content,
1849
+ onUpdate: (content) => {
1850
+ var _a2;
1851
+ return (_a2 = directoryEditor.selectedFile) == null ? void 0 : _a2.updateContent(content);
1852
+ },
1853
+ ...actions
1854
+ });
1855
+ }
1856
+ TemplateEditorTextArea.DirectoryEditor = TemplateEditorDirectoryEditorTextArea;
1857
+
1858
+ const useStyles$1 = makeStyles({
1859
+ root: {
1860
+ gridArea: "pageContent",
1861
+ display: "grid",
1862
+ gridTemplateAreas: `
1863
+ "browser editor preview"
1864
+ "results results results"
1865
+ `,
1866
+ gridTemplateColumns: "1fr 3fr 2fr",
1867
+ gridTemplateRows: "1fr auto"
1868
+ },
1869
+ browser: {
1870
+ gridArea: "browser",
1871
+ overflow: "auto"
1872
+ },
1873
+ editor: {
1874
+ gridArea: "editor",
1875
+ overflow: "auto"
1876
+ },
1877
+ preview: {
1878
+ gridArea: "preview",
1879
+ overflow: "auto"
1880
+ },
1881
+ results: {
1882
+ gridArea: "results"
1883
+ }
1884
+ });
1885
+ const TemplateEditor = (props) => {
1886
+ const classes = useStyles$1();
1887
+ const [errorText, setErrorText] = useState();
1888
+ return /* @__PURE__ */ React.createElement(DirectoryEditorProvider, {
1889
+ directory: props.directory
1890
+ }, /* @__PURE__ */ React.createElement(DryRunProvider, null, /* @__PURE__ */ React.createElement("main", {
1891
+ className: classes.root
1892
+ }, /* @__PURE__ */ React.createElement("section", {
1893
+ className: classes.browser
1894
+ }, /* @__PURE__ */ React.createElement(TemplateEditorBrowser, {
1895
+ onClose: props.onClose
1896
+ })), /* @__PURE__ */ React.createElement("section", {
1897
+ className: classes.editor
1898
+ }, /* @__PURE__ */ React.createElement(TemplateEditorTextArea.DirectoryEditor, {
1899
+ errorText
1900
+ })), /* @__PURE__ */ React.createElement("section", {
1901
+ className: classes.preview
1902
+ }, /* @__PURE__ */ React.createElement(TemplateEditorForm.DirectoryEditorDryRun, {
1903
+ setErrorText,
1904
+ fieldExtensions: props.fieldExtensions
1905
+ })), /* @__PURE__ */ React.createElement("section", {
1906
+ className: classes.results
1907
+ }, /* @__PURE__ */ React.createElement(DryRunResults, null)))));
1908
+ };
1909
+
1910
+ const EXAMPLE_TEMPLATE_PARAMS_YAML = `# Edit the template parameters below to see how they will render in the scaffolder form UI
1911
+ parameters:
1912
+ - title: Fill in some steps
1913
+ required:
1914
+ - name
1915
+ properties:
1916
+ name:
1917
+ title: Name
1918
+ type: string
1919
+ description: Unique name of the component
1920
+ owner:
1921
+ title: Owner
1922
+ type: string
1923
+ description: Owner of the component
1924
+ ui:field: OwnerPicker
1925
+ ui:options:
1926
+ allowedKinds:
1927
+ - Group
1928
+ - title: Choose a location
1929
+ required:
1930
+ - repoUrl
1931
+ properties:
1932
+ repoUrl:
1933
+ title: Repository Location
1934
+ type: string
1935
+ ui:field: RepoUrlPicker
1936
+ ui:options:
1937
+ allowedHosts:
1938
+ - github.com
1939
+ steps:
1940
+ - id: fetch-base
1941
+ name: Fetch Base
1942
+ action: fetch:template
1943
+ input:
1944
+ url: ./template
1945
+ values:
1946
+ name: \${{parameters.name}}
1947
+ `;
1948
+ const useStyles = makeStyles((theme) => ({
1949
+ root: {
1950
+ gridArea: "pageContent",
1951
+ display: "grid",
1952
+ gridTemplateAreas: `
1953
+ "controls controls"
1954
+ "textArea preview"
1955
+ `,
1956
+ gridTemplateRows: "auto 1fr",
1957
+ gridTemplateColumns: "1fr 1fr"
1958
+ },
1959
+ controls: {
1960
+ gridArea: "controls",
1961
+ display: "flex",
1962
+ flexFlow: "row nowrap",
1963
+ alignItems: "center",
1964
+ margin: theme.spacing(1)
1965
+ },
1966
+ textArea: {
1967
+ gridArea: "textArea"
1968
+ },
1969
+ preview: {
1970
+ gridArea: "preview"
1971
+ }
1972
+ }));
1973
+ const TemplateFormPreviewer = ({
1974
+ defaultPreviewTemplate = EXAMPLE_TEMPLATE_PARAMS_YAML,
1975
+ customFieldExtensions = [],
1976
+ onClose
1977
+ }) => {
1978
+ const classes = useStyles();
1979
+ const alertApi = useApi(alertApiRef);
1980
+ const catalogApi = useApi(catalogApiRef);
1981
+ const [selectedTemplate, setSelectedTemplate] = useState("");
1982
+ const [errorText, setErrorText] = useState();
1983
+ const [templateOptions, setTemplateOptions] = useState([]);
1984
+ const [templateYaml, setTemplateYaml] = useState(defaultPreviewTemplate);
1985
+ const [formState, setFormState] = useState({});
1986
+ const { loading } = useAsync(() => catalogApi.getEntities({
1987
+ filter: { kind: "template" },
1988
+ fields: [
1989
+ "kind",
1990
+ "metadata.namespace",
1991
+ "metadata.name",
1992
+ "metadata.title",
1993
+ "spec.parameters",
1994
+ "spec.steps",
1995
+ "spec.output"
1996
+ ]
1997
+ }).then(({ items }) => setTemplateOptions(items.map((template) => {
1998
+ var _a;
1999
+ return {
2000
+ label: (_a = template.metadata.title) != null ? _a : humanizeEntityRef(template, { defaultKind: "template" }),
2001
+ value: template
2002
+ };
2003
+ }))).catch((e) => alertApi.post({
2004
+ message: `Error loading exisiting templates: ${e.message}`,
2005
+ severity: "error"
2006
+ })), [catalogApi]);
2007
+ const handleSelectChange = useCallback((selected) => {
2008
+ setSelectedTemplate(selected);
2009
+ setTemplateYaml(yaml.stringify(selected.spec));
2010
+ }, [setTemplateYaml]);
2011
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, loading && /* @__PURE__ */ React.createElement(LinearProgress, null), /* @__PURE__ */ React.createElement("main", {
2012
+ className: classes.root
2013
+ }, /* @__PURE__ */ React.createElement("div", {
2014
+ className: classes.controls
2015
+ }, /* @__PURE__ */ React.createElement(FormControl, {
2016
+ variant: "outlined",
2017
+ size: "small",
2018
+ fullWidth: true
2019
+ }, /* @__PURE__ */ React.createElement(InputLabel, {
2020
+ id: "select-template-label"
2021
+ }, "Load Existing Template"), /* @__PURE__ */ React.createElement(Select, {
2022
+ value: selectedTemplate,
2023
+ label: "Load Existing Template",
2024
+ labelId: "select-template-label",
2025
+ onChange: (e) => handleSelectChange(e.target.value)
2026
+ }, templateOptions.map((option, idx) => /* @__PURE__ */ React.createElement(MenuItem$1, {
2027
+ key: idx,
2028
+ value: option.value
2029
+ }, option.label)))), /* @__PURE__ */ React.createElement(IconButton, {
2030
+ size: "medium",
2031
+ onClick: onClose
2032
+ }, /* @__PURE__ */ React.createElement(CloseIcon, null))), /* @__PURE__ */ React.createElement("div", {
2033
+ className: classes.textArea
2034
+ }, /* @__PURE__ */ React.createElement(TemplateEditorTextArea, {
2035
+ content: templateYaml,
2036
+ onUpdate: setTemplateYaml,
2037
+ errorText
2038
+ })), /* @__PURE__ */ React.createElement("div", {
2039
+ className: classes.preview
2040
+ }, /* @__PURE__ */ React.createElement(TemplateEditorForm, {
2041
+ content: templateYaml,
2042
+ contentIsSpec: true,
2043
+ fieldExtensions: customFieldExtensions,
2044
+ data: formState,
2045
+ onUpdate: setFormState,
2046
+ setErrorText
2047
+ }))));
2048
+ };
2049
+
2050
+ function TemplateEditorPage(props) {
2051
+ const [selection, setSelection] = useState();
2052
+ let content = null;
2053
+ if ((selection == null ? void 0 : selection.type) === "local") {
2054
+ content = /* @__PURE__ */ React.createElement(TemplateEditor, {
2055
+ directory: selection.directory,
2056
+ fieldExtensions: props.customFieldExtensions,
2057
+ onClose: () => setSelection(void 0)
2058
+ });
2059
+ } else if ((selection == null ? void 0 : selection.type) === "form") {
2060
+ content = /* @__PURE__ */ React.createElement(TemplateFormPreviewer, {
2061
+ defaultPreviewTemplate: props.defaultPreviewTemplate,
2062
+ customFieldExtensions: props.customFieldExtensions,
2063
+ onClose: () => setSelection(void 0)
2064
+ });
2065
+ } else {
2066
+ content = /* @__PURE__ */ React.createElement(Content, null, /* @__PURE__ */ React.createElement(TemplateEditorIntro, {
2067
+ onSelect: (option) => {
2068
+ if (option === "local") {
2069
+ WebFileSystemAccess.requestDirectoryAccess().then((directory) => setSelection({ type: "local", directory })).catch(() => {
2070
+ });
2071
+ } else if (option === "form") {
2072
+ setSelection({ type: "form" });
2073
+ }
2074
+ }
2075
+ }));
2076
+ }
2077
+ return /* @__PURE__ */ React.createElement(Page, {
2078
+ themeId: "home"
2079
+ }, /* @__PURE__ */ React.createElement(Header, {
2080
+ title: "Template Editor",
2081
+ subtitle: "Edit, preview, and try out templates and template forms"
2082
+ }), content);
2083
+ }
2084
+
2085
+ const Router = (props) => {
2086
+ const { groups, components = {}, defaultPreviewTemplate } = props;
2087
+ const { TemplateCardComponent, TaskPageComponent } = components;
2088
+ const outlet = useOutlet();
2089
+ const TaskPageElement = TaskPageComponent != null ? TaskPageComponent : TaskPage;
2090
+ const customFieldExtensions = useElementFilter(outlet, (elements) => elements.selectByComponentData({
2091
+ key: FIELD_EXTENSION_WRAPPER_KEY
2092
+ }).findComponentData({
2093
+ key: FIELD_EXTENSION_KEY
2094
+ }));
2095
+ const fieldExtensions = [
2096
+ ...customFieldExtensions,
2097
+ ...DEFAULT_SCAFFOLDER_FIELD_EXTENSIONS.filter(({ name }) => !customFieldExtensions.some((customFieldExtension) => customFieldExtension.name === name))
2098
+ ];
2099
+ return /* @__PURE__ */ React.createElement(Routes, null, /* @__PURE__ */ React.createElement(Route, {
2100
+ element: /* @__PURE__ */ React.createElement(ScaffolderPage, {
2101
+ groups,
2102
+ TemplateCardComponent,
2103
+ contextMenu: props.contextMenu
2104
+ })
2105
+ }), /* @__PURE__ */ React.createElement(Route, {
2106
+ path: selectedTemplateRouteRef.path,
2107
+ element: /* @__PURE__ */ React.createElement(SecretsContextProvider, null, /* @__PURE__ */ React.createElement(TemplatePage, {
2108
+ customFieldExtensions: fieldExtensions
2109
+ }))
2110
+ }), /* @__PURE__ */ React.createElement(Route, {
2111
+ path: scaffolderTaskRouteRef.path,
2112
+ element: /* @__PURE__ */ React.createElement(TaskPageElement, null)
2113
+ }), /* @__PURE__ */ React.createElement(Route, {
2114
+ path: actionsRouteRef.path,
2115
+ element: /* @__PURE__ */ React.createElement(ActionsPage, null)
2116
+ }), /* @__PURE__ */ React.createElement(Route, {
2117
+ path: editRouteRef.path,
2118
+ element: /* @__PURE__ */ React.createElement(SecretsContextProvider, null, /* @__PURE__ */ React.createElement(TemplateEditorPage, {
2119
+ defaultPreviewTemplate,
2120
+ customFieldExtensions: fieldExtensions
2121
+ }))
2122
+ }), /* @__PURE__ */ React.createElement(Route, {
2123
+ path: "preview",
2124
+ element: /* @__PURE__ */ React.createElement(Navigate, {
2125
+ to: "../edit"
2126
+ })
2127
+ }));
2128
+ };
2129
+
2130
+ export { Router };
2131
+ //# sourceMappingURL=Router-0396362f.esm.js.map