@guard-rail/core 0.3.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +111 -28
- package/dist/adapters/supabase/auth.js +50 -0
- package/dist/adapters/supabase/auth.js.map +1 -1
- package/dist/cli/init-db.d.ts +1 -0
- package/dist/cli/init-db.js +121 -0
- package/dist/cli/init-db.js.map +1 -0
- package/dist/core/adapter-types.d.ts +43 -1
- package/dist/core/defs.d.ts +43 -2
- package/dist/core/defs.js +29 -2
- package/dist/core/defs.js.map +1 -1
- package/dist/core/types.d.ts +16 -1
- package/dist/index.client.d.ts +7 -4
- package/dist/index.client.js +22 -1
- package/dist/index.client.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +11 -1
- package/dist/index.js.map +1 -1
- package/dist/react/Admin.js +83 -7
- package/dist/react/Admin.js.map +1 -1
- package/dist/react/AuthRedirectSync.d.ts +20 -0
- package/dist/react/AuthRedirectSync.js +38 -0
- package/dist/react/AuthRedirectSync.js.map +1 -0
- package/dist/react/GRail/client.js +5 -1
- package/dist/react/GRail/client.js.map +1 -1
- package/dist/react/Provider.js +5 -1
- package/dist/react/Provider.js.map +1 -1
- package/dist/react/Syncer.d.ts +10 -8
- package/dist/react/Syncer.js +8 -6
- package/dist/react/Syncer.js.map +1 -1
- package/dist/react/useAnchorRect.d.ts +17 -1
- package/dist/react/useAnchorRect.js +37 -9
- package/dist/react/useAnchorRect.js.map +1 -1
- package/dist/server/access.d.ts +76 -0
- package/dist/server/access.js +33 -0
- package/dist/server/access.js.map +1 -0
- package/dist/server/actions.d.ts +49 -8
- package/dist/server/actions.js +65 -10
- package/dist/server/actions.js.map +1 -1
- package/dist/server/fieldData.d.ts +4 -2
- package/dist/server/fieldData.js.map +1 -1
- package/dist/server/repeaterActions.js +1 -1
- package/dist/server/repeaterActions.js.map +1 -1
- package/dist/server/wrapper.js +9 -4
- package/dist/server/wrapper.js.map +1 -1
- package/package.json +3 -2
- package/scripts/postinstall.mjs +4 -4
package/dist/react/Syncer.js
CHANGED
|
@@ -1,17 +1,19 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { useEffect } from "react";
|
|
3
3
|
import { useSearchParams } from "next/navigation";
|
|
4
|
-
import { GR_COOKIES } from "../core/defs";
|
|
4
|
+
import { GR_COOKIES, GR_EDIT_MODE_TTL_SECONDS } from "../core/defs";
|
|
5
5
|
function EditSyncer() {
|
|
6
6
|
const searchParams = useSearchParams();
|
|
7
7
|
useEffect(() => {
|
|
8
8
|
const edit = searchParams.get("edit");
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
9
|
+
const current = document.cookie.match(
|
|
10
|
+
new RegExp(`(?:^|; )${GR_COOKIES.EDIT_MODE}=([^;]*)`)
|
|
11
|
+
)?.[1];
|
|
12
|
+
if (edit === "true" && current !== "true") {
|
|
13
|
+
document.cookie = `${GR_COOKIES.EDIT_MODE}=true; path=/; max-age=${GR_EDIT_MODE_TTL_SECONDS}; SameSite=Lax`;
|
|
12
14
|
window.location.reload();
|
|
13
|
-
} else if (edit === "false" &&
|
|
14
|
-
document.cookie = `${GR_COOKIES.EDIT_MODE}
|
|
15
|
+
} else if (edit === "false" && current !== "false") {
|
|
16
|
+
document.cookie = `${GR_COOKIES.EDIT_MODE}=false; path=/; max-age=${GR_EDIT_MODE_TTL_SECONDS}; SameSite=Lax`;
|
|
15
17
|
window.location.reload();
|
|
16
18
|
}
|
|
17
19
|
}, [searchParams]);
|
package/dist/react/Syncer.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/react/Syncer.tsx"],"sourcesContent":["\"use client\";\n\nimport { useEffect } from \"react\";\nimport { useSearchParams } from \"next/navigation\";\nimport { GR_COOKIES } from \"../core/defs\";\n\n/**\n * Turns edit mode on from the URL
|
|
1
|
+
{"version":3,"sources":["../../src/react/Syncer.tsx"],"sourcesContent":["\"use client\";\n\nimport { useEffect } from \"react\";\nimport { useSearchParams } from \"next/navigation\";\nimport { GR_COOKIES, GR_EDIT_MODE_TTL_SECONDS } from \"../core/defs\";\n\n/**\n * Turns edit mode on (or explicitly off) from the URL, via a short-lived\n * cookie rather than a persistent one — see the comment on GR_COOKIES for\n * why that boundary moved here. ?edit=true is a one-time switch, not a value\n * that has to keep appearing on every URL to hold that state, but \"holding\n * that state\" now means \"for the next ~10 minutes, or until real auth takes\n * over,\" not indefinitely.\n *\n * A page that simply doesn't mention `edit` — which is every normal link on\n * the site, including a repeater's card linking to its own route — must\n * leave the cookie alone. Treating \"no param\" as \"turn it off\" was a past\n * bug: it silently ended the edit session on the very first click to a page\n * that didn't happen to carry the query string. Only an explicit ?edit=false\n * turns it off from the URL; logging out is the normal way to end a real\n * session (and, unlike this cookie, actually needs to — see logoutAction).\n */\nexport function EditSyncer() {\n const searchParams = useSearchParams();\n\n useEffect(() => {\n const edit = searchParams.get(\"edit\");\n const current = document.cookie.match(\n new RegExp(`(?:^|; )${GR_COOKIES.EDIT_MODE}=([^;]*)`),\n )?.[1];\n\n if (edit === \"true\" && current !== \"true\") {\n document.cookie = `${GR_COOKIES.EDIT_MODE}=true; path=/; max-age=${GR_EDIT_MODE_TTL_SECONDS}; SameSite=Lax`;\n window.location.reload();\n } else if (edit === \"false\" && current !== \"false\") {\n document.cookie = `${GR_COOKIES.EDIT_MODE}=false; path=/; max-age=${GR_EDIT_MODE_TTL_SECONDS}; SameSite=Lax`;\n window.location.reload();\n }\n }, [searchParams]);\n\n return null;\n}\n"],"mappings":";AAEA,SAAS,iBAAiB;AAC1B,SAAS,uBAAuB;AAChC,SAAS,YAAY,gCAAgC;AAkB9C,SAAS,aAAa;AAC3B,QAAM,eAAe,gBAAgB;AAErC,YAAU,MAAM;AACd,UAAM,OAAO,aAAa,IAAI,MAAM;AACpC,UAAM,UAAU,SAAS,OAAO;AAAA,MAC9B,IAAI,OAAO,WAAW,WAAW,SAAS,UAAU;AAAA,IACtD,IAAI,CAAC;AAEL,QAAI,SAAS,UAAU,YAAY,QAAQ;AACzC,eAAS,SAAS,GAAG,WAAW,SAAS,0BAA0B,wBAAwB;AAC3F,aAAO,SAAS,OAAO;AAAA,IACzB,WAAW,SAAS,WAAW,YAAY,SAAS;AAClD,eAAS,SAAS,GAAG,WAAW,SAAS,2BAA2B,wBAAwB;AAC5F,aAAO,SAAS,OAAO;AAAA,IACzB;AAAA,EACF,GAAG,CAAC,YAAY,CAAC;AAEjB,SAAO;AACT;","names":[]}
|
|
@@ -11,7 +11,23 @@ interface AnchorRect {
|
|
|
11
11
|
*
|
|
12
12
|
* Listens on the capture phase so scrolling inside any ancestor container
|
|
13
13
|
* repositions the chrome, not just window scroll.
|
|
14
|
+
*
|
|
15
|
+
* Two things keep this cheap when many elements track at once (every image
|
|
16
|
+
* field does, for its idle marker, for as long as edit mode is on — not just
|
|
17
|
+
* the one actively being edited):
|
|
18
|
+
*
|
|
19
|
+
* - Measurement is coalesced to one requestAnimationFrame per scroll/resize
|
|
20
|
+
* burst, not one per raw event. A scroll can fire far more of those than
|
|
21
|
+
* the page ever paints, so N tracked elements without this meant N
|
|
22
|
+
* getBoundingClientRect() calls and N re-renders per event, not per frame.
|
|
23
|
+
* - `gateByVisibility` skips attaching any listener at all — scroll, resize,
|
|
24
|
+
* or the ResizeObserver — for an element nowhere near the viewport, via
|
|
25
|
+
* IntersectionObserver. A long page with many editable images then only
|
|
26
|
+
* pays for the handful actually in view at a given scroll position, not
|
|
27
|
+
* all of them.
|
|
14
28
|
*/
|
|
15
|
-
declare function useAnchorRect(ref: RefObject<HTMLElement | null>, active: boolean
|
|
29
|
+
declare function useAnchorRect(ref: RefObject<HTMLElement | null>, active: boolean, options?: {
|
|
30
|
+
gateByVisibility?: boolean;
|
|
31
|
+
}): AnchorRect | null;
|
|
16
32
|
|
|
17
33
|
export { type AnchorRect, useAnchorRect };
|
|
@@ -1,30 +1,58 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { useCallback, useEffect, useState } from "react";
|
|
3
|
-
function useAnchorRect(ref, active) {
|
|
2
|
+
import { useCallback, useEffect, useRef, useState } from "react";
|
|
3
|
+
function useAnchorRect(ref, active, options = {}) {
|
|
4
|
+
const { gateByVisibility = false } = options;
|
|
4
5
|
const [rect, setRect] = useState(null);
|
|
6
|
+
const rafRef = useRef(null);
|
|
5
7
|
const measure = useCallback(() => {
|
|
6
8
|
const el = ref.current;
|
|
7
9
|
if (!el) return;
|
|
8
10
|
const r = el.getBoundingClientRect();
|
|
9
11
|
setRect({ top: r.top, left: r.left, bottom: r.bottom, width: r.width });
|
|
10
12
|
}, [ref]);
|
|
13
|
+
const scheduleMeasure = useCallback(() => {
|
|
14
|
+
if (rafRef.current !== null) return;
|
|
15
|
+
rafRef.current = requestAnimationFrame(() => {
|
|
16
|
+
rafRef.current = null;
|
|
17
|
+
measure();
|
|
18
|
+
});
|
|
19
|
+
}, [measure]);
|
|
20
|
+
const [visible, setVisible] = useState(!gateByVisibility);
|
|
11
21
|
useEffect(() => {
|
|
12
|
-
if (!active)
|
|
22
|
+
if (!active || !gateByVisibility) return;
|
|
23
|
+
const el = ref.current;
|
|
24
|
+
if (!el || typeof IntersectionObserver === "undefined") {
|
|
25
|
+
setVisible(true);
|
|
26
|
+
return;
|
|
27
|
+
}
|
|
28
|
+
const io = new IntersectionObserver(
|
|
29
|
+
(entries) => setVisible(entries[0]?.isIntersecting ?? false),
|
|
30
|
+
{ rootMargin: "200px" }
|
|
31
|
+
);
|
|
32
|
+
io.observe(el);
|
|
33
|
+
return () => io.disconnect();
|
|
34
|
+
}, [active, gateByVisibility, ref]);
|
|
35
|
+
useEffect(() => {
|
|
36
|
+
if (!active || gateByVisibility && !visible) {
|
|
13
37
|
setRect(null);
|
|
14
38
|
return;
|
|
15
39
|
}
|
|
16
40
|
measure();
|
|
17
|
-
window.addEventListener("scroll",
|
|
18
|
-
window.addEventListener("resize",
|
|
19
|
-
const observer = typeof ResizeObserver !== "undefined" ? new ResizeObserver(
|
|
41
|
+
window.addEventListener("scroll", scheduleMeasure, true);
|
|
42
|
+
window.addEventListener("resize", scheduleMeasure);
|
|
43
|
+
const observer = typeof ResizeObserver !== "undefined" ? new ResizeObserver(scheduleMeasure) : null;
|
|
20
44
|
if (observer && ref.current) observer.observe(ref.current);
|
|
21
45
|
if (observer) observer.observe(document.body);
|
|
22
46
|
return () => {
|
|
23
|
-
window.removeEventListener("scroll",
|
|
24
|
-
window.removeEventListener("resize",
|
|
47
|
+
window.removeEventListener("scroll", scheduleMeasure, true);
|
|
48
|
+
window.removeEventListener("resize", scheduleMeasure);
|
|
25
49
|
observer?.disconnect();
|
|
50
|
+
if (rafRef.current !== null) {
|
|
51
|
+
cancelAnimationFrame(rafRef.current);
|
|
52
|
+
rafRef.current = null;
|
|
53
|
+
}
|
|
26
54
|
};
|
|
27
|
-
}, [active, measure, ref]);
|
|
55
|
+
}, [active, gateByVisibility, visible, measure, scheduleMeasure, ref]);
|
|
28
56
|
return rect;
|
|
29
57
|
}
|
|
30
58
|
export {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/react/useAnchorRect.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useState, type RefObject } from \"react\";\n\nexport interface AnchorRect {\n top: number;\n left: number;\n bottom: number;\n width: number;\n}\n\n/**\n * Tracks an element's viewport rect so editing chrome can sit against it.\n *\n * Listens on the capture phase so scrolling inside any ancestor container\n * repositions the chrome, not just window scroll.\n */\nexport function useAnchorRect(\n ref: RefObject<HTMLElement | null>,\n active: boolean,\n): AnchorRect | null {\n const [rect, setRect] = useState<AnchorRect | null>(null);\n\n const measure = useCallback(() => {\n const el = ref.current;\n if (!el) return;\n const r = el.getBoundingClientRect();\n setRect({ top: r.top, left: r.left, bottom: r.bottom, width: r.width });\n }, [ref]);\n\n useEffect(() => {\n if (!active) {\n setRect(null);\n return;\n }\n\n measure();\n window.addEventListener(\"scroll\",
|
|
1
|
+
{"version":3,"sources":["../../src/react/useAnchorRect.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useRef, useState, type RefObject } from \"react\";\n\nexport interface AnchorRect {\n top: number;\n left: number;\n bottom: number;\n width: number;\n}\n\n/**\n * Tracks an element's viewport rect so editing chrome can sit against it.\n *\n * Listens on the capture phase so scrolling inside any ancestor container\n * repositions the chrome, not just window scroll.\n *\n * Two things keep this cheap when many elements track at once (every image\n * field does, for its idle marker, for as long as edit mode is on — not just\n * the one actively being edited):\n *\n * - Measurement is coalesced to one requestAnimationFrame per scroll/resize\n * burst, not one per raw event. A scroll can fire far more of those than\n * the page ever paints, so N tracked elements without this meant N\n * getBoundingClientRect() calls and N re-renders per event, not per frame.\n * - `gateByVisibility` skips attaching any listener at all — scroll, resize,\n * or the ResizeObserver — for an element nowhere near the viewport, via\n * IntersectionObserver. A long page with many editable images then only\n * pays for the handful actually in view at a given scroll position, not\n * all of them.\n */\nexport function useAnchorRect(\n ref: RefObject<HTMLElement | null>,\n active: boolean,\n options: { gateByVisibility?: boolean } = {},\n): AnchorRect | null {\n const { gateByVisibility = false } = options;\n const [rect, setRect] = useState<AnchorRect | null>(null);\n const rafRef = useRef<number | null>(null);\n\n const measure = useCallback(() => {\n const el = ref.current;\n if (!el) return;\n const r = el.getBoundingClientRect();\n setRect({ top: r.top, left: r.left, bottom: r.bottom, width: r.width });\n }, [ref]);\n\n const scheduleMeasure = useCallback(() => {\n if (rafRef.current !== null) return;\n rafRef.current = requestAnimationFrame(() => {\n rafRef.current = null;\n measure();\n });\n }, [measure]);\n\n const [visible, setVisible] = useState(!gateByVisibility);\n\n useEffect(() => {\n if (!active || !gateByVisibility) return;\n const el = ref.current;\n if (!el || typeof IntersectionObserver === \"undefined\") {\n setVisible(true);\n return;\n }\n // A margin outside the viewport, not just inside it — so tracking (and\n // the marker) is already live the instant an image scrolls into view,\n // not a frame behind.\n const io = new IntersectionObserver(\n (entries) => setVisible(entries[0]?.isIntersecting ?? false),\n { rootMargin: \"200px\" },\n );\n io.observe(el);\n return () => io.disconnect();\n }, [active, gateByVisibility, ref]);\n\n useEffect(() => {\n if (!active || (gateByVisibility && !visible)) {\n setRect(null);\n return;\n }\n\n measure();\n window.addEventListener(\"scroll\", scheduleMeasure, true);\n window.addEventListener(\"resize\", scheduleMeasure);\n\n // Catches layout shifts from the edit itself (text reflowing the element).\n const observer =\n typeof ResizeObserver !== \"undefined\" ? new ResizeObserver(scheduleMeasure) : null;\n if (observer && ref.current) observer.observe(ref.current);\n // Content changing size above or beside the element moves it without\n // resizing it, which observing the element alone never sees. The body's\n // own height changes in most of those cases.\n if (observer) observer.observe(document.body);\n\n return () => {\n window.removeEventListener(\"scroll\", scheduleMeasure, true);\n window.removeEventListener(\"resize\", scheduleMeasure);\n observer?.disconnect();\n if (rafRef.current !== null) {\n cancelAnimationFrame(rafRef.current);\n rafRef.current = null;\n }\n };\n }, [active, gateByVisibility, visible, measure, scheduleMeasure, ref]);\n\n return rect;\n}\n"],"mappings":";AAEA,SAAS,aAAa,WAAW,QAAQ,gBAAgC;AA6BlE,SAAS,cACd,KACA,QACA,UAA0C,CAAC,GACxB;AACnB,QAAM,EAAE,mBAAmB,MAAM,IAAI;AACrC,QAAM,CAAC,MAAM,OAAO,IAAI,SAA4B,IAAI;AACxD,QAAM,SAAS,OAAsB,IAAI;AAEzC,QAAM,UAAU,YAAY,MAAM;AAChC,UAAM,KAAK,IAAI;AACf,QAAI,CAAC,GAAI;AACT,UAAM,IAAI,GAAG,sBAAsB;AACnC,YAAQ,EAAE,KAAK,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,EAAE,QAAQ,OAAO,EAAE,MAAM,CAAC;AAAA,EACxE,GAAG,CAAC,GAAG,CAAC;AAER,QAAM,kBAAkB,YAAY,MAAM;AACxC,QAAI,OAAO,YAAY,KAAM;AAC7B,WAAO,UAAU,sBAAsB,MAAM;AAC3C,aAAO,UAAU;AACjB,cAAQ;AAAA,IACV,CAAC;AAAA,EACH,GAAG,CAAC,OAAO,CAAC;AAEZ,QAAM,CAA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|
6
|
+
*
|
|
7
|
+
* Deliberately NOT in a "use server" file: every export of one of those is a
|
|
8
|
+
* callable Server Action endpoint, which is the wrong shape for an
|
|
9
|
+
* authorization helper — it should only ever run inside the server code that
|
|
10
|
+
* calls it.
|
|
11
|
+
*
|
|
12
|
+
* The client's copy of the role (useGRail().role) decides what to *show*; it
|
|
13
|
+
* never decides what is *allowed*. A hidden button is not authorization, so
|
|
14
|
+
* any Server Action behind a custom admin UI must call one of these itself.
|
|
15
|
+
*/
|
|
16
|
+
/**
|
|
17
|
+
* Returns the signed-in viewer if their role is in `allowed`, otherwise null.
|
|
18
|
+
* The building block for the two helpers below; reach for this directly only
|
|
19
|
+
* when you need the viewer itself (their email, say), not just a yes/no.
|
|
20
|
+
*/
|
|
21
|
+
declare function requireRole(allowed: readonly GRRole[]): Promise<GRViewer | null>;
|
|
22
|
+
/** True for a signed-in admin of this site — team management, and everything an editor can do. */
|
|
23
|
+
declare function isAdmin(): Promise<boolean>;
|
|
24
|
+
/**
|
|
25
|
+
* True for anyone who may edit this site's content: an editor, or an admin
|
|
26
|
+
* (admins can do everything editors can). The check for a custom drawer's
|
|
27
|
+
* Server Action that changes content. Use isAdmin() instead for anything that
|
|
28
|
+
* touches the team.
|
|
29
|
+
*/
|
|
30
|
+
declare function isEditor(): Promise<boolean>;
|
|
31
|
+
/**
|
|
32
|
+
* True when this viewer may edit AND the site is currently in edit mode — the
|
|
33
|
+
* one check for "should I show editing UI / do edit-only work right now."
|
|
34
|
+
* Admin vs editor doesn't matter; use isAdmin() when it does.
|
|
35
|
+
*
|
|
36
|
+
* For a custom drawer's trigger rendered in a Server Component. In a Client
|
|
37
|
+
* Component, read `canEdit` from useGRail() instead — same answer, same rule.
|
|
38
|
+
* Don't use it as the only authorization on a Server Action: edit mode is a
|
|
39
|
+
* display preference (a cookie the visitor controls), so the action should
|
|
40
|
+
* call isEditor() — this answers "show it," that answers "allow it."
|
|
41
|
+
*
|
|
42
|
+
* Reads cookies, which makes the calling route dynamic — nothing new in
|
|
43
|
+
* practice, since withGuardrail() already does the same in the root layout.
|
|
44
|
+
*/
|
|
45
|
+
declare function canEdit(): Promise<boolean>;
|
|
46
|
+
/**
|
|
47
|
+
* The one definition of "is the site in edit mode," shared by withGuardrail()
|
|
48
|
+
* (which hands it to the client as useGRail().isEditMode) and canEdit() so the
|
|
49
|
+
* two can't drift apart.
|
|
50
|
+
*
|
|
51
|
+
* "false" is an explicit, deliberate suppression (?edit=false while still
|
|
52
|
+
* signed in, to preview without chrome) and wins outright. Otherwise, a real
|
|
53
|
+
* session is enough on its own — an authenticated editor's chrome persists for
|
|
54
|
+
* as long as that session does, with no separate cookie timer to fall out of
|
|
55
|
+
* sync with it. "true" only matters for someone not yet authenticated: a
|
|
56
|
+
* short-lived grace window (see GR_EDIT_MODE_TTL_SECONDS) to actually reach
|
|
57
|
+
* the sign-in form, not a standing invitation — the previous design kept this
|
|
58
|
+
* cookie alive indefinitely once set, which meant a stray copy of it kept
|
|
59
|
+
* showing the sign-in bar to whoever's browser it was sitting in, for as long
|
|
60
|
+
* as that browser stayed open.
|
|
61
|
+
*
|
|
62
|
+
* needsPassword is set by completeAuthRedirectAction the moment an
|
|
63
|
+
* invite/recovery link finishes — it forces chrome on regardless of the
|
|
64
|
+
* edit-mode cookie, since the whole point is to show the set-password prompt
|
|
65
|
+
* right away, not require also having ?edit=true or an unsuppressed cookie.
|
|
66
|
+
*/
|
|
67
|
+
declare function resolveEditMode(viewer: GRViewer | null, cookieStore: {
|
|
68
|
+
get(name: string): {
|
|
69
|
+
value: string;
|
|
70
|
+
} | undefined;
|
|
71
|
+
}): {
|
|
72
|
+
isEditMode: boolean;
|
|
73
|
+
needsPassword: boolean;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
export { canEdit, isAdmin, isEditor, requireRole, resolveEditMode };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { cookies } from "next/headers";
|
|
2
|
+
import { getCachedViewer } from "./session";
|
|
3
|
+
import { GR_COOKIES } from "../core/defs";
|
|
4
|
+
async function requireRole(allowed) {
|
|
5
|
+
const viewer = await getCachedViewer();
|
|
6
|
+
if (!viewer || !viewer.role || !allowed.includes(viewer.role)) return null;
|
|
7
|
+
return viewer;
|
|
8
|
+
}
|
|
9
|
+
async function isAdmin() {
|
|
10
|
+
return await requireRole(["admin"]) !== null;
|
|
11
|
+
}
|
|
12
|
+
async function isEditor() {
|
|
13
|
+
return await requireRole(["admin", "editor"]) !== null;
|
|
14
|
+
}
|
|
15
|
+
async function canEdit() {
|
|
16
|
+
const viewer = await requireRole(["admin", "editor"]);
|
|
17
|
+
if (!viewer) return false;
|
|
18
|
+
return resolveEditMode(viewer, await cookies()).isEditMode;
|
|
19
|
+
}
|
|
20
|
+
function resolveEditMode(viewer, cookieStore) {
|
|
21
|
+
const editCookie = cookieStore.get(GR_COOKIES.EDIT_MODE)?.value;
|
|
22
|
+
const needsPassword = cookieStore.get(GR_COOKIES.NEEDS_PASSWORD)?.value === "true";
|
|
23
|
+
const isEditMode = needsPassword || (editCookie === "false" ? false : editCookie === "true" || viewer !== null);
|
|
24
|
+
return { isEditMode, needsPassword };
|
|
25
|
+
}
|
|
26
|
+
export {
|
|
27
|
+
canEdit,
|
|
28
|
+
isAdmin,
|
|
29
|
+
isEditor,
|
|
30
|
+
requireRole,
|
|
31
|
+
resolveEditMode
|
|
32
|
+
};
|
|
33
|
+
//# sourceMappingURL=access.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/server/access.ts"],"sourcesContent":["import { cookies } from \"next/headers\";\nimport { getCachedViewer } from \"./session\";\nimport { GR_COOKIES } from \"../core/defs\";\nimport type { GRRole, GRViewer } from \"../core/types\";\n\n/**\n * Role checks, server-side only.\n *\n * Deliberately NOT in a \"use server\" file: every export of one of those is a\n * callable Server Action endpoint, which is the wrong shape for an\n * authorization helper — it should only ever run inside the server code that\n * calls it.\n *\n * The client's copy of the role (useGRail().role) decides what to *show*; it\n * never decides what is *allowed*. A hidden button is not authorization, so\n * any Server Action behind a custom admin UI must call one of these itself.\n */\n\n/**\n * Returns the signed-in viewer if their role is in `allowed`, otherwise null.\n * The building block for the two helpers below; reach for this directly only\n * when you need the viewer itself (their email, say), not just a yes/no.\n */\nexport async function requireRole(\n allowed: readonly GRRole[],\n): Promise<GRViewer | null> {\n const viewer = await getCachedViewer();\n if (!viewer || !viewer.role || !allowed.includes(viewer.role)) return null;\n return viewer;\n}\n\n/** True for a signed-in admin of this site — team management, and everything an editor can do. */\nexport async function isAdmin(): Promise<boolean> {\n return (await requireRole([\"admin\"])) !== null;\n}\n\n/**\n * True for anyone who may edit this site's content: an editor, or an admin\n * (admins can do everything editors can). The check for a custom drawer's\n * Server Action that changes content. Use isAdmin() instead for anything that\n * touches the team.\n */\nexport async function isEditor(): Promise<boolean> {\n return (await requireRole([\"admin\", \"editor\"])) !== null;\n}\n\n/**\n * True when this viewer may edit AND the site is currently in edit mode — the\n * one check for \"should I show editing UI / do edit-only work right now.\"\n * Admin vs editor doesn't matter; use isAdmin() when it does.\n *\n * For a custom drawer's trigger rendered in a Server Component. In a Client\n * Component, read `canEdit` from useGRail() instead — same answer, same rule.\n * Don't use it as the only authorization on a Server Action: edit mode is a\n * display preference (a cookie the visitor controls), so the action should\n * call isEditor() — this answers \"show it,\" that answers \"allow it.\"\n *\n * Reads cookies, which makes the calling route dynamic — nothing new in\n * practice, since withGuardrail() already does the same in the root layout.\n */\nexport async function canEdit(): Promise<boolean> {\n const viewer = await requireRole([\"admin\", \"editor\"]);\n if (!viewer) return false;\n return resolveEditMode(viewer, await cookies()).isEditMode;\n}\n\n/**\n * The one definition of \"is the site in edit mode,\" shared by withGuardrail()\n * (which hands it to the client as useGRail().isEditMode) and canEdit() so the\n * two can't drift apart.\n *\n * \"false\" is an explicit, deliberate suppression (?edit=false while still\n * signed in, to preview without chrome) and wins outright. Otherwise, a real\n * session is enough on its own — an authenticated editor's chrome persists for\n * as long as that session does, with no separate cookie timer to fall out of\n * sync with it. \"true\" only matters for someone not yet authenticated: a\n * short-lived grace window (see GR_EDIT_MODE_TTL_SECONDS) to actually reach\n * the sign-in form, not a standing invitation — the previous design kept this\n * cookie alive indefinitely once set, which meant a stray copy of it kept\n * showing the sign-in bar to whoever's browser it was sitting in, for as long\n * as that browser stayed open.\n *\n * needsPassword is set by completeAuthRedirectAction the moment an\n * invite/recovery link finishes — it forces chrome on regardless of the\n * edit-mode cookie, since the whole point is to show the set-password prompt\n * right away, not require also having ?edit=true or an unsuppressed cookie.\n */\nexport function resolveEditMode(\n viewer: GRViewer | null,\n cookieStore: { get(name: string): { value: string } | undefined },\n): { isEditMode: boolean; needsPassword: boolean } {\n const editCookie = cookieStore.get(GR_COOKIES.EDIT_MODE)?.value;\n const needsPassword = cookieStore.get(GR_COOKIES.NEEDS_PASSWORD)?.value === \"true\";\n const isEditMode =\n needsPassword ||\n (editCookie === \"false\" ? false : editCookie === \"true\" || viewer !== null);\n return { isEditMode, needsPassword };\n}\n"],"mappings":"AAAA,SAAS,eAAe;AACxB,SAAS,uBAAuB;AAChC,SAAS,kBAAkB;AAqB3B,eAAsB,YACpB,SAC0B;AAC1B,QAAM,SAAS,MAAM,gBAAgB;AACrC,MAAI,CAAC,UAAU,CAAC,OAAO,QAAQ,CAAC,QAAQ,SAAS,OAAO,IAAI,EAAG,QAAO;AACtE,SAAO;AACT;AAGA,eAAsB,UAA4B;AAChD,SAAQ,MAAM,YAAY,CAAC,OAAO,CAAC,MAAO;AAC5C;AAQA,eAAsB,WAA6B;AACjD,SAAQ,MAAM,YAAY,CAAC,SAAS,QAAQ,CAAC,MAAO;AACtD;AAgBA,eAAsB,UAA4B;AAChD,QAAM,SAAS,MAAM,YAAY,CAAC,SAAS,QAAQ,CAAC;AACpD,MAAI,CAAC,OAAQ,QAAO;AACpB,SAAO,gBAAgB,QAAQ,MAAM,QAAQ,CAAC,EAAE;AAClD;AAuBO,SAAS,gBACd,QACA,aACiD;AACjD,QAAM,aAAa,YAAY,IAAI,WAAW,SAAS,GAAG;AAC1D,QAAM,gBAAgB,YAAY,IAAI,WAAW,cAAc,GAAG,UAAU;AAC5E,QAAM,aACJ,kBACC,eAAe,UAAU,QAAQ,eAAe,UAAU,WAAW;AACxE,SAAO,EAAE,YAAY,cAAc;AACrC;","names":[]}
|
package/dist/server/actions.d.ts
CHANGED
|
@@ -1,18 +1,31 @@
|
|
|
1
|
-
import { GRRole, GRAsset, GRMember,
|
|
2
|
-
import { GRUploadTarget } from '../core/adapter-types.js';
|
|
1
|
+
import { GRRole, GRAsset, GRMember, OverrideValue, SetPasswordState, ActionState, OverrideRow } from '../core/types.js';
|
|
2
|
+
import { GRUploadTarget, AuthRedirectParams } from '../core/adapter-types.js';
|
|
3
3
|
import 'react';
|
|
4
4
|
|
|
5
5
|
type Result = {
|
|
6
6
|
success: boolean;
|
|
7
7
|
error?: string;
|
|
8
8
|
};
|
|
9
|
+
declare function saveOverride(row: OverrideRow): Promise<Result>;
|
|
9
10
|
/**
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
11
|
+
* Writes one field's value by id, with no <GRail> involved — the setter that
|
|
12
|
+
* pairs with getFieldValue(). It exists for fields with nothing on the page to
|
|
13
|
+
* click: an SEO title or meta description, an og:image, a product's stock
|
|
14
|
+
* note. Build a drawer or form of your own, and have it (or a Server Action of
|
|
15
|
+
* yours) call this.
|
|
16
|
+
*
|
|
17
|
+
* A bare string is shorthand for a text field. Pass an OverrideValue for the
|
|
18
|
+
* other types ({ type: "image", src, alt }, a link, a button).
|
|
19
|
+
*
|
|
20
|
+
* Does its own role check — an editor or admin — so it is safe to call
|
|
21
|
+
* directly from a Client Component, the same as saveOverride. If your own
|
|
22
|
+
* action does other work first, check isEditor() there too.
|
|
23
|
+
*
|
|
24
|
+
* Writes the same row a <GRail> with this id would, so the two stay
|
|
25
|
+
* interchangeable: a field first written here can later be given a visible
|
|
26
|
+
* <GRail>, and vice versa.
|
|
13
27
|
*/
|
|
14
|
-
declare function
|
|
15
|
-
declare function saveOverride(row: OverrideRow): Promise<Result>;
|
|
28
|
+
declare function setFieldValue(id: string, value: string | OverrideValue): Promise<Result>;
|
|
16
29
|
/**
|
|
17
30
|
* Authorizes an upload and returns where the browser should send the bytes.
|
|
18
31
|
* Only metadata comes through here — the file itself goes straight to storage.
|
|
@@ -37,5 +50,33 @@ declare function loginAction(_prev: ActionState, formData: FormData): Promise<Ac
|
|
|
37
50
|
declare function logoutAction(): Promise<{
|
|
38
51
|
success: boolean;
|
|
39
52
|
}>;
|
|
53
|
+
/**
|
|
54
|
+
* Completes a session that arrived via an invite, magic-link, or
|
|
55
|
+
* password-recovery redirect. Called by AuthRedirectSync (react/), the
|
|
56
|
+
* generic client component that notices this kind of link and hands off
|
|
57
|
+
* whatever it found in the URL — the actual token exchange is entirely the
|
|
58
|
+
* auth adapter's job (see GRAuthAdapter.completeAuthRedirect); core only
|
|
59
|
+
* orchestrates the result.
|
|
60
|
+
*
|
|
61
|
+
* A no-op {success:false}, not an error, when the adapter doesn't implement
|
|
62
|
+
* this — most page loads carry no redirect data at all, and an adapter with
|
|
63
|
+
* no such concept should not make every one of them fail.
|
|
64
|
+
*/
|
|
65
|
+
declare function completeAuthRedirectAction(params: AuthRedirectParams): Promise<{
|
|
66
|
+
success: boolean;
|
|
67
|
+
needsPassword?: boolean;
|
|
68
|
+
error?: string;
|
|
69
|
+
}>;
|
|
70
|
+
/**
|
|
71
|
+
* Sets the current session's password — the prompt completeAuthRedirectAction
|
|
72
|
+
* triggers via needsPassword. Requires only a valid session, not a role: an
|
|
73
|
+
* invited person's role is claimed as a side effect of getCachedViewer()
|
|
74
|
+
* resolving them, which already happens independently of this.
|
|
75
|
+
*/
|
|
76
|
+
declare function setPasswordAction(_prev: SetPasswordState, formData: FormData): Promise<SetPasswordState>;
|
|
77
|
+
/** Dismisses the set-password prompt without setting one — see Admin.tsx. */
|
|
78
|
+
declare function skipSetPasswordAction(): Promise<{
|
|
79
|
+
success: boolean;
|
|
80
|
+
}>;
|
|
40
81
|
|
|
41
|
-
export { createAssetUpload, inviteMember, listAssets, listTeam, loginAction, logoutAction, removeMember,
|
|
82
|
+
export { completeAuthRedirectAction, createAssetUpload, inviteMember, listAssets, listTeam, loginAction, logoutAction, removeMember, saveOverride, setFieldValue, setPasswordAction, skipSetPasswordAction, updateMemberRole };
|
package/dist/server/actions.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use server";
|
|
2
2
|
import { revalidatePath } from "next/cache";
|
|
3
|
-
import { headers } from "next/headers";
|
|
3
|
+
import { cookies, headers } from "next/headers";
|
|
4
4
|
import {
|
|
5
5
|
getAuth,
|
|
6
6
|
getDB,
|
|
@@ -10,21 +10,33 @@ import {
|
|
|
10
10
|
resolveSiteId
|
|
11
11
|
} from "../core/config";
|
|
12
12
|
import { getCachedViewer } from "./session";
|
|
13
|
+
import { requireRole } from "./access";
|
|
13
14
|
import { rethrowIfBailout } from "../core/bailout";
|
|
15
|
+
import { GR_COOKIES, GR_NEEDS_PASSWORD_TTL_SECONDS } from "../core/defs";
|
|
14
16
|
const DENIED = { success: false, error: "Unauthorized." };
|
|
15
|
-
async function requireRole(allowed) {
|
|
16
|
-
const viewer = await getCachedViewer();
|
|
17
|
-
if (!viewer || !viewer.role || !allowed.includes(viewer.role)) return null;
|
|
18
|
-
return viewer;
|
|
19
|
-
}
|
|
20
17
|
async function saveOverride(row) {
|
|
21
18
|
const viewer = await requireRole(["admin", "editor"]);
|
|
22
19
|
if (!viewer) return DENIED;
|
|
20
|
+
return writeOverride(row.pathKey, row.value);
|
|
21
|
+
}
|
|
22
|
+
const OVERRIDE_TYPES = ["text", "link", "image", "button"];
|
|
23
|
+
async function setFieldValue(id, value) {
|
|
24
|
+
const viewer = await requireRole(["admin", "editor"]);
|
|
25
|
+
if (!viewer) return DENIED;
|
|
26
|
+
const pathKey = id.trim();
|
|
27
|
+
if (!pathKey) return { success: false, error: "A field id is required." };
|
|
28
|
+
const normalized = typeof value === "string" ? { type: "text", text: value } : value;
|
|
29
|
+
if (!OVERRIDE_TYPES.includes(normalized.type)) {
|
|
30
|
+
return { success: false, error: `Unknown field type "${normalized.type}".` };
|
|
31
|
+
}
|
|
32
|
+
return writeOverride(pathKey, normalized);
|
|
33
|
+
}
|
|
34
|
+
async function writeOverride(pathKey, value) {
|
|
23
35
|
const rowToSend = {
|
|
24
|
-
pathKey
|
|
36
|
+
pathKey,
|
|
25
37
|
siteId: await resolveSiteId(),
|
|
26
|
-
type:
|
|
27
|
-
value
|
|
38
|
+
type: value.type,
|
|
39
|
+
value
|
|
28
40
|
};
|
|
29
41
|
try {
|
|
30
42
|
const db = getDB();
|
|
@@ -196,10 +208,51 @@ async function loginAction(_prev, formData) {
|
|
|
196
208
|
async function logoutAction() {
|
|
197
209
|
const auth = getAuth();
|
|
198
210
|
await auth.logout();
|
|
211
|
+
const cookieStore = await cookies();
|
|
212
|
+
cookieStore.delete(GR_COOKIES.EDIT_MODE);
|
|
213
|
+
revalidatePath("/", "layout");
|
|
214
|
+
return { success: true };
|
|
215
|
+
}
|
|
216
|
+
async function completeAuthRedirectAction(params) {
|
|
217
|
+
const auth = getAuth();
|
|
218
|
+
if (!auth.completeAuthRedirect) return { success: false };
|
|
219
|
+
const res = await auth.completeAuthRedirect(params);
|
|
220
|
+
if (res.success) {
|
|
221
|
+
if (res.needsPassword) {
|
|
222
|
+
const cookieStore = await cookies();
|
|
223
|
+
cookieStore.set(GR_COOKIES.NEEDS_PASSWORD, "true", {
|
|
224
|
+
path: "/",
|
|
225
|
+
maxAge: GR_NEEDS_PASSWORD_TTL_SECONDS
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
revalidatePath("/", "layout");
|
|
229
|
+
}
|
|
230
|
+
return res;
|
|
231
|
+
}
|
|
232
|
+
async function setPasswordAction(_prev, formData) {
|
|
233
|
+
const viewer = await getCachedViewer();
|
|
234
|
+
if (!viewer) return { success: false, error: "Not signed in." };
|
|
235
|
+
const auth = getAuth();
|
|
236
|
+
if (!auth.setPassword) {
|
|
237
|
+
return { success: false, error: "This site's auth provider does not support setting a password." };
|
|
238
|
+
}
|
|
239
|
+
const password = String(formData.get("password") ?? "");
|
|
240
|
+
const res = await auth.setPassword(password);
|
|
241
|
+
if (res.success) {
|
|
242
|
+
const cookieStore = await cookies();
|
|
243
|
+
cookieStore.delete(GR_COOKIES.NEEDS_PASSWORD);
|
|
244
|
+
revalidatePath("/", "layout");
|
|
245
|
+
}
|
|
246
|
+
return res;
|
|
247
|
+
}
|
|
248
|
+
async function skipSetPasswordAction() {
|
|
249
|
+
const cookieStore = await cookies();
|
|
250
|
+
cookieStore.delete(GR_COOKIES.NEEDS_PASSWORD);
|
|
199
251
|
revalidatePath("/", "layout");
|
|
200
252
|
return { success: true };
|
|
201
253
|
}
|
|
202
254
|
export {
|
|
255
|
+
completeAuthRedirectAction,
|
|
203
256
|
createAssetUpload,
|
|
204
257
|
inviteMember,
|
|
205
258
|
listAssets,
|
|
@@ -207,8 +260,10 @@ export {
|
|
|
207
260
|
loginAction,
|
|
208
261
|
logoutAction,
|
|
209
262
|
removeMember,
|
|
210
|
-
requireRole,
|
|
211
263
|
saveOverride,
|
|
264
|
+
setFieldValue,
|
|
265
|
+
setPasswordAction,
|
|
266
|
+
skipSetPasswordAction,
|
|
212
267
|
updateMemberRole
|
|
213
268
|
};
|
|
214
269
|
//# sourceMappingURL=actions.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/server/actions.ts"],"sourcesContent":["\"use server\";\n\nimport { revalidatePath } from \"next/cache\";\nimport { headers } from \"next/headers\";\nimport {\n getAuth,\n getDB,\n getInviteHandler,\n getMembers,\n getStorage,\n resolveSiteId,\n} from \"../core/config\";\nimport { getCachedViewer } from \"./session\";\nimport { rethrowIfBailout } from \"../core/bailout\";\nimport type {\n ActionState,\n GRAsset,\n GRMember,\n GRRole,\n GRViewer,\n OverrideRow,\n} from \"../core/types\";\nimport type { GRStorageRow, GRUploadTarget } from \"../core/adapter-types\";\n\ntype Result = { success: boolean; error?: string };\n\nconst DENIED: Result = { success: false, error: \"Unauthorized.\" };\n\n/**\n * Every mutation re-resolves the viewer server-side. The client's copy of the\n * role decides what to *show*; it never decides what is *allowed*. A hidden\n * button is not authorization — this is the same lesson as the session cookie.\n */\nexport async function requireRole(\n allowed: readonly GRRole[],\n): Promise<GRViewer | null> {\n const viewer = await getCachedViewer();\n if (!viewer || !viewer.role || !allowed.includes(viewer.role)) return null;\n return viewer;\n}\n\nexport async function saveOverride(row: OverrideRow): Promise<Result> {\n const viewer = await requireRole([\"admin\", \"editor\"]);\n if (!viewer) return DENIED;\n\n const rowToSend: GRStorageRow = {\n pathKey: row.pathKey,\n siteId: await resolveSiteId(),\n type: row.value.type,\n value: row.value,\n };\n\n try {\n const db = getDB();\n const res = await db.setOverride(rowToSend);\n if (!res.success) return res;\n\n // TODO: too broad — purges every cached route on any single-field save.\n revalidatePath(\"/\", \"layout\");\n return { success: true };\n } catch (e) {\n rethrowIfBailout(e);\n console.error(\"Guardrail: save failed\", e);\n return { success: false, error: \"Database write failed.\" };\n }\n}\n\n/* --------------------------------------------------------------- media --- */\n\n// SVG is excluded on purpose: it can carry script, and next/image refuses it\n// by default anyway.\nconst IMAGE_TYPES = [\"image/png\", \"image/jpeg\", \"image/webp\", \"image/gif\", \"image/avif\"];\nconst MAX_UPLOAD_BYTES = 10 * 1024 * 1024;\n\n/**\n * Authorizes an upload and returns where the browser should send the bytes.\n * Only metadata comes through here — the file itself goes straight to storage.\n */\nexport async function createAssetUpload(file: {\n name: string;\n contentType: string;\n size: number;\n}): Promise<\n { success: true; target: GRUploadTarget } | { success: false; error: string }\n> {\n const viewer = await requireRole([\"admin\", \"editor\"]);\n if (!viewer) return { success: false, error: \"Unauthorized.\" };\n\n const storage = getStorage();\n if (!storage) {\n return { success: false, error: \"No storage adapter is configured.\" };\n }\n if (!IMAGE_TYPES.includes(file.contentType)) {\n return { success: false, error: \"Upload a PNG, JPEG, WebP, GIF, or AVIF image.\" };\n }\n if (!(file.size > 0) || file.size > MAX_UPLOAD_BYTES) {\n return { success: false, error: \"Images must be under 10 MB.\" };\n }\n\n try {\n const target = await storage.createUpload(await resolveSiteId(), file);\n return { success: true, target };\n } catch (e) {\n rethrowIfBailout(e);\n console.error(\"Guardrail: createUpload failed\", e);\n // Failures here are almost always setup (missing SQL, bucket, or policy),\n // so show the cause while developing. Production keeps it generic rather\n // than exposing backend detail to editors.\n const detail =\n process.env.NODE_ENV !== \"production\" && e instanceof Error\n ? ` ${e.message}`\n : \"\";\n return { success: false, error: `Could not start the upload.${detail}` };\n }\n}\n\nexport async function listAssets(): Promise<GRAsset[]> {\n const viewer = await requireRole([\"admin\", \"editor\"]);\n const storage = getStorage();\n if (!viewer || !storage) return [];\n return storage.listAssets(await resolveSiteId());\n}\n\n/* ---------------------------------------------------------------- team --- */\n\nexport async function listTeam(): Promise<GRMember[]> {\n // Any member may see who else is on the site; only admins may change it.\n const viewer = await requireRole([\"admin\", \"editor\"]);\n if (!viewer) return [];\n\n const members = getMembers();\n return members.listMembers(await resolveSiteId());\n}\n\nexport async function inviteMember(\n email: string,\n role: GRRole,\n): Promise<Result> {\n const viewer = await requireRole([\"admin\"]);\n if (!viewer) return DENIED;\n\n const normalized = email.toLowerCase().trim();\n if (!/^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/.test(normalized)) {\n return { success: false, error: \"Enter a valid email address.\" };\n }\n\n const siteId = await resolveSiteId();\n const members = getMembers();\n\n const existing = await members.getMember(siteId, { email: normalized });\n if (existing?.status === \"active\") {\n return { success: false, error: \"That address is already on the team.\" };\n }\n\n // A pending invite is re-sent rather than rejected: provider email is\n // rate-limited and unreliable enough that resending has to be possible.\n if (!existing) {\n const res = await members.upsertMember(siteId, {\n email: normalized,\n role,\n userId: null,\n status: \"pending\",\n });\n if (!res.success) return res;\n }\n\n const auth = getAuth();\n if (auth.inviteUser) {\n // The membership is already written; a failed send must not undo it.\n const sent = await auth.inviteUser(normalized, {\n redirectTo: `${await requestOrigin()}/?edit=true`,\n });\n revalidatePath(\"/\", \"layout\");\n return sent.success\n ? { success: true }\n : {\n success: false,\n error: `Invite saved, but the email failed: ${sent.error}`,\n };\n }\n\n // No provider-side delivery, so hand off to the app.\n try {\n await getInviteHandler()?.({\n email: normalized,\n role: existing?.role ?? role,\n siteId,\n invitedBy: viewer.email ?? viewer.userId,\n });\n } catch (e) {\n console.error(\"Guardrail: onInvite handler threw\", e);\n }\n\n revalidatePath(\"/\", \"layout\");\n return { success: true };\n}\n\nexport async function updateMemberRole(\n email: string,\n role: GRRole,\n): Promise<Result> {\n const viewer = await requireRole([\"admin\"]);\n if (!viewer) return DENIED;\n\n const siteId = await resolveSiteId();\n const members = getMembers();\n\n const target = await members.getMember(siteId, {\n email: email.toLowerCase().trim(),\n });\n if (!target) return { success: false, error: \"No such member.\" };\n\n if (target.role === \"admin\" && role !== \"admin\") {\n const guard = await wouldStrandSite(siteId, target.email);\n if (guard) return guard;\n }\n\n const res = await members.upsertMember(siteId, {\n email: target.email,\n role,\n userId: target.userId,\n status: target.status,\n });\n if (res.success) revalidatePath(\"/\", \"layout\");\n return res;\n}\n\nexport async function removeMember(email: string): Promise<Result> {\n const viewer = await requireRole([\"admin\"]);\n if (!viewer) return DENIED;\n\n const siteId = await resolveSiteId();\n const members = getMembers();\n const normalized = email.toLowerCase().trim();\n\n const guard = await wouldStrandSite(siteId, normalized);\n if (guard) return guard;\n\n const res = await members.removeMember(siteId, normalized);\n if (res.success) revalidatePath(\"/\", \"layout\");\n return res;\n}\n\nasync function requestOrigin(): Promise<string> {\n const h = await headers();\n const origin = h.get(\"origin\");\n if (origin) return origin;\n const host = h.get(\"x-forwarded-host\") ?? h.get(\"host\") ?? \"localhost\";\n const proto = h.get(\"x-forwarded-proto\") ?? (host.startsWith(\"localhost\") ? \"http\" : \"https\");\n return `${proto}://${host}`;\n}\n\n/**\n * Refuses changes that would leave a site with no admin, which would lock\n * everyone out of team management with no in-app way to recover.\n */\nasync function wouldStrandSite(\n siteId: string,\n email: string,\n): Promise<Result | null> {\n const members = getMembers();\n const all = await members.listMembers(siteId);\n const admins = all.filter((m) => m.role === \"admin\");\n\n if (admins.length <= 1 && admins.some((m) => m.email === email)) {\n return {\n success: false,\n error: \"A site must keep at least one admin.\",\n };\n }\n return null;\n}\n\n/* ---------------------------------------------------------------- auth --- */\n\nexport async function loginAction(\n _prev: ActionState,\n formData: FormData,\n): Promise<ActionState> {\n const email = String(formData.get(\"email\") ?? \"\");\n const password = String(formData.get(\"password\") ?? \"\");\n\n const auth = getAuth();\n if (!auth.authenticate) {\n return {\n success: false,\n error: \"This site's auth provider does not accept passwords.\",\n email,\n };\n }\n\n const result = await auth.authenticate(email, password);\n if (!result.success) {\n return { success: false, error: result.error, email };\n }\n\n revalidatePath(\"/\", \"layout\");\n return { success: true, email };\n}\n\nexport async function logoutAction(): Promise<{ success: boolean }> {\n const auth = getAuth();\n await auth.logout();\n revalidatePath(\"/\", \"layout\");\n return { success: true };\n}\n"],"mappings":";AAEA,SAAS,sBAAsB;AAC/B,SAAS,eAAe;AACxB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,wBAAwB;AAajC,MAAM,SAAiB,EAAE,SAAS,OAAO,OAAO,gBAAgB;AAOhE,eAAsB,YACpB,SAC0B;AAC1B,QAAM,SAAS,MAAM,gBAAgB;AACrC,MAAI,CAAC,UAAU,CAAC,OAAO,QAAQ,CAAC,QAAQ,SAAS,OAAO,IAAI,EAAG,QAAO;AACtE,SAAO;AACT;AAEA,eAAsB,aAAa,KAAmC;AACpE,QAAM,SAAS,MAAM,YAAY,CAAC,SAAS,QAAQ,CAAC;AACpD,MAAI,CAAC,OAAQ,QAAO;AAEpB,QAAM,YAA0B;AAAA,IAC9B,SAAS,IAAI;AAAA,IACb,QAAQ,MAAM,cAAc;AAAA,IAC5B,MAAM,IAAI,MAAM;A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,SAAS;AACnB,WAAO,EAAE,SAAS,OAAO,OAAO,OAAO,OAAO,MAAM;AAAA,EACtD;AAEA,iBAAe,KAAK,QAAQ;AAC5B,SAAO,EAAE,SAAS,MAAM,MAAM;AAChC;AAEA,eAAsB,eAA8C;AAClE,QAAM,OAAO,QAAQ;AACrB,QAAM,KAAK,OAAO;AAClB,iBAAe,KAAK,QAAQ;AAC5B,SAAO,EAAE,SAAS,KAAK;AACzB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/server/actions.ts"],"sourcesContent":["\"use server\";\n\nimport { revalidatePath } from \"next/cache\";\nimport { cookies, headers } from \"next/headers\";\nimport {\n getAuth,\n getDB,\n getInviteHandler,\n getMembers,\n getStorage,\n resolveSiteId,\n} from \"../core/config\";\nimport { getCachedViewer } from \"./session\";\nimport { requireRole } from \"./access\";\nimport { rethrowIfBailout } from \"../core/bailout\";\nimport { GR_COOKIES, GR_NEEDS_PASSWORD_TTL_SECONDS } from \"../core/defs\";\nimport type {\n ActionState,\n GRAsset,\n GRMember,\n GRRole,\n OverrideRow,\n OverrideType,\n OverrideValue,\n SetPasswordState,\n} from \"../core/types\";\nimport type {\n AuthRedirectParams,\n GRStorageRow,\n GRUploadTarget,\n} from \"../core/adapter-types\";\n\ntype Result = { success: boolean; error?: string };\n\nconst DENIED: Result = { success: false, error: \"Unauthorized.\" };\n\n// Every mutation below re-resolves the viewer server-side through\n// requireRole() (see access.ts) — the client's copy of the role decides what\n// to *show*, never what is *allowed*.\n\nexport async function saveOverride(row: OverrideRow): Promise<Result> {\n const viewer = await requireRole([\"admin\", \"editor\"]);\n if (!viewer) return DENIED;\n return writeOverride(row.pathKey, row.value);\n}\n\nconst OVERRIDE_TYPES: readonly OverrideType[] = [\"text\", \"link\", \"image\", \"button\"];\n\n/**\n * Writes one field's value by id, with no <GRail> involved — the setter that\n * pairs with getFieldValue(). It exists for fields with nothing on the page to\n * click: an SEO title or meta description, an og:image, a product's stock\n * note. Build a drawer or form of your own, and have it (or a Server Action of\n * yours) call this.\n *\n * A bare string is shorthand for a text field. Pass an OverrideValue for the\n * other types ({ type: \"image\", src, alt }, a link, a button).\n *\n * Does its own role check — an editor or admin — so it is safe to call\n * directly from a Client Component, the same as saveOverride. If your own\n * action does other work first, check isEditor() there too.\n *\n * Writes the same row a <GRail> with this id would, so the two stay\n * interchangeable: a field first written here can later be given a visible\n * <GRail>, and vice versa.\n */\nexport async function setFieldValue(\n id: string,\n value: string | OverrideValue,\n): Promise<Result> {\n const viewer = await requireRole([\"admin\", \"editor\"]);\n if (!viewer) return DENIED;\n\n const pathKey = id.trim();\n if (!pathKey) return { success: false, error: \"A field id is required.\" };\n\n const normalized: OverrideValue =\n typeof value === \"string\" ? { type: \"text\", text: value } : value;\n if (!OVERRIDE_TYPES.includes(normalized.type)) {\n return { success: false, error: `Unknown field type \"${normalized.type}\".` };\n }\n\n return writeOverride(pathKey, normalized);\n}\n\n/** The write shared by saveOverride and setFieldValue; the caller has already authorized. */\nasync function writeOverride(\n pathKey: string,\n value: OverrideValue,\n): Promise<Result> {\n const rowToSend: GRStorageRow = {\n pathKey,\n siteId: await resolveSiteId(),\n type: value.type,\n value,\n };\n\n try {\n const db = getDB();\n const res = await db.setOverride(rowToSend);\n if (!res.success) return res;\n\n // TODO: too broad — purges every cached route on any single-field save.\n revalidatePath(\"/\", \"layout\");\n return { success: true };\n } catch (e) {\n rethrowIfBailout(e);\n console.error(\"Guardrail: save failed\", e);\n return { success: false, error: \"Database write failed.\" };\n }\n}\n\n/* --------------------------------------------------------------- media --- */\n\n// SVG is excluded on purpose: it can carry script, and next/image refuses it\n// by default anyway.\nconst IMAGE_TYPES = [\"image/png\", \"image/jpeg\", \"image/webp\", \"image/gif\", \"image/avif\"];\nconst MAX_UPLOAD_BYTES = 10 * 1024 * 1024;\n\n/**\n * Authorizes an upload and returns where the browser should send the bytes.\n * Only metadata comes through here — the file itself goes straight to storage.\n */\nexport async function createAssetUpload(file: {\n name: string;\n contentType: string;\n size: number;\n}): Promise<\n { success: true; target: GRUploadTarget } | { success: false; error: string }\n> {\n const viewer = await requireRole([\"admin\", \"editor\"]);\n if (!viewer) return { success: false, error: \"Unauthorized.\" };\n\n const storage = getStorage();\n if (!storage) {\n return { success: false, error: \"No storage adapter is configured.\" };\n }\n if (!IMAGE_TYPES.includes(file.contentType)) {\n return { success: false, error: \"Upload a PNG, JPEG, WebP, GIF, or AVIF image.\" };\n }\n if (!(file.size > 0) || file.size > MAX_UPLOAD_BYTES) {\n return { success: false, error: \"Images must be under 10 MB.\" };\n }\n\n try {\n const target = await storage.createUpload(await resolveSiteId(), file);\n return { success: true, target };\n } catch (e) {\n rethrowIfBailout(e);\n console.error(\"Guardrail: createUpload failed\", e);\n // Failures here are almost always setup (missing SQL, bucket, or policy),\n // so show the cause while developing. Production keeps it generic rather\n // than exposing backend detail to editors.\n const detail =\n process.env.NODE_ENV !== \"production\" && e instanceof Error\n ? ` ${e.message}`\n : \"\";\n return { success: false, error: `Could not start the upload.${detail}` };\n }\n}\n\nexport async function listAssets(): Promise<GRAsset[]> {\n const viewer = await requireRole([\"admin\", \"editor\"]);\n const storage = getStorage();\n if (!viewer || !storage) return [];\n return storage.listAssets(await resolveSiteId());\n}\n\n/* ---------------------------------------------------------------- team --- */\n\nexport async function listTeam(): Promise<GRMember[]> {\n // Any member may see who else is on the site; only admins may change it.\n const viewer = await requireRole([\"admin\", \"editor\"]);\n if (!viewer) return [];\n\n const members = getMembers();\n return members.listMembers(await resolveSiteId());\n}\n\nexport async function inviteMember(\n email: string,\n role: GRRole,\n): Promise<Result> {\n const viewer = await requireRole([\"admin\"]);\n if (!viewer) return DENIED;\n\n const normalized = email.toLowerCase().trim();\n if (!/^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$/.test(normalized)) {\n return { success: false, error: \"Enter a valid email address.\" };\n }\n\n const siteId = await resolveSiteId();\n const members = getMembers();\n\n const existing = await members.getMember(siteId, { email: normalized });\n if (existing?.status === \"active\") {\n return { success: false, error: \"That address is already on the team.\" };\n }\n\n // A pending invite is re-sent rather than rejected: provider email is\n // rate-limited and unreliable enough that resending has to be possible.\n if (!existing) {\n const res = await members.upsertMember(siteId, {\n email: normalized,\n role,\n userId: null,\n status: \"pending\",\n });\n if (!res.success) return res;\n }\n\n const auth = getAuth();\n if (auth.inviteUser) {\n // The membership is already written; a failed send must not undo it.\n const sent = await auth.inviteUser(normalized, {\n redirectTo: `${await requestOrigin()}/?edit=true`,\n });\n revalidatePath(\"/\", \"layout\");\n return sent.success\n ? { success: true }\n : {\n success: false,\n error: `Invite saved, but the email failed: ${sent.error}`,\n };\n }\n\n // No provider-side delivery, so hand off to the app.\n try {\n await getInviteHandler()?.({\n email: normalized,\n role: existing?.role ?? role,\n siteId,\n invitedBy: viewer.email ?? viewer.userId,\n });\n } catch (e) {\n console.error(\"Guardrail: onInvite handler threw\", e);\n }\n\n revalidatePath(\"/\", \"layout\");\n return { success: true };\n}\n\nexport async function updateMemberRole(\n email: string,\n role: GRRole,\n): Promise<Result> {\n const viewer = await requireRole([\"admin\"]);\n if (!viewer) return DENIED;\n\n const siteId = await resolveSiteId();\n const members = getMembers();\n\n const target = await members.getMember(siteId, {\n email: email.toLowerCase().trim(),\n });\n if (!target) return { success: false, error: \"No such member.\" };\n\n if (target.role === \"admin\" && role !== \"admin\") {\n const guard = await wouldStrandSite(siteId, target.email);\n if (guard) return guard;\n }\n\n const res = await members.upsertMember(siteId, {\n email: target.email,\n role,\n userId: target.userId,\n status: target.status,\n });\n if (res.success) revalidatePath(\"/\", \"layout\");\n return res;\n}\n\nexport async function removeMember(email: string): Promise<Result> {\n const viewer = await requireRole([\"admin\"]);\n if (!viewer) return DENIED;\n\n const siteId = await resolveSiteId();\n const members = getMembers();\n const normalized = email.toLowerCase().trim();\n\n const guard = await wouldStrandSite(siteId, normalized);\n if (guard) return guard;\n\n const res = await members.removeMember(siteId, normalized);\n if (res.success) revalidatePath(\"/\", \"layout\");\n return res;\n}\n\nasync function requestOrigin(): Promise<string> {\n const h = await headers();\n const origin = h.get(\"origin\");\n if (origin) return origin;\n const host = h.get(\"x-forwarded-host\") ?? h.get(\"host\") ?? \"localhost\";\n const proto = h.get(\"x-forwarded-proto\") ?? (host.startsWith(\"localhost\") ? \"http\" : \"https\");\n return `${proto}://${host}`;\n}\n\n/**\n * Refuses changes that would leave a site with no admin, which would lock\n * everyone out of team management with no in-app way to recover.\n */\nasync function wouldStrandSite(\n siteId: string,\n email: string,\n): Promise<Result | null> {\n const members = getMembers();\n const all = await members.listMembers(siteId);\n const admins = all.filter((m) => m.role === \"admin\");\n\n if (admins.length <= 1 && admins.some((m) => m.email === email)) {\n return {\n success: false,\n error: \"A site must keep at least one admin.\",\n };\n }\n return null;\n}\n\n/* ---------------------------------------------------------------- auth --- */\n\nexport async function loginAction(\n _prev: ActionState,\n formData: FormData,\n): Promise<ActionState> {\n const email = String(formData.get(\"email\") ?? \"\");\n const password = String(formData.get(\"password\") ?? \"\");\n\n const auth = getAuth();\n if (!auth.authenticate) {\n return {\n success: false,\n error: \"This site's auth provider does not accept passwords.\",\n email,\n };\n }\n\n const result = await auth.authenticate(email, password);\n if (!result.success) {\n return { success: false, error: result.error, email };\n }\n\n revalidatePath(\"/\", \"layout\");\n return { success: true, email };\n}\n\nexport async function logoutAction(): Promise<{ success: boolean }> {\n const auth = getAuth();\n await auth.logout();\n // Cleared here, not by the client afterward: a Server Action's own\n // revalidatePath() below triggers Next's router to refresh the current\n // route automatically, which can race a client-side navigation attempted\n // right after this resolves — confirmed live, where that automatic\n // refresh (for the pre-logout URL, ?edit=true) won the race and silently\n // undid a client-side `window.location.href` to the plain path. Deleting\n // the cookie here instead makes it part of the one server round-trip that\n // revalidatePath already accounts for, with nothing left to race.\n const cookieStore = await cookies();\n cookieStore.delete(GR_COOKIES.EDIT_MODE);\n revalidatePath(\"/\", \"layout\");\n return { success: true };\n}\n\n/* ---------------------------------------------------------- redirects --- */\n\n/**\n * Completes a session that arrived via an invite, magic-link, or\n * password-recovery redirect. Called by AuthRedirectSync (react/), the\n * generic client component that notices this kind of link and hands off\n * whatever it found in the URL — the actual token exchange is entirely the\n * auth adapter's job (see GRAuthAdapter.completeAuthRedirect); core only\n * orchestrates the result.\n *\n * A no-op {success:false}, not an error, when the adapter doesn't implement\n * this — most page loads carry no redirect data at all, and an adapter with\n * no such concept should not make every one of them fail.\n */\nexport async function completeAuthRedirectAction(\n params: AuthRedirectParams,\n): Promise<{ success: boolean; needsPassword?: boolean; error?: string }> {\n const auth = getAuth();\n if (!auth.completeAuthRedirect) return { success: false };\n\n const res = await auth.completeAuthRedirect(params);\n if (res.success) {\n if (res.needsPassword) {\n const cookieStore = await cookies();\n cookieStore.set(GR_COOKIES.NEEDS_PASSWORD, \"true\", {\n path: \"/\",\n maxAge: GR_NEEDS_PASSWORD_TTL_SECONDS,\n });\n }\n revalidatePath(\"/\", \"layout\");\n }\n return res;\n}\n\n/**\n * Sets the current session's password — the prompt completeAuthRedirectAction\n * triggers via needsPassword. Requires only a valid session, not a role: an\n * invited person's role is claimed as a side effect of getCachedViewer()\n * resolving them, which already happens independently of this.\n */\nexport async function setPasswordAction(\n _prev: SetPasswordState,\n formData: FormData,\n): Promise<SetPasswordState> {\n const viewer = await getCachedViewer();\n if (!viewer) return { success: false, error: \"Not signed in.\" };\n\n const auth = getAuth();\n if (!auth.setPassword) {\n return { success: false, error: \"This site's auth provider does not support setting a password.\" };\n }\n\n const password = String(formData.get(\"password\") ?? \"\");\n const res = await auth.setPassword(password);\n if (res.success) {\n const cookieStore = await cookies();\n cookieStore.delete(GR_COOKIES.NEEDS_PASSWORD);\n revalidatePath(\"/\", \"layout\");\n }\n return res;\n}\n\n/** Dismisses the set-password prompt without setting one — see Admin.tsx. */\nexport async function skipSetPasswordAction(): Promise<{ success: boolean }> {\n const cookieStore = await cookies();\n cookieStore.delete(GR_COOKIES.NEEDS_PASSWORD);\n revalidatePath(\"/\", \"layout\");\n return { success: true };\n}\n"],"mappings":";AAEA,SAAS,sBAAsB;AAC/B,SAA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: this does not make a field editable on its own. Give the same
|
|
13
|
-
* id a normal <GRail> somewhere for an editor to change it
|
|
14
|
-
*
|
|
13
|
+
* id a normal <GRail> somewhere for an editor to change it, or — for a field
|
|
14
|
+
* with nothing on the page to click, like a meta description — build your own
|
|
15
|
+
* editing UI around setFieldValue(). This just reads whatever the field
|
|
16
|
+
* currently holds.
|
|
15
17
|
*
|
|
16
18
|
* Shares <GRail>'s request-scoped batching loader, so calling this alongside
|
|
17
19
|
* other fields — including several of these via Promise.all — still resolves
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/server/fieldData.ts"],"sourcesContent":["import { loadOverride } from \"./loader\";\nimport type { OverrideValue } from \"../core/types\";\n\n/**\n * Reads a field's current value with no rendering attached.\n *\n * <GRail> covers \"render this as an editable element.\" This covers \"give me\n * the data so I can build something GRail doesn't render itself\" — an embed\n * iframe's src, an og:image meta tag, structured data, a third-party widget's\n * config.\n *\n * Read-only: this does not make a field editable on its own. Give the same\n * id a normal <GRail> somewhere for an editor to change it
|
|
1
|
+
{"version":3,"sources":["../../src/server/fieldData.ts"],"sourcesContent":["import { loadOverride } from \"./loader\";\nimport type { OverrideValue } from \"../core/types\";\n\n/**\n * Reads a field's current value with no rendering attached.\n *\n * <GRail> covers \"render this as an editable element.\" This covers \"give me\n * the data so I can build something GRail doesn't render itself\" — an embed\n * iframe's src, an og:image meta tag, structured data, a third-party widget's\n * config.\n *\n * Read-only: this does not make a field editable on its own. Give the same\n * id a normal <GRail> somewhere for an editor to change it, or — for a field\n * with nothing on the page to click, like a meta description — build your own\n * editing UI around setFieldValue(). This just reads whatever the field\n * currently holds.\n *\n * Shares <GRail>'s request-scoped batching loader, so calling this alongside\n * other fields — including several of these via Promise.all — still resolves\n * in one query, not one per call.\n *\n * Returns null when nothing has been saved yet. There is no `children`\n * fallback to fall back to here, since nothing is rendered — supply your own\n * default in the calling code.\n */\nexport async function getFieldValue(id: string): Promise<OverrideValue | null> {\n const row = await loadOverride(id);\n return row?.value ?? null;\n}\n"],"mappings":"AAAA,SAAS,oBAAoB;AAyB7B,eAAsB,cAAc,IAA2C;AAC7E,QAAM,MAAM,MAAM,aAAa,EAAE;AACjC,SAAO,KAAK,SAAS;AACvB;","names":[]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
"use server";
|
|
2
2
|
import { revalidatePath } from "next/cache";
|
|
3
3
|
import { getDB, getRepeaters, resolveSiteId } from "../core/config";
|
|
4
|
-
import { requireRole } from "./
|
|
4
|
+
import { requireRole } from "./access";
|
|
5
5
|
import { rethrowIfBailout } from "../core/bailout";
|
|
6
6
|
const DENIED = { success: false, error: "Unauthorized." };
|
|
7
7
|
async function addRepeaterItem(repeaterId, options) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/server/repeaterActions.ts"],"sourcesContent":["\"use server\";\n\nimport { revalidatePath } from \"next/cache\";\nimport { getDB, getRepeaters, resolveSiteId } from \"../core/config\";\nimport { requireRole } from \"./
|
|
1
|
+
{"version":3,"sources":["../../src/server/repeaterActions.ts"],"sourcesContent":["\"use server\";\n\nimport { revalidatePath } from \"next/cache\";\nimport { getDB, getRepeaters, resolveSiteId } from \"../core/config\";\nimport { requireRole } from \"./access\";\nimport { rethrowIfBailout } from \"../core/bailout\";\nimport type { GRRepeaterItem } from \"../core/types\";\n\ntype Result = { success: boolean; error?: string };\n\nconst DENIED: Result = { success: false, error: \"Unauthorized.\" };\n\nexport async function addRepeaterItem(\n repeaterId: string,\n options?: { slug?: string },\n): Promise<\n { success: true; item: GRRepeaterItem } | { success: false; error: string }\n> {\n const viewer = await requireRole([\"admin\", \"editor\"]);\n if (!viewer) return { success: false, error: \"Unauthorized.\" };\n\n if (options?.slug !== undefined) {\n const slug = options.slug.trim();\n if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(slug)) {\n return {\n success: false,\n error: \"Use lowercase letters, numbers, and hyphens only.\",\n };\n }\n options = { slug };\n }\n\n try {\n const repeaters = getRepeaters();\n const res = await repeaters.addItem(repeaterId, await resolveSiteId(), options);\n if (res.success) revalidatePath(\"/\", \"layout\");\n return res;\n } catch (e) {\n rethrowIfBailout(e);\n console.error(\"Guardrail: addRepeaterItem failed\", e);\n return { success: false, error: \"Could not add the item.\" };\n }\n}\n\nexport async function removeRepeaterItem(\n repeaterId: string,\n itemId: string,\n): Promise<Result> {\n const viewer = await requireRole([\"admin\", \"editor\"]);\n if (!viewer) return DENIED;\n\n try {\n const siteId = await resolveSiteId();\n const repeaters = getRepeaters();\n const res = await repeaters.removeItem(repeaterId, siteId, itemId);\n if (!res.success) return res;\n\n // Best-effort: an adapter that can't do this cheaply just leaves the old\n // field values behind, unreachable but harmless.\n const db = getDB();\n await db.deleteOverrides?.(`${repeaterId}.${itemId}.`, siteId);\n\n revalidatePath(\"/\", \"layout\");\n return { success: true };\n } catch (e) {\n rethrowIfBailout(e);\n console.error(\"Guardrail: removeRepeaterItem failed\", e);\n return { success: false, error: \"Could not remove the item.\" };\n }\n}\n\nexport async function reorderRepeaterItems(\n repeaterId: string,\n orderedItemIds: string[],\n): Promise<Result> {\n const viewer = await requireRole([\"admin\", \"editor\"]);\n if (!viewer) return DENIED;\n\n try {\n const repeaters = getRepeaters();\n const res = await repeaters.reorderItems(\n repeaterId,\n await resolveSiteId(),\n orderedItemIds,\n );\n if (res.success) revalidatePath(\"/\", \"layout\");\n return res;\n } catch (e) {\n rethrowIfBailout(e);\n console.error(\"Guardrail: reorderRepeaterItems failed\", e);\n return { success: false, error: \"Could not reorder the items.\" };\n }\n}\n"],"mappings":";AAEA,SAAS,sBAAsB;AAC/B,SAAS,OAAO,cAAc,qBAAqB;AACnD,SAAS,mBAAmB;AAC5B,SAAS,wBAAwB;AAKjC,MAAM,SAAiB,EAAE,SAAS,OAAO,OAAO,gBAAgB;AAEhE,eAAsB,gBACpB,YACA,SAGA;AACA,QAAM,SAAS,MAAM,YAAY,CAAC,SAAS,QAAQ,CAAC;AACpD,MAAI,CAAC,OAAQ,QA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