@perses-dev/plugin-system 0.55.0-beta.12 → 0.55.0-beta.14
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/components/HTTPSettingsEditor/HTTPProxyTimeoutEditor.d.ts +11 -0
- package/dist/components/HTTPSettingsEditor/HTTPProxyTimeoutEditor.d.ts.map +1 -0
- package/dist/components/HTTPSettingsEditor/HTTPProxyTimeoutEditor.js +58 -0
- package/dist/components/HTTPSettingsEditor/HTTPProxyTimeoutEditor.js.map +1 -0
- package/dist/components/HTTPSettingsEditor/HTTPSettingsEditor.d.ts +1 -1
- package/dist/components/HTTPSettingsEditor/HTTPSettingsEditor.d.ts.map +1 -1
- package/dist/components/HTTPSettingsEditor/HTTPSettingsEditor.js +9 -3
- package/dist/components/HTTPSettingsEditor/HTTPSettingsEditor.js.map +1 -1
- package/dist/components/PluginRegistry/PluginRegistry.js +5 -3
- package/dist/components/PluginRegistry/PluginRegistry.js.map +1 -1
- package/dist/model/datasource.d.ts +3 -0
- package/dist/model/datasource.d.ts.map +1 -1
- package/dist/model/datasource.js.map +1 -1
- package/dist/model/plugin-loading.d.ts +1 -0
- package/dist/model/plugin-loading.d.ts.map +1 -1
- package/dist/model/plugin-loading.js.map +1 -1
- package/dist/remote/PluginRuntime.d.ts.map +1 -1
- package/dist/remote/PluginRuntime.js +14 -13
- package/dist/remote/PluginRuntime.js.map +1 -1
- package/dist/remote/remotePluginLoader.d.ts.map +1 -1
- package/dist/remote/remotePluginLoader.js +1 -0
- package/dist/remote/remotePluginLoader.js.map +1 -1
- package/dist/runtime/plugin-registry.d.ts +1 -0
- package/dist/runtime/plugin-registry.d.ts.map +1 -1
- package/dist/runtime/plugin-registry.js.map +1 -1
- package/package.json +5 -5
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { HTTPProxySpec } from '@perses-dev/spec';
|
|
2
|
+
import type { ReactElement } from 'react';
|
|
3
|
+
interface HTTPProxyTimeoutEditorProps {
|
|
4
|
+
value: HTTPProxySpec;
|
|
5
|
+
onChange: (next: HTTPProxySpec) => void;
|
|
6
|
+
isReadonly?: boolean;
|
|
7
|
+
}
|
|
8
|
+
/** Edits the optional connection timeout of an HTTP proxy. An empty value unsets the timeout. */
|
|
9
|
+
export declare function HTTPProxyTimeoutEditor({ value, onChange, isReadonly }: HTTPProxyTimeoutEditorProps): ReactElement;
|
|
10
|
+
export {};
|
|
11
|
+
//# sourceMappingURL=HTTPProxyTimeoutEditor.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"HTTPProxyTimeoutEditor.d.ts","sourceRoot":"","sources":["../../../src/components/HTTPSettingsEditor/HTTPProxyTimeoutEditor.tsx"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAkB,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEtE,OAAO,KAAK,EAAe,YAAY,EAAE,MAAM,OAAO,CAAC;AAKvD,UAAU,2BAA2B;IACnC,KAAK,EAAE,aAAa,CAAC;IACrB,QAAQ,EAAE,CAAC,IAAI,EAAE,aAAa,KAAK,IAAI,CAAC;IACxC,UAAU,CAAC,EAAE,OAAO,CAAC;CACtB;AAED,iGAAiG;AACjG,wBAAgB,sBAAsB,CAAC,EAAE,KAAK,EAAE,QAAQ,EAAE,UAAU,EAAE,EAAE,2BAA2B,GAAG,YAAY,CAiCjH"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
// Copyright The Perses Authors
|
|
3
|
+
// Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
// you may not use this file except in compliance with the License.
|
|
5
|
+
// You may obtain a copy of the License at
|
|
6
|
+
//
|
|
7
|
+
// http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
//
|
|
9
|
+
// Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
// distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
// See the License for the specific language governing permissions and
|
|
13
|
+
// limitations under the License.
|
|
14
|
+
import { TextField } from "@mui/material";
|
|
15
|
+
import { isDurationString } from "@perses-dev/spec";
|
|
16
|
+
import { useCallback, useMemo } from "react";
|
|
17
|
+
const timeoutFieldSx = {
|
|
18
|
+
mb: 2
|
|
19
|
+
};
|
|
20
|
+
/** Edits the optional connection timeout of an HTTP proxy. An empty value unsets the timeout. */ export function HTTPProxyTimeoutEditor({ value, onChange, isReadonly }) {
|
|
21
|
+
const timeout = value.timeout ?? '';
|
|
22
|
+
// TODO this thing should be handled by a form schema.
|
|
23
|
+
const isInvalid = timeout !== '' && !isDurationString(timeout);
|
|
24
|
+
const handleChange = useCallback((e)=>{
|
|
25
|
+
const nextTimeout = e.target.value;
|
|
26
|
+
onChange({
|
|
27
|
+
...value,
|
|
28
|
+
timeout: nextTimeout === '' ? undefined : nextTimeout
|
|
29
|
+
});
|
|
30
|
+
}, [
|
|
31
|
+
value,
|
|
32
|
+
onChange
|
|
33
|
+
]);
|
|
34
|
+
const inputProps = useMemo(()=>({
|
|
35
|
+
readOnly: isReadonly
|
|
36
|
+
}), [
|
|
37
|
+
isReadonly
|
|
38
|
+
]);
|
|
39
|
+
const inputLabelProps = useMemo(()=>({
|
|
40
|
+
shrink: isReadonly ? true : undefined
|
|
41
|
+
}), [
|
|
42
|
+
isReadonly
|
|
43
|
+
]);
|
|
44
|
+
return /*#__PURE__*/ _jsx(TextField, {
|
|
45
|
+
fullWidth: true,
|
|
46
|
+
label: "Timeout",
|
|
47
|
+
placeholder: "e.g. 30s, 1m30s",
|
|
48
|
+
value: timeout,
|
|
49
|
+
error: isInvalid,
|
|
50
|
+
helperText: isInvalid ? 'Must be a valid duration string (e.g. 30s, 1m30s)' : 'Maximum time allowed to establish a connection to the datasource. Leave empty or set to 0s to use the Perses server default.',
|
|
51
|
+
InputProps: inputProps,
|
|
52
|
+
InputLabelProps: inputLabelProps,
|
|
53
|
+
onChange: handleChange,
|
|
54
|
+
sx: timeoutFieldSx
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
//# sourceMappingURL=HTTPProxyTimeoutEditor.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../src/components/HTTPSettingsEditor/HTTPProxyTimeoutEditor.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { TextField } from '@mui/material';\nimport type { DurationString, HTTPProxySpec } from '@perses-dev/spec';\nimport { isDurationString } from '@perses-dev/spec';\nimport type { ChangeEvent, ReactElement } from 'react';\nimport { useCallback, useMemo } from 'react';\n\nconst timeoutFieldSx = { mb: 2 };\n\ninterface HTTPProxyTimeoutEditorProps {\n value: HTTPProxySpec;\n onChange: (next: HTTPProxySpec) => void;\n isReadonly?: boolean;\n}\n\n/** Edits the optional connection timeout of an HTTP proxy. An empty value unsets the timeout. */\nexport function HTTPProxyTimeoutEditor({ value, onChange, isReadonly }: HTTPProxyTimeoutEditorProps): ReactElement {\n const timeout = value.timeout ?? '';\n // TODO this thing should be handled by a form schema.\n const isInvalid = timeout !== '' && !isDurationString(timeout);\n\n const handleChange = useCallback(\n (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement>): void => {\n const nextTimeout = e.target.value;\n onChange({ ...value, timeout: nextTimeout === '' ? undefined : (nextTimeout as DurationString) });\n },\n [value, onChange],\n );\n const inputProps = useMemo(() => ({ readOnly: isReadonly }), [isReadonly]);\n const inputLabelProps = useMemo(() => ({ shrink: isReadonly ? true : undefined }), [isReadonly]);\n\n return (\n <TextField\n fullWidth\n label=\"Timeout\"\n placeholder=\"e.g. 30s, 1m30s\"\n value={timeout}\n error={isInvalid}\n helperText={\n isInvalid\n ? 'Must be a valid duration string (e.g. 30s, 1m30s)'\n : 'Maximum time allowed to establish a connection to the datasource. Leave empty or set to 0s to use the Perses server default.'\n }\n InputProps={inputProps}\n InputLabelProps={inputLabelProps}\n onChange={handleChange}\n sx={timeoutFieldSx}\n />\n );\n}\n"],"names":["TextField","isDurationString","useCallback","useMemo","timeoutFieldSx","mb","HTTPProxyTimeoutEditor","value","onChange","isReadonly","timeout","isInvalid","handleChange","e","nextTimeout","target","undefined","inputProps","readOnly","inputLabelProps","shrink","fullWidth","label","placeholder","error","helperText","InputProps","InputLabelProps","sx"],"mappings":";AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAASA,SAAS,QAAQ,gBAAgB;AAE1C,SAASC,gBAAgB,QAAQ,mBAAmB;AAEpD,SAASC,WAAW,EAAEC,OAAO,QAAQ,QAAQ;AAE7C,MAAMC,iBAAiB;IAAEC,IAAI;AAAE;AAQ/B,+FAA+F,GAC/F,OAAO,SAASC,uBAAuB,EAAEC,KAAK,EAAEC,QAAQ,EAAEC,UAAU,EAA+B;IACjG,MAAMC,UAAUH,MAAMG,OAAO,IAAI;IACjC,sDAAsD;IACtD,MAAMC,YAAYD,YAAY,MAAM,CAACT,iBAAiBS;IAEtD,MAAME,eAAeV,YACnB,CAACW;QACC,MAAMC,cAAcD,EAAEE,MAAM,CAACR,KAAK;QAClCC,SAAS;YAAE,GAAGD,KAAK;YAAEG,SAASI,gBAAgB,KAAKE,YAAaF;QAA+B;IACjG,GACA;QAACP;QAAOC;KAAS;IAEnB,MAAMS,aAAad,QAAQ,IAAO,CAAA;YAAEe,UAAUT;QAAW,CAAA,GAAI;QAACA;KAAW;IACzE,MAAMU,kBAAkBhB,QAAQ,IAAO,CAAA;YAAEiB,QAAQX,aAAa,OAAOO;QAAU,CAAA,GAAI;QAACP;KAAW;IAE/F,qBACE,KAACT;QACCqB,SAAS;QACTC,OAAM;QACNC,aAAY;QACZhB,OAAOG;QACPc,OAAOb;QACPc,YACEd,YACI,sDACA;QAENe,YAAYT;QACZU,iBAAiBR;QACjBX,UAAUI;QACVgB,IAAIxB;;AAGV"}
|
|
@@ -8,6 +8,6 @@ export interface HTTPSettingsEditor {
|
|
|
8
8
|
initialSpecProxy: HTTPDatasourceSpec;
|
|
9
9
|
testConnection?: () => Promise<void>;
|
|
10
10
|
}
|
|
11
|
-
/** Edits direct URLs and proxy settings, including mutually exclusive allow/drop request header lists. */
|
|
11
|
+
/** Edits direct URLs and proxy settings, including the connection timeout and mutually exclusive allow/drop request header lists. */
|
|
12
12
|
export declare function HTTPSettingsEditor(props: HTTPSettingsEditor): ReactElement;
|
|
13
13
|
//# sourceMappingURL=HTTPSettingsEditor.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HTTPSettingsEditor.d.ts","sourceRoot":"","sources":["../../../src/components/HTTPSettingsEditor/HTTPSettingsEditor.tsx"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,kBAAkB,EAAiB,MAAM,kBAAkB,CAAC;AAI1E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;
|
|
1
|
+
{"version":3,"file":"HTTPSettingsEditor.d.ts","sourceRoot":"","sources":["../../../src/components/HTTPSettingsEditor/HTTPSettingsEditor.tsx"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,kBAAkB,EAAiB,MAAM,kBAAkB,CAAC;AAI1E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAqB1C,MAAM,WAAW,kBAAkB;IACjC,KAAK,EAAE,kBAAkB,CAAC;IAC1B,QAAQ,EAAE,CAAC,IAAI,EAAE,kBAAkB,KAAK,IAAI,CAAC;IAC7C,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB,iBAAiB,EAAE,kBAAkB,CAAC;IACtC,gBAAgB,EAAE,kBAAkB,CAAC;IACrC,cAAc,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CACtC;AAED,qIAAqI;AACrI,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,kBAAkB,GAAG,YAAY,CAue1E"}
|
|
@@ -21,8 +21,9 @@ import { z } from "zod";
|
|
|
21
21
|
import { DatasourceTestConnectionButton } from "../DatasourceTestConnectionButton/index.js";
|
|
22
22
|
import { OptionsEditorRadios } from "../OptionsEditorRadios/index.js";
|
|
23
23
|
import { HTTPHeaderPolicyEditor } from "./HTTPHeaderPolicyEditor.js";
|
|
24
|
+
import { HTTPProxyTimeoutEditor } from "./HTTPProxyTimeoutEditor.js";
|
|
24
25
|
const urlSchema = z.string().url();
|
|
25
|
-
/** Edits direct URLs and proxy settings, including mutually exclusive allow/drop request header lists. */ export function HTTPSettingsEditor(props) {
|
|
26
|
+
/** Edits direct URLs and proxy settings, including the connection timeout and mutually exclusive allow/drop request header lists. */ export function HTTPSettingsEditor(props) {
|
|
26
27
|
const { value, onChange, isReadonly, initialSpecDirect, initialSpecProxy, testConnection } = props;
|
|
27
28
|
const strDirect = 'Direct access';
|
|
28
29
|
const strProxy = 'Proxy';
|
|
@@ -75,7 +76,7 @@ const urlSchema = z.string().url();
|
|
|
75
76
|
}
|
|
76
77
|
}));
|
|
77
78
|
};
|
|
78
|
-
const
|
|
79
|
+
const handleProxySpecChange = useCallback((next)=>{
|
|
79
80
|
onChange(produce(value, (draft)=>{
|
|
80
81
|
if (draft.proxy !== undefined) {
|
|
81
82
|
draft.proxy.spec = next;
|
|
@@ -127,6 +128,11 @@ const urlSchema = z.string().url();
|
|
|
127
128
|
disabled: !urlSchema.safeParse(value.proxy?.spec.url).success
|
|
128
129
|
})
|
|
129
130
|
}),
|
|
131
|
+
value.proxy && /*#__PURE__*/ _jsx(HTTPProxyTimeoutEditor, {
|
|
132
|
+
value: value.proxy.spec,
|
|
133
|
+
isReadonly: isReadonly,
|
|
134
|
+
onChange: handleProxySpecChange
|
|
135
|
+
}),
|
|
130
136
|
/*#__PURE__*/ _jsx(Typography, {
|
|
131
137
|
variant: "h5",
|
|
132
138
|
mb: 2,
|
|
@@ -433,7 +439,7 @@ const urlSchema = z.string().url();
|
|
|
433
439
|
value.proxy && /*#__PURE__*/ _jsx(HTTPHeaderPolicyEditor, {
|
|
434
440
|
value: value.proxy.spec,
|
|
435
441
|
isReadonly: isReadonly,
|
|
436
|
-
onChange:
|
|
442
|
+
onChange: handleProxySpecChange
|
|
437
443
|
}),
|
|
438
444
|
/*#__PURE__*/ _jsxs(Stack, {
|
|
439
445
|
spacing: 1,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/HTTPSettingsEditor/HTTPSettingsEditor.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { Box, Grid, IconButton, MenuItem, Stack, TextField, Typography } from '@mui/material';\nimport type { RequestHeaders } from '@perses-dev/client';\nimport type { HTTPDatasourceSpec, HTTPProxySpec } from '@perses-dev/spec';\nimport { produce } from 'immer';\nimport MinusIcon from 'mdi-material-ui/Minus';\nimport PlusIcon from 'mdi-material-ui/Plus';\nimport type { ReactElement } from 'react';\nimport React, { Fragment, useCallback, useState } from 'react';\nimport { Controller, useFieldArray, useForm } from 'react-hook-form';\nimport { z } from 'zod';\n\nimport { DatasourceTestConnectionButton } from '../DatasourceTestConnectionButton';\nimport { OptionsEditorRadios } from '../OptionsEditorRadios';\nimport { HTTPHeaderPolicyEditor } from './HTTPHeaderPolicyEditor';\n\nconst urlSchema = z.string().url();\n\ntype HeaderEntry = {\n name: string;\n value: string;\n};\n\ntype HeaderFormValues = {\n headers: HeaderEntry[];\n};\n\nexport interface HTTPSettingsEditor {\n value: HTTPDatasourceSpec;\n onChange: (next: HTTPDatasourceSpec) => void;\n isReadonly?: boolean;\n initialSpecDirect: HTTPDatasourceSpec;\n initialSpecProxy: HTTPDatasourceSpec;\n testConnection?: () => Promise<void>;\n}\n\n/** Edits direct URLs and proxy settings, including mutually exclusive allow/drop request header lists. */\nexport function HTTPSettingsEditor(props: HTTPSettingsEditor): ReactElement {\n const { value, onChange, isReadonly, initialSpecDirect, initialSpecProxy, testConnection } = props;\n const strDirect = 'Direct access';\n const strProxy = 'Proxy';\n\n // Initialize Proxy mode by default, if neither direct nor proxy mode is selected.\n if (value.directUrl === undefined && value.proxy === undefined) {\n Object.assign(value, initialSpecProxy);\n }\n\n // Use local state to maintain an array of header entries during editing, instead of\n // manipulating a map directly which causes weird UX.\n const headersForm = useForm<HeaderFormValues>({\n defaultValues: {\n headers: Object.entries(value.proxy?.spec.headers ?? {}).map(([name, headerValue]) => ({\n name,\n value: headerValue as string,\n })),\n },\n });\n\n const { fields, append, remove } = useFieldArray({\n control: headersForm.control,\n name: 'headers',\n });\n\n // Watch the headers array for changes to detect duplicates\n const watchedHeaders = headersForm.watch('headers');\n\n // Check for duplicate header names\n // TODO: duplication detection logic to be replaced by proper zod schema validation in the future\n // ref https://github.com/perses/perses/issues/3014\n const nameMap = new Map<string, number>();\n const duplicateNames = new Set<string>();\n watchedHeaders.forEach(({ name }) => {\n if (name !== '') {\n const count = (nameMap.get(name) || 0) + 1;\n nameMap.set(name, count);\n if (count > 1) {\n duplicateNames.add(name);\n }\n }\n });\n const hasDuplicates = duplicateNames.size > 0;\n\n // Sync headers to parent\n const syncHeadersToParent = (headers: HeaderEntry[]): void => {\n const headersObject: RequestHeaders = {};\n headers.forEach(({ name, value: headerValue }) => {\n if (name !== '') {\n headersObject[name] = headerValue;\n }\n });\n\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.headers = Object.keys(headersObject).length > 0 ? headersObject : undefined;\n }\n }),\n );\n };\n\n const handleHeaderPolicyChange = useCallback(\n (next: HTTPProxySpec): void => {\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec = next;\n }\n }),\n );\n },\n [value, onChange],\n );\n\n const tabs = [\n {\n label: strProxy,\n content: (\n <>\n <Controller\n name=\"URL\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"URL\"\n value={value.proxy?.spec.url || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.url = e.target.value;\n }\n }),\n );\n }}\n sx={{ mb: 2 }}\n />\n )}\n />\n {testConnection && (\n <Box mb={2} display=\"flex\" justifyContent=\"flex-end\">\n <DatasourceTestConnectionButton\n testConnection={testConnection}\n disabled={!urlSchema.safeParse(value.proxy?.spec.url).success}\n />\n </Box>\n )}\n <Typography variant=\"h5\" mb={2}>\n Allowed endpoints\n </Typography>\n <Grid container spacing={2} mb={2}>\n {value.proxy?.spec.allowedEndpoints && value.proxy?.spec.allowedEndpoints.length !== 0 ? (\n value.proxy.spec.allowedEndpoints.map(({ endpointPattern, method }, i) => {\n return (\n <Fragment key={i}>\n <Grid item xs={8}>\n <Controller\n name={`Endpoint pattern ${i}`}\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"Endpoint pattern\"\n value={endpointPattern}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = draft.proxy.spec.allowedEndpoints?.map(\n (item, itemIndex) => {\n if (i === itemIndex) {\n return {\n endpointPattern: e.target.value,\n method: item.method,\n };\n } else {\n return item;\n }\n },\n );\n }\n }),\n );\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={3}>\n <Controller\n name={`Method ${i}`}\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n select\n fullWidth\n label=\"Method\"\n value={method}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = draft.proxy.spec.allowedEndpoints?.map(\n (item, itemIndex) => {\n if (i === itemIndex) {\n return {\n endpointPattern: item.endpointPattern,\n method: e.target.value,\n };\n } else {\n return item;\n }\n },\n );\n }\n }),\n );\n }}\n >\n <MenuItem value=\"GET\">GET</MenuItem>\n <MenuItem value=\"POST\">POST</MenuItem>\n <MenuItem value=\"PUT\">PUT</MenuItem>\n <MenuItem value=\"PATCH\">PATCH</MenuItem>\n <MenuItem value=\"DELETE\">DELETE</MenuItem>\n </TextField>\n )}\n />\n </Grid>\n <Grid item xs={1}>\n <Controller\n name={`Remove Endpoint ${i}`}\n render={({ field }) => (\n <IconButton\n {...field}\n disabled={isReadonly}\n // Remove the given allowed endpoint from the list\n onClick={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = [\n ...(draft.proxy.spec.allowedEndpoints?.filter((item, itemIndex) => {\n return itemIndex !== i;\n }) || []),\n ];\n }\n }),\n );\n }}\n >\n <MinusIcon />\n </IconButton>\n )}\n />\n </Grid>\n </Fragment>\n );\n })\n ) : (\n <Grid item xs={4}>\n <Typography sx={{ fontStyle: 'italic' }}>None</Typography>\n </Grid>\n )}\n <Grid item xs={12} sx={{ paddingTop: '0px !important', paddingLeft: '5px !important' }}>\n <IconButton\n disabled={isReadonly}\n // Add a new (empty) allowed endpoint to the list\n onClick={() =>\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = [\n ...(draft.proxy.spec.allowedEndpoints ?? []),\n { endpointPattern: '', method: '' },\n ];\n }\n }),\n )\n }\n >\n <PlusIcon />\n </IconButton>\n </Grid>\n </Grid>\n <Typography variant=\"h5\" mb={2}>\n Request Headers\n </Typography>\n <Grid container spacing={2} mb={2}>\n {fields.length > 0 ? (\n fields.map((field, index) => (\n <Fragment key={field.id}>\n <Grid item xs={4}>\n <Controller\n control={headersForm.control}\n name={`headers.${index}.name`}\n render={({ field: controllerField, fieldState }) => (\n <TextField\n {...controllerField}\n fullWidth\n label=\"Header name\"\n error={!!fieldState.error || duplicateNames.has(controllerField.value)}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n controllerField.onChange(e);\n const updatedHeaders = [...watchedHeaders];\n updatedHeaders[index] = { name: e.target.value, value: updatedHeaders[index]?.value ?? '' };\n syncHeadersToParent(updatedHeaders);\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={7}>\n <Controller\n control={headersForm.control}\n name={`headers.${index}.value`}\n render={({ field: controllerField, fieldState }) => (\n <TextField\n {...controllerField}\n fullWidth\n label=\"Header value\"\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n controllerField.onChange(e);\n const updatedHeaders = [...watchedHeaders];\n updatedHeaders[index] = { name: updatedHeaders[index]?.name ?? '', value: e.target.value };\n syncHeadersToParent(updatedHeaders);\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={1}>\n <IconButton\n disabled={isReadonly}\n aria-label={`Remove header ${watchedHeaders[index]?.name || index}`}\n onClick={() => {\n remove(index);\n const updatedHeaders = watchedHeaders.filter((_, i) => i !== index);\n syncHeadersToParent(updatedHeaders);\n }}\n >\n <MinusIcon />\n </IconButton>\n </Grid>\n </Fragment>\n ))\n ) : (\n <Grid item xs={4}>\n <Typography sx={{ fontStyle: 'italic' }}>None</Typography>\n </Grid>\n )}\n {hasDuplicates && (\n <Grid item xs={12}>\n <Typography variant=\"body2\" color=\"error\">\n Duplicate header names detected. Each header name must be unique.\n </Typography>\n </Grid>\n )}\n <Grid item xs={12} sx={{ paddingTop: '0px !important', paddingLeft: '5px !important' }}>\n <IconButton disabled={isReadonly} onClick={() => append({ name: '', value: '' })}>\n <PlusIcon />\n </IconButton>\n </Grid>\n </Grid>\n\n {value.proxy && (\n <HTTPHeaderPolicyEditor\n value={value.proxy.spec}\n isReadonly={isReadonly}\n onChange={handleHeaderPolicyChange}\n />\n )}\n\n <Stack spacing={1}>\n <Typography variant=\"h5\">Secret</Typography>\n <Controller\n name=\"Secret\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"Secret\"\n value={value.proxy?.spec.secret || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.secret = e.target.value;\n }\n }),\n );\n }}\n />\n )}\n />\n </Stack>\n </>\n ),\n },\n {\n label: strDirect,\n content: (\n <>\n <Controller\n name=\"URL\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"URL\"\n value={value.directUrl || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n draft.directUrl = e.target.value;\n }),\n );\n }}\n />\n )}\n />\n {testConnection && (\n <Box my={2} display=\"flex\" justifyContent=\"flex-end\">\n <DatasourceTestConnectionButton\n testConnection={testConnection}\n disabled={!urlSchema.safeParse(value.directUrl).success}\n />\n </Box>\n )}\n </>\n ),\n },\n ];\n\n // Use of findIndex instead of providing hardcoded values to avoid desynchronisatio or\n // bug in case the tabs get eventually swapped in the future.\n const directModeId = tabs.findIndex((tab) => tab.label === strDirect);\n const proxyModeId = tabs.findIndex((tab) => tab.label === strProxy);\n\n // Set defaultTab to the mode that this datasource is currently relying on.\n const defaultTab = value.proxy ? proxyModeId : directModeId;\n\n // For better user experience, save previous states in mind for both mode.\n // This avoids losing everything when the user changes their mind back.\n const [previousSpecDirect, setPreviousSpecDirect] = useState(initialSpecDirect);\n const [previousSpecProxy, setPreviousSpecProxy] = useState(initialSpecProxy);\n\n // When changing mode, remove previous mode's config + append default values for the new mode.\n const handleModeChange = (v: number): void => {\n if (tabs[v]?.label === strDirect) {\n setPreviousSpecProxy(value);\n\n // Copy all settings (for example, scrapeInterval), except 'proxy'\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { proxy, ...newValue } = value;\n onChange({ ...newValue, directUrl: previousSpecDirect.directUrl });\n } else if (tabs[v]?.label === strProxy) {\n setPreviousSpecDirect(value);\n\n // Copy all settings (for example, scrapeInterval), except 'directUrl'\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { directUrl, ...newValue } = value;\n onChange({ ...newValue, proxy: previousSpecProxy.proxy });\n }\n };\n\n return (\n <>\n <Typography variant=\"h4\" mt={2}>\n HTTP Settings\n </Typography>\n <OptionsEditorRadios\n isReadonly={isReadonly}\n tabs={tabs}\n defaultTab={defaultTab}\n onModeChange={handleModeChange}\n />\n </>\n );\n}\n"],"names":["Box","Grid","IconButton","MenuItem","Stack","TextField","Typography","produce","MinusIcon","PlusIcon","React","Fragment","useCallback","useState","Controller","useFieldArray","useForm","z","DatasourceTestConnectionButton","OptionsEditorRadios","HTTPHeaderPolicyEditor","urlSchema","string","url","HTTPSettingsEditor","props","value","onChange","isReadonly","initialSpecDirect","initialSpecProxy","testConnection","strDirect","strProxy","directUrl","undefined","proxy","Object","assign","headersForm","defaultValues","headers","entries","spec","map","name","headerValue","fields","append","remove","control","watchedHeaders","watch","nameMap","Map","duplicateNames","Set","forEach","count","get","set","add","hasDuplicates","size","syncHeadersToParent","headersObject","draft","keys","length","handleHeaderPolicyChange","next","tabs","label","content","render","field","fieldState","fullWidth","error","helperText","message","InputProps","readOnly","InputLabelProps","shrink","e","target","sx","mb","display","justifyContent","disabled","safeParse","success","variant","container","spacing","allowedEndpoints","endpointPattern","method","i","item","xs","itemIndex","select","onClick","filter","fontStyle","paddingTop","paddingLeft","index","controllerField","has","updatedHeaders","aria-label","_","id","color","secret","my","directModeId","findIndex","tab","proxyModeId","defaultTab","previousSpecDirect","setPreviousSpecDirect","previousSpecProxy","setPreviousSpecProxy","handleModeChange","v","newValue","mt","onModeChange"],"mappings":";AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAASA,GAAG,EAAEC,IAAI,EAAEC,UAAU,EAAEC,QAAQ,EAAEC,KAAK,EAAEC,SAAS,EAAEC,UAAU,QAAQ,gBAAgB;AAG9F,SAASC,OAAO,QAAQ,QAAQ;AAChC,OAAOC,eAAe,wBAAwB;AAC9C,OAAOC,cAAc,uBAAuB;AAE5C,OAAOC,SAASC,QAAQ,EAAEC,WAAW,EAAEC,QAAQ,QAAQ,QAAQ;AAC/D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,OAAO,IAAIqC,IAAI,CAAC2D,EAAE,EAAE1D,UAAUvC,UAAU;YACtC6F,sBAAsBpG;YAEtB,sEAAsE;YACtE,6DAA6D;YAC7D,MAAM,EAAEQ,SAAS,EAAE,GAAGiG,UAAU,GAAGzG;YACnCC,SAAS;gBAAE,GAAGwG,QAAQ;gBAAE/F,OAAO2F,kBAAkB3F,KAAK;YAAC;QACzD;IACF;IAEA,qBACE;;0BACE,KAAC9B;gBAAWwF,SAAQ;gBAAKsC,IAAI;0BAAG;;0BAGhC,KAACjH;gBACCS,YAAYA;gBACZ2C,MAAMA;gBACNqD,YAAYA;gBACZS,cAAcJ;;;;AAItB"}
|
|
1
|
+
{"version":3,"sources":["../../../src/components/HTTPSettingsEditor/HTTPSettingsEditor.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { Box, Grid, IconButton, MenuItem, Stack, TextField, Typography } from '@mui/material';\nimport type { RequestHeaders } from '@perses-dev/client';\nimport type { HTTPDatasourceSpec, HTTPProxySpec } from '@perses-dev/spec';\nimport { produce } from 'immer';\nimport MinusIcon from 'mdi-material-ui/Minus';\nimport PlusIcon from 'mdi-material-ui/Plus';\nimport type { ReactElement } from 'react';\nimport React, { Fragment, useCallback, useState } from 'react';\nimport { Controller, useFieldArray, useForm } from 'react-hook-form';\nimport { z } from 'zod';\n\nimport { DatasourceTestConnectionButton } from '../DatasourceTestConnectionButton';\nimport { OptionsEditorRadios } from '../OptionsEditorRadios';\nimport { HTTPHeaderPolicyEditor } from './HTTPHeaderPolicyEditor';\nimport { HTTPProxyTimeoutEditor } from './HTTPProxyTimeoutEditor';\n\nconst urlSchema = z.string().url();\n\ntype HeaderEntry = {\n name: string;\n value: string;\n};\n\ntype HeaderFormValues = {\n headers: HeaderEntry[];\n};\n\nexport interface HTTPSettingsEditor {\n value: HTTPDatasourceSpec;\n onChange: (next: HTTPDatasourceSpec) => void;\n isReadonly?: boolean;\n initialSpecDirect: HTTPDatasourceSpec;\n initialSpecProxy: HTTPDatasourceSpec;\n testConnection?: () => Promise<void>;\n}\n\n/** Edits direct URLs and proxy settings, including the connection timeout and mutually exclusive allow/drop request header lists. */\nexport function HTTPSettingsEditor(props: HTTPSettingsEditor): ReactElement {\n const { value, onChange, isReadonly, initialSpecDirect, initialSpecProxy, testConnection } = props;\n const strDirect = 'Direct access';\n const strProxy = 'Proxy';\n\n // Initialize Proxy mode by default, if neither direct nor proxy mode is selected.\n if (value.directUrl === undefined && value.proxy === undefined) {\n Object.assign(value, initialSpecProxy);\n }\n\n // Use local state to maintain an array of header entries during editing, instead of\n // manipulating a map directly which causes weird UX.\n const headersForm = useForm<HeaderFormValues>({\n defaultValues: {\n headers: Object.entries(value.proxy?.spec.headers ?? {}).map(([name, headerValue]) => ({\n name,\n value: headerValue as string,\n })),\n },\n });\n\n const { fields, append, remove } = useFieldArray({\n control: headersForm.control,\n name: 'headers',\n });\n\n // Watch the headers array for changes to detect duplicates\n const watchedHeaders = headersForm.watch('headers');\n\n // Check for duplicate header names\n // TODO: duplication detection logic to be replaced by proper zod schema validation in the future\n // ref https://github.com/perses/perses/issues/3014\n const nameMap = new Map<string, number>();\n const duplicateNames = new Set<string>();\n watchedHeaders.forEach(({ name }) => {\n if (name !== '') {\n const count = (nameMap.get(name) || 0) + 1;\n nameMap.set(name, count);\n if (count > 1) {\n duplicateNames.add(name);\n }\n }\n });\n const hasDuplicates = duplicateNames.size > 0;\n\n // Sync headers to parent\n const syncHeadersToParent = (headers: HeaderEntry[]): void => {\n const headersObject: RequestHeaders = {};\n headers.forEach(({ name, value: headerValue }) => {\n if (name !== '') {\n headersObject[name] = headerValue;\n }\n });\n\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.headers = Object.keys(headersObject).length > 0 ? headersObject : undefined;\n }\n }),\n );\n };\n\n const handleProxySpecChange = useCallback(\n (next: HTTPProxySpec): void => {\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec = next;\n }\n }),\n );\n },\n [value, onChange],\n );\n\n const tabs = [\n {\n label: strProxy,\n content: (\n <>\n <Controller\n name=\"URL\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"URL\"\n value={value.proxy?.spec.url || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.url = e.target.value;\n }\n }),\n );\n }}\n sx={{ mb: 2 }}\n />\n )}\n />\n {testConnection && (\n <Box mb={2} display=\"flex\" justifyContent=\"flex-end\">\n <DatasourceTestConnectionButton\n testConnection={testConnection}\n disabled={!urlSchema.safeParse(value.proxy?.spec.url).success}\n />\n </Box>\n )}\n {value.proxy && (\n <HTTPProxyTimeoutEditor value={value.proxy.spec} isReadonly={isReadonly} onChange={handleProxySpecChange} />\n )}\n <Typography variant=\"h5\" mb={2}>\n Allowed endpoints\n </Typography>\n <Grid container spacing={2} mb={2}>\n {value.proxy?.spec.allowedEndpoints && value.proxy?.spec.allowedEndpoints.length !== 0 ? (\n value.proxy.spec.allowedEndpoints.map(({ endpointPattern, method }, i) => {\n return (\n <Fragment key={i}>\n <Grid item xs={8}>\n <Controller\n name={`Endpoint pattern ${i}`}\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"Endpoint pattern\"\n value={endpointPattern}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = draft.proxy.spec.allowedEndpoints?.map(\n (item, itemIndex) => {\n if (i === itemIndex) {\n return {\n endpointPattern: e.target.value,\n method: item.method,\n };\n } else {\n return item;\n }\n },\n );\n }\n }),\n );\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={3}>\n <Controller\n name={`Method ${i}`}\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n select\n fullWidth\n label=\"Method\"\n value={method}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = draft.proxy.spec.allowedEndpoints?.map(\n (item, itemIndex) => {\n if (i === itemIndex) {\n return {\n endpointPattern: item.endpointPattern,\n method: e.target.value,\n };\n } else {\n return item;\n }\n },\n );\n }\n }),\n );\n }}\n >\n <MenuItem value=\"GET\">GET</MenuItem>\n <MenuItem value=\"POST\">POST</MenuItem>\n <MenuItem value=\"PUT\">PUT</MenuItem>\n <MenuItem value=\"PATCH\">PATCH</MenuItem>\n <MenuItem value=\"DELETE\">DELETE</MenuItem>\n </TextField>\n )}\n />\n </Grid>\n <Grid item xs={1}>\n <Controller\n name={`Remove Endpoint ${i}`}\n render={({ field }) => (\n <IconButton\n {...field}\n disabled={isReadonly}\n // Remove the given allowed endpoint from the list\n onClick={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = [\n ...(draft.proxy.spec.allowedEndpoints?.filter((item, itemIndex) => {\n return itemIndex !== i;\n }) || []),\n ];\n }\n }),\n );\n }}\n >\n <MinusIcon />\n </IconButton>\n )}\n />\n </Grid>\n </Fragment>\n );\n })\n ) : (\n <Grid item xs={4}>\n <Typography sx={{ fontStyle: 'italic' }}>None</Typography>\n </Grid>\n )}\n <Grid item xs={12} sx={{ paddingTop: '0px !important', paddingLeft: '5px !important' }}>\n <IconButton\n disabled={isReadonly}\n // Add a new (empty) allowed endpoint to the list\n onClick={() =>\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.allowedEndpoints = [\n ...(draft.proxy.spec.allowedEndpoints ?? []),\n { endpointPattern: '', method: '' },\n ];\n }\n }),\n )\n }\n >\n <PlusIcon />\n </IconButton>\n </Grid>\n </Grid>\n <Typography variant=\"h5\" mb={2}>\n Request Headers\n </Typography>\n <Grid container spacing={2} mb={2}>\n {fields.length > 0 ? (\n fields.map((field, index) => (\n <Fragment key={field.id}>\n <Grid item xs={4}>\n <Controller\n control={headersForm.control}\n name={`headers.${index}.name`}\n render={({ field: controllerField, fieldState }) => (\n <TextField\n {...controllerField}\n fullWidth\n label=\"Header name\"\n error={!!fieldState.error || duplicateNames.has(controllerField.value)}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n controllerField.onChange(e);\n const updatedHeaders = [...watchedHeaders];\n updatedHeaders[index] = { name: e.target.value, value: updatedHeaders[index]?.value ?? '' };\n syncHeadersToParent(updatedHeaders);\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={7}>\n <Controller\n control={headersForm.control}\n name={`headers.${index}.value`}\n render={({ field: controllerField, fieldState }) => (\n <TextField\n {...controllerField}\n fullWidth\n label=\"Header value\"\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n controllerField.onChange(e);\n const updatedHeaders = [...watchedHeaders];\n updatedHeaders[index] = { name: updatedHeaders[index]?.name ?? '', value: e.target.value };\n syncHeadersToParent(updatedHeaders);\n }}\n />\n )}\n />\n </Grid>\n <Grid item xs={1}>\n <IconButton\n disabled={isReadonly}\n aria-label={`Remove header ${watchedHeaders[index]?.name || index}`}\n onClick={() => {\n remove(index);\n const updatedHeaders = watchedHeaders.filter((_, i) => i !== index);\n syncHeadersToParent(updatedHeaders);\n }}\n >\n <MinusIcon />\n </IconButton>\n </Grid>\n </Fragment>\n ))\n ) : (\n <Grid item xs={4}>\n <Typography sx={{ fontStyle: 'italic' }}>None</Typography>\n </Grid>\n )}\n {hasDuplicates && (\n <Grid item xs={12}>\n <Typography variant=\"body2\" color=\"error\">\n Duplicate header names detected. Each header name must be unique.\n </Typography>\n </Grid>\n )}\n <Grid item xs={12} sx={{ paddingTop: '0px !important', paddingLeft: '5px !important' }}>\n <IconButton disabled={isReadonly} onClick={() => append({ name: '', value: '' })}>\n <PlusIcon />\n </IconButton>\n </Grid>\n </Grid>\n\n {value.proxy && (\n <HTTPHeaderPolicyEditor value={value.proxy.spec} isReadonly={isReadonly} onChange={handleProxySpecChange} />\n )}\n\n <Stack spacing={1}>\n <Typography variant=\"h5\">Secret</Typography>\n <Controller\n name=\"Secret\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"Secret\"\n value={value.proxy?.spec.secret || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n if (draft.proxy !== undefined) {\n draft.proxy.spec.secret = e.target.value;\n }\n }),\n );\n }}\n />\n )}\n />\n </Stack>\n </>\n ),\n },\n {\n label: strDirect,\n content: (\n <>\n <Controller\n name=\"URL\"\n render={({ field, fieldState }) => (\n <TextField\n {...field}\n fullWidth\n label=\"URL\"\n value={value.directUrl || ''}\n error={!!fieldState.error}\n helperText={fieldState.error?.message}\n InputProps={{\n readOnly: isReadonly,\n }}\n InputLabelProps={{ shrink: isReadonly ? true : undefined }}\n onChange={(e) => {\n field.onChange(e);\n onChange(\n produce(value, (draft) => {\n draft.directUrl = e.target.value;\n }),\n );\n }}\n />\n )}\n />\n {testConnection && (\n <Box my={2} display=\"flex\" justifyContent=\"flex-end\">\n <DatasourceTestConnectionButton\n testConnection={testConnection}\n disabled={!urlSchema.safeParse(value.directUrl).success}\n />\n </Box>\n )}\n </>\n ),\n },\n ];\n\n // Use of findIndex instead of providing hardcoded values to avoid desynchronisatio or\n // bug in case the tabs get eventually swapped in the future.\n const directModeId = tabs.findIndex((tab) => tab.label === strDirect);\n const proxyModeId = tabs.findIndex((tab) => tab.label === strProxy);\n\n // Set defaultTab to the mode that this datasource is currently relying on.\n const defaultTab = value.proxy ? proxyModeId : directModeId;\n\n // For better user experience, save previous states in mind for both mode.\n // This avoids losing everything when the user changes their mind back.\n const [previousSpecDirect, setPreviousSpecDirect] = useState(initialSpecDirect);\n const [previousSpecProxy, setPreviousSpecProxy] = useState(initialSpecProxy);\n\n // When changing mode, remove previous mode's config + append default values for the new mode.\n const handleModeChange = (v: number): void => {\n if (tabs[v]?.label === strDirect) {\n setPreviousSpecProxy(value);\n\n // Copy all settings (for example, scrapeInterval), except 'proxy'\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { proxy, ...newValue } = value;\n onChange({ ...newValue, directUrl: previousSpecDirect.directUrl });\n } else if (tabs[v]?.label === strProxy) {\n setPreviousSpecDirect(value);\n\n // Copy all settings (for example, scrapeInterval), except 'directUrl'\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { directUrl, ...newValue } = value;\n onChange({ ...newValue, proxy: previousSpecProxy.proxy });\n }\n };\n\n return (\n <>\n <Typography variant=\"h4\" mt={2}>\n HTTP Settings\n </Typography>\n <OptionsEditorRadios\n isReadonly={isReadonly}\n tabs={tabs}\n defaultTab={defaultTab}\n onModeChange={handleModeChange}\n />\n </>\n );\n}\n"],"names":["Box","Grid","IconButton","MenuItem","Stack","TextField","Typography","produce","MinusIcon","PlusIcon","React","Fragment","useCallback","useState","Controller","useFieldArray","useForm","z","DatasourceTestConnectionButton","OptionsEditorRadios","HTTPHeaderPolicyEditor","HTTPProxyTimeoutEditor","urlSchema","string","url","HTTPSettingsEditor","props","value","onChange","isReadonly","initialSpecDirect","initialSpecProxy","testConnection","strDirect","strProxy","directUrl","undefined","proxy","Object","assign","headersForm","defaultValues","headers","entries","spec","map","name","headerValue","fields","append","remove","control","watchedHeaders","watch","nameMap","Map","duplicateNames","Set","forEach","count","get","set","add","hasDuplicates","size","syncHeadersToParent","headersObject","draft","keys","length","handleProxySpecChange","next","tabs","label","content","render","field","fieldState","fullWidth","error","helperText","message","InputProps","readOnly","InputLabelProps","shrink","e","target","sx","mb","display","justifyContent","disabled","safeParse","success","variant","container","spacing","allowedEndpoints","endpointPattern","method","i","item","xs","itemIndex","select","onClick","filter","fontStyle","paddingTop","paddingLeft","index","controllerField","has","updatedHeaders","aria-label","_","id","color","secret","my","directModeId","findIndex","tab","proxyModeId","defaultTab","previousSpecDirect","setPreviousSpecDirect","previousSpecProxy","setPreviousSpecProxy","handleModeChange","v","newValue","mt","onModeChange"],"mappings":";AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAASA,GAAG,EAAEC,IAAI,EAAEC,UAAU,EAAEC,QAAQ,EAAEC,KAAK,EAAEC,SAAS,EAAEC,UAAU,QAAQ,gBAAgB;AAG9F,SAASC,OAAO,QAAQ,QAAQ;AAChC,OAAOC,eAAe,wBAAwB;AAC9C,OAAOC,cAAc,uBAAuB;AAE5C,OAAOC,SAASC,QAAQ,EAAEC,WAAW,EAAEC,QAAQ,QAAQ,QAAQ;AAC/D,SAASC,UAAU,EAA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AM,EAAEU,KAAK,EAAE,GAAG+F,UAAU,GAAGzG;YAC/BC,SAAS;gBAAE,GAAGwG,QAAQ;gBAAEjG,WAAW2F,mBAAmB3F,SAAS;YAAC;QAClE,OAAO,IAAIqC,IAAI,CAAC2D,EAAE,EAAE1D,UAAUvC,UAAU;YACtC6F,sBAAsBpG;YAEtB,sEAAsE;YACtE,6DAA6D;YAC7D,MAAM,EAAEQ,SAAS,EAAE,GAAGiG,UAAU,GAAGzG;YACnCC,SAAS;gBAAE,GAAGwG,QAAQ;gBAAE/F,OAAO2F,kBAAkB3F,KAAK;YAAC;QACzD;IACF;IAEA,qBACE;;0BACE,KAAC/B;gBAAWyF,SAAQ;gBAAKsC,IAAI;0BAAG;;0BAGhC,KAAClH;gBACCU,YAAYA;gBACZ2C,MAAMA;gBACNqD,YAAYA;gBACZS,cAAcJ;;;;AAItB"}
|
|
@@ -55,7 +55,7 @@ import { usePluginIndexes } from "./plugin-indexes.js";
|
|
|
55
55
|
* PluginRegistryContext provider that keeps track of all available plugins and provides an API for getting them or
|
|
56
56
|
* querying the metadata about them.
|
|
57
57
|
*/ export function PluginRegistry(props) {
|
|
58
|
-
const { pluginLoader: { getInstalledPlugins, importPluginModule }, children, defaultPluginKinds } = props;
|
|
58
|
+
const { pluginLoader: { getInstalledPlugins, importPluginModule, baseURL: pluginsBaseURL }, children, defaultPluginKinds } = props;
|
|
59
59
|
const getPluginIndexes = usePluginIndexes(getInstalledPlugins);
|
|
60
60
|
// De-dupe calls to import plugin modules
|
|
61
61
|
const importCache = useRef(new Map());
|
|
@@ -129,11 +129,13 @@ import { usePluginIndexes } from "./plugin-indexes.js";
|
|
|
129
129
|
const context = useMemo(()=>({
|
|
130
130
|
getPlugin,
|
|
131
131
|
listPluginMetadata,
|
|
132
|
-
defaultPluginKinds
|
|
132
|
+
defaultPluginKinds,
|
|
133
|
+
pluginsBaseURL
|
|
133
134
|
}), [
|
|
134
135
|
getPlugin,
|
|
135
136
|
listPluginMetadata,
|
|
136
|
-
defaultPluginKinds
|
|
137
|
+
defaultPluginKinds,
|
|
138
|
+
pluginsBaseURL
|
|
137
139
|
]);
|
|
138
140
|
return /*#__PURE__*/ _jsx(PluginRegistryContext.Provider, {
|
|
139
141
|
value: context,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/components/PluginRegistry/PluginRegistry.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { UnknownSpec } from '@perses-dev/spec';\nimport type { ReactNode, ReactElement } from 'react';\nimport { useRef, useCallback, useMemo } from 'react';\n\nimport type {\n PluginModuleResource,\n PluginType,\n PluginImplementation,\n Plugin,\n PluginLoader,\n DefaultPluginKinds,\n} from '../../model';\nimport { PluginRegistryContext } from '../../runtime';\nimport { comparePluginVersions, useEvent } from '../../utils';\nimport { resolvePluginKeys } from './getPluginSearchHelper';\nimport type { PluginCompoundKey } from './plugin-indexes';\nimport { usePluginIndexes } from './plugin-indexes';\n\nexport interface PluginRegistryProps {\n pluginLoader: PluginLoader;\n defaultPluginKinds?: DefaultPluginKinds;\n children?: ReactNode;\n}\n\n/**\n * Returns the indexed key of a plugin served by a local dev server for the given plugin type and kind, if any.\n * Keys are `${kind}:${name}:${registry}:${version}`, so we match on the `kind:name:` prefix.\n */\nfunction findDevPluginKey(devPluginKeys: Set<string>, kind: string, name: string): string | undefined {\n const prefix = `${kind}:${name}:`;\n for (const key of devPluginKeys) {\n if (key.startsWith(prefix)) {\n return key;\n }\n }\n return undefined;\n}\n\n/**\n * Returns the indexed keys (`${kind}:${name}:${registry}:${version}`) matching *every* field supplied in the query.\n * `kind` and `name` are always compared; `registry` and `version` are only compared when they are set, so a\n * version-only pin matches whatever registry the plugin happens to be installed under, and a registry-only pin never\n * leaks into another registry. Results are ordered from the newest version to the oldest.\n */\nfunction findMatchingPluginKeys<T extends PluginType>(\n allKeys: Iterable<string>,\n query: PluginCompoundKey<T>,\n): string[] {\n const { kind, name, registry, version } = query;\n const prefix = `${kind}:${name}:`;\n const matches: Array<{ key: string; version: string }> = [];\n\n for (const key of allKeys) {\n if (!key.startsWith(prefix)) continue;\n const parts = key.split(':');\n if (parts.length !== 4) continue;\n const [, , keyRegistry, keyVersion] = parts;\n if (registry !== undefined && keyRegistry !== registry) continue;\n if (version !== undefined && keyVersion !== version) continue;\n matches.push({ key, version: keyVersion ?? '' });\n }\n\n return matches.toSorted((a, b) => comparePluginVersions(b.version, a.version)).map((match) => match.key);\n}\n\n/**\n * PluginRegistryContext provider that keeps track of all available plugins and provides an API for getting them or\n * querying the metadata about them.\n */\nexport function PluginRegistry(props: PluginRegistryProps): ReactElement {\n const {\n pluginLoader: { getInstalledPlugins, importPluginModule },\n children,\n defaultPluginKinds,\n } = props;\n\n const getPluginIndexes = usePluginIndexes(getInstalledPlugins);\n\n // De-dupe calls to import plugin modules\n const importCache = useRef(new Map<PluginModuleResource, Promise<unknown>>());\n\n // Do useEvent here since this accesses the importPluginModule prop and we want a stable reference to it for the\n // callback below\n const loadPluginModule = useEvent((resource: PluginModuleResource) => {\n let request = importCache.current.get(resource);\n if (request === undefined) {\n request = importPluginModule(resource);\n importCache.current.set(resource, request);\n\n // Remove failed requests from the cache so they can potentially be retried\n request.catch(() => importCache.current.delete(resource));\n }\n return request;\n });\n\n const getPlugin = useCallback(\n async <T extends PluginType>(compoundKeyObj: PluginCompoundKey<T>): Promise<PluginImplementation<T>> => {\n const pluginIndexes = await getPluginIndexes();\n const { kind, name, version, registry } = compoundKeyObj;\n const allKeys = pluginIndexes.pluginResourcesByNameKindRegistryVersion.keys();\n\n let candidateKeys: string[];\n if (version || registry) {\n // A pin is an exact constraint: only the plugins matching every supplied field are acceptable, and we never\n // silently fall back to another version or another registry.\n candidateKeys = findMatchingPluginKeys(allKeys, compoundKeyObj);\n } else {\n candidateKeys = resolvePluginKeys(allKeys, compoundKeyObj);\n // Nothing pinned: a plugin served by a local dev server (`percli plugin start`) wins over installed archives,\n // whatever their versions. Otherwise a dev plugin whose package version is lower than an installed archive would\n // never be used, which defeats the purpose of running it in dev.\n const devKey = findDevPluginKey(pluginIndexes.devPluginKeys, kind, name);\n if (devKey) {\n candidateKeys = [devKey, ...candidateKeys.filter((key) => key !== devKey)];\n }\n }\n\n for (const resourceKey of candidateKeys) {\n const resource = pluginIndexes.pluginResourcesByNameKindRegistryVersion.get(resourceKey);\n if (!resource) continue;\n\n const pluginModule = (await loadPluginModule(resource)) as Record<string, Plugin<UnknownSpec>>;\n // Try to get the plugin implementation from the module using the versioned export first\n const plugin = pluginModule?.[resourceKey];\n if (plugin) return plugin as PluginImplementation<T>;\n // If the plugin module doesn't have a versioned export, fallback to the plugin name\n const versionlessPlugin = pluginModule?.[name];\n if (versionlessPlugin) return versionlessPlugin as PluginImplementation<T>;\n }\n\n const pins = [\n version ? `version '${version}'` : undefined,\n registry ? `registry '${registry}'` : undefined,\n ].filter((pin) => pin !== undefined);\n throw new Error(\n pins.length > 0\n ? `A ${name} plugin for kind '${kind}' with ${pins.join(' and ')} is not installed`\n : `A ${name} plugin for kind '${kind}' is not installed`,\n );\n },\n [getPluginIndexes, loadPluginModule],\n );\n\n const listPluginMetadata = useCallback(\n async (pluginTypes?: PluginType[]) => {\n const pluginIndexes = await getPluginIndexes();\n if (pluginTypes === undefined) {\n // No filter: return the metadata of every installed plugin, whatever its type.\n return [...pluginIndexes.pluginMetadataByKind.values()].flat();\n }\n return pluginTypes.flatMap((type) => pluginIndexes.pluginMetadataByKind.get(type) ?? []);\n },\n [getPluginIndexes],\n );\n\n // Create the registry's context value and render\n const context = useMemo(\n () => ({ getPlugin, listPluginMetadata, defaultPluginKinds }),\n [getPlugin, listPluginMetadata, defaultPluginKinds],\n );\n return <PluginRegistryContext.Provider value={context}>{children}</PluginRegistryContext.Provider>;\n}\n"],"names":["useRef","useCallback","useMemo","PluginRegistryContext","comparePluginVersions","useEvent","resolvePluginKeys","usePluginIndexes","findDevPluginKey","devPluginKeys","kind","name","prefix","key","startsWith","undefined","findMatchingPluginKeys","allKeys","query","registry","version","matches","parts","split","length","keyRegistry","keyVersion","push","toSorted","a","b","map","match","PluginRegistry","props","pluginLoader","getInstalledPlugins","importPluginModule","children","defaultPluginKinds","getPluginIndexes","importCache","Map","loadPluginModule","resource","request","current","get","set","catch","delete","getPlugin","compoundKeyObj","pluginIndexes","pluginResourcesByNameKindRegistryVersion","keys","candidateKeys","devKey","filter","resourceKey","pluginModule","plugin","versionlessPlugin","pins","pin","Error","join","listPluginMetadata","pluginTypes","pluginMetadataByKind","values","flat","flatMap","type","context","Provider","value"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAIjC,SAASA,MAAM,EAAEC,WAAW,EAAEC,OAAO,QAAQ,QAAQ;AAUrD,SAASC,qBAAqB,QAAQ,yBAAgB;AACtD,SAASC,qBAAqB,EAAEC,QAAQ,QAAQ,uBAAc;AAC9D,SAASC,iBAAiB,QAAQ,6BAA0B;AAE5D,SAASC,gBAAgB,QAAQ,sBAAmB;AAQpD;;;CAGC,GACD,SAASC,iBAAiBC,aAA0B,EAAEC,IAAY,EAAEC,IAAY;IAC9E,MAAMC,SAAS,GAAGF,KAAK,CAAC,EAAEC,KAAK,CAAC,CAAC;IACjC,KAAK,MAAME,OAAOJ,cAAe;QAC/B,IAAII,IAAIC,UAAU,CAACF,SAAS;YAC1B,OAAOC;QACT;IACF;IACA,OAAOE;AACT;AAEA;;;;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AK,OAAO,EAAEqD,KAAKG,IAAI,CAAC,SAAS,iBAAiB,CAAC,GACjF,CAAC,EAAE,EAAEvD,KAAK,kBAAkB,EAAED,KAAK,kBAAkB,CAAC;IAE9D,GACA;QAAC8B;QAAkBG;KAAiB;IAGtC,MAAMwB,qBAAqBlE,YACzB,OAAOmE;QACL,MAAMf,gBAAgB,MAAMb;QAC5B,IAAI4B,gBAAgBrD,WAAW;YAC7B,+EAA+E;YAC/E,OAAO;mBAAIsC,cAAcgB,oBAAoB,CAACC,MAAM;aAAG,CAACC,IAAI;QAC9D;QACA,OAAOH,YAAYI,OAAO,CAAC,CAACC,OAASpB,cAAcgB,oBAAoB,CAACtB,GAAG,CAAC0B,SAAS,EAAE;IACzF,GACA;QAACjC;KAAiB;IAGpB,iDAAiD;IACjD,MAAMkC,UAAUxE,QACd,IAAO,CAAA;YAAEiD;YAAWgB;YAAoB5B;QAAmB,CAAA,GAC3D;QAACY;QAAWgB;QAAoB5B;KAAmB;IAErD,qBAAO,KAACpC,sBAAsBwE,QAAQ;QAACC,OAAOF;kBAAUpC;;AAC1D"}
|
|
1
|
+
{"version":3,"sources":["../../../src/components/PluginRegistry/PluginRegistry.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { UnknownSpec } from '@perses-dev/spec';\nimport type { ReactNode, ReactElement } from 'react';\nimport { useRef, useCallback, useMemo } from 'react';\n\nimport type {\n PluginModuleResource,\n PluginType,\n PluginImplementation,\n Plugin,\n PluginLoader,\n DefaultPluginKinds,\n} from '../../model';\nimport { PluginRegistryContext } from '../../runtime';\nimport { comparePluginVersions, useEvent } from '../../utils';\nimport { resolvePluginKeys } from './getPluginSearchHelper';\nimport type { PluginCompoundKey } from './plugin-indexes';\nimport { usePluginIndexes } from './plugin-indexes';\n\nexport interface PluginRegistryProps {\n pluginLoader: PluginLoader;\n defaultPluginKinds?: DefaultPluginKinds;\n children?: ReactNode;\n}\n\n/**\n * Returns the indexed key of a plugin served by a local dev server for the given plugin type and kind, if any.\n * Keys are `${kind}:${name}:${registry}:${version}`, so we match on the `kind:name:` prefix.\n */\nfunction findDevPluginKey(devPluginKeys: Set<string>, kind: string, name: string): string | undefined {\n const prefix = `${kind}:${name}:`;\n for (const key of devPluginKeys) {\n if (key.startsWith(prefix)) {\n return key;\n }\n }\n return undefined;\n}\n\n/**\n * Returns the indexed keys (`${kind}:${name}:${registry}:${version}`) matching *every* field supplied in the query.\n * `kind` and `name` are always compared; `registry` and `version` are only compared when they are set, so a\n * version-only pin matches whatever registry the plugin happens to be installed under, and a registry-only pin never\n * leaks into another registry. Results are ordered from the newest version to the oldest.\n */\nfunction findMatchingPluginKeys<T extends PluginType>(\n allKeys: Iterable<string>,\n query: PluginCompoundKey<T>,\n): string[] {\n const { kind, name, registry, version } = query;\n const prefix = `${kind}:${name}:`;\n const matches: Array<{ key: string; version: string }> = [];\n\n for (const key of allKeys) {\n if (!key.startsWith(prefix)) continue;\n const parts = key.split(':');\n if (parts.length !== 4) continue;\n const [, , keyRegistry, keyVersion] = parts;\n if (registry !== undefined && keyRegistry !== registry) continue;\n if (version !== undefined && keyVersion !== version) continue;\n matches.push({ key, version: keyVersion ?? '' });\n }\n\n return matches.toSorted((a, b) => comparePluginVersions(b.version, a.version)).map((match) => match.key);\n}\n\n/**\n * PluginRegistryContext provider that keeps track of all available plugins and provides an API for getting them or\n * querying the metadata about them.\n */\nexport function PluginRegistry(props: PluginRegistryProps): ReactElement {\n const {\n pluginLoader: { getInstalledPlugins, importPluginModule, baseURL: pluginsBaseURL },\n children,\n defaultPluginKinds,\n } = props;\n\n const getPluginIndexes = usePluginIndexes(getInstalledPlugins);\n\n // De-dupe calls to import plugin modules\n const importCache = useRef(new Map<PluginModuleResource, Promise<unknown>>());\n\n // Do useEvent here since this accesses the importPluginModule prop and we want a stable reference to it for the\n // callback below\n const loadPluginModule = useEvent((resource: PluginModuleResource) => {\n let request = importCache.current.get(resource);\n if (request === undefined) {\n request = importPluginModule(resource);\n importCache.current.set(resource, request);\n\n // Remove failed requests from the cache so they can potentially be retried\n request.catch(() => importCache.current.delete(resource));\n }\n return request;\n });\n\n const getPlugin = useCallback(\n async <T extends PluginType>(compoundKeyObj: PluginCompoundKey<T>): Promise<PluginImplementation<T>> => {\n const pluginIndexes = await getPluginIndexes();\n const { kind, name, version, registry } = compoundKeyObj;\n const allKeys = pluginIndexes.pluginResourcesByNameKindRegistryVersion.keys();\n\n let candidateKeys: string[];\n if (version || registry) {\n // A pin is an exact constraint: only the plugins matching every supplied field are acceptable, and we never\n // silently fall back to another version or another registry.\n candidateKeys = findMatchingPluginKeys(allKeys, compoundKeyObj);\n } else {\n candidateKeys = resolvePluginKeys(allKeys, compoundKeyObj);\n // Nothing pinned: a plugin served by a local dev server (`percli plugin start`) wins over installed archives,\n // whatever their versions. Otherwise a dev plugin whose package version is lower than an installed archive would\n // never be used, which defeats the purpose of running it in dev.\n const devKey = findDevPluginKey(pluginIndexes.devPluginKeys, kind, name);\n if (devKey) {\n candidateKeys = [devKey, ...candidateKeys.filter((key) => key !== devKey)];\n }\n }\n\n for (const resourceKey of candidateKeys) {\n const resource = pluginIndexes.pluginResourcesByNameKindRegistryVersion.get(resourceKey);\n if (!resource) continue;\n\n const pluginModule = (await loadPluginModule(resource)) as Record<string, Plugin<UnknownSpec>>;\n // Try to get the plugin implementation from the module using the versioned export first\n const plugin = pluginModule?.[resourceKey];\n if (plugin) return plugin as PluginImplementation<T>;\n // If the plugin module doesn't have a versioned export, fallback to the plugin name\n const versionlessPlugin = pluginModule?.[name];\n if (versionlessPlugin) return versionlessPlugin as PluginImplementation<T>;\n }\n\n const pins = [\n version ? `version '${version}'` : undefined,\n registry ? `registry '${registry}'` : undefined,\n ].filter((pin) => pin !== undefined);\n throw new Error(\n pins.length > 0\n ? `A ${name} plugin for kind '${kind}' with ${pins.join(' and ')} is not installed`\n : `A ${name} plugin for kind '${kind}' is not installed`,\n );\n },\n [getPluginIndexes, loadPluginModule],\n );\n\n const listPluginMetadata = useCallback(\n async (pluginTypes?: PluginType[]) => {\n const pluginIndexes = await getPluginIndexes();\n if (pluginTypes === undefined) {\n // No filter: return the metadata of every installed plugin, whatever its type.\n return [...pluginIndexes.pluginMetadataByKind.values()].flat();\n }\n return pluginTypes.flatMap((type) => pluginIndexes.pluginMetadataByKind.get(type) ?? []);\n },\n [getPluginIndexes],\n );\n\n // Create the registry's context value and render\n const context = useMemo(\n () => ({ getPlugin, listPluginMetadata, defaultPluginKinds, pluginsBaseURL }),\n [getPlugin, listPluginMetadata, defaultPluginKinds, pluginsBaseURL],\n );\n return <PluginRegistryContext.Provider value={context}>{children}</PluginRegistryContext.Provider>;\n}\n"],"names":["useRef","useCallback","useMemo","PluginRegistryContext","comparePluginVersions","useEvent","resolvePluginKeys","usePluginIndexes","findDevPluginKey","devPluginKeys","kind","name","prefix","key","startsWith","undefined","findMatchingPluginKeys","allKeys","query","registry","version","matches","parts","split","length","keyRegistry","keyVersion","push","toSorted","a","b","map","match","PluginRegistry","props","pluginLoader","getInstalledPlugins","importPluginModule","baseURL","pluginsBaseURL","children","defaultPluginKinds","getPluginIndexes","importCache","Map","loadPluginModule","resource","request","current","get","set","catch","delete","getPlugin","compoundKeyObj","pluginIndexes","pluginResourcesByNameKindRegistryVersion","keys","candidateKeys","devKey","filter","resourceKey","pluginModule","plugin","versionlessPlugin","pins","pin","Error","join","listPluginMetadata","pluginTypes","pluginMetadataByKind","values","flat","flatMap","type","context","Provider","value"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C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AAsB0E,QAAQ;QAACC,OAAOF;kBAAUpC;;AAC1D"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { fetch, fetchJson } from '@perses-dev/client';
|
|
1
2
|
import type { BuiltinVariableDefinition, UnknownSpec } from '@perses-dev/spec';
|
|
2
3
|
import type { OptionsEditorProps, Plugin } from './plugin-base';
|
|
3
4
|
/**
|
|
@@ -10,6 +11,8 @@ export interface DatasourcePlugin<Spec = UnknownSpec, Client = unknown, OptionsE
|
|
|
10
11
|
}
|
|
11
12
|
export interface DatasourceClientOptions {
|
|
12
13
|
proxyUrl?: string;
|
|
14
|
+
fetch?: typeof fetch;
|
|
15
|
+
fetchJson?: typeof fetchJson;
|
|
13
16
|
}
|
|
14
17
|
/**
|
|
15
18
|
* Common properties for all clients
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"datasource.d.ts","sourceRoot":"","sources":["../../src/model/datasource.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,yBAAyB,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAEhE;;GAEG;AACH,MAAM,WAAW,gBAAgB,CAC/B,IAAI,GAAG,WAAW,EAClB,MAAM,GAAG,OAAO,EAChB,sBAAsB,GAAG,qBAAqB,CAAC,IAAI,CAAC,CACpD,SAAQ,MAAM,CAAC,IAAI,EAAE,sBAAsB,CAAC;IAC5C,YAAY,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,uBAAuB,KAAK,MAAM,CAAC;IAEvE,6BAA6B,CAAC,EAAE,MAAM,yBAAyB,EAAE,CAAC;IAClE,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,EAAE,MAAM,CAAC;
|
|
1
|
+
{"version":3,"file":"datasource.d.ts","sourceRoot":"","sources":["../../src/model/datasource.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,KAAK,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,KAAK,EAAE,yBAAyB,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/E,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AAEhE;;GAEG;AACH,MAAM,WAAW,gBAAgB,CAC/B,IAAI,GAAG,WAAW,EAClB,MAAM,GAAG,OAAO,EAChB,sBAAsB,GAAG,qBAAqB,CAAC,IAAI,CAAC,CACpD,SAAQ,MAAM,CAAC,IAAI,EAAE,sBAAsB,CAAC;IAC5C,YAAY,EAAE,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,EAAE,uBAAuB,KAAK,MAAM,CAAC;IAEvE,6BAA6B,CAAC,EAAE,MAAM,yBAAyB,EAAE,CAAC;IAClE,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;IACrB,SAAS,CAAC,EAAE,OAAO,SAAS,CAAC;CAC9B;AAED;;GAEG;AACH,MAAM,WAAW,gBAAgB;IAE/B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;CACtC;AAED;;GAEG;AACH,MAAM,WAAW,qBAAqB,CAAC,IAAI,CAAE,SAAQ,kBAAkB,CAAC,IAAI,CAAC;IAC3E,cAAc,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CACtC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/model/datasource.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { BuiltinVariableDefinition, UnknownSpec } from '@perses-dev/spec';\n\nimport type { OptionsEditorProps, Plugin } from './plugin-base';\n\n/**\n * Plugin that defines options for an external system that Perses talks to for data.\n */\nexport interface DatasourcePlugin<\n Spec = UnknownSpec,\n Client = unknown,\n OptionsEditorPropsType = DatasourceEditorProps<Spec>,\n> extends Plugin<Spec, OptionsEditorPropsType> {\n createClient: (spec: Spec, options: DatasourceClientOptions) => Client;\n // Provide builtin variable definitions available on the datasource. Optional\n getBuiltinVariableDefinitions?: () => BuiltinVariableDefinition[];\n healthCheckPath?: string;\n}\n\nexport interface DatasourceClientOptions {\n proxyUrl?: string;\n}\n\n/**\n * Common properties for all clients\n */\nexport interface DatasourceClient {\n // TODO: set kind and define healthCheck function\n kind?: string;\n healthCheck?: () => Promise<boolean>;\n}\n\n/**\n * Common props passed to datasource options editor components.\n */\nexport interface DatasourceEditorProps<Spec> extends OptionsEditorProps<Spec> {\n testConnection?: () => Promise<void>;\n}\n"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;
|
|
1
|
+
{"version":3,"sources":["../../src/model/datasource.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { fetch, fetchJson } from '@perses-dev/client';\nimport type { BuiltinVariableDefinition, UnknownSpec } from '@perses-dev/spec';\n\nimport type { OptionsEditorProps, Plugin } from './plugin-base';\n\n/**\n * Plugin that defines options for an external system that Perses talks to for data.\n */\nexport interface DatasourcePlugin<\n Spec = UnknownSpec,\n Client = unknown,\n OptionsEditorPropsType = DatasourceEditorProps<Spec>,\n> extends Plugin<Spec, OptionsEditorPropsType> {\n createClient: (spec: Spec, options: DatasourceClientOptions) => Client;\n // Provide builtin variable definitions available on the datasource. Optional\n getBuiltinVariableDefinitions?: () => BuiltinVariableDefinition[];\n healthCheckPath?: string;\n}\n\nexport interface DatasourceClientOptions {\n proxyUrl?: string;\n fetch?: typeof fetch;\n fetchJson?: typeof fetchJson;\n}\n\n/**\n * Common properties for all clients\n */\nexport interface DatasourceClient {\n // TODO: set kind and define healthCheck function\n kind?: string;\n healthCheck?: () => Promise<boolean>;\n}\n\n/**\n * Common props passed to datasource options editor components.\n */\nexport interface DatasourceEditorProps<Spec> extends OptionsEditorProps<Spec> {\n testConnection?: () => Promise<void>;\n}\n"],"names":[],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAoCjC;;CAEC,GACD,WAEC"}
|
|
@@ -6,6 +6,7 @@ import type { PluginModuleResource } from './plugins';
|
|
|
6
6
|
export interface PluginLoader {
|
|
7
7
|
getInstalledPlugins: () => Promise<PluginModuleResource[]>;
|
|
8
8
|
importPluginModule: (resource: PluginModuleResource) => Promise<unknown>;
|
|
9
|
+
baseURL?: string;
|
|
9
10
|
}
|
|
10
11
|
/**
|
|
11
12
|
* The dynamic import for a single plugin resource.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin-loading.d.ts","sourceRoot":"","sources":["../../src/model/plugin-loading.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAGtD;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,mBAAmB,EAAE,MAAM,OAAO,CAAC,oBAAoB,EAAE,CAAC,CAAC;IAC3D,kBAAkB,EAAE,CAAC,QAAQ,EAAE,oBAAoB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"plugin-loading.d.ts","sourceRoot":"","sources":["../../src/model/plugin-loading.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,WAAW,CAAC;AAGtD;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,mBAAmB,EAAE,MAAM,OAAO,CAAC,oBAAoB,EAAE,CAAC,CAAC;IAC3D,kBAAkB,EAAE,CAAC,QAAQ,EAAE,oBAAoB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IACzE,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,QAAQ,EAAE,oBAAoB,CAAC;IAC/B,YAAY,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;CAClC;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,mBAAmB,EAAE,GAAG,YAAY,CA8BtF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/model/plugin-loading.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { PluginModuleResource } from './plugins';\nimport { getPluginModuleCompoundKey } from './plugins';\n\n/**\n * A component capable of loading the resource/metadata for all available plugins, then loading individual plugins for\n * those resources on-demand.\n */\nexport interface PluginLoader {\n getInstalledPlugins: () => Promise<PluginModuleResource[]>;\n importPluginModule: (resource: PluginModuleResource) => Promise<unknown>;\n}\n\n/**\n * The dynamic import for a single plugin resource.\n */\nexport interface DynamicImportPlugin {\n resource: PluginModuleResource;\n importPlugin(): Promise<unknown>;\n}\n\n/**\n * A PluginLoader for the common pattern in Perses where we eagerly import a plugin's resource file, and then lazy load\n * the plugin itself via a dynamic `import()` statement.\n */\nexport function dynamicImportPluginLoader(plugins: DynamicImportPlugin[]): PluginLoader {\n const importMap: Map<string, { resource: PluginModuleResource; importPlugin: DynamicImportPlugin['importPlugin'] }> =\n new Map();\n for (const p of plugins) {\n const {\n resource,\n resource: {\n kind,\n metadata: { name, registry, version },\n },\n importPlugin,\n } = p;\n importMap.set(getPluginModuleCompoundKey({ kind, name, registry, version }), { resource, importPlugin });\n }\n return {\n async getInstalledPlugins(): Promise<PluginModuleResource[]> {\n return Promise.resolve(Array.from(importMap.values()).map((v) => v.resource));\n },\n importPluginModule(resource): Promise<unknown> {\n const {\n kind,\n metadata: { name, version, registry },\n } = resource;\n const { importPlugin } = importMap.get(getPluginModuleCompoundKey({ kind, name, registry, version })) || {};\n if (importPlugin === undefined) {\n throw new Error('Plugin not found');\n }\n return importPlugin();\n },\n };\n}\n"],"names":["getPluginModuleCompoundKey","dynamicImportPluginLoader","plugins","importMap","Map","p","resource","kind","metadata","name","registry","version","importPlugin","set","getInstalledPlugins","Promise","resolve","Array","from","values","map","v","importPluginModule","get","undefined","Error"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,SAASA,0BAA0B,QAAQ,eAAY;
|
|
1
|
+
{"version":3,"sources":["../../src/model/plugin-loading.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { PluginModuleResource } from './plugins';\nimport { getPluginModuleCompoundKey } from './plugins';\n\n/**\n * A component capable of loading the resource/metadata for all available plugins, then loading individual plugins for\n * those resources on-demand.\n */\nexport interface PluginLoader {\n getInstalledPlugins: () => Promise<PluginModuleResource[]>;\n importPluginModule: (resource: PluginModuleResource) => Promise<unknown>;\n baseURL?: string;\n}\n\n/**\n * The dynamic import for a single plugin resource.\n */\nexport interface DynamicImportPlugin {\n resource: PluginModuleResource;\n importPlugin(): Promise<unknown>;\n}\n\n/**\n * A PluginLoader for the common pattern in Perses where we eagerly import a plugin's resource file, and then lazy load\n * the plugin itself via a dynamic `import()` statement.\n */\nexport function dynamicImportPluginLoader(plugins: DynamicImportPlugin[]): PluginLoader {\n const importMap: Map<string, { resource: PluginModuleResource; importPlugin: DynamicImportPlugin['importPlugin'] }> =\n new Map();\n for (const p of plugins) {\n const {\n resource,\n resource: {\n kind,\n metadata: { name, registry, version },\n },\n importPlugin,\n } = p;\n importMap.set(getPluginModuleCompoundKey({ kind, name, registry, version }), { resource, importPlugin });\n }\n return {\n async getInstalledPlugins(): Promise<PluginModuleResource[]> {\n return Promise.resolve(Array.from(importMap.values()).map((v) => v.resource));\n },\n importPluginModule(resource): Promise<unknown> {\n const {\n kind,\n metadata: { name, version, registry },\n } = resource;\n const { importPlugin } = importMap.get(getPluginModuleCompoundKey({ kind, name, registry, version })) || {};\n if (importPlugin === undefined) {\n throw new Error('Plugin not found');\n }\n return importPlugin();\n },\n };\n}\n"],"names":["getPluginModuleCompoundKey","dynamicImportPluginLoader","plugins","importMap","Map","p","resource","kind","metadata","name","registry","version","importPlugin","set","getInstalledPlugins","Promise","resolve","Array","from","values","map","v","importPluginModule","get","undefined","Error"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAGjC,SAASA,0BAA0B,QAAQ,eAAY;AAoBvD;;;CAGC,GACD,OAAO,SAASC,0BAA0BC,OAA8B;IACtE,MAAMC,YACJ,IAAIC;IACN,KAAK,MAAMC,KAAKH,QAAS;QACvB,MAAM,EACJI,QAAQ,EACRA,UAAU,EACRC,IAAI,EACJC,UAAU,EAAEC,IAAI,EAAEC,QAAQ,EAAEC,OAAO,EAAE,EACtC,EACDC,YAAY,EACb,GAAGP;QACJF,UAAUU,GAAG,CAACb,2BAA2B;YAAEO;YAAME;YAAMC;YAAUC;QAAQ,IAAI;YAAEL;YAAUM;QAAa;IACxG;IACA,OAAO;QACL,MAAME;YACJ,OAAOC,QAAQC,OAAO,CAACC,MAAMC,IAAI,CAACf,UAAUgB,MAAM,IAAIC,GAAG,CAAC,CAACC,IAAMA,EAAEf,QAAQ;QAC7E;QACAgB,oBAAmBhB,QAAQ;YACzB,MAAM,EACJC,IAAI,EACJC,UAAU,EAAEC,IAAI,EAAEE,OAAO,EAAED,QAAQ,EAAE,EACtC,GAAGJ;YACJ,MAAM,EAAEM,YAAY,EAAE,GAAGT,UAAUoB,GAAG,CAACvB,2BAA2B;gBAAEO;gBAAME;gBAAMC;gBAAUC;YAAQ,OAAO,CAAC;YAC1G,IAAIC,iBAAiBY,WAAW;gBAC9B,MAAM,IAAIC,MAAM;YAClB;YACA,OAAOb;QACT;IACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PluginRuntime.d.ts","sourceRoot":"","sources":["../../src/remote/PluginRuntime.tsx"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AAQ5E,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"PluginRuntime.d.ts","sourceRoot":"","sources":["../../src/remote/PluginRuntime.tsx"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qCAAqC,CAAC;AAQ5E,OAAO,KAAK,EAAE,YAAY,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAa7E,MAAM,WAAW,iBAAiB;IAChC,kBAAkB,EAAE,OAAO,CAAC;IAC5B,oBAAoB,EAAE,OAAO,CAAC;IAC9B,wBAAwB,EAAE,OAAO,CAAC;IAClC,2BAA2B,EAAE,OAAO,CAAC;IACrC,qBAAqB,EAAE,OAAO,CAAC;IAC/B,wBAAwB,EAAE,OAAO,CAAC;CACnC;AAUD,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,iBAAiB,GAAG,IAAI,CAI1E;AA+ND,eAAO,MAAM,UAAU,WAAkB;IACvC,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,KAAG,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAOpC,CAAC;AAEF,wBAAgB,gBAAgB,CAAC,EAAE,MAAM,EAAE,EAAE;IAAE,MAAM,EAAE,YAAY,CAAA;CAAE,GAAG;IACtE,aAAa,EAAE,gBAAgB,CAAC;IAChC,UAAU,EAAE,MAAM,OAAO,CAAC,kBAAkB,GAAG,IAAI,CAAC,CAAC;CACtD,CAQA"}
|
|
@@ -19,6 +19,7 @@ import ReactDOM from "react-dom";
|
|
|
19
19
|
import * as ReactHookForm from "react-hook-form";
|
|
20
20
|
import * as ReactRouterDOM from "react-router-dom";
|
|
21
21
|
let instance = null;
|
|
22
|
+
const DEFAULT_PLUGINS_ASSETS_BASE_URL = '/plugins';
|
|
22
23
|
function createSharedModuleLoader(loadModule) {
|
|
23
24
|
return async ()=>{
|
|
24
25
|
const module = await loadModule();
|
|
@@ -104,51 +105,51 @@ const getPluginRuntime = ()=>{
|
|
|
104
105
|
}
|
|
105
106
|
},
|
|
106
107
|
'@perses-dev/spec': {
|
|
107
|
-
version: '0.3.0-beta.
|
|
108
|
+
version: '0.3.0-beta.10',
|
|
108
109
|
lib: ()=>getHostSharedModule('@perses-dev/spec'),
|
|
109
110
|
shareConfig: {
|
|
110
111
|
singleton: true,
|
|
111
|
-
requiredVersion: '^0.3.0-beta.
|
|
112
|
+
requiredVersion: '^0.3.0-beta.10'
|
|
112
113
|
}
|
|
113
114
|
},
|
|
114
115
|
'@perses-dev/client': {
|
|
115
|
-
version: '0.55.0-beta.
|
|
116
|
+
version: '0.55.0-beta.14',
|
|
116
117
|
lib: ()=>getHostSharedModule('@perses-dev/client'),
|
|
117
118
|
shareConfig: {
|
|
118
119
|
singleton: true,
|
|
119
|
-
requiredVersion: '^0.55.0-beta.
|
|
120
|
+
requiredVersion: '^0.55.0-beta.14'
|
|
120
121
|
}
|
|
121
122
|
},
|
|
122
123
|
'@perses-dev/components': {
|
|
123
|
-
version: '0.55.0-beta.
|
|
124
|
+
version: '0.55.0-beta.14',
|
|
124
125
|
lib: ()=>getHostSharedModule('@perses-dev/components'),
|
|
125
126
|
shareConfig: {
|
|
126
127
|
singleton: true,
|
|
127
|
-
requiredVersion: '^0.55.0-beta.
|
|
128
|
+
requiredVersion: '^0.55.0-beta.14'
|
|
128
129
|
}
|
|
129
130
|
},
|
|
130
131
|
'@perses-dev/plugin-system': {
|
|
131
|
-
version: '0.55.0-beta.
|
|
132
|
+
version: '0.55.0-beta.14',
|
|
132
133
|
lib: ()=>getHostSharedModule('@perses-dev/plugin-system'),
|
|
133
134
|
shareConfig: {
|
|
134
135
|
singleton: true,
|
|
135
|
-
requiredVersion: '^0.55.0-beta.
|
|
136
|
+
requiredVersion: '^0.55.0-beta.14'
|
|
136
137
|
}
|
|
137
138
|
},
|
|
138
139
|
'@perses-dev/explore': {
|
|
139
|
-
version: '0.55.0-beta.
|
|
140
|
+
version: '0.55.0-beta.14',
|
|
140
141
|
lib: ()=>getHostSharedModule('@perses-dev/explore'),
|
|
141
142
|
shareConfig: {
|
|
142
143
|
singleton: true,
|
|
143
|
-
requiredVersion: '^0.55.0-beta.
|
|
144
|
+
requiredVersion: '^0.55.0-beta.14'
|
|
144
145
|
}
|
|
145
146
|
},
|
|
146
147
|
'@perses-dev/dashboards': {
|
|
147
|
-
version: '0.55.0-beta.
|
|
148
|
+
version: '0.55.0-beta.14',
|
|
148
149
|
lib: ()=>getHostSharedModule('@perses-dev/dashboards'),
|
|
149
150
|
shareConfig: {
|
|
150
151
|
singleton: true,
|
|
151
|
-
requiredVersion: '^0.55.0-beta.
|
|
152
|
+
requiredVersion: '^0.55.0-beta.14'
|
|
152
153
|
}
|
|
153
154
|
},
|
|
154
155
|
// Below are the shared modules that are used by the plugins and are loaded asynchronously on demand using get rather than lib.
|
|
@@ -237,7 +238,7 @@ const registerRemote = (name, registry, version, baseURL)=>{
|
|
|
237
238
|
version,
|
|
238
239
|
registry
|
|
239
240
|
].filter(Boolean).join('~');
|
|
240
|
-
const prefix = baseURL
|
|
241
|
+
const prefix = baseURL ?? DEFAULT_PLUGINS_ASSETS_BASE_URL;
|
|
241
242
|
const remoteEntryURL = `${prefix}/${nameVersionRegistry}/mf-manifest.json`;
|
|
242
243
|
pluginRuntime.registerRemotes([
|
|
243
244
|
{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/remote/PluginRuntime.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport * as EmotionReact from '@emotion/react';\nimport * as EmotionStyled from '@emotion/styled';\nimport type { ModuleFederation } from '@module-federation/enhanced/runtime';\nimport { createInstance } from '@module-federation/enhanced/runtime';\nimport * as ReactQuery from '@tanstack/react-query';\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport * as ReactHookForm from 'react-hook-form';\nimport * as ReactRouterDOM from 'react-router-dom';\n\nimport type { PersesPlugin, RemotePluginModule } from './PersesPlugin.types';\n\nlet instance: ModuleFederation | null = null;\n\nfunction createSharedModuleLoader<TModule>(loadModule: () => Promise<TModule>): () => Promise<() => TModule> {\n return async () => {\n const module = await loadModule();\n return () => module;\n };\n}\n\nexport interface HostSharedModules {\n '@perses-dev/spec': unknown;\n '@perses-dev/client': unknown;\n '@perses-dev/components': unknown;\n '@perses-dev/plugin-system': unknown;\n '@perses-dev/explore': unknown;\n '@perses-dev/dashboards': unknown;\n}\n\ntype HostSharedModuleName = keyof HostSharedModules;\n\nconst hostSharedModules = new Map<HostSharedModuleName, unknown>();\n\n/*\n * Shared singletons must be provided to Module Federation *synchronously* (via `lib`) so the host's\n * copy wins singleton negotiation to avoid loader deadlocks or multiple instances.\n */\nexport function registerHostSharedModules(modules: HostSharedModules): void {\n for (const [name, module] of Object.entries(modules) as Array<[HostSharedModuleName, unknown]>) {\n hostSharedModules.set(name, module);\n }\n}\n\nfunction getHostSharedModule(name: HostSharedModuleName): unknown {\n const module = hostSharedModules.get(name);\n if (!module) {\n throw new Error(\n `Shared module \"${name}\" was not registered before a plugin tried to consume it. ` +\n `Call registerHostSharedModules() during app bootstrap.`,\n );\n }\n return module;\n}\n\nconst getPluginRuntime = (): ModuleFederation => {\n if (instance === null) {\n const pluginRuntime = createInstance({\n name: '@perses/perses-ui-host',\n remotes: [], // all remotes are loaded dynamically\n shared: {\n react: {\n version: React.version,\n lib: () => React,\n shareConfig: {\n singleton: true,\n requiredVersion: `^${React.version}`,\n },\n },\n 'react-dom': {\n version: '18.3.1',\n lib: () => ReactDOM,\n shareConfig: {\n singleton: true,\n requiredVersion: `^18.3.1`,\n },\n },\n 'react-router-dom': {\n version: '6.30.4',\n lib: () => ReactRouterDOM,\n shareConfig: {\n singleton: true,\n requiredVersion: '^6.26.0',\n },\n },\n '@tanstack/react-query': {\n version: '4.44.0',\n lib: () => ReactQuery,\n shareConfig: {\n singleton: true,\n requiredVersion: '^4.39.1',\n },\n },\n 'react-hook-form': {\n version: '7.87.0',\n lib: () => ReactHookForm,\n shareConfig: {\n singleton: true,\n requiredVersion: '^7.87.0',\n },\n },\n '@emotion/react': {\n version: '11.14.0',\n lib: () => EmotionReact,\n shareConfig: {\n singleton: true,\n requiredVersion: '^11.11.3',\n },\n },\n '@emotion/styled': {\n version: '11.14.1',\n lib: () => EmotionStyled,\n shareConfig: {\n singleton: true,\n requiredVersion: '^11.11.0',\n },\n },\n '@perses-dev/spec': {\n version: '0.3.0-beta.8',\n lib: () => getHostSharedModule('@perses-dev/spec'),\n shareConfig: {\n singleton: true,\n requiredVersion: '^0.3.0-beta.8',\n },\n },\n '@perses-dev/client': {\n version: '0.55.0-beta.12',\n lib: () => getHostSharedModule('@perses-dev/client'),\n shareConfig: {\n singleton: true,\n requiredVersion: '^0.55.0-beta.12',\n },\n },\n '@perses-dev/components': {\n version: '0.55.0-beta.12',\n lib: () => getHostSharedModule('@perses-dev/components'),\n shareConfig: {\n singleton: true,\n requiredVersion: '^0.55.0-beta.12',\n },\n },\n '@perses-dev/plugin-system': {\n version: '0.55.0-beta.12',\n lib: () => getHostSharedModule('@perses-dev/plugin-system'),\n shareConfig: {\n singleton: true,\n requiredVersion: '^0.55.0-beta.12',\n },\n },\n '@perses-dev/explore': {\n version: '0.55.0-beta.12',\n lib: () => getHostSharedModule('@perses-dev/explore'),\n shareConfig: {\n singleton: true,\n requiredVersion: '^0.55.0-beta.12',\n },\n },\n '@perses-dev/dashboards': {\n version: '0.55.0-beta.12',\n lib: () => getHostSharedModule('@perses-dev/dashboards'),\n shareConfig: {\n singleton: true,\n requiredVersion: '^0.55.0-beta.12',\n },\n },\n // Below are the shared modules that are used by the plugins and are loaded asynchronously on demand using get rather than lib.\n // This is to avoid loading the modules if they are not used by the plugin.\n echarts: {\n version: '5.5.0',\n get: createSharedModuleLoader(() => import('echarts')),\n shareConfig: {\n singleton: true,\n requiredVersion: '^5.5.0',\n },\n },\n 'date-fns': {\n version: '4.2.1',\n get: createSharedModuleLoader(() => import('date-fns')),\n shareConfig: {\n singleton: true,\n requiredVersion: '^4.1.0',\n },\n },\n 'date-fns-tz': {\n version: '3.2.0',\n get: createSharedModuleLoader(() => import('date-fns-tz')),\n shareConfig: {\n singleton: true,\n requiredVersion: '^3.2.0',\n },\n },\n lodash: {\n version: '4.18.1',\n get: createSharedModuleLoader(() => import('lodash')),\n shareConfig: {\n singleton: true,\n requiredVersion: '^4.17.21',\n },\n },\n '@hookform/resolvers/zod': {\n version: '5.9.1',\n get: createSharedModuleLoader(() => import('@hookform/resolvers/zod')),\n shareConfig: {\n singleton: true,\n requiredVersion: '^5.9.1',\n },\n },\n 'use-resize-observer': {\n version: '9.1.0',\n get: createSharedModuleLoader(() => import('use-resize-observer')),\n shareConfig: {\n singleton: true,\n requiredVersion: '^9.1.0',\n },\n },\n 'mdi-material-ui': {\n version: '7.9.4',\n get: createSharedModuleLoader(() => import('mdi-material-ui')),\n shareConfig: {\n singleton: true,\n requiredVersion: '^7.4.0',\n },\n },\n immer: {\n version: '10.2.0',\n get: createSharedModuleLoader(() => import('immer')),\n shareConfig: {\n singleton: true,\n requiredVersion: '^10.1.1',\n },\n },\n },\n });\n\n instance = pluginRuntime;\n\n return instance;\n }\n return instance;\n};\n\nfunction getModuleFederationRemoteName(name: string, registry?: string, version?: string): string {\n return `${name}:${registry ?? ''}:${version ?? ''}`;\n}\n\nconst registerRemote = (name: string, registry?: string, version?: string, baseURL?: string): void => {\n const pluginRuntime = getPluginRuntime();\n const registryName = getModuleFederationRemoteName(name, registry, version);\n\n const existingRemote = pluginRuntime.options.remotes.find((remote) => remote.name === registryName);\n if (!existingRemote) {\n const nameVersionRegistry = [name, version, registry].filter(Boolean).join('~');\n const prefix = baseURL || '/plugins';\n const remoteEntryURL = `${prefix}/${nameVersionRegistry}/mf-manifest.json`;\n\n pluginRuntime.registerRemotes([\n {\n name: registryName,\n entry: remoteEntryURL,\n alias: registryName,\n },\n ]);\n }\n};\n\nexport const loadPlugin = async (target: {\n moduleName: string;\n pluginName: string;\n registry?: string;\n version?: string;\n baseURL?: string;\n}): Promise<RemotePluginModule | null> => {\n const { moduleName, pluginName, registry, version, baseURL } = target;\n registerRemote(moduleName, registry, version, baseURL);\n\n const pluginRuntime = getPluginRuntime();\n const registryName = getModuleFederationRemoteName(moduleName, registry, version);\n return pluginRuntime.loadRemote<RemotePluginModule>(`${registryName}/${pluginName}`);\n};\n\nexport function usePluginRuntime({ plugin }: { plugin: PersesPlugin }): {\n pluginRuntime: ModuleFederation;\n loadPlugin: () => Promise<RemotePluginModule | null>;\n} {\n return {\n pluginRuntime: getPluginRuntime(),\n loadPlugin: (): Promise<RemotePluginModule | null> => {\n const { moduleName, name: pluginName, registry, version, baseURL } = plugin;\n return loadPlugin({ moduleName, pluginName, registry, version, baseURL });\n },\n };\n}\n"],"names":["EmotionReact","EmotionStyled","createInstance","ReactQuery","React","ReactDOM","ReactHookForm","ReactRouterDOM","instance","createSharedModuleLoader","loadModule","module","hostSharedModules","Map","registerHostSharedModules","modules","name","Object","entries","set","getHostSharedModule","get","Error","getPluginRuntime","pluginRuntime","remotes","shared","react","version","lib","shareConfig","singleton","requiredVersion","echarts","lodash","immer","getModuleFederationRemoteName","registry","registerRemote","baseURL","registryName","existingRemote","options","find","remote","nameVersionRegistry","filter","Boolean","join","prefix","remoteEntryURL","registerRemotes","entry","alias","loadPlugin","target","moduleName","pluginName","loadRemote","usePluginRuntime","plugin"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,YAAYA,kBAAkB,iBAAiB;AAC/C,YAAYC,mBAAmB,kBAAkB;AAEjD,SAASC,cAAc,QAAQ,sCAAsC;AACrE,YAAYC,gBAAgB,wBAAwB;AACpD,OAAOC,WAAW,QAAQ;AAC1B,OAAOC,cAAc,YAAY;AACjC,YAAYC,mBAAmB,kBAAkB;AACjD,YAAYC,oBAAoB,mBAAmB;AAInD,IAAIC,WAAoC;AAExC,SAASC,yBAAkCC,UAAkC;IAC3E,OAAO;QACL,MAAMC,SAAS,MAAMD;QACrB,OAAO,IAAMC;IACf;AACF;AAaA,MAAMC,oBAAoB,IAAIC;AAE9B;;;CAGC,GACD,OAAO,SAASC,0BAA0BC,OAA0B;IAClE,KAAK,MAAM,CAACC,MAAML,OAAO,IAAIM,OAAOC,OAAO,CAACH,SAAoD;QAC9FH,kBAAkBO,GAAG,CAACH,MAAML;IAC9B;AACF;AAEA,SAASS,oBAAoBJ,IAA0B;IACrD,MAAML,SAASC,kBAAkBS,GAAG,CAACL;IACrC,IAAI,CAACL,QAAQ;QACX,MAAM,IAAIW,MACR,CAAC,eAAe,EAAEN,KAAK,0DAA0D,CAAC,GAChF,CAAC,sDAAsD,CAAC;IAE9D;IACA,OAAOL;AACT;AAEA,MAAMY,mBAAmB;IACvB,IAAIf,aAAa,MAAM;QACrB,MAAMgB,gBAAgBtB,eAAe;YACnCc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ACrF,EAAE;AAEF,OAAO,SAASE,iBAAiB,EAAEC,MAAM,EAA4B;IAInE,OAAO;QACLpC,eAAeD;QACf+B,YAAY;YACV,MAAM,EAAEE,UAAU,EAAExC,MAAMyC,UAAU,EAAEpB,QAAQ,EAAET,OAAO,EAAEW,OAAO,EAAE,GAAGqB;YACrE,OAAON,WAAW;gBAAEE;gBAAYC;gBAAYpB;gBAAUT;gBAASW;YAAQ;QACzE;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/remote/PluginRuntime.tsx"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport * as EmotionReact from '@emotion/react';\nimport * as EmotionStyled from '@emotion/styled';\nimport type { ModuleFederation } from '@module-federation/enhanced/runtime';\nimport { createInstance } from '@module-federation/enhanced/runtime';\nimport * as ReactQuery from '@tanstack/react-query';\nimport React from 'react';\nimport ReactDOM from 'react-dom';\nimport * as ReactHookForm from 'react-hook-form';\nimport * as ReactRouterDOM from 'react-router-dom';\n\nimport type { PersesPlugin, RemotePluginModule } from './PersesPlugin.types';\n\nlet instance: ModuleFederation | null = null;\n\nconst DEFAULT_PLUGINS_ASSETS_BASE_URL = '/plugins';\n\nfunction createSharedModuleLoader<TModule>(loadModule: () => Promise<TModule>): () => Promise<() => TModule> {\n return async () => {\n const module = await loadModule();\n return () => module;\n };\n}\n\nexport interface HostSharedModules {\n '@perses-dev/spec': unknown;\n '@perses-dev/client': unknown;\n '@perses-dev/components': unknown;\n '@perses-dev/plugin-system': unknown;\n '@perses-dev/explore': unknown;\n '@perses-dev/dashboards': unknown;\n}\n\ntype HostSharedModuleName = keyof HostSharedModules;\n\nconst hostSharedModules = new Map<HostSharedModuleName, unknown>();\n\n/*\n * Shared singletons must be provided to Module Federation *synchronously* (via `lib`) so the host's\n * copy wins singleton negotiation to avoid loader deadlocks or multiple instances.\n */\nexport function registerHostSharedModules(modules: HostSharedModules): void {\n for (const [name, module] of Object.entries(modules) as Array<[HostSharedModuleName, unknown]>) {\n hostSharedModules.set(name, module);\n }\n}\n\nfunction getHostSharedModule(name: HostSharedModuleName): unknown {\n const module = hostSharedModules.get(name);\n if (!module) {\n throw new Error(\n `Shared module \"${name}\" was not registered before a plugin tried to consume it. ` +\n `Call registerHostSharedModules() during app bootstrap.`,\n );\n }\n return module;\n}\n\nconst getPluginRuntime = (): ModuleFederation => {\n if (instance === null) {\n const pluginRuntime = createInstance({\n name: '@perses/perses-ui-host',\n remotes: [], // all remotes are loaded dynamically\n shared: {\n react: {\n version: React.version,\n lib: () => React,\n shareConfig: {\n singleton: true,\n requiredVersion: `^${React.version}`,\n },\n },\n 'react-dom': {\n version: '18.3.1',\n lib: () => ReactDOM,\n shareConfig: {\n singleton: true,\n requiredVersion: `^18.3.1`,\n },\n },\n 'react-router-dom': {\n version: '6.30.4',\n lib: () => ReactRouterDOM,\n shareConfig: {\n singleton: true,\n requiredVersion: '^6.26.0',\n },\n },\n '@tanstack/react-query': {\n version: '4.44.0',\n lib: () => ReactQuery,\n shareConfig: {\n singleton: true,\n requiredVersion: '^4.39.1',\n },\n },\n 'react-hook-form': {\n version: '7.87.0',\n lib: () => ReactHookForm,\n shareConfig: {\n singleton: true,\n requiredVersion: '^7.87.0',\n },\n },\n '@emotion/react': {\n version: '11.14.0',\n lib: () => EmotionReact,\n shareConfig: {\n singleton: true,\n requiredVersion: '^11.11.3',\n },\n },\n '@emotion/styled': {\n version: '11.14.1',\n lib: () => EmotionStyled,\n shareConfig: {\n singleton: true,\n requiredVersion: '^11.11.0',\n },\n },\n '@perses-dev/spec': {\n version: '0.3.0-beta.10',\n lib: () => getHostSharedModule('@perses-dev/spec'),\n shareConfig: {\n singleton: true,\n requiredVersion: '^0.3.0-beta.10',\n },\n },\n '@perses-dev/client': {\n version: '0.55.0-beta.14',\n lib: () => getHostSharedModule('@perses-dev/client'),\n shareConfig: {\n singleton: true,\n requiredVersion: '^0.55.0-beta.14',\n },\n },\n '@perses-dev/components': {\n version: '0.55.0-beta.14',\n lib: () => getHostSharedModule('@perses-dev/components'),\n shareConfig: {\n singleton: true,\n requiredVersion: '^0.55.0-beta.14',\n },\n },\n '@perses-dev/plugin-system': {\n version: '0.55.0-beta.14',\n lib: () => getHostSharedModule('@perses-dev/plugin-system'),\n shareConfig: {\n singleton: true,\n requiredVersion: '^0.55.0-beta.14',\n },\n },\n '@perses-dev/explore': {\n version: '0.55.0-beta.14',\n lib: () => getHostSharedModule('@perses-dev/explore'),\n shareConfig: {\n singleton: true,\n requiredVersion: '^0.55.0-beta.14',\n },\n },\n '@perses-dev/dashboards': {\n version: '0.55.0-beta.14',\n lib: () => getHostSharedModule('@perses-dev/dashboards'),\n shareConfig: {\n singleton: true,\n requiredVersion: '^0.55.0-beta.14',\n },\n },\n // Below are the shared modules that are used by the plugins and are loaded asynchronously on demand using get rather than lib.\n // This is to avoid loading the modules if they are not used by the plugin.\n echarts: {\n version: '5.5.0',\n get: createSharedModuleLoader(() => import('echarts')),\n shareConfig: {\n singleton: true,\n requiredVersion: '^5.5.0',\n },\n },\n 'date-fns': {\n version: '4.2.1',\n get: createSharedModuleLoader(() => import('date-fns')),\n shareConfig: {\n singleton: true,\n requiredVersion: '^4.1.0',\n },\n },\n 'date-fns-tz': {\n version: '3.2.0',\n get: createSharedModuleLoader(() => import('date-fns-tz')),\n shareConfig: {\n singleton: true,\n requiredVersion: '^3.2.0',\n },\n },\n lodash: {\n version: '4.18.1',\n get: createSharedModuleLoader(() => import('lodash')),\n shareConfig: {\n singleton: true,\n requiredVersion: '^4.17.21',\n },\n },\n '@hookform/resolvers/zod': {\n version: '5.9.1',\n get: createSharedModuleLoader(() => import('@hookform/resolvers/zod')),\n shareConfig: {\n singleton: true,\n requiredVersion: '^5.9.1',\n },\n },\n 'use-resize-observer': {\n version: '9.1.0',\n get: createSharedModuleLoader(() => import('use-resize-observer')),\n shareConfig: {\n singleton: true,\n requiredVersion: '^9.1.0',\n },\n },\n 'mdi-material-ui': {\n version: '7.9.4',\n get: createSharedModuleLoader(() => import('mdi-material-ui')),\n shareConfig: {\n singleton: true,\n requiredVersion: '^7.4.0',\n },\n },\n immer: {\n version: '10.2.0',\n get: createSharedModuleLoader(() => import('immer')),\n shareConfig: {\n singleton: true,\n requiredVersion: '^10.1.1',\n },\n },\n },\n });\n\n instance = pluginRuntime;\n\n return instance;\n }\n return instance;\n};\n\nfunction getModuleFederationRemoteName(name: string, registry?: string, version?: string): string {\n return `${name}:${registry ?? ''}:${version ?? ''}`;\n}\n\nconst registerRemote = (name: string, registry?: string, version?: string, baseURL?: string): void => {\n const pluginRuntime = getPluginRuntime();\n const registryName = getModuleFederationRemoteName(name, registry, version);\n\n const existingRemote = pluginRuntime.options.remotes.find((remote) => remote.name === registryName);\n if (!existingRemote) {\n const nameVersionRegistry = [name, version, registry].filter(Boolean).join('~');\n const prefix = baseURL ?? DEFAULT_PLUGINS_ASSETS_BASE_URL;\n const remoteEntryURL = `${prefix}/${nameVersionRegistry}/mf-manifest.json`;\n\n pluginRuntime.registerRemotes([\n {\n name: registryName,\n entry: remoteEntryURL,\n alias: registryName,\n },\n ]);\n }\n};\n\nexport const loadPlugin = async (target: {\n moduleName: string;\n pluginName: string;\n registry?: string;\n version?: string;\n baseURL?: string;\n}): Promise<RemotePluginModule | null> => {\n const { moduleName, pluginName, registry, version, baseURL } = target;\n registerRemote(moduleName, registry, version, baseURL);\n\n const pluginRuntime = getPluginRuntime();\n const registryName = getModuleFederationRemoteName(moduleName, registry, version);\n return pluginRuntime.loadRemote<RemotePluginModule>(`${registryName}/${pluginName}`);\n};\n\nexport function usePluginRuntime({ plugin }: { plugin: PersesPlugin }): {\n pluginRuntime: ModuleFederation;\n loadPlugin: () => Promise<RemotePluginModule | null>;\n} {\n return {\n pluginRuntime: getPluginRuntime(),\n loadPlugin: (): Promise<RemotePluginModule | null> => {\n const { moduleName, name: pluginName, registry, version, baseURL } = plugin;\n return loadPlugin({ moduleName, pluginName, registry, version, baseURL });\n },\n };\n}\n"],"names":["EmotionReact","EmotionStyled","createInstance","ReactQuery","React","ReactDOM","ReactHookForm","ReactRouterDOM","instance","DEFAULT_PLUGINS_ASSETS_BASE_URL","createSharedModuleLoader","loadModule","module","hostSharedModules","Map","registerHostSharedModules","modules","name","Object","entries","set","getHostSharedModule","get","Error","getPluginRuntime","pluginRuntime","remotes","shared","react","version","lib","shareConfig","singleton","requiredVersion","echarts","lodash","immer","getModuleFederationRemoteName","registry","registerRemote","baseURL","registryName","existingRemote","options","find","remote","nameVersionRegistry","filter","Boolean","join","prefix","remoteEntryURL","registerRemotes","entry","alias","loadPlugin","target","moduleName","pluginName","loadRemote","usePluginRuntime","plugin"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,YAAYA,kBAAkB,iBAAiB;AAC/C,YAAYC,mBAAmB,kBAAkB;AAEjD,SAASC,cAAc,QAAQ,sCAAsC;AACrE,YAAYC,gBAAgB,wBAAwB;AACpD,OAAOC,WAAW,QAAQ;AAC1B,OAAOC,cAAc,YAAY;AACjC,YAAYC,mBAAmB,kBAAkB;AACjD,YAAYC,oBAAoB,mBAAmB;AAInD,IAAIC,WAAoC;AAExC,MAAMC,kCAAkC;AAExC,SAASC,yBAAkCC,UAAkC;IAC3E,OAAO;QACL,MAAMC,SAAS,MAAMD;QACrB,OAAO,IAAMC;IACf;AACF;AAaA,MAAMC,oBAAoB,IAAIC;AAE9B;;;CAGC,GACD,OAA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1
|
+
{"version":3,"file":"remotePluginLoader.d.ts","sourceRoot":"","sources":["../../src/remote/remotePluginLoader.ts"],"names":[],"mappings":"AAcA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,KAAK,EAAE,YAAY,EAAoD,MAAM,2BAA2B,CAAC;AAgChH,KAAK,yBAAyB,GAAG;IAC/B;;;QAGI;IACJ,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;QAGI;IACJ,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,CAAC;AAwBF;;;GAGG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,CAAC,EAAE,yBAAyB,GAAG,YAAY,CA2DpF"}
|
|
@@ -40,6 +40,7 @@ const paramToOptions = (options)=>{
|
|
|
40
40
|
const { pluginsApiPath, pluginsAssetsPath } = paramToOptions(options);
|
|
41
41
|
const fetchFn = options?.fetchFn ?? defaultFetch;
|
|
42
42
|
return {
|
|
43
|
+
baseURL: pluginsAssetsPath,
|
|
43
44
|
getInstalledPlugins: async ()=>{
|
|
44
45
|
const pluginsResponse = await fetchFn(pluginsApiPath);
|
|
45
46
|
const plugins = await pluginsResponse.json();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/remote/remotePluginLoader.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { fetch as defaultFetch } from '@perses-dev/client';\nimport type { FetchFn } from '@perses-dev/client';\nimport type { PluginLoader, PluginMetadata, PluginModuleResource, PluginType } from '@perses-dev/plugin-system';\nimport { getPluginModuleCompoundKey } from '@perses-dev/plugin-system';\n\nimport type { RemotePluginModule } from './PersesPlugin.types';\nimport { loadPlugin } from './PluginRuntime';\n\nconst isPluginMetadata = (plugin: unknown): plugin is PluginMetadata => {\n return (\n typeof plugin === 'object' &&\n plugin !== null &&\n 'kind' in plugin &&\n 'spec' in plugin &&\n typeof plugin.spec === 'object' &&\n plugin.spec !== null &&\n 'name' in plugin.spec\n );\n};\n\nconst isPluginModuleResource = (pluginModule: unknown): pluginModule is PluginModuleResource => {\n return (\n typeof pluginModule === 'object' &&\n pluginModule !== null &&\n 'metadata' in pluginModule &&\n 'spec' in pluginModule &&\n typeof pluginModule.spec === 'object' &&\n pluginModule.spec !== null &&\n 'plugins' in pluginModule.spec &&\n Array.isArray(pluginModule.spec.plugins) &&\n pluginModule.spec.plugins.every(isPluginMetadata)\n );\n};\n\ntype RemotePluginLoaderOptions = {\n /**\n * The API path for fetching available Perses plugins. Used to construct the full URL to the `/api/v1/plugins` endpoint.\n * @default ''\n **/\n apiPrefix?: string;\n /**\n * The base URL for loading plugin assets (e.g., JavaScript files). Used to construct the full URL to the `/plugins` directory\n * @default ''\n **/\n baseURL?: string;\n /**\n * Optional custom fetch function to use for network requests. If not provided, the default fetch implementation will be used.\n */\n fetchFn?: FetchFn;\n};\n\ntype ParsedPluginOptions = {\n pluginsApiPath: string;\n pluginsAssetsPath: string;\n};\n\nconst DEFAULT_PLUGINS_API_PATH = '/api/v1/plugins';\nconst DEFAULT_PLUGINS_ASSETS_PATH = '/plugins';\n\nconst paramToOptions = (options?: RemotePluginLoaderOptions): ParsedPluginOptions => {\n if (options === undefined) {\n return {\n pluginsApiPath: DEFAULT_PLUGINS_API_PATH,\n pluginsAssetsPath: DEFAULT_PLUGINS_ASSETS_PATH,\n };\n }\n\n return {\n pluginsApiPath: `${options?.apiPrefix ?? ''}${DEFAULT_PLUGINS_API_PATH}`,\n pluginsAssetsPath: `${options?.baseURL ?? ''}${DEFAULT_PLUGINS_ASSETS_PATH}`,\n };\n};\n\n/**\n * Get a PluginLoader that fetches the list of installed plugins from a remote server and loads them as needed.\n * @param options - Optional configuration options for the remote plugin loader.\n */\nexport function remotePluginLoader(options?: RemotePluginLoaderOptions): PluginLoader {\n const { pluginsApiPath, pluginsAssetsPath } = paramToOptions(options);\n const fetchFn = options?.fetchFn ?? defaultFetch;\n\n return {\n getInstalledPlugins: async (): Promise<PluginModuleResource[]> => {\n const pluginsResponse = await fetchFn(pluginsApiPath);\n\n const plugins = await pluginsResponse.json();\n let pluginModules: PluginModuleResource[] = [];\n\n if (Array.isArray(plugins)) {\n pluginModules = plugins.filter(isPluginModuleResource);\n } else {\n console.error('RemotePluginLoader: Error loading plugins, response is not an array');\n }\n\n if (!pluginModules.length) {\n console.error('RemotePluginLoader: No valid plugins found');\n }\n\n return pluginModules;\n },\n importPluginModule: async (resource): Promise<RemotePluginModule> => {\n const { name: pluginModuleName, version, registry } = resource.metadata;\n\n const pluginModule: RemotePluginModule = {};\n\n const loadPromises = resource.spec.plugins.map(async (plugin) => {\n const remotePluginModule = await loadPlugin({\n moduleName: pluginModuleName,\n pluginName: plugin.spec.name,\n registry,\n version,\n baseURL: pluginsAssetsPath,\n });\n\n const remotePlugin = remotePluginModule?.[plugin.spec.name];\n if (remotePlugin) {\n return { kind: plugin.kind as PluginType, name: plugin.spec.name, remotePlugin };\n } else {\n console.error(`RemotePluginLoader: Error loading plugin ${plugin.spec.name}`);\n return null;\n }\n });\n\n const loadedPlugins = await Promise.all(loadPromises);\n\n loadedPlugins.forEach((item) => {\n if (item?.remotePlugin) {\n pluginModule[getPluginModuleCompoundKey({ kind: item.kind, name: item.name, registry, version })] =\n item.remotePlugin;\n }\n });\n\n return pluginModule;\n },\n };\n}\n"],"names":["fetch","defaultFetch","getPluginModuleCompoundKey","loadPlugin","isPluginMetadata","plugin","spec","isPluginModuleResource","pluginModule","Array","isArray","plugins","every","DEFAULT_PLUGINS_API_PATH","DEFAULT_PLUGINS_ASSETS_PATH","paramToOptions","options","undefined","pluginsApiPath","pluginsAssetsPath","apiPrefix","baseURL","remotePluginLoader","fetchFn","getInstalledPlugins","pluginsResponse","json","pluginModules","filter","console","error","length","importPluginModule","resource","name","pluginModuleName","version","registry","metadata","loadPromises","map","remotePluginModule","moduleName","pluginName","remotePlugin","kind","loadedPlugins","Promise","all","forEach","item"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAASA,SAASC,YAAY,QAAQ,qBAAqB;AAG3D,SAASC,0BAA0B,QAAQ,4BAA4B;AAGvE,SAASC,UAAU,QAAQ,qBAAkB;AAE7C,MAAMC,mBAAmB,CAACC;IACxB,OACE,OAAOA,WAAW,YAClBA,WAAW,QACX,UAAUA,UACV,UAAUA,UACV,OAAOA,OAAOC,IAAI,KAAK,YACvBD,OAAOC,IAAI,KAAK,QAChB,UAAUD,OAAOC,IAAI;AAEzB;AAEA,MAAMC,yBAAyB,CAACC;IAC9B,OACE,OAAOA,iBAAiB,YACxBA,iBAAiB,QACjB,cAAcA,gBACd,UAAUA,gBACV,OAAOA,aAAaF,IAAI,KAAK,YAC7BE,aAAaF,IAAI,KAAK,QACtB,aAAaE,aAAaF,IAAI,IAC9BG,MAAMC,OAAO,CAACF,aAAaF,IAAI,CAACK,OAAO,KACvCH,aAAaF,IAAI,CAACK,OAAO,CAACC,KAAK,CAACR;AAEpC;AAwBA,MAAMS,2BAA2B;AACjC,MAAMC,8BAA8B;AAEpC,MAAMC,iBAAiB,CAACC;IACtB,IAAIA,YAAYC,WAAW;QACzB,OAAO;YACLC,gBAAgBL;YAChBM,mBAAmBL;QACrB;IACF;IAEA,OAAO;QACLI,gBAAgB,GAAGF,SAASI,aAAa,KAAKP,0BAA0B;QACxEM,mBAAmB,GAAGH,SAASK,WAAW,KAAKP,6BAA6B;IAC9E;AACF;AAEA;;;CAGC,GACD,OAAO,SAASQ,mBAAmBN,OAAmC;IACpE,MAAM,EAAEE,cAAc,EAAEC,iBAAiB,EAAE,GAAGJ,eAAeC;IAC7D,MAAMO,UAAUP,SAASO,WAAWtB;IAEpC,OAAO;
|
|
1
|
+
{"version":3,"sources":["../../src/remote/remotePluginLoader.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport { fetch as defaultFetch } from '@perses-dev/client';\nimport type { FetchFn } from '@perses-dev/client';\nimport type { PluginLoader, PluginMetadata, PluginModuleResource, PluginType } from '@perses-dev/plugin-system';\nimport { getPluginModuleCompoundKey } from '@perses-dev/plugin-system';\n\nimport type { RemotePluginModule } from './PersesPlugin.types';\nimport { loadPlugin } from './PluginRuntime';\n\nconst isPluginMetadata = (plugin: unknown): plugin is PluginMetadata => {\n return (\n typeof plugin === 'object' &&\n plugin !== null &&\n 'kind' in plugin &&\n 'spec' in plugin &&\n typeof plugin.spec === 'object' &&\n plugin.spec !== null &&\n 'name' in plugin.spec\n );\n};\n\nconst isPluginModuleResource = (pluginModule: unknown): pluginModule is PluginModuleResource => {\n return (\n typeof pluginModule === 'object' &&\n pluginModule !== null &&\n 'metadata' in pluginModule &&\n 'spec' in pluginModule &&\n typeof pluginModule.spec === 'object' &&\n pluginModule.spec !== null &&\n 'plugins' in pluginModule.spec &&\n Array.isArray(pluginModule.spec.plugins) &&\n pluginModule.spec.plugins.every(isPluginMetadata)\n );\n};\n\ntype RemotePluginLoaderOptions = {\n /**\n * The API path for fetching available Perses plugins. Used to construct the full URL to the `/api/v1/plugins` endpoint.\n * @default ''\n **/\n apiPrefix?: string;\n /**\n * The base URL for loading plugin assets (e.g., JavaScript files). Used to construct the full URL to the `/plugins` directory\n * @default ''\n **/\n baseURL?: string;\n /**\n * Optional custom fetch function to use for network requests. If not provided, the default fetch implementation will be used.\n */\n fetchFn?: FetchFn;\n};\n\ntype ParsedPluginOptions = {\n pluginsApiPath: string;\n pluginsAssetsPath: string;\n};\n\nconst DEFAULT_PLUGINS_API_PATH = '/api/v1/plugins';\nconst DEFAULT_PLUGINS_ASSETS_PATH = '/plugins';\n\nconst paramToOptions = (options?: RemotePluginLoaderOptions): ParsedPluginOptions => {\n if (options === undefined) {\n return {\n pluginsApiPath: DEFAULT_PLUGINS_API_PATH,\n pluginsAssetsPath: DEFAULT_PLUGINS_ASSETS_PATH,\n };\n }\n\n return {\n pluginsApiPath: `${options?.apiPrefix ?? ''}${DEFAULT_PLUGINS_API_PATH}`,\n pluginsAssetsPath: `${options?.baseURL ?? ''}${DEFAULT_PLUGINS_ASSETS_PATH}`,\n };\n};\n\n/**\n * Get a PluginLoader that fetches the list of installed plugins from a remote server and loads them as needed.\n * @param options - Optional configuration options for the remote plugin loader.\n */\nexport function remotePluginLoader(options?: RemotePluginLoaderOptions): PluginLoader {\n const { pluginsApiPath, pluginsAssetsPath } = paramToOptions(options);\n const fetchFn = options?.fetchFn ?? defaultFetch;\n\n return {\n baseURL: pluginsAssetsPath,\n getInstalledPlugins: async (): Promise<PluginModuleResource[]> => {\n const pluginsResponse = await fetchFn(pluginsApiPath);\n\n const plugins = await pluginsResponse.json();\n let pluginModules: PluginModuleResource[] = [];\n\n if (Array.isArray(plugins)) {\n pluginModules = plugins.filter(isPluginModuleResource);\n } else {\n console.error('RemotePluginLoader: Error loading plugins, response is not an array');\n }\n\n if (!pluginModules.length) {\n console.error('RemotePluginLoader: No valid plugins found');\n }\n\n return pluginModules;\n },\n importPluginModule: async (resource): Promise<RemotePluginModule> => {\n const { name: pluginModuleName, version, registry } = resource.metadata;\n\n const pluginModule: RemotePluginModule = {};\n\n const loadPromises = resource.spec.plugins.map(async (plugin) => {\n const remotePluginModule = await loadPlugin({\n moduleName: pluginModuleName,\n pluginName: plugin.spec.name,\n registry,\n version,\n baseURL: pluginsAssetsPath,\n });\n\n const remotePlugin = remotePluginModule?.[plugin.spec.name];\n if (remotePlugin) {\n return { kind: plugin.kind as PluginType, name: plugin.spec.name, remotePlugin };\n } else {\n console.error(`RemotePluginLoader: Error loading plugin ${plugin.spec.name}`);\n return null;\n }\n });\n\n const loadedPlugins = await Promise.all(loadPromises);\n\n loadedPlugins.forEach((item) => {\n if (item?.remotePlugin) {\n pluginModule[getPluginModuleCompoundKey({ kind: item.kind, name: item.name, registry, version })] =\n item.remotePlugin;\n }\n });\n\n return pluginModule;\n },\n };\n}\n"],"names":["fetch","defaultFetch","getPluginModuleCompoundKey","loadPlugin","isPluginMetadata","plugin","spec","isPluginModuleResource","pluginModule","Array","isArray","plugins","every","DEFAULT_PLUGINS_API_PATH","DEFAULT_PLUGINS_ASSETS_PATH","paramToOptions","options","undefined","pluginsApiPath","pluginsAssetsPath","apiPrefix","baseURL","remotePluginLoader","fetchFn","getInstalledPlugins","pluginsResponse","json","pluginModules","filter","console","error","length","importPluginModule","resource","name","pluginModuleName","version","registry","metadata","loadPromises","map","remotePluginModule","moduleName","pluginName","remotePlugin","kind","loadedPlugins","Promise","all","forEach","item"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAEjC,SAASA,SAASC,YAAY,QAAQ,qBAAqB;AAG3D,SAASC,0BAA0B,QAAQ,4BAA4B;AAGvE,SAASC,UAAU,QAAQ,qBAAkB;AAE7C,MAAMC,mBAAmB,CAACC;IACxB,OACE,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QACAK,oBAAoB,OAAOC;YACzB,MAAM,EAAEC,MAAMC,gBAAgB,EAAEC,OAAO,EAAEC,QAAQ,EAAE,GAAGJ,SAASK,QAAQ;YAEvE,MAAM9B,eAAmC,CAAC;YAE1C,MAAM+B,eAAeN,SAAS3B,IAAI,CAACK,OAAO,CAAC6B,GAAG,CAAC,OAAOnC;gBACpD,MAAMoC,qBAAqB,MAAMtC,WAAW;oBAC1CuC,YAAYP;oBACZQ,YAAYtC,OAAOC,IAAI,CAAC4B,IAAI;oBAC5BG;oBACAD;oBACAf,SAASF;gBACX;gBAEA,MAAMyB,eAAeH,oBAAoB,CAACpC,OAAOC,IAAI,CAAC4B,IAAI,CAAC;gBAC3D,IAAIU,cAAc;oBAChB,OAAO;wBAAEC,MAAMxC,OAAOwC,IAAI;wBAAgBX,MAAM7B,OAAOC,IAAI,CAAC4B,IAAI;wBAAEU;oBAAa;gBACjF,OAAO;oBACLf,QAAQC,KAAK,CAAC,CAAC,yCAAyC,EAAEzB,OAAOC,IAAI,CAAC4B,IAAI,EAAE;oBAC5E,OAAO;gBACT;YACF;YAEA,MAAMY,gBAAgB,MAAMC,QAAQC,GAAG,CAACT;YAExCO,cAAcG,OAAO,CAAC,CAACC;gBACrB,IAAIA,MAAMN,cAAc;oBACtBpC,YAAY,CAACN,2BAA2B;wBAAE2C,MAAMK,KAAKL,IAAI;wBAAEX,MAAMgB,KAAKhB,IAAI;wBAAEG;wBAAUD;oBAAQ,GAAG,GAC/Fc,KAAKN,YAAY;gBACrB;YACF;YAEA,OAAOpC;QACT;IACF;AACF"}
|
|
@@ -5,6 +5,7 @@ export interface PluginRegistryContextType {
|
|
|
5
5
|
getPlugin<T extends PluginType>(compoundKey: PluginCompoundKey<T>): Promise<PluginImplementation<T>>;
|
|
6
6
|
listPluginMetadata(pluginTypes?: PluginType[]): Promise<PluginMetadataWithModule[]>;
|
|
7
7
|
defaultPluginKinds?: DefaultPluginKinds;
|
|
8
|
+
pluginsBaseURL?: string;
|
|
8
9
|
}
|
|
9
10
|
export declare const PluginRegistryContext: import("react").Context<PluginRegistryContextType | undefined>;
|
|
10
11
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"plugin-registry.d.ts","sourceRoot":"","sources":["../../src/runtime/plugin-registry.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAC5F,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAI7E,OAAO,KAAK,EACV,kBAAkB,EAClB,oBAAoB,EACpB,wBAAwB,EACxB,UAAU,EACV,iBAAiB,EAClB,MAAM,UAAU,CAAC;AAElB,MAAM,WAAW,yBAAyB;IACxC,SAAS,CAAC,CAAC,SAAS,UAAU,EAAE,WAAW,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAAC;IACrG,kBAAkB,CAAC,WAAW,CAAC,EAAE,UAAU,EAAE,GAAG,OAAO,CAAC,wBAAwB,EAAE,CAAC,CAAC;IACpF,kBAAkB,CAAC,EAAE,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"plugin-registry.d.ts","sourceRoot":"","sources":["../../src/runtime/plugin-registry.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,yBAAyB,EAAE,wBAAwB,EAAE,MAAM,kBAAkB,CAAC;AAC5F,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAI7E,OAAO,KAAK,EACV,kBAAkB,EAClB,oBAAoB,EACpB,wBAAwB,EACxB,UAAU,EACV,iBAAiB,EAClB,MAAM,UAAU,CAAC;AAElB,MAAM,WAAW,yBAAyB;IACxC,SAAS,CAAC,CAAC,SAAS,UAAU,EAAE,WAAW,EAAE,iBAAiB,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,oBAAoB,CAAC,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C,CA6BhD;AAGD,KAAK,4BAA4B,GAAG,IAAI,CACtC,eAAe,CAAC,wBAAwB,EAAE,EAAE,KAAK,EAAE,wBAAwB,EAAE,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC,EAClG,UAAU,GAAG,SAAS,CACvB,CAAC;AAEF;;;GAGG;AACH,wBAAgB,qBAAqB,CACnC,WAAW,CAAC,EAAE,UAAU,EAAE,EAC1B,OAAO,CAAC,EAAE,4BAA4B,GACrC,cAAc,CAAC,wBAAwB,EAAE,CAAC,CAQ5C;AAED,wBAAgB,mCAAmC,IAAI,cAAc,CAAC,yBAAyB,EAAE,CAAC,CAkBjG"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/runtime/plugin-registry.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { BuiltinVariableDefinition, PluginDefinitionMetadata } from '@perses-dev/spec';\nimport type { UseQueryOptions, UseQueryResult } from '@tanstack/react-query';\nimport { useQueries, useQuery } from '@tanstack/react-query';\nimport { createContext, useContext } from 'react';\n\nimport type {\n DefaultPluginKinds,\n PluginImplementation,\n PluginMetadataWithModule,\n PluginType,\n PluginCompoundKey,\n} from '../model';\n\nexport interface PluginRegistryContextType {\n getPlugin<T extends PluginType>(compoundKey: PluginCompoundKey<T>): Promise<PluginImplementation<T>>;\n listPluginMetadata(pluginTypes?: PluginType[]): Promise<PluginMetadataWithModule[]>;\n defaultPluginKinds?: DefaultPluginKinds;\n}\n\nexport const PluginRegistryContext = createContext<PluginRegistryContextType | undefined>(undefined);\n\n/**\n * Use the PluginRegistry context directly. This is meant as an escape hatch for custom async flows. You should probably\n * be using `usePlugin` or `useListPluginMetadata` instead.\n */\nexport function usePluginRegistry(): PluginRegistryContextType {\n const ctx = useContext(PluginRegistryContext);\n if (ctx === undefined) {\n throw new Error('PluginRegistryContext not found. Did you forget a provider?');\n }\n return ctx;\n}\n\ntype UsePluginQueryKey = [string, PluginType | undefined, string, string, string];\n\n// Allows consumers to pass useQuery options from react-query when loading a plugin\ntype UsePluginOptions<T extends PluginType> = Omit<\n UseQueryOptions<PluginImplementation<T>, Error, PluginImplementation<T>, UsePluginQueryKey>,\n 'queryKey' | 'queryFn'\n> & {\n /** Pin resolution to a specific plugin version. When omitted, the latest available version is used. */\n version?: string;\n /** Pin resolution to a specific plugin registry. */\n registry?: string;\n};\n\n/**\n * Loads a plugin and returns the plugin implementation, along with loading/error state.\n *\n * When `options.version` is provided, the plugin is resolved with an exact version match: if that version is not\n * installed, the query fails instead of silently falling back to the latest available version.\n */\nexport function usePlugin<T extends PluginType>(\n pluginType: T | undefined,\n kind: string,\n options?: UsePluginOptions<T>,\n): UseQueryResult<PluginImplementation<T>, Error> {\n const { version, registry, ...queryOptions } = options ?? {};\n // We never want to ask for a plugin when the kind isn't set yet, so disable those queries automatically\n const useQueryOptions = {\n ...queryOptions,\n enabled: (queryOptions.enabled ?? true) && pluginType !== undefined && kind !== '',\n };\n const { getPlugin } = usePluginRegistry();\n return useQuery({\n queryKey: ['getPlugin', pluginType, kind, version ?? '', registry ?? ''],\n queryFn: () => getPlugin({ kind: pluginType!, name: kind, version, registry }),\n ...useQueryOptions,\n });\n}\n\n/**\n * A plugin reference to load, optionally pinned to a specific version/registry.\n */\nexport interface UsePluginsItem extends PluginDefinitionMetadata {\n kind: string;\n}\n\n/**\n * Full identity of a plugin to load. Two definitions pinned to different versions (or registries) of the same kind are\n * distinct plugins and must be loaded independently.\n */\nfunction getUsePluginsItemIdentity(plugin: UsePluginsItem): string {\n return `${plugin.kind}:${plugin.version ?? ''}:${plugin.registry ?? ''}`;\n}\n\n/**\n * Loads a list of plugins and returns the plugin implementation, along with loading/error state.\n */\nexport function usePlugins<T extends PluginType>(\n pluginType: T,\n plugins: UsePluginsItem[],\n): Array<UseQueryResult<PluginImplementation<T>>> {\n const { getPlugin } = usePluginRegistry();\n\n // useQueries() does not support queries with duplicate keys, therefore we de-duplicate the plugins before running useQueries()\n // This resolves the following warning in the JS console: \"[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.\"\n // https://github.com/TanStack/query/issues/8224#issuecomment-2523554831\n // https://github.com/TanStack/query/issues/4187#issuecomment-1256336901\n const uniquePlugins = new Map<string, UsePluginsItem>();\n for (const p of plugins) {\n const key = getUsePluginsItemIdentity(p);\n if (!uniquePlugins.has(key)) {\n uniquePlugins.set(key, p);\n }\n }\n const uniqueKeys = [...uniquePlugins.keys()];\n const uniqueValues = [...uniquePlugins.values()];\n\n const result: Array<UseQueryResult<PluginImplementation<T>>> = useQueries({\n queries: uniqueValues.map((p) => {\n return {\n queryKey: ['getPlugin', pluginType, p.kind, p.version ?? '', p.registry ?? ''],\n queryFn: () => getPlugin({ kind: pluginType, name: p.kind, version: p.version, registry: p.registry }),\n };\n }),\n });\n\n // Re-assemble array in original order. Index lookups go through a Map so this stays linear on large panels.\n const indexByIdentity = new Map(uniqueKeys.map((key, index) => [key, index]));\n return plugins.map((p) => result[indexByIdentity.get(getUsePluginsItemIdentity(p))!]!);\n}\n\n// Allow consumers to pass useQuery options from react-query when listing metadata\ntype UseListPluginMetadataOptions = Omit<\n UseQueryOptions<PluginMetadataWithModule[], Error, PluginMetadataWithModule[], [string, string[]]>,\n 'queryKey' | 'queryFn'\n>;\n\n/**\n * Gets a list of plugin metadata for the specified plugin types and returns it, along with loading/error state. When\n * `pluginTypes` is omitted, the metadata of every installed plugin is returned, whatever its type.\n */\nexport function useListPluginMetadata(\n pluginTypes?: PluginType[],\n options?: UseListPluginMetadataOptions,\n): UseQueryResult<PluginMetadataWithModule[]> {\n const { listPluginMetadata } = usePluginRegistry();\n return useQuery({\n // `['*']` marks the \"every plugin type\" query so it gets its own cache entry.\n queryKey: ['listPluginMetadata', pluginTypes ?? ['*']],\n queryFn: () => listPluginMetadata(pluginTypes),\n ...options,\n });\n}\n\nexport function usePluginBuiltinVariableDefinitions(): UseQueryResult<BuiltinVariableDefinition[]> {\n const { getPlugin, listPluginMetadata } = usePluginRegistry();\n\n return useQuery({\n queryKey: ['usePluginBuiltinVariableDefinitions'],\n queryFn: async () => {\n const datasources = await listPluginMetadata(['Datasource']);\n const datasourceNames = new Set(datasources.map((datasource) => datasource.spec.name));\n const result: BuiltinVariableDefinition[] = [];\n for (const name of datasourceNames) {\n const plugin = await getPlugin({ kind: 'Datasource', name });\n if (plugin.getBuiltinVariableDefinitions) {\n plugin.getBuiltinVariableDefinitions().forEach((definition) => result.push(definition));\n }\n }\n return result;\n },\n });\n}\n"],"names":["useQueries","useQuery","createContext","useContext","PluginRegistryContext","undefined","usePluginRegistry","ctx","Error","usePlugin","pluginType","kind","options","version","registry","queryOptions","useQueryOptions","enabled","getPlugin","queryKey","queryFn","name","getUsePluginsItemIdentity","plugin","usePlugins","plugins","uniquePlugins","Map","p","key","has","set","uniqueKeys","keys","uniqueValues","values","result","queries","map","indexByIdentity","index","get","useListPluginMetadata","pluginTypes","listPluginMetadata","usePluginBuiltinVariableDefinitions","datasources","datasourceNames","Set","datasource","spec","getBuiltinVariableDefinitions","forEach","definition","push"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAIjC,SAASA,UAAU,EAAEC,QAAQ,QAAQ,wBAAwB;AAC7D,SAASC,aAAa,EAAEC,UAAU,QAAQ,QAAQ;AAgBlD,OAAO,MAAMC,wBAAwBF,cAAqDG,WAAW;AAErG;;;CAGC,G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MAAM;oBAAcU;gBAAK;gBAC1D,IAAIE,OAAO4B,6BAA6B,EAAE;oBACxC5B,OAAO4B,6BAA6B,GAAGC,OAAO,CAAC,CAACC,aAAejB,OAAOkB,IAAI,CAACD;gBAC7E;YACF;YACA,OAAOjB;QACT;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../src/runtime/plugin-registry.ts"],"sourcesContent":["// Copyright The Perses Authors\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\nimport type { BuiltinVariableDefinition, PluginDefinitionMetadata } from '@perses-dev/spec';\nimport type { UseQueryOptions, UseQueryResult } from '@tanstack/react-query';\nimport { useQueries, useQuery } from '@tanstack/react-query';\nimport { createContext, useContext } from 'react';\n\nimport type {\n DefaultPluginKinds,\n PluginImplementation,\n PluginMetadataWithModule,\n PluginType,\n PluginCompoundKey,\n} from '../model';\n\nexport interface PluginRegistryContextType {\n getPlugin<T extends PluginType>(compoundKey: PluginCompoundKey<T>): Promise<PluginImplementation<T>>;\n listPluginMetadata(pluginTypes?: PluginType[]): Promise<PluginMetadataWithModule[]>;\n defaultPluginKinds?: DefaultPluginKinds;\n pluginsBaseURL?: string;\n}\n\nexport const PluginRegistryContext = createContext<PluginRegistryContextType | undefined>(undefined);\n\n/**\n * Use the PluginRegistry context directly. This is meant as an escape hatch for custom async flows. You should probably\n * be using `usePlugin` or `useListPluginMetadata` instead.\n */\nexport function usePluginRegistry(): PluginRegistryContextType {\n const ctx = useContext(PluginRegistryContext);\n if (ctx === undefined) {\n throw new Error('PluginRegistryContext not found. Did you forget a provider?');\n }\n return ctx;\n}\n\ntype UsePluginQueryKey = [string, PluginType | undefined, string, string, string];\n\n// Allows consumers to pass useQuery options from react-query when loading a plugin\ntype UsePluginOptions<T extends PluginType> = Omit<\n UseQueryOptions<PluginImplementation<T>, Error, PluginImplementation<T>, UsePluginQueryKey>,\n 'queryKey' | 'queryFn'\n> & {\n /** Pin resolution to a specific plugin version. When omitted, the latest available version is used. */\n version?: string;\n /** Pin resolution to a specific plugin registry. */\n registry?: string;\n};\n\n/**\n * Loads a plugin and returns the plugin implementation, along with loading/error state.\n *\n * When `options.version` is provided, the plugin is resolved with an exact version match: if that version is not\n * installed, the query fails instead of silently falling back to the latest available version.\n */\nexport function usePlugin<T extends PluginType>(\n pluginType: T | undefined,\n kind: string,\n options?: UsePluginOptions<T>,\n): UseQueryResult<PluginImplementation<T>, Error> {\n const { version, registry, ...queryOptions } = options ?? {};\n // We never want to ask for a plugin when the kind isn't set yet, so disable those queries automatically\n const useQueryOptions = {\n ...queryOptions,\n enabled: (queryOptions.enabled ?? true) && pluginType !== undefined && kind !== '',\n };\n const { getPlugin } = usePluginRegistry();\n return useQuery({\n queryKey: ['getPlugin', pluginType, kind, version ?? '', registry ?? ''],\n queryFn: () => getPlugin({ kind: pluginType!, name: kind, version, registry }),\n ...useQueryOptions,\n });\n}\n\n/**\n * A plugin reference to load, optionally pinned to a specific version/registry.\n */\nexport interface UsePluginsItem extends PluginDefinitionMetadata {\n kind: string;\n}\n\n/**\n * Full identity of a plugin to load. Two definitions pinned to different versions (or registries) of the same kind are\n * distinct plugins and must be loaded independently.\n */\nfunction getUsePluginsItemIdentity(plugin: UsePluginsItem): string {\n return `${plugin.kind}:${plugin.version ?? ''}:${plugin.registry ?? ''}`;\n}\n\n/**\n * Loads a list of plugins and returns the plugin implementation, along with loading/error state.\n */\nexport function usePlugins<T extends PluginType>(\n pluginType: T,\n plugins: UsePluginsItem[],\n): Array<UseQueryResult<PluginImplementation<T>>> {\n const { getPlugin } = usePluginRegistry();\n\n // useQueries() does not support queries with duplicate keys, therefore we de-duplicate the plugins before running useQueries()\n // This resolves the following warning in the JS console: \"[QueriesObserver]: Duplicate Queries found. This might result in unexpected behavior.\"\n // https://github.com/TanStack/query/issues/8224#issuecomment-2523554831\n // https://github.com/TanStack/query/issues/4187#issuecomment-1256336901\n const uniquePlugins = new Map<string, UsePluginsItem>();\n for (const p of plugins) {\n const key = getUsePluginsItemIdentity(p);\n if (!uniquePlugins.has(key)) {\n uniquePlugins.set(key, p);\n }\n }\n const uniqueKeys = [...uniquePlugins.keys()];\n const uniqueValues = [...uniquePlugins.values()];\n\n const result: Array<UseQueryResult<PluginImplementation<T>>> = useQueries({\n queries: uniqueValues.map((p) => {\n return {\n queryKey: ['getPlugin', pluginType, p.kind, p.version ?? '', p.registry ?? ''],\n queryFn: () => getPlugin({ kind: pluginType, name: p.kind, version: p.version, registry: p.registry }),\n };\n }),\n });\n\n // Re-assemble array in original order. Index lookups go through a Map so this stays linear on large panels.\n const indexByIdentity = new Map(uniqueKeys.map((key, index) => [key, index]));\n return plugins.map((p) => result[indexByIdentity.get(getUsePluginsItemIdentity(p))!]!);\n}\n\n// Allow consumers to pass useQuery options from react-query when listing metadata\ntype UseListPluginMetadataOptions = Omit<\n UseQueryOptions<PluginMetadataWithModule[], Error, PluginMetadataWithModule[], [string, string[]]>,\n 'queryKey' | 'queryFn'\n>;\n\n/**\n * Gets a list of plugin metadata for the specified plugin types and returns it, along with loading/error state. When\n * `pluginTypes` is omitted, the metadata of every installed plugin is returned, whatever its type.\n */\nexport function useListPluginMetadata(\n pluginTypes?: PluginType[],\n options?: UseListPluginMetadataOptions,\n): UseQueryResult<PluginMetadataWithModule[]> {\n const { listPluginMetadata } = usePluginRegistry();\n return useQuery({\n // `['*']` marks the \"every plugin type\" query so it gets its own cache entry.\n queryKey: ['listPluginMetadata', pluginTypes ?? ['*']],\n queryFn: () => listPluginMetadata(pluginTypes),\n ...options,\n });\n}\n\nexport function usePluginBuiltinVariableDefinitions(): UseQueryResult<BuiltinVariableDefinition[]> {\n const { getPlugin, listPluginMetadata } = usePluginRegistry();\n\n return useQuery({\n queryKey: ['usePluginBuiltinVariableDefinitions'],\n queryFn: async () => {\n const datasources = await listPluginMetadata(['Datasource']);\n const datasourceNames = new Set(datasources.map((datasource) => datasource.spec.name));\n const result: BuiltinVariableDefinition[] = [];\n for (const name of datasourceNames) {\n const plugin = await getPlugin({ kind: 'Datasource', name });\n if (plugin.getBuiltinVariableDefinitions) {\n plugin.getBuiltinVariableDefinitions().forEach((definition) => result.push(definition));\n }\n }\n return result;\n },\n });\n}\n"],"names":["useQueries","useQuery","createContext","useContext","PluginRegistryContext","undefined","usePluginRegistry","ctx","Error","usePlugin","pluginType","kind","options","version","registry","queryOptions","useQueryOptions","enabled","getPlugin","queryKey","queryFn","name","getUsePluginsItemIdentity","plugin","usePlugins","plugins","uniquePlugins","Map","p","key","has","set","uniqueKeys","keys","uniqueValues","values","result","queries","map","indexByIdentity","index","get","useListPluginMetadata","pluginTypes","listPluginMetadata","usePluginBuiltinVariableDefinitions","datasources","datasourceNames","Set","datasource","spec","getBuiltinVariableDefinitions","forEach","definition","push"],"mappings":"AAAA,+BAA+B;AAC/B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,6CAA6C;AAC7C,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;AAIjC,SAASA,UAAU,EAAEC,QAAQ,QAAQ,wBAAwB;AAC7D,SAASC,aAAa,EAAEC,UAAU,QAAQ,QAAQ;AAiBlD,OAAO,MAAMC,wBAAwBF,cAAqDG,WAAW;AAErG;;;CAGC,GACD,OAAO,SAASC;IACd,MAAMC,MAAMJ,WAAWC;IACvB,IAAIG,QAAQF,WAAW;QACrB,MAAM,IAAIG,MAAM;IAClB;IACA,OAAOD;AACT;AAeA;;;;;CAKC,GACD,OAAO,SAASE,UACdC,UAAyB,EACzBC,IAAY,EACZC,OAA6B;IAE7B,MAAM,EAAEC,OAAO,EAAEC,QAAQ,EAAE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
|
|
2
2
|
"name": "@perses-dev/plugin-system",
|
|
3
|
-
"version": "0.55.0-beta.
|
|
3
|
+
"version": "0.55.0-beta.14",
|
|
4
4
|
"description": "The plugin feature in Pereses",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"homepage": "https://github.com/perses/perses/blob/main/README.md",
|
|
@@ -29,10 +29,10 @@
|
|
|
29
29
|
"lint:fix": "oxlint --fix src"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@module-federation/enhanced": "^2.9.
|
|
33
|
-
"@perses-dev/client": "0.55.0-beta.
|
|
34
|
-
"@perses-dev/components": "0.55.0-beta.
|
|
35
|
-
"@perses-dev/spec": "0.3.0-beta.
|
|
32
|
+
"@module-federation/enhanced": "^2.9.1",
|
|
33
|
+
"@perses-dev/client": "0.55.0-beta.14",
|
|
34
|
+
"@perses-dev/components": "0.55.0-beta.14",
|
|
35
|
+
"@perses-dev/spec": "0.3.0-beta.10",
|
|
36
36
|
"date-fns": "^4.1.0",
|
|
37
37
|
"date-fns-tz": "^3.2.0",
|
|
38
38
|
"fast-uri": "3.1.6",
|