@plugmatica/blocks 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2634 @@
1
+ // src/useAsyncResource.ts
2
+ import * as React from "react";
3
+
4
+ // src/internal/async.ts
5
+ function toError(reason) {
6
+ if (reason instanceof Error) return reason;
7
+ const detail = reason;
8
+ const error = new Error(
9
+ typeof detail?.message === "string" ? detail.message : String(reason),
10
+ { cause: reason }
11
+ );
12
+ if (typeof detail?.status === "number") {
13
+ Object.defineProperty(error, "status", { value: detail.status });
14
+ }
15
+ return error;
16
+ }
17
+ var LatestRequest = class {
18
+ generation = 0;
19
+ controller = null;
20
+ cancel() {
21
+ this.generation += 1;
22
+ this.controller?.abort();
23
+ this.controller = null;
24
+ }
25
+ async run(load, commit) {
26
+ this.cancel();
27
+ const generation = this.generation;
28
+ const controller = new AbortController();
29
+ this.controller = controller;
30
+ const current = () => generation === this.generation && !controller.signal.aborted;
31
+ await Promise.resolve();
32
+ if (!current()) return { status: "cancelled" };
33
+ let result;
34
+ try {
35
+ result = { status: "success", value: await load(controller.signal) };
36
+ } catch (reason) {
37
+ result = { status: "error", error: toError(reason) };
38
+ }
39
+ if (!current()) return { status: "cancelled" };
40
+ this.controller = null;
41
+ commit(result);
42
+ return result;
43
+ }
44
+ };
45
+ var SingleFlight = class {
46
+ pending = false;
47
+ async run(action) {
48
+ if (this.pending) return { status: "busy" };
49
+ this.pending = true;
50
+ try {
51
+ return { status: "success", value: await action() };
52
+ } catch (reason) {
53
+ return { status: "error", error: toError(reason) };
54
+ } finally {
55
+ this.pending = false;
56
+ }
57
+ }
58
+ };
59
+
60
+ // src/useAsyncResource.ts
61
+ function useAsyncResource(load, { enabled = true, keepPreviousData = false, scopeKey } = {}) {
62
+ const [runner] = React.useState(() => new LatestRequest());
63
+ const mounted = React.useRef(false);
64
+ const live = React.useRef({ load, enabled, scopeKey });
65
+ const [snapshot, setSnapshot] = React.useState(() => ({
66
+ scopeKey,
67
+ load,
68
+ value: null,
69
+ error: null,
70
+ loading: enabled
71
+ }));
72
+ const execute = React.useCallback(async () => {
73
+ if (!enabled || !mounted.current || !live.current.enabled || live.current.load !== load || live.current.scopeKey !== scopeKey) return { status: "cancelled" };
74
+ setSnapshot((previous) => ({
75
+ scopeKey,
76
+ load,
77
+ value: previous.scopeKey === scopeKey && (keepPreviousData || previous.load === load) ? previous.value : null,
78
+ error: null,
79
+ loading: true
80
+ }));
81
+ return runner.run(load, (result) => {
82
+ if (!mounted.current) return;
83
+ setSnapshot((previous) => ({
84
+ scopeKey,
85
+ load,
86
+ value: result.status === "success" ? result.value : previous.value,
87
+ error: result.status === "error" ? result.error : null,
88
+ loading: false
89
+ }));
90
+ });
91
+ }, [enabled, keepPreviousData, load, runner, scopeKey]);
92
+ const refresh = React.useCallback(async () => {
93
+ const result = await execute();
94
+ return result.status === "success" ? result.value : void 0;
95
+ }, [execute]);
96
+ const reload = React.useCallback(async () => {
97
+ const result = await execute();
98
+ if (result.status === "error") throw result.error;
99
+ if (result.status === "cancelled") {
100
+ throw new DOMException("Resource request cancelled or disabled", "AbortError");
101
+ }
102
+ return result.value;
103
+ }, [execute]);
104
+ React.useEffect(() => {
105
+ mounted.current = true;
106
+ live.current = { load, enabled, scopeKey };
107
+ if (enabled) {
108
+ void refresh();
109
+ } else {
110
+ runner.cancel();
111
+ setSnapshot({ scopeKey, load, value: null, error: null, loading: false });
112
+ }
113
+ return () => {
114
+ mounted.current = false;
115
+ runner.cancel();
116
+ };
117
+ }, [enabled, load, refresh, runner, scopeKey]);
118
+ const setValue = React.useCallback(
119
+ (update) => {
120
+ if (!mounted.current || !live.current.enabled || live.current.load !== load || live.current.scopeKey !== scopeKey) return;
121
+ setSnapshot((previous) => ({
122
+ ...previous,
123
+ scopeKey,
124
+ load,
125
+ value: typeof update === "function" ? update(previous.load === load && previous.scopeKey === scopeKey ? previous.value : null) : update
126
+ }));
127
+ },
128
+ [load, scopeKey]
129
+ );
130
+ const sameScope = snapshot.scopeKey === scopeKey;
131
+ const sameResource = sameScope && snapshot.load === load;
132
+ return {
133
+ value: enabled && sameScope && (sameResource || keepPreviousData) ? snapshot.value : null,
134
+ error: enabled && sameResource ? snapshot.error : null,
135
+ loading: enabled && (!sameResource || snapshot.loading),
136
+ refresh,
137
+ reload,
138
+ setValue
139
+ };
140
+ }
141
+
142
+ // src/usePluginResource.ts
143
+ import { usePluginApi } from "@plugmatica/plugin-sdk";
144
+ import * as React2 from "react";
145
+ function usePluginResource(path, body, options = {}) {
146
+ const api = usePluginApi();
147
+ const hasBody = body !== void 0;
148
+ const bodyKey = hasBody ? JSON.stringify(body) : void 0;
149
+ const load = React2.useCallback((signal) => {
150
+ if (hasBody && bodyKey === void 0) {
151
+ throw new TypeError("Resource body must be JSON serializable");
152
+ }
153
+ return bodyKey === void 0 ? api.get(path, { signal }) : api.post(path, JSON.parse(bodyKey), { signal });
154
+ }, [api, path, bodyKey, hasBody]);
155
+ return useAsyncResource(load, { ...options, scopeKey: api });
156
+ }
157
+
158
+ // src/useAsyncAction.ts
159
+ import * as React3 from "react";
160
+ function useAsyncAction(action) {
161
+ const [flight] = React3.useState(() => new SingleFlight());
162
+ const mounted = React3.useRef(false);
163
+ const [pending, setPending] = React3.useState(false);
164
+ const [error, setError] = React3.useState(null);
165
+ React3.useEffect(() => {
166
+ mounted.current = true;
167
+ return () => {
168
+ mounted.current = false;
169
+ };
170
+ }, []);
171
+ const run = React3.useCallback(async (...args) => {
172
+ if (flight.pending) return { status: "busy" };
173
+ if (mounted.current) {
174
+ setPending(true);
175
+ setError(null);
176
+ }
177
+ const result = await flight.run(() => action(...args));
178
+ if (mounted.current) {
179
+ setPending(false);
180
+ setError(result.status === "error" ? result.error : null);
181
+ }
182
+ return result;
183
+ }, [action, flight]);
184
+ const reset = React3.useCallback(() => {
185
+ if (!flight.pending && mounted.current) setError(null);
186
+ }, [flight]);
187
+ const isPending = React3.useCallback(() => flight.pending, [flight]);
188
+ return { pending, error, run, isPending, reset };
189
+ }
190
+
191
+ // src/useCrudEditor.ts
192
+ import * as React4 from "react";
193
+ function useCrudEditor(options) {
194
+ const [state, setState] = React4.useState({ mode: "closed" });
195
+ const current = React4.useRef(state);
196
+ const mounted = React4.useRef(false);
197
+ React4.useEffect(() => {
198
+ mounted.current = true;
199
+ return () => {
200
+ mounted.current = false;
201
+ };
202
+ }, []);
203
+ const mutation = useAsyncAction(async (selection, values) => {
204
+ if (selection.mode === "create") return options.create(values);
205
+ if (!options.update) throw new Error("This editor has no update handler");
206
+ return options.update(selection.record, values);
207
+ });
208
+ const transition = (next) => {
209
+ if (mutation.isPending()) return false;
210
+ current.current = next;
211
+ setState(next);
212
+ mutation.reset();
213
+ return true;
214
+ };
215
+ return {
216
+ state,
217
+ isOpen: state.mode !== "closed",
218
+ pending: mutation.pending,
219
+ error: mutation.error,
220
+ openCreate: () => transition({ mode: "create" }),
221
+ openEdit: (record2) => Boolean(options.update) && transition({ mode: "edit", record: record2 }),
222
+ close: () => transition({ mode: "closed" }),
223
+ submit: async (values) => {
224
+ const selection = current.current;
225
+ if (selection.mode === "closed") return { status: "closed" };
226
+ const result = await mutation.run(selection, values);
227
+ if (result.status === "success" && mounted.current && current.current === selection) transition({ mode: "closed" });
228
+ return result;
229
+ }
230
+ };
231
+ }
232
+
233
+ // src/ResourceFeedback.tsx
234
+ import { ErrorState, Spinner, Stack, useUiI18n } from "@plugmatica/ui-kit";
235
+
236
+ // src/internal/resourceErrorStatus.ts
237
+ function resourceErrorStatus(error) {
238
+ if (error === null || typeof error !== "object") return void 0;
239
+ const direct = error.status;
240
+ if (typeof direct === "number" && Number.isInteger(direct) && direct >= 100 && direct <= 599) return direct;
241
+ const response = error.response;
242
+ if (response === null || typeof response !== "object") return void 0;
243
+ const nested = response.status;
244
+ return typeof nested === "number" && Number.isInteger(nested) && nested >= 100 && nested <= 599 ? nested : void 0;
245
+ }
246
+ function showBackgroundCollectionError(error, currentRows) {
247
+ if (error == null || currentRows <= 0) return false;
248
+ return ![401, 403, 404].includes(resourceErrorStatus(error) ?? 0);
249
+ }
250
+
251
+ // src/ResourceFeedback.tsx
252
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
253
+ function ResourceError({ error, retry, title, description }) {
254
+ const { t } = useUiI18n();
255
+ const status = resourceErrorStatus(error);
256
+ return /* @__PURE__ */ jsx(
257
+ ErrorState,
258
+ {
259
+ role: "alert",
260
+ title: title ?? (status === 403 ? t("states.forbiddenFeature") : status === 404 ? t("states.recordNotFound") : t("states.requestFailed")),
261
+ description: description ?? t("states.errorHelp"),
262
+ actions: retry ? [{ key: "retry", label: t("actions.retry") }] : void 0,
263
+ onAction: retry ? () => retry() : void 0
264
+ }
265
+ );
266
+ }
267
+ function ResourceLoading() {
268
+ const { t } = useUiI18n();
269
+ return /* @__PURE__ */ jsx(Stack, { align: "center", children: /* @__PURE__ */ jsx(Spinner, { size: "lg", "aria-label": t("states.loadingInformation") }) });
270
+ }
271
+ function ResourceBoundary({ resource, children, empty = null, loading }) {
272
+ if (resource.value === null && resource.loading) return loading ?? /* @__PURE__ */ jsx(ResourceLoading, {});
273
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
274
+ resource.error ? /* @__PURE__ */ jsx(ResourceError, { error: resource.error, retry: resource.refresh }) : null,
275
+ resource.value !== null ? children(resource.value) : resource.error ? null : empty
276
+ ] });
277
+ }
278
+
279
+ // src/useResourceTable.tsx
280
+ import * as React5 from "react";
281
+ import { jsx as jsx2 } from "react/jsx-runtime";
282
+ function useResourceTable(resource, selectRows) {
283
+ const data = React5.useMemo(
284
+ () => resource.value === null ? [] : selectRows ? selectRows(resource.value) : resource.value,
285
+ [resource.value, selectRows]
286
+ );
287
+ return {
288
+ data,
289
+ loading: resource.loading,
290
+ error: resource.error,
291
+ errorState: resource.error ? /* @__PURE__ */ jsx2(ResourceError, { error: resource.error, retry: resource.refresh }) : void 0,
292
+ onRefresh: resource.refresh
293
+ };
294
+ }
295
+
296
+ // src/components/CollectionBlock.tsx
297
+ import {
298
+ DataTable,
299
+ EmptyState,
300
+ Stack as Stack2
301
+ } from "@plugmatica/ui-kit";
302
+ import { jsx as jsx3, jsxs as jsxs2 } from "react/jsx-runtime";
303
+ function CollectionBlock({
304
+ empty,
305
+ emptyState,
306
+ error,
307
+ errorState,
308
+ onRefresh,
309
+ data,
310
+ ...table
311
+ }) {
312
+ const backgroundFailure = showBackgroundCollectionError(error, data.length);
313
+ const feedback = error ? typeof errorState === "function" ? errorState(error) : errorState ?? /* @__PURE__ */ jsx3(ResourceError, { error, retry: onRefresh }) : void 0;
314
+ return /* @__PURE__ */ jsxs2(Stack2, { gap: "md", children: [
315
+ backgroundFailure ? feedback : null,
316
+ /* @__PURE__ */ jsx3(
317
+ DataTable,
318
+ {
319
+ ...table,
320
+ onRefresh,
321
+ data,
322
+ error: backgroundFailure ? void 0 : error,
323
+ errorState: feedback,
324
+ emptyState: emptyState ?? (empty ? /* @__PURE__ */ jsx3(EmptyState, { ...empty }) : void 0)
325
+ }
326
+ )
327
+ ] });
328
+ }
329
+
330
+ // src/components/CollectionPage.tsx
331
+ import * as React6 from "react";
332
+ import { Page, PageHeader } from "@plugmatica/ui-kit";
333
+ import { jsx as jsx4, jsxs as jsxs3 } from "react/jsx-runtime";
334
+ function CollectionPage({ header, table, beforeTable, afterTable, ...page }) {
335
+ return /* @__PURE__ */ jsxs3(Page, { ...page, children: [
336
+ /* @__PURE__ */ jsx4(PageHeader, { ...header }, "header"),
337
+ beforeTable == null ? null : /* @__PURE__ */ jsx4(React6.Fragment, { children: beforeTable }, "before-table"),
338
+ /* @__PURE__ */ jsx4(CollectionBlock, { ...table }, "table"),
339
+ afterTable == null ? null : /* @__PURE__ */ jsx4(React6.Fragment, { children: afterTable }, "after-table")
340
+ ] });
341
+ }
342
+
343
+ // src/components/FormBlock.tsx
344
+ import * as React7 from "react";
345
+ import {
346
+ Button,
347
+ Form,
348
+ Grid,
349
+ SheetBody,
350
+ SheetFooter,
351
+ useUiI18n as useUiI18n2
352
+ } from "@plugmatica/ui-kit";
353
+
354
+ // src/internal/definitions.ts
355
+ function assertStableKeys(keys, owner) {
356
+ const seen = /* @__PURE__ */ new Set();
357
+ for (const key of keys) {
358
+ if (typeof key !== "string" || !key.trim() || key !== key.trim()) {
359
+ throw new Error(`${owner}: identities must be non-empty, trimmed strings.`);
360
+ }
361
+ if (seen.has(key)) throw new Error(`${owner}: duplicate identity '${key}'.`);
362
+ seen.add(key);
363
+ }
364
+ }
365
+
366
+ // src/components/FormBlock.tsx
367
+ import { Fragment as Fragment3, jsx as jsx5, jsxs as jsxs4 } from "react/jsx-runtime";
368
+ function renderField(field, disabled) {
369
+ switch (field.kind) {
370
+ case "text": {
371
+ const { kind: _kind, hidden: _hidden, ...props } = field;
372
+ return /* @__PURE__ */ jsx5(Form.Input, { ...props, disabled: disabled || props.disabled });
373
+ }
374
+ case "textarea": {
375
+ const { kind: _kind, hidden: _hidden, ...props } = field;
376
+ return /* @__PURE__ */ jsx5(Form.TextArea, { ...props, disabled: disabled || props.disabled });
377
+ }
378
+ case "number": {
379
+ const { kind: _kind, hidden: _hidden, ...props } = field;
380
+ return /* @__PURE__ */ jsx5(Form.InputNumber, { ...props, disabled: disabled || props.disabled });
381
+ }
382
+ case "select": {
383
+ const { kind: _kind, hidden: _hidden, ...props } = field;
384
+ return /* @__PURE__ */ jsx5(Form.Select, { ...props, disabled: disabled || props.disabled });
385
+ }
386
+ case "checkbox": {
387
+ const { kind: _kind, hidden: _hidden, ...props } = field;
388
+ return /* @__PURE__ */ jsx5(Form.Checkbox, { ...props, disabled: disabled || props.disabled });
389
+ }
390
+ case "switch": {
391
+ const { kind: _kind, hidden: _hidden, ...props } = field;
392
+ return /* @__PURE__ */ jsx5(Form.Switch, { ...props, disabled: disabled || props.disabled });
393
+ }
394
+ case "date": {
395
+ const { kind: _kind, hidden: _hidden, ...props } = field;
396
+ return /* @__PURE__ */ jsx5(Form.DatePicker, { ...props, disabled: disabled || props.disabled });
397
+ }
398
+ case "datetime": {
399
+ const { kind: _kind, hidden: _hidden, ...props } = field;
400
+ return /* @__PURE__ */ jsx5(Form.DateTimePicker, { ...props, disabled: disabled || props.disabled });
401
+ }
402
+ case "time": {
403
+ const { kind: _kind, hidden: _hidden, ...props } = field;
404
+ return /* @__PURE__ */ jsx5(Form.TimePicker, { ...props, disabled: disabled || props.disabled });
405
+ }
406
+ case "slider": {
407
+ const { kind: _kind, hidden: _hidden, ...props } = field;
408
+ return /* @__PURE__ */ jsx5(Form.Slider, { ...props, disabled: disabled || props.disabled });
409
+ }
410
+ default:
411
+ throw new TypeError("Unsupported FormBlock field kind.");
412
+ }
413
+ }
414
+ function FormBlock({
415
+ fields,
416
+ actions,
417
+ onAction,
418
+ pending = false,
419
+ disabled = false,
420
+ error,
421
+ extraFields,
422
+ fieldLayout,
423
+ presentation = "inline",
424
+ form,
425
+ onSubmit,
426
+ ...props
427
+ }) {
428
+ const { t } = useUiI18n2();
429
+ const [actionError, setActionError] = React7.useState(null);
430
+ const busy = pending || form.formState.isSubmitting;
431
+ assertStableKeys(fields.map((field) => field.name), "FormBlock.fields");
432
+ assertStableKeys(actions.map((action) => action.key), "FormBlock.actions");
433
+ for (const field of fields) {
434
+ if (!field.label.trim()) throw new Error(`FormBlock: field '${field.name}' needs a visible label.`);
435
+ }
436
+ const controls = fields.map((field) => {
437
+ const control = renderField(field, busy || disabled);
438
+ return Object.hasOwn(field, "hidden") ? /* @__PURE__ */ jsx5("div", { hidden: Boolean(field.hidden), children: control }, field.name) : React7.cloneElement(control, { key: field.name });
439
+ });
440
+ const body = /* @__PURE__ */ jsxs4(Fragment3, { children: [
441
+ error || actionError ? /* @__PURE__ */ jsx5(ResourceError, { error: error ?? actionError }) : null,
442
+ /* @__PURE__ */ jsx5(Form.ErrorSummary, {}),
443
+ /* @__PURE__ */ jsxs4(Form.Fields, { children: [
444
+ fieldLayout ? /* @__PURE__ */ jsx5(Grid, { ...fieldLayout, children: controls }) : controls,
445
+ extraFields
446
+ ] })
447
+ ] });
448
+ const footer = /* @__PURE__ */ jsx5(Form.Actions, { children: actions.filter((action) => !action.hidden).map((definition) => {
449
+ const runtime = definition;
450
+ const submit = definition.type === "submit";
451
+ return /* @__PURE__ */ jsx5(
452
+ Button,
453
+ {
454
+ ...{ __pmExtension: runtime.__pmExtension },
455
+ extension: definition.extension ?? definition.key,
456
+ extensionOrder: definition.order,
457
+ type: definition.type ?? "button",
458
+ color: definition.color ?? (submit ? "primary" : "default"),
459
+ variant: definition.variant ?? (submit ? "solid" : "outlined"),
460
+ leading: definition.icon,
461
+ trailing: definition.trailing,
462
+ "aria-label": definition.ariaLabel,
463
+ loading: definition.loading || submit && busy,
464
+ disabled: disabled || busy || definition.disabled,
465
+ actionData: definition.data,
466
+ action: onAction ? (payload) => {
467
+ setActionError(null);
468
+ return onAction(definition, payload);
469
+ } : void 0,
470
+ onActionError: setActionError,
471
+ children: definition.label
472
+ },
473
+ definition.key
474
+ );
475
+ }) });
476
+ return /* @__PURE__ */ jsx5(
477
+ Form,
478
+ {
479
+ ...props,
480
+ form,
481
+ fill: presentation === "sheet" || props.fill,
482
+ "aria-busy": busy || void 0,
483
+ submitErrorMessage: props.submitErrorMessage ?? t("states.requestFailed"),
484
+ onSubmit: (values, event) => {
485
+ if (pending || disabled) return;
486
+ setActionError(null);
487
+ return onSubmit(values, event);
488
+ },
489
+ children: presentation === "sheet" ? /* @__PURE__ */ jsxs4(Fragment3, { children: [
490
+ /* @__PURE__ */ jsx5(SheetBody, { children: body }),
491
+ /* @__PURE__ */ jsx5(SheetFooter, { children: footer })
492
+ ] }) : /* @__PURE__ */ jsxs4(Fragment3, { children: [
493
+ body,
494
+ footer
495
+ ] })
496
+ }
497
+ );
498
+ }
499
+
500
+ // src/components/EditorSheet.tsx
501
+ import * as React9 from "react";
502
+ import {
503
+ Button as Button2,
504
+ Dialog,
505
+ Sheet,
506
+ SheetContent,
507
+ SheetDescription,
508
+ SheetHeader,
509
+ SheetTitle,
510
+ useUiI18n as useUiI18n3
511
+ } from "@plugmatica/ui-kit";
512
+
513
+ // src/internal/useOverlayFocus.ts
514
+ import * as React8 from "react";
515
+ function useOverlayFocus(open, returnFocusRef) {
516
+ const opener = React8.useRef(null);
517
+ const wasOpen = React8.useRef(false);
518
+ React8.useEffect(() => {
519
+ if (open && !wasOpen.current && typeof document !== "undefined") {
520
+ opener.current ??= document.activeElement instanceof HTMLElement ? document.activeElement : null;
521
+ }
522
+ wasOpen.current = open;
523
+ }, [open]);
524
+ return {
525
+ onOpenAutoFocus: () => {
526
+ opener.current = typeof document !== "undefined" && document.activeElement instanceof HTMLElement ? document.activeElement : null;
527
+ },
528
+ onCloseAutoFocus: (event) => {
529
+ const preferred = returnFocusRef?.current;
530
+ const target = preferred?.isConnected ? preferred : opener.current;
531
+ opener.current = null;
532
+ if (target?.isConnected) {
533
+ event.preventDefault();
534
+ target.focus();
535
+ }
536
+ }
537
+ };
538
+ }
539
+
540
+ // src/components/EditorSheet.tsx
541
+ import { Fragment as Fragment4, jsx as jsx6, jsxs as jsxs5 } from "react/jsx-runtime";
542
+ function EditorSheet({
543
+ open,
544
+ onOpenChange,
545
+ title,
546
+ description,
547
+ size = "md",
548
+ dirty,
549
+ discard,
550
+ returnFocusRef,
551
+ dismissActionKey = "cancel",
552
+ ...formProps
553
+ }) {
554
+ const { t } = useUiI18n3();
555
+ const [discardOpen, setDiscardOpen] = React9.useState(false);
556
+ const focus = useOverlayFocus(open, returnFocusRef);
557
+ const discardFocus = useOverlayFocus(open && discardOpen);
558
+ const submitting = React9.useRef(null);
559
+ const session = React9.useMemo(() => /* @__PURE__ */ Symbol("editor"), [open]);
560
+ const activeSession = React9.useRef(null);
561
+ React9.useLayoutEffect(() => {
562
+ activeSession.current = open ? session : null;
563
+ return () => {
564
+ activeSession.current = null;
565
+ };
566
+ }, [open, session]);
567
+ const keepEditing = React9.useRef(null);
568
+ const busy = Boolean(formProps.pending || formProps.form.formState.isSubmitting || submitting.current === session);
569
+ const isDirty = dirty ?? formProps.form.formState.isDirty;
570
+ React9.useEffect(() => {
571
+ if (!open) setDiscardOpen(false);
572
+ }, [open]);
573
+ const requestClose = () => {
574
+ if (busy || submitting.current === session) return;
575
+ if (isDirty) setDiscardOpen(true);
576
+ else onOpenChange(false);
577
+ };
578
+ return /* @__PURE__ */ jsx6(Sheet, { open, onOpenChange: (next) => {
579
+ if (!next) requestClose();
580
+ }, children: /* @__PURE__ */ jsxs5(
581
+ SheetContent,
582
+ {
583
+ side: "right",
584
+ size,
585
+ closeButton: !busy,
586
+ "aria-busy": busy || void 0,
587
+ ...!description ? { "aria-describedby": void 0 } : {},
588
+ onOpenAutoFocus: focus.onOpenAutoFocus,
589
+ onCloseAutoFocus: focus.onCloseAutoFocus,
590
+ onEscapeKeyDown: (event) => {
591
+ if (busy || submitting.current === session || discardOpen) event.preventDefault();
592
+ },
593
+ onInteractOutside: (event) => event.preventDefault(),
594
+ children: [
595
+ /* @__PURE__ */ jsxs5(SheetHeader, { children: [
596
+ /* @__PURE__ */ jsx6(SheetTitle, { children: title }),
597
+ description ? /* @__PURE__ */ jsx6(SheetDescription, { children: description }) : null
598
+ ] }),
599
+ /* @__PURE__ */ jsx6(
600
+ FormBlock,
601
+ {
602
+ ...formProps,
603
+ presentation: "sheet",
604
+ onSubmit: async (values, event) => {
605
+ if (activeSession.current !== session) {
606
+ const error = new Error("This editor session is no longer open.");
607
+ error.name = "AbortError";
608
+ throw error;
609
+ }
610
+ if (submitting.current === session) return;
611
+ submitting.current = session;
612
+ try {
613
+ return await formProps.onSubmit(values, event);
614
+ } finally {
615
+ if (submitting.current === session) submitting.current = null;
616
+ }
617
+ },
618
+ onAction: (action, payload) => action.key === dismissActionKey ? requestClose() : formProps.onAction?.(action, payload)
619
+ }
620
+ ),
621
+ /* @__PURE__ */ jsx6(
622
+ Dialog,
623
+ {
624
+ open: open && discardOpen,
625
+ onOpenChange: (next) => {
626
+ if (!busy && submitting.current !== session) setDiscardOpen(next);
627
+ },
628
+ title: discard?.title ?? t("form.discardTitle"),
629
+ description: discard?.description ?? t("form.unsavedChanges"),
630
+ onOpenAutoFocus: (event) => {
631
+ discardFocus.onOpenAutoFocus();
632
+ event.preventDefault();
633
+ keepEditing.current?.focus();
634
+ },
635
+ onCloseAutoFocus: discardFocus.onCloseAutoFocus,
636
+ onEscapeKeyDown: (event) => {
637
+ if (busy || submitting.current === session) event.preventDefault();
638
+ },
639
+ closeButton: !busy,
640
+ onInteractOutside: (event) => event.preventDefault(),
641
+ footer: /* @__PURE__ */ jsxs5(Fragment4, { children: [
642
+ /* @__PURE__ */ jsx6(Button2, { ref: keepEditing, variant: "outlined", disabled: busy, onClick: () => setDiscardOpen(false), children: discard?.cancelLabel ?? t("form.keepEditing") }),
643
+ /* @__PURE__ */ jsx6(Button2, { color: "destructive", disabled: busy, onClick: () => {
644
+ if (busy || submitting.current === session) return;
645
+ setDiscardOpen(false);
646
+ onOpenChange(false);
647
+ }, children: discard?.confirmLabel ?? t("form.discardChanges") })
648
+ ] })
649
+ }
650
+ )
651
+ ]
652
+ }
653
+ ) });
654
+ }
655
+
656
+ // src/components/DetailsBlock.tsx
657
+ import {
658
+ Card,
659
+ DescriptionList,
660
+ Typography,
661
+ useUiI18n as useUiI18n4
662
+ } from "@plugmatica/ui-kit";
663
+
664
+ // src/components/detailValueModel.ts
665
+ function resolveDetailDisplayValue(value, emptyValue, yes, no) {
666
+ if (value === null || value === void 0 || value === "") return emptyValue;
667
+ if (typeof value === "boolean") return value ? yes : no;
668
+ return value;
669
+ }
670
+
671
+ // src/components/DetailsBlock.tsx
672
+ import { jsx as jsx7 } from "react/jsx-runtime";
673
+ function DetailsBlock({ items, columns = 2, orientation = "vertical", density, emptyValue, ...card }) {
674
+ const { t } = useUiI18n4();
675
+ assertStableKeys(items.map((item) => item.key), "DetailsBlock.items");
676
+ return /* @__PURE__ */ jsx7(Card, { ...card, density, children: /* @__PURE__ */ jsx7(
677
+ DescriptionList,
678
+ {
679
+ density: density === "compact" ? "compact" : "default",
680
+ columns,
681
+ orientation,
682
+ items: items.filter((item) => !item.hidden).map(({ hidden: _hidden, ...item }) => ({
683
+ ...item,
684
+ value: resolveDetailDisplayValue(
685
+ item.value,
686
+ emptyValue ?? /* @__PURE__ */ jsx7(Typography.Text, { color: "muted", children: t("labels.empty") }),
687
+ t("labels.yes"),
688
+ t("labels.no")
689
+ )
690
+ }))
691
+ }
692
+ ) });
693
+ }
694
+
695
+ // src/components/SettingsBlock.tsx
696
+ import { Card as Card2 } from "@plugmatica/ui-kit";
697
+ import { jsx as jsx8 } from "react/jsx-runtime";
698
+ function SettingsBlock({ form, ...card }) {
699
+ const busy = Boolean(form.pending || form.form.formState.isSubmitting);
700
+ return /* @__PURE__ */ jsx8(Card2, { ...card, "aria-busy": card["aria-busy"] ?? (busy || void 0), children: /* @__PURE__ */ jsx8(FormBlock, { ...form }) });
701
+ }
702
+
703
+ // src/components/ConfirmDialog.tsx
704
+ import * as React10 from "react";
705
+ import { Button as Button3, Dialog as Dialog2, useUiI18n as useUiI18n5 } from "@plugmatica/ui-kit";
706
+ import { Fragment as Fragment5, jsx as jsx9, jsxs as jsxs6 } from "react/jsx-runtime";
707
+ function ConfirmDialog({
708
+ open,
709
+ onOpenChange,
710
+ title,
711
+ description,
712
+ confirmLabel,
713
+ cancelLabel,
714
+ color = "primary",
715
+ disabled = false,
716
+ onConfirm,
717
+ returnFocusRef,
718
+ requestKey,
719
+ ...semantic
720
+ }) {
721
+ const { t } = useUiI18n5();
722
+ const action = useAsyncAction(onConfirm);
723
+ const focus = useOverlayFocus(open, returnFocusRef);
724
+ const cancel = React10.useRef(null);
725
+ const [failure, setFailure] = React10.useState(null);
726
+ const session = React10.useMemo(() => /* @__PURE__ */ Symbol("confirmation"), [open, requestKey]);
727
+ const activeSession = React10.useRef(session);
728
+ React10.useLayoutEffect(() => {
729
+ activeSession.current = session;
730
+ setFailure(null);
731
+ }, [session]);
732
+ const mounted = React10.useRef(false);
733
+ React10.useEffect(() => {
734
+ mounted.current = true;
735
+ return () => {
736
+ mounted.current = false;
737
+ };
738
+ }, []);
739
+ React10.useEffect(() => {
740
+ if (!open) action.reset();
741
+ }, [open, action.reset]);
742
+ const dismiss = () => {
743
+ if (!action.isPending()) onOpenChange(false);
744
+ };
745
+ return /* @__PURE__ */ jsx9(
746
+ Dialog2,
747
+ {
748
+ open,
749
+ onOpenChange: (next) => {
750
+ if (!next) dismiss();
751
+ },
752
+ title,
753
+ description,
754
+ closeButton: !action.pending,
755
+ "aria-busy": action.pending || void 0,
756
+ onOpenAutoFocus: (event) => {
757
+ focus.onOpenAutoFocus();
758
+ event.preventDefault();
759
+ cancel.current?.focus();
760
+ },
761
+ onCloseAutoFocus: focus.onCloseAutoFocus,
762
+ onEscapeKeyDown: (event) => {
763
+ if (action.isPending()) event.preventDefault();
764
+ },
765
+ onInteractOutside: (event) => event.preventDefault(),
766
+ footer: /* @__PURE__ */ jsxs6(Fragment5, { children: [
767
+ /* @__PURE__ */ jsx9(Button3, { ref: cancel, variant: "outlined", disabled: action.pending, onClick: dismiss, children: cancelLabel ?? t("actions.cancel") }),
768
+ /* @__PURE__ */ jsx9(
769
+ Button3,
770
+ {
771
+ ...semantic,
772
+ color,
773
+ loading: action.pending,
774
+ disabled: disabled || action.pending,
775
+ action: async () => {
776
+ if (disabled || !mounted.current || activeSession.current !== session) return;
777
+ setFailure(null);
778
+ const result = await action.run();
779
+ if (!mounted.current || activeSession.current !== session) return;
780
+ if (result.status === "error") throw result.error;
781
+ if (result.status === "success") onOpenChange(false);
782
+ },
783
+ onActionError: (error) => {
784
+ if (mounted.current && activeSession.current === session) setFailure(error);
785
+ },
786
+ children: confirmLabel
787
+ }
788
+ )
789
+ ] }),
790
+ children: failure ? /* @__PURE__ */ jsx9(ResourceError, { error: failure }) : null
791
+ }
792
+ );
793
+ }
794
+
795
+ // src/components/DestructiveConfirmationDialog.tsx
796
+ import * as React11 from "react";
797
+ import {
798
+ Dialog as Dialog3,
799
+ ErrorState as ErrorState2,
800
+ Spinner as Spinner2,
801
+ Stack as Stack3,
802
+ Typography as Typography2,
803
+ useUiI18n as useUiI18n6
804
+ } from "@plugmatica/ui-kit";
805
+
806
+ // src/components/destructiveConfirmPolicy.ts
807
+ function destructiveConfirmDisabled(canConfirm, pending, usageLoading) {
808
+ return !canConfirm || pending || usageLoading;
809
+ }
810
+
811
+ // src/components/DestructiveConfirmationDialog.tsx
812
+ import { jsx as jsx10, jsxs as jsxs7 } from "react/jsx-runtime";
813
+ function DestructiveConfirmationDialog({
814
+ open,
815
+ onOpenChange,
816
+ title,
817
+ description,
818
+ closeButtonLabel,
819
+ size,
820
+ cancelVariant,
821
+ actions,
822
+ canConfirm,
823
+ pending,
824
+ confirmLabel,
825
+ pendingLabel,
826
+ onConfirm,
827
+ usage,
828
+ usageLoading,
829
+ checkingLabel,
830
+ safeLabel,
831
+ blockedLabel,
832
+ renderReference,
833
+ error,
834
+ errorTitle,
835
+ children,
836
+ ...semantic
837
+ }) {
838
+ const [cancel, confirm] = actions;
839
+ const { t } = useUiI18n6();
840
+ const [failure, setFailure] = React11.useState(null);
841
+ React11.useEffect(() => {
842
+ if (!open) setFailure(null);
843
+ }, [open]);
844
+ const hasBody = Boolean(children || usageLoading || usage || error || failure);
845
+ return /* @__PURE__ */ jsx10(
846
+ Dialog3,
847
+ {
848
+ ...semantic,
849
+ open,
850
+ onOpenChange: (next) => {
851
+ if (!next) setFailure(null);
852
+ onOpenChange(next);
853
+ },
854
+ size,
855
+ title,
856
+ description,
857
+ closeButtonLabel,
858
+ busy: pending,
859
+ actions: [
860
+ { ...cancel, variant: cancelVariant ?? "outlined", disabled: pending, dismiss: false },
861
+ {
862
+ ...confirm,
863
+ label: pending ? pendingLabel ?? confirmLabel : confirmLabel,
864
+ color: "destructive",
865
+ disabled: destructiveConfirmDisabled(canConfirm, pending, Boolean(usageLoading)),
866
+ loading: pending,
867
+ dismiss: false
868
+ }
869
+ ],
870
+ onAction: ({ key }) => {
871
+ if (key === cancel.key) return onOpenChange(false);
872
+ if (key === confirm.key) {
873
+ setFailure(null);
874
+ return onConfirm();
875
+ }
876
+ },
877
+ onActionError: (actionError, action) => {
878
+ if (action.key === confirm.key) setFailure(actionError);
879
+ },
880
+ children: hasBody ? /* @__PURE__ */ jsxs7(Stack3, { gap: "sm", align: "stretch", children: [
881
+ children,
882
+ usageLoading ? /* @__PURE__ */ jsxs7(Stack3, { direction: "row", gap: "sm", align: "center", children: [
883
+ /* @__PURE__ */ jsx10(Spinner2, { size: "sm", "aria-label": t("states.loadingInformation") }),
884
+ checkingLabel ? /* @__PURE__ */ jsx10(Typography2.Text, { children: checkingLabel }) : null
885
+ ] }) : null,
886
+ usage?.referenceCount === 0 && safeLabel ? /* @__PURE__ */ jsx10(Typography2.Text, { children: safeLabel }) : null,
887
+ usage && usage.referenceCount > 0 ? /* @__PURE__ */ jsxs7(Stack3, { gap: "xs", align: "stretch", children: [
888
+ blockedLabel ? /* @__PURE__ */ jsx10(Typography2.Text, { children: blockedLabel }) : null,
889
+ renderReference ? usage.references.slice(0, 8).map((reference) => {
890
+ const item = renderReference(reference);
891
+ return /* @__PURE__ */ jsxs7(Stack3, { direction: "row", justify: "between", align: "center", gap: "sm", children: [
892
+ /* @__PURE__ */ jsx10(Typography2.Text, { children: item.label }),
893
+ item.detail ? /* @__PURE__ */ jsx10(Typography2.Text, { color: "muted", children: item.detail }) : null
894
+ ] }, item.key);
895
+ }) : null
896
+ ] }) : null,
897
+ error ? /* @__PURE__ */ jsx10(ErrorState2, { title: errorTitle, description: error, role: "alert" }) : null,
898
+ failure ? /* @__PURE__ */ jsx10(ResourceError, { error: failure }) : null
899
+ ] }) : null
900
+ }
901
+ );
902
+ }
903
+
904
+ // src/components/ConnectionPickerSheet.tsx
905
+ import * as React14 from "react";
906
+ import {
907
+ Badge as Badge2,
908
+ Button as Button4,
909
+ Callout,
910
+ Input as Input3,
911
+ List,
912
+ Select as Select3,
913
+ Sheet as Sheet2,
914
+ SheetBody as SheetBody2,
915
+ SheetContent as SheetContent2,
916
+ SheetDescription as SheetDescription2,
917
+ SheetFooter as SheetFooter2,
918
+ SheetHeader as SheetHeader2,
919
+ SheetTitle as SheetTitle2,
920
+ Stack as Stack6,
921
+ Typography as Typography5
922
+ } from "@plugmatica/ui-kit";
923
+
924
+ // src/components/ConnectionEditorForm.tsx
925
+ import * as React13 from "react";
926
+ import { Input as Input2, Select as Select2, Stack as Stack5, Switch as Switch2, Typography as Typography4 } from "@plugmatica/ui-kit";
927
+
928
+ // src/components/ConnectionConfigFields.tsx
929
+ import {
930
+ Badge,
931
+ Input,
932
+ NumberInput,
933
+ Select,
934
+ Stack as Stack4,
935
+ Switch,
936
+ Textarea,
937
+ Typography as Typography3
938
+ } from "@plugmatica/ui-kit";
939
+ import * as React12 from "react";
940
+
941
+ // src/components/connectionEditorModel.ts
942
+ function propertyKind(property) {
943
+ const types = Array.isArray(property.type) ? property.type : [property.type];
944
+ return types.find((type) => type && type !== "null") ?? (property.properties ? "object" : void 0);
945
+ }
946
+ function record(value) {
947
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
948
+ }
949
+ function safeFieldName(key) {
950
+ return key !== "__proto__" && key !== "prototype" && key !== "constructor";
951
+ }
952
+ function compatiblePresetValue(property, value) {
953
+ const declaredTypes = Array.isArray(property.type) ? property.type : [property.type];
954
+ if (declaredTypes.some((type) => type != null)) {
955
+ const valid = declaredTypes.some((type) => {
956
+ switch (type) {
957
+ case "string":
958
+ return typeof value === "string";
959
+ case "integer":
960
+ return typeof value === "number" && Number.isSafeInteger(value);
961
+ case "number":
962
+ return typeof value === "number" && Number.isFinite(value);
963
+ case "boolean":
964
+ return typeof value === "boolean";
965
+ case "array":
966
+ return Array.isArray(value);
967
+ case "object":
968
+ return record(value) !== null;
969
+ case "null":
970
+ return value === null;
971
+ default:
972
+ return false;
973
+ }
974
+ });
975
+ if (!valid) return false;
976
+ }
977
+ return !property.enum || property.enum.some((option) => Object.is(option, value));
978
+ }
979
+ function connectionConfigHasPreset(schema, field) {
980
+ if (!safeFieldName(field)) return false;
981
+ const properties = record(schema.properties);
982
+ const controlling = properties && Object.prototype.hasOwnProperty.call(properties, field) && record(properties[field]);
983
+ return Boolean(controlling && Array.isArray(controlling.enum) && record(controlling["x-plugmatica-presets"]));
984
+ }
985
+ function applyConnectionConfigPreset(schema, config, field, selected) {
986
+ const result = { ...config };
987
+ if (!safeFieldName(field)) return result;
988
+ result[field] = selected;
989
+ const properties = record(schema.properties);
990
+ const controlling = properties && record(properties[field]);
991
+ const presets = controlling && record(controlling["x-plugmatica-presets"]);
992
+ if (!properties || !controlling || !presets || !Array.isArray(controlling.enum) || !controlling.enum.some((value) => value === selected) || typeof selected !== "string" && typeof selected !== "number" && typeof selected !== "boolean") {
993
+ return result;
994
+ }
995
+ const chosen = Object.prototype.hasOwnProperty.call(presets, String(selected)) ? record(presets[String(selected)]) : null;
996
+ if (!chosen) return result;
997
+ for (const [key, presetValue] of Object.entries(chosen)) {
998
+ if (!safeFieldName(key) || key === field || !Object.prototype.hasOwnProperty.call(properties, key)) continue;
999
+ const target = record(properties[key]);
1000
+ if (!target || Object.prototype.hasOwnProperty.call(target, "const") || target["x-plugmatica-ui"] === "hidden" || !compatiblePresetValue(target, presetValue)) continue;
1001
+ result[key] = structuredClone(presetValue);
1002
+ }
1003
+ return result;
1004
+ }
1005
+ function defaultConnectionConfig(schema) {
1006
+ let result = {};
1007
+ const properties = schema.properties ?? {};
1008
+ for (const [key, property] of Object.entries(properties)) {
1009
+ if (!safeFieldName(key) || !record(property)) continue;
1010
+ if (Object.prototype.hasOwnProperty.call(property, "const")) {
1011
+ result[key] = structuredClone(property.const);
1012
+ } else if (Object.prototype.hasOwnProperty.call(property, "default")) {
1013
+ result[key] = structuredClone(property.default);
1014
+ } else if (propertyKind(property) === "object") {
1015
+ const nested = defaultConnectionConfig(property);
1016
+ if (Object.keys(nested).length) result[key] = nested;
1017
+ }
1018
+ }
1019
+ for (const key of Object.keys(properties)) {
1020
+ if (Object.prototype.hasOwnProperty.call(result, key) && connectionConfigHasPreset(schema, key)) {
1021
+ result = applyConnectionConfigPreset(schema, result, key, result[key]);
1022
+ }
1023
+ }
1024
+ return result;
1025
+ }
1026
+ function createConnectionDraft(type) {
1027
+ return {
1028
+ resourceType: type?.key ?? "",
1029
+ profileKey: "",
1030
+ config: type ? defaultConnectionConfig(type.configSchema) : {},
1031
+ secretValues: {},
1032
+ enabled: true
1033
+ };
1034
+ }
1035
+ function editConnectionDraft(profile) {
1036
+ return {
1037
+ resourceType: profile.resourceType,
1038
+ profileKey: profile.profileKey,
1039
+ config: structuredClone(profile.config),
1040
+ // Only profile.secretMetadata is returned by the server: never fabricate values.
1041
+ secretValues: {},
1042
+ enabled: profile.enabled
1043
+ };
1044
+ }
1045
+ function connectionAuthoringTypes(types, { compatibleTypes = [], compatibleCapabilities = [] } = {}) {
1046
+ const counts = /* @__PURE__ */ new Map();
1047
+ for (const type of types) counts.set(type.key, (counts.get(type.key) ?? 0) + 1);
1048
+ return types.filter(
1049
+ (type) => counts.get(type.key) === 1 && (!compatibleTypes.length || compatibleTypes.includes(type.key)) && compatibleCapabilities.every((capability) => type.capabilities.includes(capability))
1050
+ );
1051
+ }
1052
+ function splitConnectionHostPort(value) {
1053
+ const trimmed = value.trim();
1054
+ const bracketed = trimmed.match(/^\[([^\]]+)]:(\d{1,5})$/);
1055
+ const simple = trimmed.match(/^([^:]+):(\d{1,5})$/);
1056
+ const parts = bracketed ?? simple;
1057
+ if (!parts || !parts[1].trim()) return null;
1058
+ const port = Number(parts[2]);
1059
+ return port >= 1 && port <= 65535 ? { host: parts[1].trim(), port } : null;
1060
+ }
1061
+ function missingRequiredConnectionSecrets(schema, storedKeys, values) {
1062
+ const required = schema?.required;
1063
+ if (!Array.isArray(required)) return [];
1064
+ const stored = new Set(storedKeys);
1065
+ return required.filter((key) => typeof key === "string" && !stored.has(key) && !values[key]?.length);
1066
+ }
1067
+ async function saveConnectionDraft(api, draft) {
1068
+ const resourceType = draft.resourceType.trim();
1069
+ const separator = resourceType.indexOf(":");
1070
+ if (separator <= 0 || separator === resourceType.length - 1 || !draft.profileKey.trim()) {
1071
+ throw new Error("Connection name and type are required.");
1072
+ }
1073
+ const ownerPlugin = resourceType.slice(0, separator);
1074
+ let saved = await api.upsertConnection({
1075
+ ownerPlugin,
1076
+ profileKey: draft.profileKey.trim(),
1077
+ resourceType,
1078
+ config: draft.config,
1079
+ enabled: draft.enabled
1080
+ });
1081
+ for (const [key, value] of Object.entries(draft.secretValues)) {
1082
+ if (value.length) saved = await api.setConnectionSecret(saved.pid, key, value);
1083
+ }
1084
+ return saved;
1085
+ }
1086
+
1087
+ // src/components/connectionConfigJsonModel.ts
1088
+ function parseConnectionJsonDraft(text, arrayField) {
1089
+ try {
1090
+ const parsed = JSON.parse(text);
1091
+ if (arrayField ? Array.isArray(parsed) : parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
1092
+ return { valid: true, value: parsed };
1093
+ }
1094
+ } catch {
1095
+ }
1096
+ return { valid: false };
1097
+ }
1098
+
1099
+ // src/components/ConnectionConfigFields.tsx
1100
+ import { jsx as jsx11, jsxs as jsxs8 } from "react/jsx-runtime";
1101
+ var asObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};
1102
+ var kindOf = (schema) => {
1103
+ const types = Array.isArray(schema.type) ? schema.type : [schema.type];
1104
+ return types.find((type) => type && type !== "null") ?? (schema.properties ? "object" : "string");
1105
+ };
1106
+ function JsonValueField({
1107
+ schema,
1108
+ value,
1109
+ onChange,
1110
+ label,
1111
+ invalidMessage,
1112
+ onInvalidChange
1113
+ }) {
1114
+ const fallback = kindOf(schema) === "array" ? [] : {};
1115
+ const [draft, setDraft] = React12.useState(() => JSON.stringify(value ?? fallback, null, 2));
1116
+ const [invalid, setInvalid] = React12.useState(false);
1117
+ const errorId = React12.useId();
1118
+ const lastEmitted = React12.useRef(void 0);
1119
+ React12.useEffect(() => {
1120
+ if (value === lastEmitted.current) return;
1121
+ lastEmitted.current = void 0;
1122
+ setDraft(JSON.stringify(value ?? fallback, null, 2));
1123
+ setInvalid(false);
1124
+ onInvalidChange?.(false);
1125
+ }, [value]);
1126
+ return /* @__PURE__ */ jsxs8(Stack4, { gap: "xs", children: [
1127
+ /* @__PURE__ */ jsx11(
1128
+ Textarea,
1129
+ {
1130
+ "aria-label": label,
1131
+ value: draft,
1132
+ rows: 5,
1133
+ invalid,
1134
+ "aria-invalid": invalid || void 0,
1135
+ "aria-describedby": invalid ? errorId : void 0,
1136
+ onChange: (event) => {
1137
+ const next = event.target.value;
1138
+ setDraft(next);
1139
+ const result = parseConnectionJsonDraft(next, kindOf(schema) === "array");
1140
+ setInvalid(!result.valid);
1141
+ onInvalidChange?.(!result.valid);
1142
+ if (result.valid) {
1143
+ lastEmitted.current = result.value;
1144
+ onChange(result.value);
1145
+ }
1146
+ }
1147
+ }
1148
+ ),
1149
+ invalid ? /* @__PURE__ */ jsx11(Typography3.Text, { id: errorId, role: "alert", color: "danger", size: "sm", children: invalidMessage }) : null
1150
+ ] });
1151
+ }
1152
+ function ConnectionConfigFields({
1153
+ schema,
1154
+ value,
1155
+ onChange,
1156
+ onFieldBlur,
1157
+ labels,
1158
+ onInvalidFieldChange
1159
+ }) {
1160
+ const object = schema;
1161
+ const required = new Set(object.required ?? []);
1162
+ const set = (key, next) => {
1163
+ if (key === "__proto__" || key === "constructor" || key === "prototype") return;
1164
+ if (connectionConfigHasPreset(schema, key)) {
1165
+ onChange(applyConnectionConfigPreset(schema, value, key, next));
1166
+ return;
1167
+ }
1168
+ const copy = { ...value };
1169
+ if (next === void 0) delete copy[key];
1170
+ else copy[key] = next;
1171
+ onChange(copy);
1172
+ };
1173
+ return /* @__PURE__ */ jsx11(Stack4, { gap: "md", align: "stretch", children: Object.entries(object.properties ?? {}).map(([key, field]) => {
1174
+ if (key === "__proto__" || key === "constructor" || key === "prototype" || field["x-plugmatica-ui"] === "hidden" || "const" in field) return null;
1175
+ const kind = kindOf(field);
1176
+ const label = field.title ?? key;
1177
+ const current = value[key];
1178
+ const preset = connectionConfigHasPreset(schema, key);
1179
+ const readonly = field["x-plugmatica-ui"] === "readonly";
1180
+ const optional = !required.has(key);
1181
+ const empty = current === void 0 || current === null;
1182
+ return /* @__PURE__ */ jsxs8(Stack4, { gap: "xs", align: "stretch", children: [
1183
+ /* @__PURE__ */ jsxs8(Stack4, { direction: "row", align: "center", gap: "sm", children: [
1184
+ /* @__PURE__ */ jsx11(Typography3.Text, { weight: "medium", children: label }),
1185
+ !optional ? /* @__PURE__ */ jsx11(Badge, { size: "sm", variant: "warning", children: labels?.required ?? "Required" }) : null
1186
+ ] }),
1187
+ field.description ? /* @__PURE__ */ jsx11(Typography3.Text, { color: "muted", size: "sm", children: field.description }) : null,
1188
+ preset ? /* @__PURE__ */ jsx11(Typography3.Text, { color: "muted", size: "sm", children: labels?.presetHint ?? "Selecting an option also updates related configuration fields." }) : null,
1189
+ readonly ? /* @__PURE__ */ jsx11(Input, { "aria-label": label, value: typeof current === "string" ? current : String(current ?? ""), readOnly: true }) : field.enum ? /* @__PURE__ */ jsx11(
1190
+ Select,
1191
+ {
1192
+ value: empty ? "" : String(current),
1193
+ "aria-label": label,
1194
+ required: !optional,
1195
+ placeholder: label,
1196
+ options: field.enum.map((item) => ({ value: String(item), label: String(item) })),
1197
+ onValueChange: (next) => set(key, field.enum?.find((item) => String(item) === next) ?? next)
1198
+ }
1199
+ ) : kind === "boolean" ? /* @__PURE__ */ jsx11(Switch, { checked: current === true, label, onCheckedChange: (checked) => set(key, checked) }) : kind === "integer" || kind === "number" ? /* @__PURE__ */ jsx11(
1200
+ NumberInput,
1201
+ {
1202
+ "aria-label": label,
1203
+ "aria-required": !optional,
1204
+ value: typeof current === "number" ? current : null,
1205
+ min: field.minimum,
1206
+ max: field.maximum,
1207
+ precision: kind === "integer" ? 0 : void 0,
1208
+ commitMode: "change",
1209
+ placeholder: String(field["x-plugmatica-placeholder"] ?? ""),
1210
+ onValueChange: (next) => set(key, next ?? void 0)
1211
+ }
1212
+ ) : kind === "object" && field.properties ? /* @__PURE__ */ jsx11(
1213
+ ConnectionConfigFields,
1214
+ {
1215
+ schema: field,
1216
+ value: asObject(current),
1217
+ onChange: (next) => set(key, next),
1218
+ labels,
1219
+ onInvalidFieldChange: (path, invalid) => onInvalidFieldChange?.(`${key}.${path}`, invalid),
1220
+ onFieldBlur: (path, next) => onFieldBlur?.(`${key}.${path}`, next)
1221
+ }
1222
+ ) : kind === "object" || kind === "array" ? /* @__PURE__ */ jsx11(
1223
+ JsonValueField,
1224
+ {
1225
+ schema: field,
1226
+ value: current,
1227
+ label,
1228
+ invalidMessage: labels?.jsonInvalid ?? "Enter valid JSON.",
1229
+ onInvalidChange: (invalid) => onInvalidFieldChange?.(key, invalid),
1230
+ onChange: (next) => set(key, next)
1231
+ }
1232
+ ) : field["x-plugmatica-ui"] === "multiline" ? /* @__PURE__ */ jsx11(
1233
+ Textarea,
1234
+ {
1235
+ "aria-label": label,
1236
+ "aria-required": !optional,
1237
+ value: String(current ?? ""),
1238
+ onChange: (event) => set(key, event.target.value || (optional ? void 0 : "")),
1239
+ onBlur: (event) => onFieldBlur?.(key, event.currentTarget.value)
1240
+ }
1241
+ ) : /* @__PURE__ */ jsx11(
1242
+ Input,
1243
+ {
1244
+ "aria-label": label,
1245
+ "aria-required": !optional,
1246
+ value: String(current ?? ""),
1247
+ placeholder: String(field["x-plugmatica-placeholder"] ?? label),
1248
+ onChange: (event) => set(key, event.target.value || (optional ? void 0 : "")),
1249
+ onBlur: (event) => onFieldBlur?.(key, event.currentTarget.value)
1250
+ }
1251
+ )
1252
+ ] }, key);
1253
+ }) });
1254
+ }
1255
+
1256
+ // src/components/connectionCatalogueModel.ts
1257
+ var slug = /^[a-z][a-z0-9-]{0,31}$/u;
1258
+ var safeIcon = /^[A-Z][A-Za-z0-9]{0,31}$/u;
1259
+ var safeDocumentation = /^https:\/\/[a-z0-9][a-z0-9.-]*\.[a-z]{2,}(?:\/[\w\-./~%]*)?(?:\?[\w\-=&.%]*)?$/iu;
1260
+ function connectionCatalogueCategoryLabel(category) {
1261
+ return category === "other" ? "Other" : category.split("-").filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1)).join(" ");
1262
+ }
1263
+ function connectionCataloguePresentation(descriptor) {
1264
+ const metadata = descriptor?.catalogue;
1265
+ const category = typeof metadata?.category === "string" && slug.test(metadata.category) ? metadata.category : "other";
1266
+ const provider = typeof metadata?.providerName === "string" && metadata.providerName.trim() === metadata.providerName && metadata.providerName.length <= 80 && metadata.providerName.length > 0 && !/[\x00-\x1f\x7f]/u.test(metadata.providerName) ? metadata.providerName : descriptor?.title ?? "Provider unavailable";
1267
+ return {
1268
+ category,
1269
+ categoryLabel: connectionCatalogueCategoryLabel(category),
1270
+ provider,
1271
+ icon: typeof metadata?.icon === "string" && safeIcon.test(metadata.icon) ? metadata.icon : "Plug",
1272
+ documentationUrl: typeof metadata?.documentationUrl === "string" && metadata.documentationUrl.length <= 512 && safeDocumentation.test(metadata.documentationUrl) ? metadata.documentationUrl : null
1273
+ };
1274
+ }
1275
+ function uniqueConnectionCatalogueTypes(descriptors) {
1276
+ const result = /* @__PURE__ */ new Map();
1277
+ const conflicts = /* @__PURE__ */ new Set();
1278
+ for (const descriptor of descriptors) {
1279
+ if (result.has(descriptor.key)) conflicts.add(descriptor.key);
1280
+ else result.set(descriptor.key, descriptor);
1281
+ }
1282
+ for (const key of conflicts) result.delete(key);
1283
+ return result;
1284
+ }
1285
+ function queryTokens(value) {
1286
+ return value.slice(0, 160).trim().toLocaleLowerCase().split(/\s+/u).filter(Boolean).slice(0, 12);
1287
+ }
1288
+ function matchesTokens(fields, tokens) {
1289
+ if (!tokens.length) return true;
1290
+ const haystack = fields.filter(Boolean).join(" ").slice(0, 2048).toLocaleLowerCase();
1291
+ return tokens.every((token) => haystack.includes(token));
1292
+ }
1293
+ function connectionCatalogueSearchFields(profile, descriptor) {
1294
+ const meta = connectionCataloguePresentation(descriptor);
1295
+ return [
1296
+ profile.profileKey,
1297
+ profile.resourceType,
1298
+ profile.health,
1299
+ profile.transport,
1300
+ descriptor?.title ?? "",
1301
+ descriptor?.description ?? "",
1302
+ meta.provider,
1303
+ meta.category,
1304
+ meta.categoryLabel,
1305
+ ...descriptor?.capabilities ?? []
1306
+ ];
1307
+ }
1308
+ function connectionCatalogueTypeGroups(descriptors, capability = "", query = "") {
1309
+ const tokens = queryTokens(query);
1310
+ const buckets = /* @__PURE__ */ new Map();
1311
+ for (const descriptor of uniqueConnectionCatalogueTypes(descriptors).values()) {
1312
+ if (capability && !descriptor.capabilities.includes(capability)) continue;
1313
+ const presentation = connectionCataloguePresentation(descriptor);
1314
+ if (!matchesTokens([
1315
+ descriptor.key,
1316
+ descriptor.title,
1317
+ descriptor.description,
1318
+ descriptor.transport,
1319
+ presentation.provider,
1320
+ presentation.category,
1321
+ presentation.categoryLabel,
1322
+ ...descriptor.capabilities
1323
+ ], tokens)) continue;
1324
+ const group = buckets.get(presentation.category) ?? {
1325
+ category: presentation.category,
1326
+ label: presentation.categoryLabel,
1327
+ types: []
1328
+ };
1329
+ group.types.push(descriptor);
1330
+ buckets.set(presentation.category, group);
1331
+ }
1332
+ return [...buckets.values()].map((group) => ({
1333
+ ...group,
1334
+ types: group.types.sort((a, b) => connectionCataloguePresentation(a).provider.localeCompare(connectionCataloguePresentation(b).provider) || a.title.localeCompare(b.title) || a.key.localeCompare(b.key))
1335
+ })).sort((a, b) => a.label.localeCompare(b.label) || a.category.localeCompare(b.category));
1336
+ }
1337
+ function buildConnectionCatalogue(profiles, descriptors, filter = {}) {
1338
+ const types = uniqueConnectionCatalogueTypes(descriptors);
1339
+ const tokens = queryTokens(filter.query ?? "");
1340
+ const entries = [];
1341
+ for (const profile of profiles) {
1342
+ const descriptor = types.get(profile.resourceType) ?? null;
1343
+ if (filter.capability && !descriptor?.capabilities.includes(filter.capability)) continue;
1344
+ const presentation = connectionCataloguePresentation(descriptor);
1345
+ if (filter.category && filter.category !== "all" && filter.category !== presentation.category) continue;
1346
+ const status = !profile.enabled || profile.health === "disabled" ? "disabled" : profile.health === "ready" && profile.ownerAvailable && descriptor ? "ready" : "attention";
1347
+ if (filter.health && filter.health !== "all" && status !== filter.health) continue;
1348
+ if (!matchesTokens(connectionCatalogueSearchFields(profile, descriptor), tokens)) continue;
1349
+ entries.push({ profile, descriptor, presentation });
1350
+ }
1351
+ entries.sort((a, b) => a.presentation.categoryLabel.localeCompare(b.presentation.categoryLabel) || a.presentation.provider.localeCompare(b.presentation.provider) || a.profile.profileKey.localeCompare(b.profile.profileKey) || a.profile.pid.localeCompare(b.profile.pid));
1352
+ const buckets = /* @__PURE__ */ new Map();
1353
+ for (const entry of entries) {
1354
+ const { category, categoryLabel } = entry.presentation;
1355
+ const group = buckets.get(category) ?? { category, label: categoryLabel, entries: [] };
1356
+ group.entries.push(entry);
1357
+ buckets.set(category, group);
1358
+ }
1359
+ return { entries, groups: [...buckets.values()] };
1360
+ }
1361
+
1362
+ // src/components/ConnectionEditorForm.tsx
1363
+ import { jsx as jsx12, jsxs as jsxs9 } from "react/jsx-runtime";
1364
+ var defaultConnectionEditorLabels = {
1365
+ type: "Connection type",
1366
+ selectType: "Select connection type",
1367
+ name: "Name",
1368
+ namePlaceholder: "e.g. operations-mailbox",
1369
+ enabled: "Enabled",
1370
+ enabledDescription: "Disabled connections cannot be used by active workflows.",
1371
+ secretConfigured: "Credential stored. Enter a value only to replace it.",
1372
+ secretKeepExisting: "Leave blank to keep the stored credential",
1373
+ secretRequired: "A credential is required before this Connection can be enabled.",
1374
+ testDeclared: (name) => `Live test available: ${name}`,
1375
+ required: "Required",
1376
+ jsonInvalid: "Enter valid JSON before saving.",
1377
+ presetHint: "Selecting an option also updates related configuration fields."
1378
+ };
1379
+ function schemaProperties(schema) {
1380
+ const properties = schema.properties;
1381
+ return properties && typeof properties === "object" && !Array.isArray(properties) ? properties : {};
1382
+ }
1383
+ function ConnectionEditorForm({
1384
+ types,
1385
+ draft,
1386
+ editing,
1387
+ onChange,
1388
+ labels,
1389
+ disabled = false,
1390
+ onValidityChange
1391
+ }) {
1392
+ const copy = { ...defaultConnectionEditorLabels, ...labels };
1393
+ const [invalidFields, setInvalidFields] = React13.useState(() => /* @__PURE__ */ new Set());
1394
+ const secretErrorBase = React13.useId();
1395
+ React13.useEffect(() => {
1396
+ setInvalidFields(/* @__PURE__ */ new Set());
1397
+ }, [draft.resourceType, editing?.pid]);
1398
+ const selectedType = types.find((type) => type.key === draft.resourceType);
1399
+ const set = (patch) => onChange({ ...draft, ...patch });
1400
+ const configured = new Set(editing?.secretMetadata.map((item) => item.key) ?? []);
1401
+ const fields = selectedType ? schemaProperties(selectedType.configSchema) : {};
1402
+ const missingSecrets = missingRequiredConnectionSecrets(
1403
+ selectedType?.secretSchema,
1404
+ configured,
1405
+ draft.secretValues
1406
+ );
1407
+ const formValid = Boolean(selectedType && draft.profileKey.trim()) && invalidFields.size === 0 && (!draft.enabled || missingSecrets.length === 0);
1408
+ React13.useEffect(() => {
1409
+ onValidityChange?.(formValid);
1410
+ }, [formValid, onValidityChange]);
1411
+ return /* @__PURE__ */ jsx12("fieldset", { disabled, style: { padding: 0, margin: 0, border: 0, minWidth: 0 }, children: /* @__PURE__ */ jsxs9(Stack5, { gap: "md", align: "stretch", children: [
1412
+ /* @__PURE__ */ jsxs9(Stack5, { gap: "xs", align: "stretch", children: [
1413
+ /* @__PURE__ */ jsx12(Typography4.Text, { weight: "medium", children: copy.type }),
1414
+ types.length === 1 || editing ? /* @__PURE__ */ jsx12(Typography4.Text, { children: selectedType?.title ?? draft.resourceType }) : /* @__PURE__ */ jsx12(
1415
+ Select2,
1416
+ {
1417
+ value: draft.resourceType,
1418
+ "aria-label": copy.type,
1419
+ placeholder: copy.selectType,
1420
+ options: [...types].sort((a, b) => {
1421
+ const first = connectionCataloguePresentation(a);
1422
+ const second = connectionCataloguePresentation(b);
1423
+ return first.categoryLabel.localeCompare(second.categoryLabel) || first.provider.localeCompare(second.provider) || a.title.localeCompare(b.title);
1424
+ }).map((type) => {
1425
+ const meta = connectionCataloguePresentation(type);
1426
+ return { value: type.key, label: `${meta.categoryLabel} \xB7 ${meta.provider} \xB7 ${type.title}` };
1427
+ }),
1428
+ onValueChange: (key) => {
1429
+ const type = types.find((item) => item.key === key);
1430
+ onChange({ ...createConnectionDraft(type ?? null), profileKey: draft.profileKey, enabled: draft.enabled });
1431
+ }
1432
+ }
1433
+ )
1434
+ ] }),
1435
+ /* @__PURE__ */ jsxs9(Stack5, { gap: "xs", align: "stretch", children: [
1436
+ /* @__PURE__ */ jsx12(Typography4.Text, { weight: "medium", children: copy.name }),
1437
+ /* @__PURE__ */ jsx12(
1438
+ Input2,
1439
+ {
1440
+ value: draft.profileKey,
1441
+ disabled: Boolean(editing),
1442
+ "aria-label": copy.name,
1443
+ "aria-required": "true",
1444
+ placeholder: copy.namePlaceholder,
1445
+ onChange: (event) => set({ profileKey: event.target.value })
1446
+ }
1447
+ )
1448
+ ] }),
1449
+ selectedType?.description ? /* @__PURE__ */ jsx12(Typography4.Text, { color: "muted", children: selectedType.description }) : null,
1450
+ selectedType ? /* @__PURE__ */ jsx12(
1451
+ ConnectionConfigFields,
1452
+ {
1453
+ schema: selectedType.configSchema,
1454
+ value: draft.config,
1455
+ onChange: (config) => set({ config }),
1456
+ labels: { required: copy.required, jsonInvalid: copy.jsonInvalid, presetHint: copy.presetHint },
1457
+ onInvalidFieldChange: (path, invalid) => setInvalidFields((current) => {
1458
+ if (current.has(path) === invalid) return current;
1459
+ const next = new Set(current);
1460
+ if (invalid) next.add(path);
1461
+ else next.delete(path);
1462
+ return next;
1463
+ }),
1464
+ onFieldBlur: (field, value) => {
1465
+ if (field !== "host" || typeof value !== "string" || !("port" in fields)) return;
1466
+ const parsed = splitConnectionHostPort(value);
1467
+ if (parsed) set({ config: { ...draft.config, host: parsed.host, port: parsed.port } });
1468
+ }
1469
+ }
1470
+ ) : null,
1471
+ selectedType ? Object.entries(schemaProperties(selectedType.secretSchema)).map(([key, schema], index) => /* @__PURE__ */ jsxs9(Stack5, { gap: "xs", align: "stretch", children: [
1472
+ /* @__PURE__ */ jsx12(Typography4.Text, { weight: "medium", children: String(schema.title ?? key) }),
1473
+ schema.description ? /* @__PURE__ */ jsx12(Typography4.Text, { color: "muted", size: "sm", children: String(schema.description) }) : null,
1474
+ configured.has(key) ? /* @__PURE__ */ jsx12(Typography4.Text, { size: "sm", color: "muted", children: copy.secretConfigured }) : null,
1475
+ /* @__PURE__ */ jsx12(
1476
+ Input2,
1477
+ {
1478
+ type: "password",
1479
+ autoComplete: "new-password",
1480
+ "aria-label": String(schema.title ?? key),
1481
+ "aria-required": draft.enabled && missingSecrets.includes(key) || void 0,
1482
+ "aria-invalid": draft.enabled && missingSecrets.includes(key) || void 0,
1483
+ "aria-describedby": draft.enabled && missingSecrets.includes(key) ? `${secretErrorBase}-${index}` : void 0,
1484
+ value: draft.secretValues[key] ?? "",
1485
+ placeholder: editing ? copy.secretKeepExisting : String(schema.title ?? key),
1486
+ onChange: (event) => set({ secretValues: { ...draft.secretValues, [key]: event.target.value } })
1487
+ }
1488
+ ),
1489
+ draft.enabled && missingSecrets.includes(key) ? /* @__PURE__ */ jsx12(Typography4.Text, { id: `${secretErrorBase}-${index}`, role: "alert", color: "danger", size: "sm", children: copy.secretRequired }) : null
1490
+ ] }, key)) : null,
1491
+ /* @__PURE__ */ jsx12(
1492
+ Switch2,
1493
+ {
1494
+ checked: draft.enabled,
1495
+ onCheckedChange: (enabled) => set({ enabled }),
1496
+ label: copy.enabled,
1497
+ description: copy.enabledDescription
1498
+ }
1499
+ ),
1500
+ selectedType?.healthTest ? /* @__PURE__ */ jsx12(Typography4.Text, { color: "muted", children: copy.testDeclared(selectedType.healthTest.label || selectedType.healthTest.command) }) : null
1501
+ ] }) });
1502
+ }
1503
+
1504
+ // src/components/connectionPickerModel.ts
1505
+ function compatibleConnectionOptions(profiles, descriptors, compatibility = {}) {
1506
+ const types = /* @__PURE__ */ new Map();
1507
+ const ambiguousTypes = /* @__PURE__ */ new Set();
1508
+ for (const descriptor of descriptors) {
1509
+ if (types.has(descriptor.key)) ambiguousTypes.add(descriptor.key);
1510
+ else types.set(descriptor.key, descriptor);
1511
+ }
1512
+ for (const key of ambiguousTypes) types.delete(key);
1513
+ const requiredTypes = compatibility.compatibleTypes ?? [];
1514
+ const requiredCapabilities = compatibility.compatibleCapabilities ?? [];
1515
+ return profiles.filter((profile) => {
1516
+ if (requiredTypes.length && !requiredTypes.includes(profile.resourceType)) return false;
1517
+ const descriptor = types.get(profile.resourceType);
1518
+ return requiredCapabilities.every((capability) => descriptor?.capabilities.includes(capability) === true);
1519
+ }).map((profile) => {
1520
+ const descriptor = types.get(profile.resourceType) ?? null;
1521
+ const unavailableReason = !descriptor || !profile.ownerAvailable ? "provider" : !profile.enabled || profile.health === "disabled" ? "disabled" : ["missing", "incompatible", "unhealthy"].includes(profile.health) ? "health" : null;
1522
+ return { profile, descriptor, unavailableReason, selectable: unavailableReason === null };
1523
+ }).sort(
1524
+ (a, b) => connectionCataloguePresentation(a.descriptor).categoryLabel.localeCompare(connectionCataloguePresentation(b.descriptor).categoryLabel) || connectionCataloguePresentation(a.descriptor).provider.localeCompare(connectionCataloguePresentation(b.descriptor).provider) || a.profile.profileKey.localeCompare(b.profile.profileKey, void 0, { sensitivity: "base" }) || a.profile.pid.localeCompare(b.profile.pid)
1525
+ );
1526
+ }
1527
+ function searchConnectionOptions(options, query) {
1528
+ const tokens = query.slice(0, 160).trim().toLocaleLowerCase().split(/\s+/u).filter(Boolean).slice(0, 12);
1529
+ if (!tokens.length) return [...options];
1530
+ return options.filter(({ profile, descriptor }) => {
1531
+ const searchable = connectionCatalogueSearchFields(profile, descriptor).filter(Boolean).join(" ").slice(0, 2048).toLocaleLowerCase();
1532
+ return tokens.every((token) => searchable.includes(token));
1533
+ });
1534
+ }
1535
+ function currentPickerSelection(connectionPid, defaultBindingKey, allowDefault) {
1536
+ if (connectionPid) return { kind: "connection", pid: connectionPid };
1537
+ if (allowDefault && defaultBindingKey?.trim()) {
1538
+ return { kind: "platform-default", bindingKey: defaultBindingKey.trim() };
1539
+ }
1540
+ return null;
1541
+ }
1542
+
1543
+ // src/components/ConnectionPickerSheet.tsx
1544
+ import { Fragment as Fragment6, jsx as jsx13, jsxs as jsxs10 } from "react/jsx-runtime";
1545
+ var english = {
1546
+ title: "Choose a connection",
1547
+ description: "Select a connection without leaving this page.",
1548
+ search: "Search connections",
1549
+ category: "Provider category",
1550
+ allCategories: "All categories",
1551
+ refresh: "Refresh",
1552
+ cancel: "Cancel",
1553
+ loading: "Loading connections",
1554
+ noConnections: "No compatible connections were found.",
1555
+ noMatches: "No connections match your search.",
1556
+ unavailable: "Provider unavailable",
1557
+ disabled: "Disabled",
1558
+ unhealthy: "Not ready",
1559
+ selected: "Selected",
1560
+ defaultTitle: "Use platform default",
1561
+ defaultDescription: "Follow this node's declared platform default binding.",
1562
+ missingSelection: "The selected connection is no longer available. Choose another connection.",
1563
+ selectionFailed: "Unable to select the connection. Refresh the list and try again.",
1564
+ showMore: "Show more",
1565
+ accessDenied: "You do not have permission to view connections.",
1566
+ count: (shown, total) => `Showing ${shown} of ${total} connections`,
1567
+ health: {
1568
+ ready: "Ready",
1569
+ missing: "Missing configuration",
1570
+ incompatible: "Incompatible",
1571
+ disabled: "Disabled",
1572
+ unhealthy: "Unhealthy",
1573
+ unknown: "Not tested"
1574
+ },
1575
+ create: "Create connection",
1576
+ manage: "Manage connections",
1577
+ details: "Connection details",
1578
+ edit: "Edit connection",
1579
+ back: "Back",
1580
+ save: "Save connection",
1581
+ saving: "Saving\u2026",
1582
+ saved: "Connection saved. Test it or explicitly choose to use it.",
1583
+ saveFailed: "Could not save the connection. Check the form and try again.",
1584
+ authoringDenied: "You do not have permission to manage this connection.",
1585
+ test: "Test",
1586
+ reconnect: "Reconnect",
1587
+ testing: "Testing\u2026",
1588
+ reconnecting: "Reconnecting\u2026",
1589
+ testPassed: "Connection test passed.",
1590
+ testFailed: "Connection test failed. Check the configuration or credentials and retry.",
1591
+ reconnectPassed: "Connection reconnected.",
1592
+ reconnectFailed: "Connection could not reconnect. Retry after checking its configuration.",
1593
+ actionFailed: "Connection action failed. Retry after checking your permissions and configuration.",
1594
+ useConnection: "Use this connection",
1595
+ credentialsHint: "Stored credentials are write-only. Editing can replace them, but never read them.",
1596
+ configuredCredentials: (count) => `${count} credential field(s) configured`,
1597
+ form: {}
1598
+ };
1599
+ var PAGE_SIZE = 50;
1600
+ function ConnectionPickerSheet({
1601
+ open,
1602
+ onOpenChange,
1603
+ managedResources,
1604
+ currentConnectionPid,
1605
+ compatibleTypes,
1606
+ compatibleCapabilities,
1607
+ allowDefault = false,
1608
+ defaultBindingKey,
1609
+ enableAuthoring = false,
1610
+ onSelect,
1611
+ onInventoryChange,
1612
+ labels,
1613
+ returnFocusRef
1614
+ }) {
1615
+ const copy = {
1616
+ ...english,
1617
+ ...labels,
1618
+ health: { ...english.health, ...labels?.health },
1619
+ form: { ...english.form, ...labels?.form }
1620
+ };
1621
+ const [query, setQuery] = React14.useState("");
1622
+ const [category, setCategory] = React14.useState("all");
1623
+ const [visibleCount, setVisibleCount] = React14.useState(PAGE_SIZE);
1624
+ const [view, setView] = React14.useState("browse");
1625
+ const [draft, setDraft] = React14.useState(
1626
+ () => createConnectionDraft(null)
1627
+ );
1628
+ const [detail, setDetail] = React14.useState(null);
1629
+ const [selecting, setSelecting] = React14.useState(false);
1630
+ const [saving, setSaving] = React14.useState(false);
1631
+ const [formValid, setFormValid] = React14.useState(true);
1632
+ const [action, setAction] = React14.useState(null);
1633
+ const [loadingDetail, setLoadingDetail] = React14.useState(false);
1634
+ const [selectionError, setSelectionError] = React14.useState(
1635
+ null
1636
+ );
1637
+ const [authoringError, setAuthoringError] = React14.useState(
1638
+ null
1639
+ );
1640
+ const [actionFeedback, setActionFeedback] = React14.useState(null);
1641
+ const selectionLock = React14.useRef(false);
1642
+ const actionLock = React14.useRef(false);
1643
+ const session = React14.useRef(0);
1644
+ const searchRef = React14.useRef(null);
1645
+ const viewFocusRef = React14.useRef(null);
1646
+ const focus = useOverlayFocus(open, returnFocusRef);
1647
+ const load = React14.useCallback(async () => {
1648
+ const [descriptors, profiles] = await Promise.all([
1649
+ managedResources.listConnectionTypes(),
1650
+ managedResources.listConnections()
1651
+ ]);
1652
+ return { descriptors, profiles };
1653
+ }, [managedResources]);
1654
+ const resource = useAsyncResource(load, {
1655
+ enabled: open,
1656
+ scopeKey: managedResources
1657
+ });
1658
+ const inventoryListener = React14.useRef(onInventoryChange);
1659
+ inventoryListener.current = onInventoryChange;
1660
+ React14.useEffect(() => {
1661
+ if (open && resource.value && !resource.error)
1662
+ inventoryListener.current?.(resource.value);
1663
+ }, [open, resource.value, resource.error]);
1664
+ React14.useEffect(() => {
1665
+ ++session.current;
1666
+ selectionLock.current = false;
1667
+ actionLock.current = false;
1668
+ setSelecting(false);
1669
+ setSaving(false);
1670
+ setFormValid(true);
1671
+ setAction(null);
1672
+ setLoadingDetail(false);
1673
+ setSelectionError(null);
1674
+ setAuthoringError(null);
1675
+ setActionFeedback(null);
1676
+ setDetail(null);
1677
+ setDraft(createConnectionDraft(null));
1678
+ setView("browse");
1679
+ setQuery("");
1680
+ setCategory("all");
1681
+ setVisibleCount(PAGE_SIZE);
1682
+ }, [open, managedResources]);
1683
+ React14.useEffect(
1684
+ () => () => {
1685
+ ++session.current;
1686
+ selectionLock.current = false;
1687
+ actionLock.current = false;
1688
+ },
1689
+ []
1690
+ );
1691
+ React14.useEffect(() => {
1692
+ setVisibleCount(PAGE_SIZE);
1693
+ }, [query, category, compatibleTypes, compatibleCapabilities]);
1694
+ React14.useEffect(() => {
1695
+ if (!open) return;
1696
+ if (view === "browse") searchRef.current?.focus();
1697
+ else viewFocusRef.current?.focus();
1698
+ }, [open, view]);
1699
+ const compatibility = { compatibleTypes, compatibleCapabilities };
1700
+ const options = React14.useMemo(
1701
+ () => compatibleConnectionOptions(
1702
+ resource.value?.profiles ?? [],
1703
+ resource.value?.descriptors ?? [],
1704
+ compatibility
1705
+ ),
1706
+ [resource.value, compatibleTypes, compatibleCapabilities]
1707
+ );
1708
+ const authoringTypes = React14.useMemo(
1709
+ () => connectionAuthoringTypes(
1710
+ resource.value?.descriptors ?? [],
1711
+ compatibility
1712
+ ),
1713
+ [resource.value, compatibleTypes, compatibleCapabilities]
1714
+ );
1715
+ const categories = React14.useMemo(() => [...new Map(options.map(({ descriptor: descriptor2 }) => {
1716
+ const meta = connectionCataloguePresentation(descriptor2);
1717
+ return [meta.category, meta.categoryLabel];
1718
+ })).entries()].sort((a, b) => a[1].localeCompare(b[1])), [options]);
1719
+ const filtered = React14.useMemo(
1720
+ () => searchConnectionOptions(options, query).filter(({ descriptor: descriptor2 }) => category === "all" || connectionCataloguePresentation(descriptor2).category === category),
1721
+ [options, query, category]
1722
+ );
1723
+ const shown = filtered.slice(0, visibleCount);
1724
+ const selected = currentPickerSelection(
1725
+ currentConnectionPid,
1726
+ defaultBindingKey,
1727
+ allowDefault
1728
+ );
1729
+ const canUseDefault = Boolean(allowDefault && defaultBindingKey?.trim());
1730
+ const selectedProfile = selected?.kind === "connection" ? options.find((item) => item.profile.pid === selected.pid) : void 0;
1731
+ const missingSelection = selected?.kind === "connection" && (!selectedProfile || !selectedProfile.selectable);
1732
+ const busy = selecting || saving || loadingDetail || Boolean(action);
1733
+ const blocked = resource.loading || Boolean(resource.error) || busy;
1734
+ const isDenied = [401, 403].includes(resourceErrorStatus(resource.error) ?? 0);
1735
+ const descriptor = detail ? resource.value?.descriptors.find(
1736
+ (item) => item.key === detail.resourceType
1737
+ ) : null;
1738
+ const detailOption = detail ? compatibleConnectionOptions(
1739
+ [detail],
1740
+ resource.value?.descriptors ?? [],
1741
+ compatibility
1742
+ )[0] : null;
1743
+ const changeView = (next) => {
1744
+ if (busy) return;
1745
+ setSelectionError(null);
1746
+ setAuthoringError(null);
1747
+ setActionFeedback(null);
1748
+ setView(next);
1749
+ };
1750
+ const chooseDetail = async (option) => {
1751
+ if (!enableAuthoring || !option.descriptor || actionLock.current || busy)
1752
+ return;
1753
+ const token = session.current;
1754
+ actionLock.current = true;
1755
+ setLoadingDetail(true);
1756
+ setAuthoringError(null);
1757
+ try {
1758
+ const latest = await managedResources.getConnection(option.profile.pid);
1759
+ if (token !== session.current) return;
1760
+ if (latest.resourceType !== option.profile.resourceType) {
1761
+ setAuthoringError(copy.missingSelection);
1762
+ void resource.refresh();
1763
+ return;
1764
+ }
1765
+ setDetail(latest);
1766
+ setView("detail");
1767
+ } catch (error) {
1768
+ if (token !== session.current) return;
1769
+ setAuthoringError(
1770
+ [401, 403].includes(resourceErrorStatus(error) ?? 0) ? copy.authoringDenied : copy.missingSelection
1771
+ );
1772
+ void resource.refresh();
1773
+ } finally {
1774
+ if (token === session.current) {
1775
+ actionLock.current = false;
1776
+ setLoadingDetail(false);
1777
+ }
1778
+ }
1779
+ };
1780
+ const startCreate = () => {
1781
+ if (!enableAuthoring || !authoringTypes.length || busy) return;
1782
+ setDetail(null);
1783
+ setDraft(createConnectionDraft(authoringTypes[0]));
1784
+ setFormValid(true);
1785
+ changeView("create");
1786
+ };
1787
+ const startEdit = () => {
1788
+ if (!detail || !descriptor || busy) return;
1789
+ setDraft(editConnectionDraft(detail));
1790
+ setFormValid(true);
1791
+ changeView("edit");
1792
+ };
1793
+ const save = async () => {
1794
+ if (!enableAuthoring || actionLock.current || !open || !formValid || !draft.profileKey.trim() || !authoringTypes.some((type) => type.key === draft.resourceType) || view === "edit" && (detail?.resourceType !== draft.resourceType || detail.profileKey !== draft.profileKey))
1795
+ return;
1796
+ const token = session.current;
1797
+ actionLock.current = true;
1798
+ setSaving(true);
1799
+ setAuthoringError(null);
1800
+ setActionFeedback(null);
1801
+ try {
1802
+ const saved = await saveConnectionDraft(managedResources, draft);
1803
+ if (token !== session.current) return;
1804
+ setDraft(editConnectionDraft(saved));
1805
+ setDetail(saved);
1806
+ setView("detail");
1807
+ setActionFeedback({ ok: true, message: copy.saved });
1808
+ void resource.refresh();
1809
+ } catch (error) {
1810
+ if (token !== session.current) return;
1811
+ setAuthoringError(
1812
+ [401, 403].includes(resourceErrorStatus(error) ?? 0) ? copy.authoringDenied : copy.saveFailed
1813
+ );
1814
+ } finally {
1815
+ if (token === session.current) {
1816
+ actionLock.current = false;
1817
+ setSaving(false);
1818
+ }
1819
+ }
1820
+ };
1821
+ const runCommand = async (command) => {
1822
+ if (!enableAuthoring || !detail || actionLock.current || !open || (command === "test" ? !descriptor?.healthTest : !descriptor?.reconnect))
1823
+ return;
1824
+ const token = session.current;
1825
+ actionLock.current = true;
1826
+ setAction(command);
1827
+ setAuthoringError(null);
1828
+ setActionFeedback(null);
1829
+ try {
1830
+ const result = command === "test" ? await managedResources.testConnection(detail.pid) : await managedResources.reconnectConnection(detail.pid);
1831
+ if (token !== session.current) return;
1832
+ setActionFeedback({
1833
+ ok: result.ok,
1834
+ message: command === "test" ? result.ok ? copy.testPassed : copy.testFailed : result.ok ? copy.reconnectPassed : copy.reconnectFailed
1835
+ });
1836
+ try {
1837
+ const latest = await managedResources.getConnection(detail.pid);
1838
+ if (token === session.current) setDetail(latest);
1839
+ } catch {
1840
+ }
1841
+ if (token === session.current) void resource.refresh();
1842
+ } catch (error) {
1843
+ if (token !== session.current) return;
1844
+ setAuthoringError(
1845
+ [401, 403].includes(resourceErrorStatus(error) ?? 0) ? copy.authoringDenied : copy.actionFailed
1846
+ );
1847
+ } finally {
1848
+ if (token === session.current) {
1849
+ actionLock.current = false;
1850
+ setAction(null);
1851
+ }
1852
+ }
1853
+ };
1854
+ const select = async (selection) => {
1855
+ if (selectionLock.current || !open || blocked || !resource.value) return;
1856
+ const token = session.current;
1857
+ selectionLock.current = true;
1858
+ setSelecting(true);
1859
+ setSelectionError(null);
1860
+ try {
1861
+ if (selection.kind === "platform-default") {
1862
+ if (!canUseDefault || selection.bindingKey !== defaultBindingKey?.trim())
1863
+ return;
1864
+ } else {
1865
+ const latest = await managedResources.getConnection(selection.pid);
1866
+ if (token !== session.current) return;
1867
+ const updated = compatibleConnectionOptions(
1868
+ [latest],
1869
+ resource.value.descriptors,
1870
+ compatibility
1871
+ )[0];
1872
+ if (!updated?.selectable || latest.pid !== selection.pid) {
1873
+ setSelectionError(copy.missingSelection);
1874
+ void resource.refresh();
1875
+ return;
1876
+ }
1877
+ }
1878
+ if (token !== session.current) return;
1879
+ await onSelect(selection);
1880
+ if (token === session.current) onOpenChange(false);
1881
+ } catch (error) {
1882
+ if (token !== session.current) return;
1883
+ const status = resourceErrorStatus(error);
1884
+ setSelectionError(
1885
+ status === 404 ? copy.missingSelection : status === 401 || status === 403 ? copy.accessDenied : copy.selectionFailed
1886
+ );
1887
+ if (status === 404) void resource.refresh();
1888
+ } finally {
1889
+ if (token === session.current) {
1890
+ selectionLock.current = false;
1891
+ setSelecting(false);
1892
+ }
1893
+ }
1894
+ };
1895
+ const defaultVisible = canUseDefault && category === "all" && (!query.trim() || `${copy.defaultTitle} ${copy.defaultDescription}`.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase()));
1896
+ const defaultItem = defaultVisible ? {
1897
+ id: `default:${defaultBindingKey}`,
1898
+ title: copy.defaultTitle,
1899
+ description: copy.defaultDescription,
1900
+ metadata: selected?.kind === "platform-default" ? /* @__PURE__ */ jsx13(Badge2, { variant: "secondary", children: copy.selected }) : void 0,
1901
+ disabled: blocked,
1902
+ data: {
1903
+ kind: "platform-default",
1904
+ bindingKey: defaultBindingKey.trim()
1905
+ }
1906
+ } : null;
1907
+ const items = [
1908
+ ...defaultItem ? [defaultItem] : [],
1909
+ ...shown.map((option) => {
1910
+ const profile = option.profile;
1911
+ const status = option.unavailableReason === "provider" ? copy.unavailable : option.unavailableReason === "disabled" ? copy.disabled : option.unavailableReason === "health" ? copy.unhealthy : copy.health[profile.health] ?? profile.health;
1912
+ const isSelected = selected?.kind === "connection" && selected.pid === profile.pid;
1913
+ return {
1914
+ id: `connection:${profile.pid}`,
1915
+ title: profile.profileKey,
1916
+ description: `${connectionCataloguePresentation(option.descriptor).provider} \xB7 ${option.descriptor?.title ?? profile.resourceType} \xB7 ${status}`,
1917
+ metadata: isSelected ? /* @__PURE__ */ jsx13(Badge2, { variant: "secondary", children: copy.selected }) : void 0,
1918
+ disabled: blocked || !option.selectable,
1919
+ data: {
1920
+ kind: "connection",
1921
+ pid: profile.pid
1922
+ }
1923
+ };
1924
+ })
1925
+ ];
1926
+ const canUseDetail = Boolean(detailOption?.selectable && !blocked);
1927
+ const title = view === "browse" ? copy.title : view === "manage" ? copy.manage : view === "create" ? copy.create : view === "edit" ? copy.edit : copy.details;
1928
+ const description = view === "browse" ? copy.description : view === "create" || view === "edit" ? copy.credentialsHint : detail?.profileKey ?? copy.description;
1929
+ return /* @__PURE__ */ jsx13(
1930
+ Sheet2,
1931
+ {
1932
+ open,
1933
+ onOpenChange: (next) => {
1934
+ if (!busy) onOpenChange(next);
1935
+ },
1936
+ children: /* @__PURE__ */ jsxs10(
1937
+ SheetContent2,
1938
+ {
1939
+ side: "right",
1940
+ size: "lg",
1941
+ closeButton: !busy,
1942
+ "aria-busy": busy || void 0,
1943
+ onOpenAutoFocus: (event) => {
1944
+ focus.onOpenAutoFocus();
1945
+ if (searchRef.current) {
1946
+ event.preventDefault();
1947
+ searchRef.current.focus();
1948
+ }
1949
+ },
1950
+ onCloseAutoFocus: focus.onCloseAutoFocus,
1951
+ onInteractOutside: (event) => event.preventDefault(),
1952
+ onEscapeKeyDown: (event) => {
1953
+ if (busy) event.preventDefault();
1954
+ },
1955
+ children: [
1956
+ /* @__PURE__ */ jsxs10(SheetHeader2, { children: [
1957
+ /* @__PURE__ */ jsx13(SheetTitle2, { children: title }),
1958
+ /* @__PURE__ */ jsx13(SheetDescription2, { children: description })
1959
+ ] }),
1960
+ /* @__PURE__ */ jsx13(SheetBody2, { children: /* @__PURE__ */ jsxs10(Stack6, { gap: "md", align: "stretch", children: [
1961
+ view !== "browse" ? /* @__PURE__ */ jsx13("div", { ref: viewFocusRef, tabIndex: -1, "aria-label": title }) : null,
1962
+ view === "browse" || view === "manage" ? /* @__PURE__ */ jsxs10(Fragment6, { children: [
1963
+ enableAuthoring && view === "browse" && !resource.error ? /* @__PURE__ */ jsxs10(Stack6, { direction: "row", gap: "sm", align: "center", wrap: true, children: [
1964
+ /* @__PURE__ */ jsx13(
1965
+ Button4,
1966
+ {
1967
+ color: "primary",
1968
+ disabled: blocked || authoringTypes.length === 0,
1969
+ onClick: startCreate,
1970
+ children: copy.create
1971
+ }
1972
+ ),
1973
+ /* @__PURE__ */ jsx13(
1974
+ Button4,
1975
+ {
1976
+ variant: "outlined",
1977
+ disabled: blocked || options.length === 0,
1978
+ onClick: () => changeView("manage"),
1979
+ children: copy.manage
1980
+ }
1981
+ )
1982
+ ] }) : null,
1983
+ /* @__PURE__ */ jsxs10(Stack6, { direction: "row", gap: "sm", align: "center", wrap: true, children: [
1984
+ /* @__PURE__ */ jsx13(
1985
+ Input3,
1986
+ {
1987
+ ref: searchRef,
1988
+ "aria-label": copy.search,
1989
+ placeholder: copy.search,
1990
+ value: query,
1991
+ onChange: (event) => setQuery(event.target.value.slice(0, 160))
1992
+ }
1993
+ ),
1994
+ /* @__PURE__ */ jsx13(
1995
+ Select3,
1996
+ {
1997
+ "aria-label": copy.category,
1998
+ value: category,
1999
+ options: [
2000
+ { value: "all", label: copy.allCategories },
2001
+ ...categories.map(([value, label]) => ({ value, label }))
2002
+ ],
2003
+ onValueChange: setCategory
2004
+ }
2005
+ )
2006
+ ] }),
2007
+ missingSelection && view === "browse" ? /* @__PURE__ */ jsx13(
2008
+ Callout,
2009
+ {
2010
+ variant: "warning",
2011
+ role: "status",
2012
+ title: copy.missingSelection
2013
+ }
2014
+ ) : null,
2015
+ resource.error ? /* @__PURE__ */ jsx13(
2016
+ ResourceError,
2017
+ {
2018
+ error: resource.error,
2019
+ title: isDenied ? copy.accessDenied : void 0,
2020
+ retry: resource.refresh
2021
+ }
2022
+ ) : null,
2023
+ resource.loading && !resource.value ? /* @__PURE__ */ jsxs10(Stack6, { gap: "xs", align: "center", children: [
2024
+ /* @__PURE__ */ jsx13(ResourceLoading, {}),
2025
+ /* @__PURE__ */ jsx13(Typography5.Text, { color: "muted", size: "sm", children: copy.loading })
2026
+ ] }) : null,
2027
+ resource.value && !resource.error ? /* @__PURE__ */ jsxs10(Fragment6, { children: [
2028
+ /* @__PURE__ */ jsx13(Typography5.Text, { color: "muted", size: "sm", role: "status", children: copy.count(shown.length, filtered.length) }),
2029
+ view === "browse" ? /* @__PURE__ */ jsx13(
2030
+ List,
2031
+ {
2032
+ density: "compact",
2033
+ variant: "outline",
2034
+ "aria-label": copy.title,
2035
+ items,
2036
+ onItemSelect: (item) => {
2037
+ void select(item.data);
2038
+ },
2039
+ emptyContent: /* @__PURE__ */ jsx13(Typography5.Text, { color: "muted", children: options.length === 0 ? copy.noConnections : copy.noMatches })
2040
+ }
2041
+ ) : /* @__PURE__ */ jsxs10(Stack6, { gap: "sm", align: "stretch", children: [
2042
+ shown.length === 0 ? /* @__PURE__ */ jsx13(Typography5.Text, { color: "muted", children: options.length === 0 ? copy.noConnections : copy.noMatches }) : null,
2043
+ shown.map((option) => /* @__PURE__ */ jsxs10(
2044
+ Stack6,
2045
+ {
2046
+ direction: "row",
2047
+ gap: "sm",
2048
+ align: "center",
2049
+ justify: "between",
2050
+ children: [
2051
+ /* @__PURE__ */ jsxs10(Stack6, { gap: "xs", align: "stretch", children: [
2052
+ /* @__PURE__ */ jsx13(Typography5.Text, { weight: "medium", children: option.profile.profileKey }),
2053
+ /* @__PURE__ */ jsxs10(Typography5.Text, { size: "sm", color: "muted", children: [
2054
+ connectionCataloguePresentation(option.descriptor).provider,
2055
+ " \xB7 ",
2056
+ option.descriptor?.title ?? copy.unavailable
2057
+ ] })
2058
+ ] }),
2059
+ /* @__PURE__ */ jsx13(
2060
+ Button4,
2061
+ {
2062
+ variant: "outlined",
2063
+ disabled: blocked || !option.descriptor || !option.profile.ownerAvailable,
2064
+ onClick: () => {
2065
+ void chooseDetail(option);
2066
+ },
2067
+ children: copy.details
2068
+ }
2069
+ )
2070
+ ]
2071
+ },
2072
+ option.profile.pid
2073
+ ))
2074
+ ] }),
2075
+ shown.length < filtered.length ? /* @__PURE__ */ jsx13(
2076
+ Button4,
2077
+ {
2078
+ variant: "outlined",
2079
+ disabled: blocked,
2080
+ onClick: () => setVisibleCount((n) => n + PAGE_SIZE),
2081
+ children: copy.showMore
2082
+ }
2083
+ ) : null
2084
+ ] }) : null
2085
+ ] }) : null,
2086
+ view === "create" || view === "edit" ? /* @__PURE__ */ jsx13(
2087
+ ConnectionEditorForm,
2088
+ {
2089
+ types: authoringTypes,
2090
+ draft,
2091
+ editing: view === "edit" ? detail : null,
2092
+ onChange: setDraft,
2093
+ onValidityChange: setFormValid,
2094
+ disabled: saving,
2095
+ labels: copy.form
2096
+ }
2097
+ ) : null,
2098
+ view === "detail" && detail ? /* @__PURE__ */ jsxs10(Stack6, { gap: "sm", align: "stretch", children: [
2099
+ /* @__PURE__ */ jsx13(Typography5.Text, { weight: "medium", children: detail.profileKey }),
2100
+ /* @__PURE__ */ jsxs10(Typography5.Text, { color: "muted", size: "sm", children: [
2101
+ descriptor?.title ?? copy.unavailable,
2102
+ " \xB7",
2103
+ " ",
2104
+ copy.health[detail.health] ?? detail.health
2105
+ ] }),
2106
+ /* @__PURE__ */ jsx13(Typography5.Text, { color: "muted", size: "sm", children: copy.configuredCredentials(detail.secretMetadata.length) }),
2107
+ /* @__PURE__ */ jsx13(Typography5.Text, { color: "muted", size: "sm", children: copy.credentialsHint }),
2108
+ /* @__PURE__ */ jsxs10(Stack6, { direction: "row", gap: "sm", align: "center", wrap: true, children: [
2109
+ /* @__PURE__ */ jsx13(
2110
+ Button4,
2111
+ {
2112
+ variant: "outlined",
2113
+ disabled: blocked || !descriptor,
2114
+ onClick: startEdit,
2115
+ children: copy.edit
2116
+ }
2117
+ ),
2118
+ descriptor?.healthTest ? /* @__PURE__ */ jsx13(
2119
+ Button4,
2120
+ {
2121
+ variant: "outlined",
2122
+ disabled: blocked,
2123
+ onClick: () => {
2124
+ void runCommand("test");
2125
+ },
2126
+ children: action === "test" ? copy.testing : copy.test
2127
+ }
2128
+ ) : null,
2129
+ descriptor?.reconnect ? /* @__PURE__ */ jsx13(
2130
+ Button4,
2131
+ {
2132
+ variant: "outlined",
2133
+ disabled: blocked,
2134
+ onClick: () => {
2135
+ void runCommand("reconnect");
2136
+ },
2137
+ children: action === "reconnect" ? copy.reconnecting : copy.reconnect
2138
+ }
2139
+ ) : null
2140
+ ] }),
2141
+ /* @__PURE__ */ jsx13(
2142
+ Button4,
2143
+ {
2144
+ color: "primary",
2145
+ disabled: !canUseDetail,
2146
+ onClick: () => {
2147
+ void select({ kind: "connection", pid: detail.pid });
2148
+ },
2149
+ children: copy.useConnection
2150
+ }
2151
+ )
2152
+ ] }) : null,
2153
+ resource.error && view !== "browse" && view !== "manage" ? /* @__PURE__ */ jsx13(
2154
+ ResourceError,
2155
+ {
2156
+ error: resource.error,
2157
+ title: isDenied ? copy.accessDenied : void 0,
2158
+ retry: resource.refresh
2159
+ }
2160
+ ) : null,
2161
+ selectionError ? /* @__PURE__ */ jsx13(Callout, { variant: "danger", role: "alert", title: selectionError }) : null,
2162
+ authoringError ? /* @__PURE__ */ jsx13(Callout, { role: "alert", variant: "danger", title: authoringError }) : null,
2163
+ actionFeedback ? /* @__PURE__ */ jsx13(
2164
+ Callout,
2165
+ {
2166
+ role: "status",
2167
+ variant: actionFeedback.ok ? "success" : "danger",
2168
+ title: actionFeedback.message
2169
+ }
2170
+ ) : null
2171
+ ] }) }),
2172
+ /* @__PURE__ */ jsx13(SheetFooter2, { children: view === "browse" ? /* @__PURE__ */ jsxs10(Fragment6, { children: [
2173
+ /* @__PURE__ */ jsx13(
2174
+ Button4,
2175
+ {
2176
+ variant: "outlined",
2177
+ disabled: busy,
2178
+ onClick: () => onOpenChange(false),
2179
+ children: copy.cancel
2180
+ }
2181
+ ),
2182
+ /* @__PURE__ */ jsx13(
2183
+ Button4,
2184
+ {
2185
+ variant: "outlined",
2186
+ disabled: resource.loading || busy,
2187
+ onClick: () => {
2188
+ setSelectionError(null);
2189
+ void resource.refresh();
2190
+ },
2191
+ children: copy.refresh
2192
+ }
2193
+ )
2194
+ ] }) : /* @__PURE__ */ jsxs10(Fragment6, { children: [
2195
+ /* @__PURE__ */ jsx13(
2196
+ Button4,
2197
+ {
2198
+ variant: "outlined",
2199
+ disabled: busy,
2200
+ onClick: () => {
2201
+ if (view === "edit") {
2202
+ setDraft(createConnectionDraft(null));
2203
+ changeView("detail");
2204
+ } else if (view === "detail") {
2205
+ setDetail(null);
2206
+ changeView("manage");
2207
+ } else {
2208
+ setDraft(createConnectionDraft(null));
2209
+ changeView("browse");
2210
+ }
2211
+ },
2212
+ children: copy.back
2213
+ }
2214
+ ),
2215
+ view === "create" || view === "edit" ? /* @__PURE__ */ jsx13(
2216
+ Button4,
2217
+ {
2218
+ color: "primary",
2219
+ disabled: busy || !formValid || !draft.profileKey.trim() || !authoringTypes.some(
2220
+ (type) => type.key === draft.resourceType
2221
+ ),
2222
+ onClick: () => {
2223
+ void save();
2224
+ },
2225
+ children: saving ? copy.saving : copy.save
2226
+ }
2227
+ ) : null
2228
+ ] }) })
2229
+ ]
2230
+ }
2231
+ )
2232
+ }
2233
+ );
2234
+ }
2235
+
2236
+ // src/components/WorkflowField.tsx
2237
+ import {
2238
+ DEFAULT_WORKFLOW_FIELD_LABELS,
2239
+ useWorkflowNodeField
2240
+ } from "@plugmatica/plugin-sdk";
2241
+ import {
2242
+ Button as Button5,
2243
+ Callout as Callout2,
2244
+ CommandDialog,
2245
+ Icon,
2246
+ Input as Input4,
2247
+ NumberInput as NumberInput2,
2248
+ Select as Select4,
2249
+ Stack as Stack7,
2250
+ Textarea as Textarea2,
2251
+ Typography as Typography6
2252
+ } from "@plugmatica/ui-kit";
2253
+ import * as React15 from "react";
2254
+
2255
+ // src/components/workflowJsonDraft.ts
2256
+ function parseWorkflowJsonDraft(text, expectedType) {
2257
+ try {
2258
+ const value = JSON.parse(text);
2259
+ if (expectedType === "array") {
2260
+ if (!Array.isArray(value)) return { ok: false };
2261
+ } else if (value === null || typeof value !== "object" || Array.isArray(value)) {
2262
+ return { ok: false };
2263
+ }
2264
+ return {
2265
+ ok: true,
2266
+ value,
2267
+ canonical: JSON.stringify(value, null, 2)
2268
+ };
2269
+ } catch {
2270
+ return { ok: false };
2271
+ }
2272
+ }
2273
+
2274
+ // src/components/WorkflowField.tsx
2275
+ import { jsx as jsx14, jsxs as jsxs11 } from "react/jsx-runtime";
2276
+ function primaryType(field) {
2277
+ const type = field.schema.type;
2278
+ return Array.isArray(type) ? type.find((item) => item !== "null") : type;
2279
+ }
2280
+ function initialValue(field) {
2281
+ if (field.schema.default !== void 0) return field.schema.default;
2282
+ if (field.schema.enum?.length) return field.schema.enum[0];
2283
+ const type = primaryType(field);
2284
+ if (type === "boolean") return false;
2285
+ if (type === "number" || type === "integer") return 0;
2286
+ if (type === "object") return {};
2287
+ if (type === "array") return [];
2288
+ if (type === "null") return null;
2289
+ return "";
2290
+ }
2291
+ function WorkflowFixedInput({
2292
+ field,
2293
+ fields,
2294
+ label
2295
+ }) {
2296
+ const type = primaryType(field);
2297
+ const invalid = field.issues.some((issue) => issue.severity === "error");
2298
+ if (field.schema.enum?.length) {
2299
+ return /* @__PURE__ */ jsx14(
2300
+ Select4,
2301
+ {
2302
+ "aria-label": label,
2303
+ disabled: fields.readOnly,
2304
+ triggerProps: { "aria-invalid": invalid || void 0 },
2305
+ value: String(
2306
+ field.schema.enum.findIndex((item) => Object.is(item, field.value))
2307
+ ),
2308
+ options: field.schema.enum.map((item, index) => ({
2309
+ value: String(index),
2310
+ label: String(item)
2311
+ })),
2312
+ onValueChange: (index) => fields.setLiteral(field.path, field.schema.enum?.[Number(index)])
2313
+ }
2314
+ );
2315
+ }
2316
+ if (type === "boolean")
2317
+ return /* @__PURE__ */ jsx14(
2318
+ Select4,
2319
+ {
2320
+ "aria-label": label,
2321
+ disabled: fields.readOnly,
2322
+ triggerProps: { "aria-invalid": invalid || void 0 },
2323
+ value: String(field.value === true),
2324
+ options: [
2325
+ { value: "true", label: fields.labels.trueLabel },
2326
+ { value: "false", label: fields.labels.falseLabel }
2327
+ ],
2328
+ onValueChange: (next) => fields.setLiteral(field.path, next === "true")
2329
+ }
2330
+ );
2331
+ if (type === "number" || type === "integer")
2332
+ return /* @__PURE__ */ jsx14(
2333
+ NumberInput2,
2334
+ {
2335
+ "aria-label": label,
2336
+ disabled: fields.readOnly,
2337
+ invalid,
2338
+ precision: type === "integer" ? 0 : void 0,
2339
+ commitMode: "change",
2340
+ value: typeof field.value === "number" ? field.value : null,
2341
+ onValueChange: (value) => {
2342
+ if (value !== null) fields.setLiteral(field.path, value);
2343
+ }
2344
+ }
2345
+ );
2346
+ if (type === "object" || type === "array")
2347
+ return /* @__PURE__ */ jsx14(
2348
+ StructuredLiteralInput,
2349
+ {
2350
+ field,
2351
+ fields,
2352
+ label,
2353
+ invalid
2354
+ },
2355
+ field.path
2356
+ );
2357
+ return /* @__PURE__ */ jsx14(
2358
+ Input4,
2359
+ {
2360
+ "aria-label": label,
2361
+ disabled: fields.readOnly,
2362
+ invalid,
2363
+ value: field.value === void 0 || field.value === null ? "" : String(field.value),
2364
+ onChange: (event) => fields.setLiteral(field.path, event.target.value)
2365
+ }
2366
+ );
2367
+ }
2368
+ function StructuredLiteralInput({
2369
+ field,
2370
+ fields,
2371
+ label,
2372
+ invalid
2373
+ }) {
2374
+ const encodedValue = JSON.stringify(field.value, null, 2) ?? "";
2375
+ const [draft, setDraft] = React15.useState(() => encodedValue);
2376
+ const [parseError, setParseError] = React15.useState(false);
2377
+ const committedValue = React15.useRef(encodedValue);
2378
+ React15.useEffect(() => {
2379
+ if (encodedValue === committedValue.current) return;
2380
+ committedValue.current = encodedValue;
2381
+ setDraft(encodedValue);
2382
+ setParseError(false);
2383
+ }, [encodedValue]);
2384
+ return /* @__PURE__ */ jsx14(
2385
+ Textarea2,
2386
+ {
2387
+ "aria-label": label,
2388
+ disabled: fields.readOnly,
2389
+ invalid: invalid || parseError,
2390
+ rows: 4,
2391
+ value: draft,
2392
+ onChange: (event) => {
2393
+ const text = event.target.value;
2394
+ setDraft(text);
2395
+ const result = parseWorkflowJsonDraft(text, primaryType(field) === "array" ? "array" : "object");
2396
+ if (!result.ok) {
2397
+ setParseError(true);
2398
+ return;
2399
+ }
2400
+ const previous = committedValue.current;
2401
+ committedValue.current = result.canonical;
2402
+ try {
2403
+ fields.setLiteral(field.path, result.value);
2404
+ setParseError(false);
2405
+ } catch {
2406
+ committedValue.current = previous;
2407
+ setParseError(true);
2408
+ }
2409
+ }
2410
+ }
2411
+ );
2412
+ }
2413
+ function WorkflowField({
2414
+ fields,
2415
+ path,
2416
+ label,
2417
+ description
2418
+ }) {
2419
+ const field = useWorkflowNodeField(fields, path);
2420
+ const [open, setOpen] = React15.useState(false);
2421
+ const [draftFormula, setDraftFormula] = React15.useState(false);
2422
+ React15.useEffect(() => {
2423
+ setOpen(false);
2424
+ setDraftFormula(false);
2425
+ }, [fields.nodeId, path]);
2426
+ if (!field) return null;
2427
+ const copy = fields.labels ?? DEFAULT_WORKFLOW_FIELD_LABELS;
2428
+ const fieldLabel = label ?? field.label;
2429
+ const formula = draftFormula || field.mode === "formula";
2430
+ const invalid = field.issues.some((issue) => issue.severity === "error");
2431
+ const source = field.sources.find(
2432
+ (item) => item.expression === field.expression.trim()
2433
+ );
2434
+ const chooseSource = (expression) => {
2435
+ fields.setMapping(path, expression);
2436
+ setDraftFormula(false);
2437
+ setOpen(false);
2438
+ };
2439
+ const commandItems = field.sources.map((item) => ({
2440
+ recommended: item.recommended === true,
2441
+ command: {
2442
+ id: `${item.nodeId}:${item.expression}`,
2443
+ value: `${item.nodeLabel} ${item.fieldLabel} ${item.fieldPath}`,
2444
+ keywords: [item.nodeLabel, item.fieldLabel, item.fieldPath, item.description ?? ""],
2445
+ label: /* @__PURE__ */ jsxs11(Stack7, { gap: "xs", align: "stretch", children: [
2446
+ /* @__PURE__ */ jsxs11(Typography6.Text, { children: [
2447
+ item.nodeLabel,
2448
+ " \u2192 ",
2449
+ item.fieldLabel
2450
+ ] }),
2451
+ item.availability === "conditional" || item.presence === "optional" ? /* @__PURE__ */ jsx14(Typography6.Text, { size: "sm", color: "muted", children: item.availability === "conditional" ? copy.conditional : copy.optional }) : null
2452
+ ] }),
2453
+ onSelect: () => chooseSource(item.expression)
2454
+ }
2455
+ }));
2456
+ const preferredItems = commandItems.filter((item) => item.recommended).map((item) => item.command);
2457
+ const otherItems = commandItems.filter((item) => !item.recommended).map((item) => item.command);
2458
+ const groups = [
2459
+ ...preferredItems.length ? [{ heading: copy.recommended, items: preferredItems }] : [],
2460
+ ...otherItems.length ? [{ heading: copy.choose, items: otherItems }] : [],
2461
+ {
2462
+ heading: copy.formula,
2463
+ items: [
2464
+ ...field.supportsFixed ? [
2465
+ {
2466
+ id: `fixed:${path}`,
2467
+ value: copy.fixed,
2468
+ label: copy.fixed,
2469
+ onSelect: () => {
2470
+ fields.setLiteral(path, initialValue(field));
2471
+ setDraftFormula(false);
2472
+ setOpen(false);
2473
+ }
2474
+ }
2475
+ ] : [],
2476
+ ...field.supportsExpression ? [
2477
+ {
2478
+ id: `formula:${path}`,
2479
+ value: copy.formula,
2480
+ label: copy.formula,
2481
+ onSelect: () => {
2482
+ setDraftFormula(true);
2483
+ setOpen(false);
2484
+ }
2485
+ }
2486
+ ] : [],
2487
+ ...field.mode !== "unset" ? [
2488
+ {
2489
+ id: `clear:${path}`,
2490
+ value: copy.clear,
2491
+ label: copy.clear,
2492
+ onSelect: () => {
2493
+ fields.clear(path);
2494
+ setDraftFormula(false);
2495
+ setOpen(false);
2496
+ }
2497
+ }
2498
+ ] : []
2499
+ ]
2500
+ }
2501
+ ];
2502
+ return /* @__PURE__ */ jsxs11(
2503
+ Stack7,
2504
+ {
2505
+ ref: (element) => fields.registerAnchor(path, element),
2506
+ gap: "xs",
2507
+ align: "stretch",
2508
+ children: [
2509
+ /* @__PURE__ */ jsxs11(Stack7, { direction: "row", gap: "xs", align: "center", children: [
2510
+ /* @__PURE__ */ jsx14("div", { style: { minWidth: 0, width: "38%" }, children: /* @__PURE__ */ jsxs11(Typography6.Text, { size: "sm", weight: "medium", title: fieldLabel, children: [
2511
+ fieldLabel,
2512
+ field.required ? " *" : ""
2513
+ ] }) }),
2514
+ /* @__PURE__ */ jsxs11(
2515
+ "div",
2516
+ {
2517
+ style: {
2518
+ display: "flex",
2519
+ alignItems: "center",
2520
+ gap: "var(--pm-space-1_5)",
2521
+ flex: 1,
2522
+ minWidth: 0
2523
+ },
2524
+ children: [
2525
+ /* @__PURE__ */ jsx14("div", { style: { flex: 1, minWidth: 0 }, children: formula ? /* @__PURE__ */ jsx14(
2526
+ Input4,
2527
+ {
2528
+ "aria-label": fieldLabel,
2529
+ placeholder: copy.formula,
2530
+ disabled: fields.readOnly,
2531
+ invalid,
2532
+ value: field.expression,
2533
+ onChange: (event) => fields.setMapping(path, event.target.value)
2534
+ }
2535
+ ) : field.mode === "fixed" && field.supportsFixed ? /* @__PURE__ */ jsx14(
2536
+ WorkflowFixedInput,
2537
+ {
2538
+ field,
2539
+ fields,
2540
+ label: fieldLabel
2541
+ }
2542
+ ) : /* @__PURE__ */ jsx14(
2543
+ Button5,
2544
+ {
2545
+ size: "sm",
2546
+ variant: "outlined",
2547
+ disabled: fields.readOnly,
2548
+ "aria-label": fieldLabel,
2549
+ style: { width: "100%", justifyContent: "space-between" },
2550
+ trailing: /* @__PURE__ */ jsx14(Icon, { name: "ChevronDown", size: 15 }),
2551
+ onClick: () => setOpen(true),
2552
+ children: source ? `${source.nodeLabel} \u2192 ${source.fieldLabel}` : copy.choose
2553
+ }
2554
+ ) }),
2555
+ field.mode === "fixed" || formula ? /* @__PURE__ */ jsx14(
2556
+ Button5,
2557
+ {
2558
+ size: "sm",
2559
+ variant: "outlined",
2560
+ disabled: fields.readOnly,
2561
+ "aria-label": `${copy.choose}: ${fieldLabel}`,
2562
+ leading: /* @__PURE__ */ jsx14(Icon, { name: "ChevronDown", size: 15 }),
2563
+ onClick: () => setOpen(true)
2564
+ }
2565
+ ) : null
2566
+ ]
2567
+ }
2568
+ )
2569
+ ] }),
2570
+ description ?? field.schema.description ? /* @__PURE__ */ jsx14(Typography6.Text, { size: "sm", color: "muted", children: description ?? field.schema.description }) : null,
2571
+ source?.availability === "conditional" || source?.presence === "optional" ? /* @__PURE__ */ jsx14(Typography6.Text, { size: "sm", color: "muted", children: source.availability === "conditional" ? copy.conditional : copy.optional }) : null,
2572
+ field.referenceStatus === "unverified" ? /* @__PURE__ */ jsx14(Callout2, { size: "sm", variant: "warning", title: copy.unverified }) : null,
2573
+ field.issues.map((issue) => /* @__PURE__ */ jsx14(
2574
+ Callout2,
2575
+ {
2576
+ size: "sm",
2577
+ variant: issue.severity === "error" ? "danger" : "warning",
2578
+ title: issue.message
2579
+ },
2580
+ `${issue.field ?? path}:${issue.code}:${issue.message}`
2581
+ )),
2582
+ /* @__PURE__ */ jsx14(
2583
+ CommandDialog,
2584
+ {
2585
+ open,
2586
+ onOpenChange: setOpen,
2587
+ placeholder: copy.search,
2588
+ groups,
2589
+ emptyContent: copy.empty
2590
+ }
2591
+ )
2592
+ ]
2593
+ }
2594
+ );
2595
+ }
2596
+ export {
2597
+ CollectionBlock,
2598
+ CollectionPage,
2599
+ ConfirmDialog,
2600
+ ConnectionConfigFields,
2601
+ ConnectionEditorForm,
2602
+ ConnectionPickerSheet,
2603
+ DestructiveConfirmationDialog,
2604
+ DetailsBlock,
2605
+ EditorSheet,
2606
+ FormBlock,
2607
+ ResourceBoundary,
2608
+ ResourceError,
2609
+ ResourceLoading,
2610
+ SettingsBlock,
2611
+ WorkflowField,
2612
+ applyConnectionConfigPreset,
2613
+ buildConnectionCatalogue,
2614
+ compatibleConnectionOptions,
2615
+ connectionAuthoringTypes,
2616
+ connectionCatalogueCategoryLabel,
2617
+ connectionCataloguePresentation,
2618
+ connectionCatalogueSearchFields,
2619
+ connectionCatalogueTypeGroups,
2620
+ connectionConfigHasPreset,
2621
+ createConnectionDraft,
2622
+ defaultConnectionConfig,
2623
+ defaultConnectionEditorLabels,
2624
+ editConnectionDraft,
2625
+ missingRequiredConnectionSecrets,
2626
+ saveConnectionDraft,
2627
+ splitConnectionHostPort,
2628
+ uniqueConnectionCatalogueTypes,
2629
+ useAsyncAction,
2630
+ useAsyncResource,
2631
+ useCrudEditor,
2632
+ usePluginResource,
2633
+ useResourceTable
2634
+ };