@rebasepro/cms 0.29.1 → 0.29.3
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/collection_editor/serializable_types.d.ts +2 -0
- package/dist/collection_editor/ui/collection_editor/CollectionRelationsTab.d.ts +1 -1
- package/dist/components/CollectionPanel.js +22 -13
- package/dist/components/CollectionPanel.js.map +1 -1
- package/dist/components/CollectionTableBinding/fields/TableStorageUpload.js +1 -1
- package/dist/components/CollectionTableBinding/fields/TableStorageUpload.js.map +1 -1
- package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.d.ts +1 -1
- package/dist/components/CollectionTableBinding/internal/popup_field/PopupFormField.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionCardViewBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionListViewBinding.js +39 -14
- package/dist/components/CollectionViewBinding/CollectionListViewBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/CollectionViewContent.d.ts +11 -0
- package/dist/components/CollectionViewBinding/CollectionViewContent.js +19 -2
- package/dist/components/CollectionViewBinding/CollectionViewContent.js.map +1 -1
- package/dist/components/CollectionViewBinding/EntityCardBinding.d.ts +1 -1
- package/dist/components/CollectionViewBinding/EntityCardBinding.js +1 -1
- package/dist/components/CollectionViewBinding/EntityCardBinding.js.map +1 -1
- package/dist/components/CollectionViewBinding/SlotValue.js.map +1 -1
- package/dist/components/CollectionViewBinding/usePreviewSlots.d.ts +19 -1
- package/dist/components/CollectionViewBinding/usePreviewSlots.js +18 -7
- package/dist/components/CollectionViewBinding/usePreviewSlots.js.map +1 -1
- package/dist/components/EntityPreviewBinding.d.ts +20 -0
- package/dist/components/EntityPreviewBinding.js +121 -18
- package/dist/components/EntityPreviewBinding.js.map +1 -1
- package/dist/components/HomePage/ContentHomePage.js +2 -3
- package/dist/components/HomePage/ContentHomePage.js.map +1 -1
- package/dist/components/RecordForm.d.ts +25 -4
- package/dist/components/RecordForm.js +21 -3
- package/dist/components/RecordForm.js.map +1 -1
- package/dist/components/RelationSelector.js.map +1 -1
- package/dist/components/SelectableTable/filters/FilterFieldBinding.d.ts +13 -1
- package/dist/components/SelectableTable/filters/FilterFieldBinding.js +19 -3
- package/dist/components/SelectableTable/filters/FilterFieldBinding.js.map +1 -1
- package/dist/components/SelectableTable/filters/RelationFilterField.d.ts +1 -1
- package/dist/components/SelectableTable/filters/RelationFilterField.js.map +1 -1
- package/dist/components/history/EntityHistoryEntry.js.map +1 -1
- package/dist/data_import/utils/save_entities.d.ts +10 -2
- package/dist/data_import/utils/save_entities.js.map +1 -1
- package/dist/editor/markdown.d.ts +10 -0
- package/dist/editor/markdown.js.map +1 -1
- package/dist/form/PropertyFieldBinding.js +4 -2
- package/dist/form/PropertyFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/BinaryFieldBinding.js.map +1 -1
- package/dist/form/field_bindings/GeopointFieldBinding.js.map +1 -1
- package/dist/hooks/useBuildSidePanel.d.ts +10 -0
- package/dist/hooks/useBuildSidePanel.js +43 -4
- package/dist/hooks/useBuildSidePanel.js.map +1 -1
- package/dist/hooks/useResolvedNavigationFrom.d.ts +14 -2
- package/dist/hooks/useResolvedNavigationFrom.js.map +1 -1
- package/dist/index.d.ts +3 -1
- package/dist/index.js +4 -2
- package/dist/mcp_view/app_modules.js +4 -2
- package/dist/mcp_view/app_modules.js.map +1 -1
- package/dist/mcp_view/bridge.d.ts +21 -1
- package/dist/mcp_view/bridge.js.map +1 -1
- package/dist/mcp_view/index.d.ts +7 -7
- package/dist/mcp_view/index.js +7 -2
- package/dist/mcp_view/index.js.map +1 -1
- package/dist/mcp_view/payload.js +7 -2
- package/dist/mcp_view/payload.js.map +1 -1
- package/dist/mcp_view/screen.d.ts +6 -4
- package/dist/mcp_view/screen.js +15 -43
- package/dist/mcp_view/screen.js.map +1 -1
- package/dist/mcp_view/tool_driver.d.ts +58 -6
- package/dist/mcp_view/tool_driver.js +256 -117
- package/dist/mcp_view/tool_driver.js.map +1 -1
- package/dist/mcp_view/write_review.d.ts +35 -0
- package/dist/mcp_view/write_review.js +144 -0
- package/dist/mcp_view/write_review.js.map +1 -0
- package/dist/preview/compact_text.d.ts +1 -1
- package/dist/preview/compact_text.js.map +1 -1
- package/dist/preview/components/RelationPreview.js +7 -2
- package/dist/preview/components/RelationPreview.js.map +1 -1
- package/dist/saved_apps/SavedAppsView.d.ts +17 -0
- package/dist/saved_apps/SavedAppsView.js +167 -0
- package/dist/saved_apps/SavedAppsView.js.map +1 -0
- package/dist/saved_apps/admin_apps_client.d.ts +24 -0
- package/dist/saved_apps/admin_apps_client.js +46 -0
- package/dist/saved_apps/admin_apps_client.js.map +1 -0
- package/dist/saved_apps/saved_app_frame.d.ts +20 -0
- package/dist/saved_apps/saved_app_frame.js +143 -0
- package/dist/saved_apps/saved_app_frame.js.map +1 -0
- package/dist/selection/resolve_selection.d.ts +10 -2
- package/dist/selection/resolve_selection.js.map +1 -1
- package/dist/util/property_utils.d.ts +2 -2
- package/dist/util/property_utils.js.map +1 -1
- package/package.json +9 -9
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* EXPERIMENTAL. The apps saved to the project (save_app), for the person
|
|
3
|
+
* signed in: theirs, their roles' and the team's. Opening one runs it as
|
|
4
|
+
* Claude runs it, sandboxed (`SavedAppFrame`).
|
|
5
|
+
*
|
|
6
|
+
* Not in the navigation by default. A project that wants it adds the view:
|
|
7
|
+
*
|
|
8
|
+
* ```tsx
|
|
9
|
+
* import { savedAppsView } from "@rebasepro/cms";
|
|
10
|
+
* <RebaseCMS collections={collections} views={[savedAppsView]} />
|
|
11
|
+
* ```
|
|
12
|
+
*/
|
|
13
|
+
import React from "react";
|
|
14
|
+
import type { AppView } from "@rebasepro/cms-types";
|
|
15
|
+
export declare function SavedAppsView(): React.JSX.Element;
|
|
16
|
+
/** The view to add to `views` for saved apps in the navigation. */
|
|
17
|
+
export declare const savedAppsView: AppView;
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { createAdminAppsClient, isRecord } from "./admin_apps_client.js";
|
|
2
|
+
import { SavedAppFrame } from "./saved_app_frame.js";
|
|
3
|
+
import { useEffect, useMemo, useState } from "react";
|
|
4
|
+
import { Fragment, jsx, jsxs } from "react/jsx-runtime";
|
|
5
|
+
import { Alert, ArrowLeftIcon, Card, Chip, CircularProgress, Container, IconButton, Typography, cls } from "@rebasepro/ui";
|
|
6
|
+
import { useApiBase, useApiConfig } from "@rebasepro/app";
|
|
7
|
+
//#region src/saved_apps/SavedAppsView.tsx
|
|
8
|
+
/**
|
|
9
|
+
* EXPERIMENTAL. The apps saved to the project (save_app), for the person
|
|
10
|
+
* signed in: theirs, their roles' and the team's. Opening one runs it as
|
|
11
|
+
* Claude runs it, sandboxed (`SavedAppFrame`).
|
|
12
|
+
*
|
|
13
|
+
* Not in the navigation by default. A project that wants it adds the view:
|
|
14
|
+
*
|
|
15
|
+
* ```tsx
|
|
16
|
+
* import { savedAppsView } from "@rebasepro/cms";
|
|
17
|
+
* <RebaseCMS collections={collections} views={[savedAppsView]} />
|
|
18
|
+
* ```
|
|
19
|
+
*/
|
|
20
|
+
/** Who an app is for, as the list says it. */
|
|
21
|
+
function audience(app) {
|
|
22
|
+
if (app.visibility === "team") return "Team";
|
|
23
|
+
if (app.visibility === "roles") return app.roles.join(", ");
|
|
24
|
+
return "Only you";
|
|
25
|
+
}
|
|
26
|
+
function summariesOf(result) {
|
|
27
|
+
const content = isRecord(result) ? result.structuredContent : void 0;
|
|
28
|
+
return (isRecord(content) && Array.isArray(content.apps) ? content.apps : []).filter(isRecord).flatMap((app) => typeof app.id === "string" && typeof app.title === "string" ? [{
|
|
29
|
+
id: app.id,
|
|
30
|
+
title: app.title,
|
|
31
|
+
visibility: app.visibility === "team" || app.visibility === "roles" ? app.visibility : "personal",
|
|
32
|
+
roles: Array.isArray(app.roles) ? app.roles.filter((role) => typeof role === "string") : [],
|
|
33
|
+
collections: Array.isArray(app.collections) ? app.collections.filter((name) => typeof name === "string") : [],
|
|
34
|
+
updatedAt: typeof app.updatedAt === "string" ? app.updatedAt : ""
|
|
35
|
+
}] : []);
|
|
36
|
+
}
|
|
37
|
+
function SavedAppsView() {
|
|
38
|
+
const apiBase = useApiBase();
|
|
39
|
+
const getAuthToken = useApiConfig()?.getAuthToken;
|
|
40
|
+
const client = useMemo(() => apiBase ? createAdminAppsClient(apiBase, getAuthToken) : void 0, [apiBase, getAuthToken]);
|
|
41
|
+
const [apps, setApps] = useState();
|
|
42
|
+
const [error, setError] = useState();
|
|
43
|
+
const [open, setOpen] = useState();
|
|
44
|
+
useEffect(() => {
|
|
45
|
+
if (!client) return;
|
|
46
|
+
let cancelled = false;
|
|
47
|
+
client.request("tools/call", {
|
|
48
|
+
name: "list_apps",
|
|
49
|
+
arguments: {}
|
|
50
|
+
}).then((result) => {
|
|
51
|
+
if (!cancelled) setApps(summariesOf(result));
|
|
52
|
+
}).catch((reason) => {
|
|
53
|
+
if (!cancelled) setError(reason instanceof Error ? reason.message : String(reason));
|
|
54
|
+
});
|
|
55
|
+
return () => {
|
|
56
|
+
cancelled = true;
|
|
57
|
+
};
|
|
58
|
+
}, [client]);
|
|
59
|
+
return /* @__PURE__ */ jsx(Container, {
|
|
60
|
+
maxWidth: "6xl",
|
|
61
|
+
className: "flex flex-col gap-4 py-6",
|
|
62
|
+
children: open && client ? /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsxs("div", {
|
|
63
|
+
className: "flex items-center gap-2",
|
|
64
|
+
children: [
|
|
65
|
+
/* @__PURE__ */ jsx(IconButton, {
|
|
66
|
+
size: "small",
|
|
67
|
+
"aria-label": "Back to saved apps",
|
|
68
|
+
onClick: () => setOpen(void 0),
|
|
69
|
+
children: /* @__PURE__ */ jsx(ArrowLeftIcon, {})
|
|
70
|
+
}),
|
|
71
|
+
/* @__PURE__ */ jsx(Typography, {
|
|
72
|
+
variant: "h6",
|
|
73
|
+
className: "truncate",
|
|
74
|
+
children: open.title
|
|
75
|
+
}),
|
|
76
|
+
/* @__PURE__ */ jsx(Chip, {
|
|
77
|
+
size: "small",
|
|
78
|
+
children: audience(open)
|
|
79
|
+
})
|
|
80
|
+
]
|
|
81
|
+
}), /* @__PURE__ */ jsx(SavedAppFrame, {
|
|
82
|
+
client,
|
|
83
|
+
appId: open.id
|
|
84
|
+
})] }) : /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
85
|
+
/* @__PURE__ */ jsxs("div", {
|
|
86
|
+
className: "flex flex-col gap-1",
|
|
87
|
+
children: [/* @__PURE__ */ jsx(Typography, {
|
|
88
|
+
variant: "h5",
|
|
89
|
+
children: "Saved apps"
|
|
90
|
+
}), /* @__PURE__ */ jsx(Typography, {
|
|
91
|
+
variant: "body2",
|
|
92
|
+
color: "secondary",
|
|
93
|
+
children: "Apps built with Claude and saved to this project. Each one runs as you, on the data you can reach."
|
|
94
|
+
})]
|
|
95
|
+
}),
|
|
96
|
+
!client && /* @__PURE__ */ jsx(Alert, {
|
|
97
|
+
color: "warning",
|
|
98
|
+
size: "small",
|
|
99
|
+
children: "This admin panel has no API address to load saved apps from."
|
|
100
|
+
}),
|
|
101
|
+
error && /* @__PURE__ */ jsx(Alert, {
|
|
102
|
+
color: "error",
|
|
103
|
+
size: "small",
|
|
104
|
+
children: error
|
|
105
|
+
}),
|
|
106
|
+
client && !error && !apps && /* @__PURE__ */ jsxs("div", {
|
|
107
|
+
className: "flex items-center gap-2",
|
|
108
|
+
children: [/* @__PURE__ */ jsx(CircularProgress, { size: "small" }), /* @__PURE__ */ jsx(Typography, {
|
|
109
|
+
variant: "body2",
|
|
110
|
+
color: "secondary",
|
|
111
|
+
children: "Loading saved apps…"
|
|
112
|
+
})]
|
|
113
|
+
}),
|
|
114
|
+
apps && apps.length === 0 && /* @__PURE__ */ jsx(Typography, {
|
|
115
|
+
variant: "body2",
|
|
116
|
+
color: "secondary",
|
|
117
|
+
children: "No saved apps yet. Ask Claude to build one with show_app, then to save it with save_app."
|
|
118
|
+
}),
|
|
119
|
+
apps && apps.length > 0 && /* @__PURE__ */ jsx("div", {
|
|
120
|
+
className: "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",
|
|
121
|
+
children: apps.map((app) => /* @__PURE__ */ jsxs(Card, {
|
|
122
|
+
onClick: () => setOpen(app),
|
|
123
|
+
className: cls("flex flex-col gap-2 p-4 cursor-pointer hover:bg-surface-card-hover"),
|
|
124
|
+
children: [
|
|
125
|
+
/* @__PURE__ */ jsx(Typography, {
|
|
126
|
+
variant: "subtitle2",
|
|
127
|
+
className: "truncate",
|
|
128
|
+
children: app.title
|
|
129
|
+
}),
|
|
130
|
+
/* @__PURE__ */ jsx(Typography, {
|
|
131
|
+
variant: "caption",
|
|
132
|
+
color: "secondary",
|
|
133
|
+
className: "truncate",
|
|
134
|
+
children: app.collections.join(", ")
|
|
135
|
+
}),
|
|
136
|
+
/* @__PURE__ */ jsxs("div", {
|
|
137
|
+
className: "flex items-center justify-between gap-2",
|
|
138
|
+
children: [/* @__PURE__ */ jsx(Chip, {
|
|
139
|
+
size: "small",
|
|
140
|
+
children: audience(app)
|
|
141
|
+
}), app.updatedAt && /* @__PURE__ */ jsx(Typography, {
|
|
142
|
+
variant: "caption",
|
|
143
|
+
color: "secondary",
|
|
144
|
+
children: new Date(app.updatedAt).toLocaleDateString(void 0, {
|
|
145
|
+
month: "short",
|
|
146
|
+
day: "numeric"
|
|
147
|
+
})
|
|
148
|
+
})]
|
|
149
|
+
})
|
|
150
|
+
]
|
|
151
|
+
}, app.id))
|
|
152
|
+
})
|
|
153
|
+
] })
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
/** The view to add to `views` for saved apps in the navigation. */
|
|
157
|
+
var savedAppsView = {
|
|
158
|
+
slug: "apps",
|
|
159
|
+
name: "Saved apps",
|
|
160
|
+
description: "Apps built with Claude and saved to this project.",
|
|
161
|
+
icon: "LayoutDashboard",
|
|
162
|
+
view: /* @__PURE__ */ jsx(SavedAppsView, {})
|
|
163
|
+
};
|
|
164
|
+
//#endregion
|
|
165
|
+
export { SavedAppsView, savedAppsView };
|
|
166
|
+
|
|
167
|
+
//# sourceMappingURL=SavedAppsView.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SavedAppsView.js","names":[],"sources":["../../src/saved_apps/SavedAppsView.tsx"],"sourcesContent":["/**\n * EXPERIMENTAL. The apps saved to the project (save_app), for the person\n * signed in: theirs, their roles' and the team's. Opening one runs it as\n * Claude runs it, sandboxed (`SavedAppFrame`).\n *\n * Not in the navigation by default. A project that wants it adds the view:\n *\n * ```tsx\n * import { savedAppsView } from \"@rebasepro/cms\";\n * <RebaseCMS collections={collections} views={[savedAppsView]} />\n * ```\n */\nimport React, { useEffect, useMemo, useState } from \"react\";\nimport type { AppView } from \"@rebasepro/cms-types\";\nimport { useApiBase, useApiConfig } from \"@rebasepro/app\";\nimport { Alert, ArrowLeftIcon, Card, Chip, CircularProgress, Container, IconButton, Typography, cls } from \"@rebasepro/ui\";\nimport { createAdminAppsClient, isRecord } from \"./admin_apps_client\";\nimport { SavedAppFrame } from \"./saved_app_frame\";\n\ninterface AppSummary {\n id: string;\n title: string;\n visibility: \"personal\" | \"roles\" | \"team\";\n roles: string[];\n collections: string[];\n updatedAt: string;\n}\n\n/** Who an app is for, as the list says it. */\nfunction audience(app: AppSummary): string {\n if (app.visibility === \"team\") return \"Team\";\n if (app.visibility === \"roles\") return app.roles.join(\", \");\n return \"Only you\";\n}\n\nfunction summariesOf(result: unknown): AppSummary[] {\n const content = isRecord(result) ? result.structuredContent : undefined;\n const apps = isRecord(content) && Array.isArray(content.apps) ? content.apps : [];\n return apps.filter(isRecord).flatMap(app => typeof app.id === \"string\" && typeof app.title === \"string\"\n ? [{\n id: app.id,\n title: app.title,\n visibility: app.visibility === \"team\" || app.visibility === \"roles\" ? app.visibility : \"personal\",\n roles: Array.isArray(app.roles) ? app.roles.filter((role): role is string => typeof role === \"string\") : [],\n collections: Array.isArray(app.collections) ? app.collections.filter((name): name is string => typeof name === \"string\") : [],\n updatedAt: typeof app.updatedAt === \"string\" ? app.updatedAt : \"\"\n }]\n : []);\n}\n\nexport function SavedAppsView() {\n const apiBase = useApiBase();\n const getAuthToken = useApiConfig()?.getAuthToken;\n const client = useMemo(() => apiBase ? createAdminAppsClient(apiBase, getAuthToken) : undefined, [apiBase, getAuthToken]);\n const [apps, setApps] = useState<AppSummary[]>();\n const [error, setError] = useState<string>();\n const [open, setOpen] = useState<AppSummary>();\n\n useEffect(() => {\n if (!client) return;\n let cancelled = false;\n client.request(\"tools/call\", { name: \"list_apps\", arguments: {} })\n .then(result => {\n if (!cancelled) setApps(summariesOf(result));\n })\n .catch((reason: unknown) => {\n if (!cancelled) setError(reason instanceof Error ? reason.message : String(reason));\n });\n return () => {\n cancelled = true;\n };\n }, [client]);\n\n return (\n <Container maxWidth=\"6xl\" className=\"flex flex-col gap-4 py-6\">\n {open && client ? (\n <>\n <div className=\"flex items-center gap-2\">\n <IconButton size=\"small\" aria-label=\"Back to saved apps\" onClick={() => setOpen(undefined)}>\n <ArrowLeftIcon/>\n </IconButton>\n <Typography variant=\"h6\" className=\"truncate\">{open.title}</Typography>\n <Chip size=\"small\">{audience(open)}</Chip>\n </div>\n <SavedAppFrame client={client} appId={open.id}/>\n </>\n ) : (\n <>\n <div className=\"flex flex-col gap-1\">\n <Typography variant=\"h5\">Saved apps</Typography>\n <Typography variant=\"body2\" color=\"secondary\">\n Apps built with Claude and saved to this project. Each one runs as you, on the data you can reach.\n </Typography>\n </div>\n {!client && <Alert color=\"warning\" size=\"small\">This admin panel has no API address to load saved apps from.</Alert>}\n {error && <Alert color=\"error\" size=\"small\">{error}</Alert>}\n {client && !error && !apps && (\n <div className=\"flex items-center gap-2\"><CircularProgress size=\"small\"/><Typography variant=\"body2\" color=\"secondary\">Loading saved apps…</Typography></div>\n )}\n {apps && apps.length === 0 && (\n <Typography variant=\"body2\" color=\"secondary\">\n No saved apps yet. Ask Claude to build one with show_app, then to save it with save_app.\n </Typography>\n )}\n {apps && apps.length > 0 && (\n <div className=\"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3\">\n {apps.map(app => (\n <Card key={app.id} onClick={() => setOpen(app)} className={cls(\"flex flex-col gap-2 p-4 cursor-pointer hover:bg-surface-card-hover\")}>\n <Typography variant=\"subtitle2\" className=\"truncate\">{app.title}</Typography>\n <Typography variant=\"caption\" color=\"secondary\" className=\"truncate\">{app.collections.join(\", \")}</Typography>\n <div className=\"flex items-center justify-between gap-2\">\n <Chip size=\"small\">{audience(app)}</Chip>\n {app.updatedAt && (\n <Typography variant=\"caption\" color=\"secondary\">\n {new Date(app.updatedAt).toLocaleDateString(undefined, { month: \"short\", day: \"numeric\" })}\n </Typography>\n )}\n </div>\n </Card>\n ))}\n </div>\n )}\n </>\n )}\n </Container>\n );\n}\n\n/** The view to add to `views` for saved apps in the navigation. */\nexport const savedAppsView: AppView = {\n slug: \"apps\",\n name: \"Saved apps\",\n description: \"Apps built with Claude and saved to this project.\",\n icon: \"LayoutDashboard\",\n view: <SavedAppsView/>\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA6BA,SAAS,SAAS,KAAyB;CACvC,IAAI,IAAI,eAAe,QAAQ,OAAO;CACtC,IAAI,IAAI,eAAe,SAAS,OAAO,IAAI,MAAM,KAAK,IAAI;CAC1D,OAAO;AACX;AAEA,SAAS,YAAY,QAA+B;CAChD,MAAM,UAAU,SAAS,MAAM,IAAI,OAAO,oBAAoB,KAAA;CAE9D,QADa,SAAS,OAAO,KAAK,MAAM,QAAQ,QAAQ,IAAI,IAAI,QAAQ,OAAO,CAAC,EAAA,CACpE,OAAO,QAAQ,CAAC,CAAC,SAAQ,QAAO,OAAO,IAAI,OAAO,YAAY,OAAO,IAAI,UAAU,WACzF,CAAC;EACC,IAAI,IAAI;EACR,OAAO,IAAI;EACX,YAAY,IAAI,eAAe,UAAU,IAAI,eAAe,UAAU,IAAI,aAAa;EACvF,OAAO,MAAM,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AAD;QAAY,SAAQ;QAAU,OAAM;kBAC/B,IAAI,KAAK,IAAI,SAAS,CAAC,CAAC,mBAAmB,KAAA,GAAW;SAAE,OAAO;SAAS,KAAK;QAAU,CAAC;OACjF,CAAA,CAEf;;KACH;OAXK,IAAI,EAWT,CACT;GACA,CAAA;EAEX,EAAA,CAAA;CAEC,CAAA;AAEnB;;AAGA,IAAa,gBAAyB;CAClC,MAAM;CACN,MAAM;CACN,aAAa;CACb,MAAM;CACN,MAAM,oBAAC,eAAD,CAAe,CAAA;AACzB"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* EXPERIMENTAL. The admin panel's side of `POST /api/admin/apps/mcp`
|
|
3
|
+
* (`mcp/admin-apps-mcp.ts` in `@rebasepro/server`): JSON-RPC to the backend's
|
|
4
|
+
* MCP surface with the admin panel's own session.
|
|
5
|
+
*/
|
|
6
|
+
/** What a tool answers, as MCP shapes it. */
|
|
7
|
+
export interface AdminToolResult {
|
|
8
|
+
content?: Array<{
|
|
9
|
+
type: string;
|
|
10
|
+
text?: string;
|
|
11
|
+
}>;
|
|
12
|
+
structuredContent?: unknown;
|
|
13
|
+
isError?: boolean;
|
|
14
|
+
}
|
|
15
|
+
export interface AdminAppsClient {
|
|
16
|
+
/** A JSON-RPC method's result; rejects with the server's message. */
|
|
17
|
+
request(method: string, params: Record<string, unknown>): Promise<unknown>;
|
|
18
|
+
/** A tool's whole answer, a refusal included: the view shows its reason. */
|
|
19
|
+
callTool(name: string, args: Record<string, unknown>): Promise<AdminToolResult>;
|
|
20
|
+
}
|
|
21
|
+
export declare function createAdminAppsClient(apiBase: string, getAuthToken?: () => Promise<string | null | undefined>): AdminAppsClient;
|
|
22
|
+
/** The first text a tool answered: its refusal, when it refused. */
|
|
23
|
+
export declare function toolText(result: AdminToolResult): string | undefined;
|
|
24
|
+
export declare function isRecord(value: unknown): value is Record<string, unknown>;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
//#region src/saved_apps/admin_apps_client.ts
|
|
2
|
+
function createAdminAppsClient(apiBase, getAuthToken) {
|
|
3
|
+
let nextId = 1;
|
|
4
|
+
const request = async (method, params) => {
|
|
5
|
+
const token = await getAuthToken?.();
|
|
6
|
+
const response = await fetch(`${apiBase}/admin/apps/mcp`, {
|
|
7
|
+
method: "POST",
|
|
8
|
+
headers: {
|
|
9
|
+
"Content-Type": "application/json",
|
|
10
|
+
...token && { Authorization: `Bearer ${token}` }
|
|
11
|
+
},
|
|
12
|
+
body: JSON.stringify({
|
|
13
|
+
jsonrpc: "2.0",
|
|
14
|
+
id: nextId++,
|
|
15
|
+
method,
|
|
16
|
+
params
|
|
17
|
+
})
|
|
18
|
+
});
|
|
19
|
+
const body = await response.json().catch(() => void 0);
|
|
20
|
+
if (!isRecord(body)) throw new Error(`The server answered ${response.status} without a result.`);
|
|
21
|
+
if (isRecord(body.error)) throw new Error(String(body.error.message ?? "The server refused the request."));
|
|
22
|
+
if (!response.ok) throw new Error(`The server answered ${response.status}.`);
|
|
23
|
+
return body.result;
|
|
24
|
+
};
|
|
25
|
+
return {
|
|
26
|
+
request,
|
|
27
|
+
async callTool(name, args) {
|
|
28
|
+
const result = await request("tools/call", {
|
|
29
|
+
name,
|
|
30
|
+
arguments: args
|
|
31
|
+
});
|
|
32
|
+
return isRecord(result) ? result : {};
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** The first text a tool answered: its refusal, when it refused. */
|
|
37
|
+
function toolText(result) {
|
|
38
|
+
return result.content?.find((block) => block.type === "text" && typeof block.text === "string")?.text;
|
|
39
|
+
}
|
|
40
|
+
function isRecord(value) {
|
|
41
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
42
|
+
}
|
|
43
|
+
//#endregion
|
|
44
|
+
export { createAdminAppsClient, isRecord, toolText };
|
|
45
|
+
|
|
46
|
+
//# sourceMappingURL=admin_apps_client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"admin_apps_client.js","names":[],"sources":["../../src/saved_apps/admin_apps_client.ts"],"sourcesContent":["/**\n * EXPERIMENTAL. The admin panel's side of `POST /api/admin/apps/mcp`\n * (`mcp/admin-apps-mcp.ts` in `@rebasepro/server`): JSON-RPC to the backend's\n * MCP surface with the admin panel's own session.\n */\n\n/** What a tool answers, as MCP shapes it. */\nexport interface AdminToolResult {\n content?: Array<{ type: string; text?: string }>;\n structuredContent?: unknown;\n isError?: boolean;\n}\n\nexport interface AdminAppsClient {\n /** A JSON-RPC method's result; rejects with the server's message. */\n request(method: string, params: Record<string, unknown>): Promise<unknown>;\n /** A tool's whole answer, a refusal included: the view shows its reason. */\n callTool(name: string, args: Record<string, unknown>): Promise<AdminToolResult>;\n}\n\nexport function createAdminAppsClient(apiBase: string, getAuthToken?: () => Promise<string | null | undefined>): AdminAppsClient {\n let nextId = 1;\n const request = async (method: string, params: Record<string, unknown>): Promise<unknown> => {\n const token = await getAuthToken?.();\n const response = await fetch(`${apiBase}/admin/apps/mcp`, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\", ...(token && { Authorization: `Bearer ${token}` }) },\n body: JSON.stringify({ jsonrpc: \"2.0\", id: nextId++, method, params })\n });\n const body: unknown = await response.json().catch(() => undefined);\n if (!isRecord(body)) throw new Error(`The server answered ${response.status} without a result.`);\n if (isRecord(body.error)) throw new Error(String(body.error.message ?? \"The server refused the request.\"));\n if (!response.ok) throw new Error(`The server answered ${response.status}.`);\n return body.result;\n };\n return {\n request,\n async callTool(name, args) {\n const result = await request(\"tools/call\", { name, arguments: args });\n return isRecord(result) ? result : {};\n }\n };\n}\n\n/** The first text a tool answered: its refusal, when it refused. */\nexport function toolText(result: AdminToolResult): string | undefined {\n return result.content?.find(block => block.type === \"text\" && typeof block.text === \"string\")?.text;\n}\n\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n"],"mappings":";AAoBA,SAAgB,sBAAsB,SAAiB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boxed without `allow-same-origin`, so it has an opaque
|
|
6
|
+
* origin: no cookies, no storage of the admin panel's, no reach into this
|
|
7
|
+
* page. Its policy allows no network at all. Every read and write the app
|
|
8
|
+
* makes is a message to this page, which relays it to the admin panel's MCP
|
|
9
|
+
* endpoint as the person signed in, where it runs under their RLS — so stored
|
|
10
|
+
* code someone else wrote can do nothing the viewer could not, and cannot
|
|
11
|
+
* send their session anywhere.
|
|
12
|
+
*/
|
|
13
|
+
import React from "react";
|
|
14
|
+
import { type AdminAppsClient } from "./admin_apps_client.js";
|
|
15
|
+
/** The view document with the frame's policy at the top of its head. */
|
|
16
|
+
export declare function sandboxedViewDocument(html: string): string;
|
|
17
|
+
export declare function SavedAppFrame({ client, appId }: {
|
|
18
|
+
client: AdminAppsClient;
|
|
19
|
+
appId: string;
|
|
20
|
+
}): React.JSX.Element;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { isRecord, toolText } from "./admin_apps_client.js";
|
|
2
|
+
import { useEffect, useRef, useState } from "react";
|
|
3
|
+
import { jsx, jsxs } from "react/jsx-runtime";
|
|
4
|
+
import { Alert, CircularProgress, Typography } from "@rebasepro/ui";
|
|
5
|
+
//#region src/saved_apps/saved_app_frame.tsx
|
|
6
|
+
/**
|
|
7
|
+
* EXPERIMENTAL. A saved app in the admin panel, run as Claude runs it: the
|
|
8
|
+
* MCP App view in a frame, with this page as its host.
|
|
9
|
+
*
|
|
10
|
+
* The frame is sandboxed without `allow-same-origin`, so it has an opaque
|
|
11
|
+
* origin: no cookies, no storage of the admin panel's, no reach into this
|
|
12
|
+
* page. Its policy allows no network at all. Every read and write the app
|
|
13
|
+
* makes is a message to this page, which relays it to the admin panel's MCP
|
|
14
|
+
* endpoint as the person signed in, where it runs under their RLS — so stored
|
|
15
|
+
* code someone else wrote can do nothing the viewer could not, and cannot
|
|
16
|
+
* send their session anywhere.
|
|
17
|
+
*/
|
|
18
|
+
/** The view document's address (`MCP_APP_URI` in `@rebasepro/server`). */
|
|
19
|
+
var VIEW_URI = "ui://rebase/app.html";
|
|
20
|
+
/** No network, no frames, no forms posted anywhere: only the document's own inline code and data. */
|
|
21
|
+
var FRAME_POLICY = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; media-src data: blob:; connect-src 'none'; frame-src 'none'; form-action 'none'; base-uri 'none'";
|
|
22
|
+
/** The view document with the frame's policy at the top of its head. */
|
|
23
|
+
function sandboxedViewDocument(html) {
|
|
24
|
+
const meta = `<meta http-equiv="Content-Security-Policy" content="${FRAME_POLICY}">`;
|
|
25
|
+
return /<head[^>]*>/i.test(html) ? html.replace(/<head[^>]*>/i, (match) => `${match}${meta}`) : `${meta}${html}`;
|
|
26
|
+
}
|
|
27
|
+
function SavedAppFrame({ client, appId }) {
|
|
28
|
+
const frame = useRef(null);
|
|
29
|
+
const [document, setDocument] = useState();
|
|
30
|
+
const [opened, setOpened] = useState();
|
|
31
|
+
const [error, setError] = useState();
|
|
32
|
+
const [height, setHeight] = useState(640);
|
|
33
|
+
useEffect(() => {
|
|
34
|
+
let cancelled = false;
|
|
35
|
+
setError(void 0);
|
|
36
|
+
Promise.all([client.request("resources/read", { uri: VIEW_URI }), client.callTool("open_app", { id: appId })]).then(([read, result]) => {
|
|
37
|
+
if (cancelled) return;
|
|
38
|
+
const html = (isRecord(read) && Array.isArray(read.contents) ? read.contents : []).find(isRecord)?.text;
|
|
39
|
+
if (typeof html !== "string") throw new Error("This backend serves no app view.");
|
|
40
|
+
if (result.isError) throw new Error(toolText(result) ?? "The app could not be opened.");
|
|
41
|
+
setOpened(result);
|
|
42
|
+
setDocument(sandboxedViewDocument(html));
|
|
43
|
+
}).catch((reason) => {
|
|
44
|
+
if (!cancelled) setError(reason instanceof Error ? reason.message : String(reason));
|
|
45
|
+
});
|
|
46
|
+
return () => {
|
|
47
|
+
cancelled = true;
|
|
48
|
+
};
|
|
49
|
+
}, [client, appId]);
|
|
50
|
+
useEffect(() => {
|
|
51
|
+
if (!opened) return;
|
|
52
|
+
const target = () => frame.current?.contentWindow ?? null;
|
|
53
|
+
const send = (message) => target()?.postMessage({
|
|
54
|
+
jsonrpc: "2.0",
|
|
55
|
+
...message
|
|
56
|
+
}, "*");
|
|
57
|
+
const theme = () => window.document.documentElement.classList.contains("dark") ? "dark" : "light";
|
|
58
|
+
const receive = (event) => {
|
|
59
|
+
if (event.source === null || event.source !== target()) return;
|
|
60
|
+
const message = event.data;
|
|
61
|
+
if (!isRecord(message) || message.jsonrpc !== "2.0" || typeof message.method !== "string") return;
|
|
62
|
+
const id = typeof message.id === "string" || typeof message.id === "number" ? message.id : void 0;
|
|
63
|
+
const params = isRecord(message.params) ? message.params : {};
|
|
64
|
+
const answer = (result) => id !== void 0 && send({
|
|
65
|
+
id,
|
|
66
|
+
result
|
|
67
|
+
});
|
|
68
|
+
const refuse = (text) => id !== void 0 && send({
|
|
69
|
+
id,
|
|
70
|
+
error: {
|
|
71
|
+
code: -32e3,
|
|
72
|
+
message: text
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
switch (message.method) {
|
|
76
|
+
case "ui/initialize":
|
|
77
|
+
answer({
|
|
78
|
+
protocolVersion: params.protocolVersion,
|
|
79
|
+
hostInfo: {
|
|
80
|
+
name: "rebase-admin",
|
|
81
|
+
version: "0.1.0"
|
|
82
|
+
},
|
|
83
|
+
hostCapabilities: {},
|
|
84
|
+
hostContext: {
|
|
85
|
+
theme: theme(),
|
|
86
|
+
displayMode: "inline",
|
|
87
|
+
availableDisplayModes: ["inline"]
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
return;
|
|
91
|
+
case "ui/notifications/initialized":
|
|
92
|
+
send({
|
|
93
|
+
method: "ui/notifications/tool-result",
|
|
94
|
+
params: opened
|
|
95
|
+
});
|
|
96
|
+
return;
|
|
97
|
+
case "tools/call": {
|
|
98
|
+
const name = typeof params.name === "string" ? params.name : "";
|
|
99
|
+
const args = isRecord(params.arguments) ? params.arguments : {};
|
|
100
|
+
client.callTool(name, args).then(answer, (reason) => refuse(reason instanceof Error ? reason.message : String(reason)));
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
case "ui/notifications/size-changed":
|
|
104
|
+
if (typeof params.height === "number" && params.height > 0) setHeight(Math.ceil(params.height));
|
|
105
|
+
return;
|
|
106
|
+
case "ui/request-display-mode":
|
|
107
|
+
answer({ mode: "inline" });
|
|
108
|
+
return;
|
|
109
|
+
case "ui/update-model-context":
|
|
110
|
+
answer({});
|
|
111
|
+
return;
|
|
112
|
+
default: refuse(`The admin panel does not answer ${message.method}.`);
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
window.addEventListener("message", receive);
|
|
116
|
+
return () => window.removeEventListener("message", receive);
|
|
117
|
+
}, [opened, client]);
|
|
118
|
+
if (error) return /* @__PURE__ */ jsx(Alert, {
|
|
119
|
+
color: "error",
|
|
120
|
+
size: "small",
|
|
121
|
+
children: error
|
|
122
|
+
});
|
|
123
|
+
if (!document) return /* @__PURE__ */ jsxs("div", {
|
|
124
|
+
className: "flex items-center gap-2 p-4",
|
|
125
|
+
children: [/* @__PURE__ */ jsx(CircularProgress, { size: "small" }), /* @__PURE__ */ jsx(Typography, {
|
|
126
|
+
variant: "body2",
|
|
127
|
+
color: "secondary",
|
|
128
|
+
children: "Opening the app…"
|
|
129
|
+
})]
|
|
130
|
+
});
|
|
131
|
+
return /* @__PURE__ */ jsx("iframe", {
|
|
132
|
+
ref: frame,
|
|
133
|
+
title: "Saved app",
|
|
134
|
+
sandbox: "allow-scripts allow-forms",
|
|
135
|
+
srcDoc: document,
|
|
136
|
+
className: "w-full rounded-xl border-0",
|
|
137
|
+
style: { height }
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
//#endregion
|
|
141
|
+
export { SavedAppFrame, sandboxedViewDocument };
|
|
142
|
+
|
|
143
|
+
//# sourceMappingURL=saved_app_frame.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"saved_app_frame.js","names":[],"sources":["../../src/saved_apps/saved_app_frame.tsx"],"sourcesContent":["/**\n * EXPERIMENTAL. A saved app in the admin panel, run as Claude runs it: the\n * MCP App view in a frame, with this page as its host.\n *\n * The frame is sandboxed without `allow-same-origin`, so it has an opaque\n * origin: no cookies, no storage of the admin panel's, no reach into this\n * page. Its policy allows no network at all. Every read and write the app\n * makes is a message to this page, which relays it to the admin panel's MCP\n * endpoint as the person signed in, where it runs under their RLS — so stored\n * code someone else wrote can do nothing the viewer could not, and cannot\n * send their session anywhere.\n */\nimport React, { useEffect, useRef, useState } from \"react\";\nimport { Alert, CircularProgress, Typography } from \"@rebasepro/ui\";\nimport { isRecord, toolText, type AdminAppsClient, type AdminToolResult } from \"./admin_apps_client\";\n\n/** The view document's address (`MCP_APP_URI` in `@rebasepro/server`). */\nconst VIEW_URI = \"ui://rebase/app.html\";\n\n/** No network, no frames, no forms posted anywhere: only the document's own inline code and data. */\nconst FRAME_POLICY = \"default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; \"\n + \"font-src data:; media-src data: blob:; connect-src 'none'; frame-src 'none'; form-action 'none'; base-uri 'none'\";\n\n/** The view document with the frame's policy at the top of its head. */\nexport function sandboxedViewDocument(html: string): string {\n const meta = `<meta http-equiv=\"Content-Security-Policy\" content=\"${FRAME_POLICY}\">`;\n return /<head[^>]*>/i.test(html) ? html.replace(/<head[^>]*>/i, match => `${match}${meta}`) : `${meta}${html}`;\n}\n\nexport function SavedAppFrame({ client, appId }: { client: AdminAppsClient; appId: string }) {\n const frame = useRef<HTMLIFrameElement>(null);\n const [document, setDocument] = useState<string>();\n const [opened, setOpened] = useState<AdminToolResult>();\n const [error, setError] = useState<string>();\n const [height, setHeight] = useState(640);\n\n // The view, and the app as open_app answers it.\n useEffect(() => {\n let cancelled = false;\n setError(undefined);\n Promise.all([\n client.request(\"resources/read\", { uri: VIEW_URI }),\n client.callTool(\"open_app\", { id: appId })\n ]).then(([read, result]) => {\n if (cancelled) return;\n const contents = isRecord(read) && Array.isArray(read.contents) ? read.contents : [];\n const html = contents.find(isRecord)?.text;\n if (typeof html !== \"string\") throw new Error(\"This backend serves no app view.\");\n if (result.isError) throw new Error(toolText(result) ?? \"The app could not be opened.\");\n setOpened(result);\n setDocument(sandboxedViewDocument(html));\n }).catch((reason: unknown) => {\n if (!cancelled) setError(reason instanceof Error ? reason.message : String(reason));\n });\n return () => {\n cancelled = true;\n };\n }, [client, appId]);\n\n // The host's half of the MCP Apps protocol, for the one frame.\n useEffect(() => {\n if (!opened) return;\n const target = () => frame.current?.contentWindow ?? null;\n const send = (message: Record<string, unknown>) => target()?.postMessage({ jsonrpc: \"2.0\", ...message }, \"*\");\n const theme = () => window.document.documentElement.classList.contains(\"dark\") ? \"dark\" : \"light\";\n\n const receive = (event: MessageEvent) => {\n // Only the frame speaks to this host; its origin is opaque, so the window is the check.\n if (event.source === null || event.source !== target()) return;\n const message: unknown = event.data;\n if (!isRecord(message) || message.jsonrpc !== \"2.0\" || typeof message.method !== \"string\") return;\n const id = typeof message.id === \"string\" || typeof message.id === \"number\" ? message.id : undefined;\n const params = isRecord(message.params) ? message.params : {};\n const answer = (result: unknown) => id !== undefined && send({ id, result });\n const refuse = (text: string) => id !== undefined && send({ id, error: { code: -32000, message: text } });\n\n switch (message.method) {\n case \"ui/initialize\":\n answer({\n protocolVersion: params.protocolVersion,\n hostInfo: { name: \"rebase-admin\", version: \"0.1.0\" },\n hostCapabilities: {},\n hostContext: { theme: theme(), displayMode: \"inline\", availableDisplayModes: [\"inline\"] }\n });\n return;\n case \"ui/notifications/initialized\":\n send({ method: \"ui/notifications/tool-result\", params: opened });\n return;\n case \"tools/call\": {\n const name = typeof params.name === \"string\" ? params.name : \"\";\n const args = isRecord(params.arguments) ? params.arguments : {};\n client.callTool(name, args).then(answer, (reason: unknown) => refuse(reason instanceof Error ? reason.message : String(reason)));\n return;\n }\n case \"ui/notifications/size-changed\":\n if (typeof params.height === \"number\" && params.height > 0) setHeight(Math.ceil(params.height));\n return;\n case \"ui/request-display-mode\":\n answer({ mode: \"inline\" });\n return;\n case \"ui/update-model-context\":\n // No conversation to tell here.\n answer({});\n return;\n default:\n refuse(`The admin panel does not answer ${message.method}.`);\n }\n };\n window.addEventListener(\"message\", receive);\n return () => window.removeEventListener(\"message\", receive);\n }, [opened, client]);\n\n if (error) return <Alert color=\"error\" size=\"small\">{error}</Alert>;\n if (!document) {\n return (\n <div className=\"flex items-center gap-2 p-4\">\n <CircularProgress size=\"small\"/>\n <Typography variant=\"body2\" color=\"secondary\">Opening the app…</Typography>\n </div>\n );\n }\n return (\n <iframe\n ref={frame}\n title=\"Saved app\"\n sandbox=\"allow-scripts allow-forms\"\n srcDoc={document}\n className=\"w-full rounded-xl border-0\"\n style={{ height }}\n />\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBA,IAAM,WAAW;;AAGjB,IAAM,eAAe;;AAIrB,SAAgB,sBAAsB,MAAsB;CACxD,MAAM,OAAO,uDAAuD,aAAa;CACjF,OAAO,eAAe,KAAK,IAAI,IAAI,KAAK,QAAQ,iBAAgB,UAAS,GAAG,QAAQ,MAAM,IAAI,GAAG,OAAO;AAC5G;AAEA,SAAgB,cAAc,EAAE,QAAQ,SAAqD;CACzF,MAAM,QAAQ,OAA0B,IAAI;CAC5C,MAAM,CAAC,UAAU,eAAe,SAAiB;CACjD,MAAM,CAAC,QAAQ,aAAa,SAA0B;CACtD,MAAM,CAAC,OAAO,YAAY,SAAiB;CAC3C,MAAM,CAAC,QAAQ,aAAa,SAAS,GAAG;CAGxC,gBAAgB;EACZ,IAAI,YAAY;EAChB,SAAS,KAAA,CAAS;EAClB,QAAQ,IAAI,CACR,OAAO,QAAQ,kBAAkB,EAAE,KAAK,SAAS,CAAC,GAClD,OAAO,SAAS,YAAY,EAAE,IAAI,MAAM,CAAC,CAC7C,CAAC,CAAC,CAAC,MAAM,CAAC,MAAM,YAAY;GACxB,IAAI,WAAW;GAEf,MAAM,QADW,SAAS,IA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,OAAM;EACN,SAAQ;EACR,QAAQ;EACR,WAAU;EACV,OAAO,EAAE,OAAO;CACnB,CAAA;AAET"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CollectionConfig, Entity, FindParams,
|
|
1
|
+
import { CollectionConfig, Entity, FindParams, SDKCollectionClient } from "@rebasepro/types";
|
|
2
2
|
import { EntitySelection, RowSelection, SelectionQuery } from "@rebasepro/cms-types";
|
|
3
3
|
import { EntityPageAccessor } from "../util/entity_pages.js";
|
|
4
4
|
/**
|
|
@@ -35,11 +35,19 @@ export declare function selectionQueryToFindParams<M extends Record<string, unkn
|
|
|
35
35
|
* What {@link resolveSelection} takes: a view's selection, and where its rows
|
|
36
36
|
* are read.
|
|
37
37
|
*/
|
|
38
|
+
/**
|
|
39
|
+
* Where a query selection's rows are read: `context.data` is one, and so is
|
|
40
|
+
* anything that can `find` a collection's rows by its slug — the resolve reads
|
|
41
|
+
* nothing else.
|
|
42
|
+
*/
|
|
43
|
+
export interface SelectionRowSource {
|
|
44
|
+
collection(slug: string): Pick<SDKCollectionClient, "find">;
|
|
45
|
+
}
|
|
38
46
|
export interface ResolveSelectionParams<M extends Record<string, unknown>> {
|
|
39
47
|
/** `selectionController.selection`. */
|
|
40
48
|
selection: RowSelection<M>;
|
|
41
49
|
/** `context.data`: where a query selection's rows are read. */
|
|
42
|
-
data:
|
|
50
|
+
data: SelectionRowSource;
|
|
43
51
|
/** The selection's collection: what a row's id is read by. */
|
|
44
52
|
collection: CollectionConfig;
|
|
45
53
|
pageSize?: number;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve_selection.js","names":[],"sources":["../../src/selection/resolve_selection.ts"],"sourcesContent":["import { CollectionConfig, Entity, FindParams, OrderByTuple, RebaseSdkData } from \"@rebasepro/types\";\nimport { EntitySelection, RowSelection, SelectionQuery } from \"@rebasepro/cms-types\";\nimport { buildCompositeId, resolvePrimaryKeys } from \"@rebasepro/common\";\nimport { getRelationIncludeParams } from \"@rebasepro/app\";\nimport { EntityPageAccessor, walkEntityPages } from \"../util/entity_pages\";\n\n/**\n * Rows asked for per request while resolving a query selection.\n *\n * Same ceiling as the export walk, and for the same reason: the server refuses\n * a `limit` above its `MAX_LIST_LIMIT` rather than clamping it.\n */\nexport const SELECTION_PAGE_SIZE = 500;\n\n/**\n * Most rows one query selection will resolve to ids for.\n *\n * The write path is per-row — `deleteMany` loops the single-row delete server\n * side so hooks and row-level security still run for each — so this is a\n * genuine ceiling on the work, not just on memory. Going over it **throws**\n * rather than acting on a prefix, which is the failure that cannot be seen:\n * \"deleted 12,480 rows\" reads identically whether it was all of them or the\n * first page.\n */\nexport const MAX_SELECTION_ROWS = 20_000;\n\n/**\n * A stable string for a selection query, for comparing the query a selection\n * was made against with the one the view is showing now.\n *\n * Filter keys are sorted: `filterValues` is rebuilt on most renders and its key\n * order follows whatever order the user touched the columns in, so a plain\n * `JSON.stringify` would report the same filter as a different one and drop a\n * selection the moment anything re-rendered.\n */\nexport function serializeSelectionQuery<M extends Record<string, unknown>>(query: SelectionQuery<M>): string {\n const filter = query.filterValues\n ? Object.keys(query.filterValues).sort()\n .map(k => `${k}=${JSON.stringify((query.filterValues as Record<string, unknown>)[k])}`)\n .join(\"&\")\n : \"\";\n const order = query.sortBy?.map(([field, direction]) => `${String(field)}:${direction}`).join(\",\") ?? \"\";\n return `${query.path}|${filter}|${order}|${query.searchString ?? \"\"}`;\n}\n\n/** Turn a captured selection query into the `find` params that reproduce it. */\nexport function selectionQueryToFindParams<M extends Record<string, unknown>>(\n query: SelectionQuery<M>\n): Omit<FindParams<M>, \"limit\" | \"offset\" | \"page\"> {\n const where = query.filterValues && Object.keys(query.filterValues).length > 0\n ? query.filterValues\n : undefined;\n const orderBy = query.sortBy && query.sortBy.length > 0\n ? query.sortBy.map(([field, direction]) => [String(field), direction] as OrderByTuple)\n : undefined;\n return {\n where,\n orderBy,\n searchString: query.searchString\n } as Omit<FindParams<M>, \"limit\" | \"offset\" | \"page\">;\n}\n\n/**\n * What {@link resolveSelection} takes: a view's selection, and where its rows\n * are read.\n */\nexport interface ResolveSelectionParams<M extends Record<string, unknown>> {\n /** `selectionController.selection`. */\n selection: RowSelection<M>;\n /** `context.data`: where a query selection's rows are read. */\n data: Pick<RebaseSdkData, \"collection\">;\n /** The selection's collection: what a row's id is read by. */\n collection: CollectionConfig;\n pageSize?: number;\n maxRows?: number;\n /** Called after every page, so a long resolve can show where it is. */\n onProgress?: (loaded: number, total: number | undefined) => void;\n /** Checked between pages; aborting returns the rows read so far. */\n signal?: { aborted: boolean };\n}\n\n/**\n * {@link resolveEntitySelection}'s parameters: the admin's own selection and\n * the accessor of its own data.\n *\n * @internal\n */\nexport interface ResolveEntitySelectionParams<M extends Record<string, unknown>> {\n selection: EntitySelection<M>;\n /**\n * Reads the rows a query selection stands for. Only consulted in query\n * mode — an entities selection is already resolved and never hits the\n * network.\n */\n accessor: EntityPageAccessor<M>;\n pageSize?: number;\n maxRows?: number;\n onProgress?: (loaded: number, total: number | undefined) => void;\n signal?: { aborted: boolean };\n}\n\n/**\n * What {@link resolveSelection} hands back: the rows and their ids, as a\n * ticked selection holds them.\n */\nexport interface ResolvedSelection {\n /** The rows, as the server sends them. */\n rows: Record<string, unknown>[];\n /**\n * The id of each of `rows`, at the same position: the record's primary\n * key as a string, a composite one's parts joined by `:::` — what\n * `useRowWrites().update` and `useSidePanel().open` take.\n */\n ids: string[];\n}\n\n/**\n * The rows a selection covers, as the server sends them — ISO dates, a\n * belongsTo as its foreign key, a relation the view loads nested under its\n * name as REST's `include` returns it — one shape in both modes: a query\n * selection's rows are read with the view's own include. Their ids come\n * beside them.\n *\n * This is the *only* way to get rows out of a query selection, and it is why\n * {@link RowSelection} is a union: a bulk action has to call it, which means\n * it has to deal with the wait, the ceiling and the failure. The array this\n * replaced let the same code path read whatever the view had scrolled — 50 rows\n * of 12,480 — and report success.\n *\n * ```ts\n * const { rows, ids } = await resolveSelection({ selection, data: context.data, collection });\n * ```\n *\n * @throws When the query matches more than `maxRows` rows.\n */\nexport async function resolveSelection<M extends Record<string, unknown>>({\n data,\n collection,\n selection,\n ...rest\n}: ResolveSelectionParams<M>): Promise<ResolvedSelection> {\n if (selection.type === \"rows\") {\n rest.onProgress?.(selection.rows.length, selection.rows.length);\n return { rows: selection.rows, ids: selection.ids };\n }\n const keys = resolvePrimaryKeys(collection);\n const path = selection.query.path;\n const flat = data.collection<M>(path);\n // The relations the view reads its rows with, so a row read here is the\n // row a ticked one is.\n const include = getRelationIncludeParams(collection);\n // Walked as records, so the rows ticked off are told apart by the id the\n // view addressed them by; handed back as the rows read.\n const accessor: EntityPageAccessor<M> = {\n find: async (findParams) => {\n const page = await flat.find(include ? { ...findParams, include } : findParams);\n return {\n data: page.data.map((row) => ({ id: idOf(row, keys), path, values: row })),\n meta: page.meta\n };\n }\n };\n const excluded = new Set<string>(selection.excludedIds.map(String));\n const entities = await walkQuerySelection<M>({\n ...rest,\n query: selection.query,\n count: selection.count,\n excludedCount: selection.excludedIds.length,\n keep: (entity) => !excluded.has(String(entity.id)),\n accessor\n });\n return { rows: entities.map((entity) => entity.values), ids: entities.map((entity) => String(entity.id)) };\n}\n\nfunction idOf(row: Record<string, unknown>, keys: ReturnType<typeof resolvePrimaryKeys>): string {\n if (keys.length > 0) return buildCompositeId(row, keys);\n const id = row.id;\n return typeof id === \"string\" || typeof id === \"number\" ? String(id) : \"\";\n}\n\n/**\n * {@link resolveSelection} for the admin's own selection: the records it\n * covers, in its `Entity` view model, read through `accessor`.\n *\n * @throws When the query matches more than `maxRows` rows.\n * @internal\n */\nexport async function resolveEntitySelection<M extends Record<string, unknown>>({\n selection,\n accessor,\n pageSize = SELECTION_PAGE_SIZE,\n maxRows = MAX_SELECTION_ROWS,\n onProgress,\n signal\n}: ResolveEntitySelectionParams<M>): Promise<Entity<M>[]> {\n\n if (selection.type === \"entities\") {\n onProgress?.(selection.entities.length, selection.entities.length);\n return selection.entities;\n }\n\n const excluded = new Set(selection.excluded.map(e => `${e.path}/${e.id}`));\n return walkQuerySelection<M>({\n accessor,\n query: selection.query,\n count: selection.count,\n excludedCount: selection.excluded.length,\n keep: (e) => !excluded.has(`${e.path}/${e.id}`),\n pageSize,\n maxRows,\n onProgress,\n signal\n });\n}\n\n/**\n * Every row a query selection matches, less the ones ticked off. The ceiling\n * is on the rows left once those are out: the ticked-off rows are read with\n * the rest and dropped, so the walk may read that many past it.\n */\nasync function walkQuerySelection<M extends Record<string, unknown>>({\n accessor,\n query,\n count,\n excludedCount,\n keep,\n pageSize = SELECTION_PAGE_SIZE,\n maxRows = MAX_SELECTION_ROWS,\n onProgress,\n signal\n}: {\n accessor: EntityPageAccessor<M>;\n query: SelectionQuery<M>;\n count: number | undefined;\n excludedCount: number;\n keep: (entity: Entity<M>) => boolean;\n pageSize?: number;\n maxRows?: number;\n onProgress?: (loaded: number, total: number | undefined) => void;\n signal?: { aborted: boolean };\n}): Promise<Entity<M>[]> {\n // The count was taken when the selection was made, so it can only be a\n // forecast — but it is the one the user was shown and agreed to, and\n // refusing before the walk beats refusing forty pages in.\n if (count !== undefined && count - excludedCount > maxRows)\n throw new Error(selectionCeilingMessage(maxRows));\n\n const rows = await walkEntityPages<M>({\n accessor,\n params: selectionQueryToFindParams(query),\n pageSize,\n maxRows: maxRows + excludedCount,\n onProgress,\n signal,\n onCeiling: () => selectionCeilingMessage(maxRows)\n });\n\n if (excludedCount === 0) return rows;\n const kept = rows.filter(keep);\n if (kept.length > maxRows) throw new Error(selectionCeilingMessage(maxRows));\n return kept;\n}\n\nfunction selectionCeilingMessage(maxRows: number): string {\n return `This selection covers more than ${maxRows.toLocaleString()} rows, which is more than ` +\n \"can be acted on from the browser in one go. Filter the collection down first.\";\n}\n"],"mappings":";;;;;;;;;;AAYA,IAAa,sBAAsB;;;;;;;;;;;AAYnC,IAAa,qBAAqB;;;;;;;;;;AAWlC,SAAgB,wBAA2D,OAAkC;CACzG,MAAM,SAAS,MAAM,eACf,OAAO,KAAK,MAAM,YAAY,CAAC,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AM,OAAO,MAAM,gBAAmB;EAClC;EACA,QAAQ,2BAA2B,KAAK;EACxC;EACA,SAAS,UAAU;EACnB;EACA;EACA,iBAAiB,wBAAwB,OAAO;CACpD,CAAC;CAED,IAAI,kBAAkB,GAAG,OAAO;CAChC,MAAM,OAAO,KAAK,OAAO,IAAI;CAC7B,IAAI,KAAK,SAAS,SAAS,MAAM,IAAI,MAAM,wBAAwB,OAAO,CAAC;CAC3E,OAAO;AACX;AAEA,SAAS,wBAAwB,SAAyB;CACtD,OAAO,mCAAmC,QAAQ,eAAe,EAAE;AAEvE"}
|
|
1
|
+
{"version":3,"file":"resolve_selection.js","names":[],"sources":["../../src/selection/resolve_selection.ts"],"sourcesContent":["import { CollectionConfig, Entity, FindParams, OrderByTuple, SDKCollectionClient } from \"@rebasepro/types\";\nimport { EntitySelection, RowSelection, SelectionQuery } from \"@rebasepro/cms-types\";\nimport { buildCompositeId, resolvePrimaryKeys } from \"@rebasepro/common\";\nimport { getRelationIncludeParams } from \"@rebasepro/app\";\nimport { EntityPageAccessor, walkEntityPages } from \"../util/entity_pages\";\n\n/**\n * Rows asked for per request while resolving a query selection.\n *\n * Same ceiling as the export walk, and for the same reason: the server refuses\n * a `limit` above its `MAX_LIST_LIMIT` rather than clamping it.\n */\nexport const SELECTION_PAGE_SIZE = 500;\n\n/**\n * Most rows one query selection will resolve to ids for.\n *\n * The write path is per-row — `deleteMany` loops the single-row delete server\n * side so hooks and row-level security still run for each — so this is a\n * genuine ceiling on the work, not just on memory. Going over it **throws**\n * rather than acting on a prefix, which is the failure that cannot be seen:\n * \"deleted 12,480 rows\" reads identically whether it was all of them or the\n * first page.\n */\nexport const MAX_SELECTION_ROWS = 20_000;\n\n/**\n * A stable string for a selection query, for comparing the query a selection\n * was made against with the one the view is showing now.\n *\n * Filter keys are sorted: `filterValues` is rebuilt on most renders and its key\n * order follows whatever order the user touched the columns in, so a plain\n * `JSON.stringify` would report the same filter as a different one and drop a\n * selection the moment anything re-rendered.\n */\nexport function serializeSelectionQuery<M extends Record<string, unknown>>(query: SelectionQuery<M>): string {\n const filter = query.filterValues\n ? Object.keys(query.filterValues).sort()\n .map(k => `${k}=${JSON.stringify((query.filterValues as Record<string, unknown>)[k])}`)\n .join(\"&\")\n : \"\";\n const order = query.sortBy?.map(([field, direction]) => `${String(field)}:${direction}`).join(\",\") ?? \"\";\n return `${query.path}|${filter}|${order}|${query.searchString ?? \"\"}`;\n}\n\n/** Turn a captured selection query into the `find` params that reproduce it. */\nexport function selectionQueryToFindParams<M extends Record<string, unknown>>(\n query: SelectionQuery<M>\n): Omit<FindParams<M>, \"limit\" | \"offset\" | \"page\"> {\n const where = query.filterValues && Object.keys(query.filterValues).length > 0\n ? query.filterValues\n : undefined;\n const orderBy = query.sortBy && query.sortBy.length > 0\n ? query.sortBy.map(([field, direction]) => [String(field), direction] as OrderByTuple)\n : undefined;\n return {\n where,\n orderBy,\n searchString: query.searchString\n } as Omit<FindParams<M>, \"limit\" | \"offset\" | \"page\">;\n}\n\n/**\n * What {@link resolveSelection} takes: a view's selection, and where its rows\n * are read.\n */\n/**\n * Where a query selection's rows are read: `context.data` is one, and so is\n * anything that can `find` a collection's rows by its slug — the resolve reads\n * nothing else.\n */\nexport interface SelectionRowSource {\n collection(slug: string): Pick<SDKCollectionClient, \"find\">;\n}\n\nexport interface ResolveSelectionParams<M extends Record<string, unknown>> {\n /** `selectionController.selection`. */\n selection: RowSelection<M>;\n /** `context.data`: where a query selection's rows are read. */\n data: SelectionRowSource;\n /** The selection's collection: what a row's id is read by. */\n collection: CollectionConfig;\n pageSize?: number;\n maxRows?: number;\n /** Called after every page, so a long resolve can show where it is. */\n onProgress?: (loaded: number, total: number | undefined) => void;\n /** Checked between pages; aborting returns the rows read so far. */\n signal?: { aborted: boolean };\n}\n\n/**\n * {@link resolveEntitySelection}'s parameters: the admin's own selection and\n * the accessor of its own data.\n *\n * @internal\n */\nexport interface ResolveEntitySelectionParams<M extends Record<string, unknown>> {\n selection: EntitySelection<M>;\n /**\n * Reads the rows a query selection stands for. Only consulted in query\n * mode — an entities selection is already resolved and never hits the\n * network.\n */\n accessor: EntityPageAccessor<M>;\n pageSize?: number;\n maxRows?: number;\n onProgress?: (loaded: number, total: number | undefined) => void;\n signal?: { aborted: boolean };\n}\n\n/**\n * What {@link resolveSelection} hands back: the rows and their ids, as a\n * ticked selection holds them.\n */\nexport interface ResolvedSelection {\n /** The rows, as the server sends them. */\n rows: Record<string, unknown>[];\n /**\n * The id of each of `rows`, at the same position: the record's primary\n * key as a string, a composite one's parts joined by `:::` — what\n * `useRowWrites().update` and `useSidePanel().open` take.\n */\n ids: string[];\n}\n\n/**\n * The rows a selection covers, as the server sends them — ISO dates, a\n * belongsTo as its foreign key, a relation the view loads nested under its\n * name as REST's `include` returns it — one shape in both modes: a query\n * selection's rows are read with the view's own include. Their ids come\n * beside them.\n *\n * This is the *only* way to get rows out of a query selection, and it is why\n * {@link RowSelection} is a union: a bulk action has to call it, which means\n * it has to deal with the wait, the ceiling and the failure. The array this\n * replaced let the same code path read whatever the view had scrolled — 50 rows\n * of 12,480 — and report success.\n *\n * ```ts\n * const { rows, ids } = await resolveSelection({ selection, data: context.data, collection });\n * ```\n *\n * @throws When the query matches more than `maxRows` rows.\n */\nexport async function resolveSelection<M extends Record<string, unknown>>({\n data,\n collection,\n selection,\n ...rest\n}: ResolveSelectionParams<M>): Promise<ResolvedSelection> {\n if (selection.type === \"rows\") {\n rest.onProgress?.(selection.rows.length, selection.rows.length);\n return { rows: selection.rows, ids: selection.ids };\n }\n const keys = resolvePrimaryKeys(collection);\n const path = selection.query.path;\n const flat = data.collection(path);\n // The relations the view reads its rows with, so a row read here is the\n // row a ticked one is.\n const include = getRelationIncludeParams(collection);\n // Walked as records, so the rows ticked off are told apart by the id the\n // view addressed them by; handed back as the rows read.\n const accessor: EntityPageAccessor<Record<string, unknown>> = {\n find: async (findParams) => {\n const page = await flat.find(include ? { ...findParams, include } : findParams);\n return {\n data: page.data.map((row) => ({ id: idOf(row, keys), path, values: row })),\n meta: page.meta\n };\n }\n };\n const excluded = new Set<string>(selection.excludedIds.map(String));\n const entities = await walkQuerySelection<Record<string, unknown>>({\n ...rest,\n query: selection.query,\n count: selection.count,\n excludedCount: selection.excludedIds.length,\n keep: (entity) => !excluded.has(String(entity.id)),\n accessor\n });\n return { rows: entities.map((entity) => entity.values), ids: entities.map((entity) => String(entity.id)) };\n}\n\nfunction idOf(row: Record<string, unknown>, keys: ReturnType<typeof resolvePrimaryKeys>): string {\n if (keys.length > 0) return buildCompositeId(row, keys);\n const id = row.id;\n return typeof id === \"string\" || typeof id === \"number\" ? String(id) : \"\";\n}\n\n/**\n * {@link resolveSelection} for the admin's own selection: the records it\n * covers, in its `Entity` view model, read through `accessor`.\n *\n * @throws When the query matches more than `maxRows` rows.\n * @internal\n */\nexport async function resolveEntitySelection<M extends Record<string, unknown>>({\n selection,\n accessor,\n pageSize = SELECTION_PAGE_SIZE,\n maxRows = MAX_SELECTION_ROWS,\n onProgress,\n signal\n}: ResolveEntitySelectionParams<M>): Promise<Entity<M>[]> {\n\n if (selection.type === \"entities\") {\n onProgress?.(selection.entities.length, selection.entities.length);\n return selection.entities;\n }\n\n const excluded = new Set(selection.excluded.map(e => `${e.path}/${e.id}`));\n return walkQuerySelection<M>({\n accessor,\n query: selection.query,\n count: selection.count,\n excludedCount: selection.excluded.length,\n keep: (e) => !excluded.has(`${e.path}/${e.id}`),\n pageSize,\n maxRows,\n onProgress,\n signal\n });\n}\n\n/**\n * Every row a query selection matches, less the ones ticked off. The ceiling\n * is on the rows left once those are out: the ticked-off rows are read with\n * the rest and dropped, so the walk may read that many past it.\n */\nasync function walkQuerySelection<M extends Record<string, unknown>>({\n accessor,\n query,\n count,\n excludedCount,\n keep,\n pageSize = SELECTION_PAGE_SIZE,\n maxRows = MAX_SELECTION_ROWS,\n onProgress,\n signal\n}: {\n accessor: EntityPageAccessor<M>;\n query: SelectionQuery<M>;\n count: number | undefined;\n excludedCount: number;\n keep: (entity: Entity<M>) => boolean;\n pageSize?: number;\n maxRows?: number;\n onProgress?: (loaded: number, total: number | undefined) => void;\n signal?: { aborted: boolean };\n}): Promise<Entity<M>[]> {\n // The count was taken when the selection was made, so it can only be a\n // forecast — but it is the one the user was shown and agreed to, and\n // refusing before the walk beats refusing forty pages in.\n if (count !== undefined && count - excludedCount > maxRows)\n throw new Error(selectionCeilingMessage(maxRows));\n\n const rows = await walkEntityPages<M>({\n accessor,\n params: selectionQueryToFindParams(query),\n pageSize,\n maxRows: maxRows + excludedCount,\n onProgress,\n signal,\n onCeiling: () => selectionCeilingMessage(maxRows)\n });\n\n if (excludedCount === 0) return rows;\n const kept = rows.filter(keep);\n if (kept.length > maxRows) throw new Error(selectionCeilingMessage(maxRows));\n return kept;\n}\n\nfunction selectionCeilingMessage(maxRows: number): string {\n return `This selection covers more than ${maxRows.toLocaleString()} rows, which is more than ` +\n \"can be acted on from the browser in one go. Filter the collection down first.\";\n}\n"],"mappings":";;;;;;;;;;AAYA,IAAa,sBAAsB;;;;;;;;;;;AAYnC,IAAa,qBAAqB;;;;;;;;;;AAWlC,SAAgB,wBAA2D,OAAkC;CACzG,MAAM,SAAS,MAAM,eACf,OAAO,KAAK,MAAM,YAAY,CAAC,CAAC,KAAK,CAAC,CACnC,KAAI,MAAK,GAAG,EAAE,GAAG,KAAK,UAAW,MAAM,aAAyC,EAAE,GAAG,CAAC,CACtF,KAAK,GAAG,IACX;CACN,MAAM,QAAQ,MAAM,QAAQ,KAAK,CAAC,OAAO,eAAe,GAAG,OAAO,KAAK,EAAE,GAAG,WAAW,CAAC,CAAC,KAAK,GAAG,KAAK;CACtG,OAAO,GAAG,MAAM,KAAK,GAAG,OAAO,GAAG,MAAM,GAAG,MAAM,gBAAgB;AACrE;;AAGA,SAAgB,2BACZ,OACgD;CAOhD,OAAO;EACH,OAPU,MAAM,gBAAgB,OAAO,KAAK,MAAM,YAAY,CAAC,CAAC,SAAS,IACvE,MAAM,eACN,KAAA;EAMF,SALY,MAAM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tD,MAAM,KAAK,IAAI;CACf,OAAO,OAAO,OAAO,YAAY,OAAO,OAAO,WAAW,OAAO,EAAE,IAAI;AAC3E;;;;;;;;AASA,eAAsB,uBAA0D,EAC5E,WACA,UACA,WAAA,KACA,UAAU,oBACV,YACA,UACsD;CAEtD,IAAI,UAAU,SAAS,YAAY;EAC/B,aAAa,UAAU,SAAS,QAAQ,UAAU,SAAS,MAAM;EACjE,OAAO,UAAU;CACrB;CAEA,MAAM,WAAW,IAAI,IAAI,UAAU,SAAS,KAAI,MAAK,GAAG,EAAE,KAAK,GAAG,EAAE,IAAI,CAAC;CACzE,OAAO,mBAAsB;EACzB;EACA,OAAO,UAAU;EACjB,OAAO,UAAU;EACjB,eAAe,UAAU,SAAS;EAClC,OAAO,MAAM,CAAC,SAAS,IAAI,GAAG,EAAE,KAAK,GAAG,EAAE,IAAI;EAC9C;EACA;EACA;EACA;CACJ,CAAC;AACL;;;;;;AAOA,eAAe,mBAAsD,EACjE,UACA,OACA,OACA,eACA,MACA,WAAA,KACA,UAAU,oBACV,YACA,UAWqB;CAIrB,IAAI,UAAU,KAAA,KAAa,QAAQ,gBAAgB,SAC/C,MAAM,IAAI,MAAM,wBAAwB,OAAO,CAAC;CAEpD,MAAM,OAAO,MAAM,gBAAmB;EAClC;EACA,QAAQ,2BAA2B,KAAK;EACxC;EACA,SAAS,UAAU;EACnB;EACA;EACA,iBAAiB,wBAAwB,OAAO;CACpD,CAAC;CAED,IAAI,kBAAkB,GAAG,OAAO;CAChC,MAAM,OAAO,KAAK,OAAO,IAAI;CAC7B,IAAI,KAAK,SAAS,SAAS,MAAM,IAAI,MAAM,wBAAwB,OAAO,CAAC;CAC3E,OAAO;AACX;AAEA,SAAS,wBAAwB,SAAyB;CACtD,OAAO,mCAAmC,QAAQ,eAAe,EAAE;AAEvE"}
|
|
@@ -3,8 +3,8 @@ import type { Property } from "@rebasepro/types";
|
|
|
3
3
|
import type { PropertyConfig, AdminCollection } from "@rebasepro/cms-types";
|
|
4
4
|
import React from "react";
|
|
5
5
|
import type { IconSize } from "@rebasepro/ui";
|
|
6
|
-
export declare function isReferenceProperty(property: Property): boolean | null;
|
|
7
|
-
export declare function isRelationProperty(property: Property): boolean | null;
|
|
6
|
+
export declare function isReferenceProperty(property: Property | null | undefined): boolean | null;
|
|
7
|
+
export declare function isRelationProperty(property: Property | null | undefined): boolean | null;
|
|
8
8
|
export declare function getIconForWidget(widget: PropertyConfig | undefined, size: IconSize | number): React.JSX.Element;
|
|
9
9
|
export declare function getIconForProperty(property: Property, size?: IconSize | number, fields?: Record<string, PropertyConfig>): React.ReactNode;
|
|
10
10
|
/**
|