@devbie/fewbie-cli 1.13.1 → 1.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/lib/template-ownership.js +1 -1
- package/dist/lib/template-ownership.js.map +1 -1
- package/dist/registry/copilot/contract.json +87 -0
- package/dist/registry/copilot/fewbie.module.json +144 -0
- package/dist/registry/data-table/fewbie.module.json +1 -1
- package/dist/registry/forgot-password/contract.json +1 -1
- package/dist/registry/forgot-password/fewbie.module.json +8 -5
- package/dist/registry/frontend-monitor-sdk/fewbie.module.json +1 -1
- package/dist/registry/login-form/contract.json +1 -1
- package/dist/registry/login-form/fewbie.module.json +6 -6
- package/dist/registry/login-page/contract.json +1 -1
- package/dist/registry/login-page/fewbie.module.json +4 -4
- package/dist/registry/notification-center/contract.json +67 -0
- package/dist/registry/notification-center/fewbie.module.json +109 -0
- package/dist/registry/password-checklist/contract.json +1 -1
- package/dist/registry/password-checklist/fewbie.module.json +6 -6
- package/dist/registry/preferences-settings/contract.json +1 -1
- package/dist/registry/preferences-settings/fewbie.module.json +5 -5
- package/dist/registry/profile-settings/contract.json +1 -1
- package/dist/registry/profile-settings/fewbie.module.json +4 -4
- package/dist/registry/security-settings/contract.json +1 -1
- package/dist/registry/security-settings/fewbie.module.json +5 -5
- package/dist/registry/settings-required-state/contract.json +4 -5
- package/dist/registry/settings-required-state/fewbie.module.json +10 -11
- package/dist/registry/sse-stream/fewbie.module.json +1 -1
- package/dist/registry/theme/fewbie.module.json +1 -1
- package/package.json +1 -1
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"x-fewbie.contract": {
|
|
9
9
|
"version": "1.0.0",
|
|
10
10
|
"framework": "^1.7.0",
|
|
11
|
-
"entry": "src/
|
|
11
|
+
"entry": "src/features/profile-settings/index.ts",
|
|
12
12
|
"labels": [
|
|
13
13
|
"personalInfo",
|
|
14
14
|
"firstName",
|
|
@@ -37,17 +37,17 @@
|
|
|
37
37
|
},
|
|
38
38
|
"files": [
|
|
39
39
|
{
|
|
40
|
-
"path": "src/
|
|
40
|
+
"path": "src/features/profile-settings/index.ts",
|
|
41
41
|
"content": "export { ProfileSettings } from \"./profile-settings\";\nexport type { ProfileSettingsLabels, ProfileSettingsProps, ProfileSettingsValues } from \"./types\";\n",
|
|
42
42
|
"type": "registry:block"
|
|
43
43
|
},
|
|
44
44
|
{
|
|
45
|
-
"path": "src/
|
|
45
|
+
"path": "src/features/profile-settings/types.ts",
|
|
46
46
|
"content": "/**\n * Every string the card renders. The host supplies translated copy.\n */\nexport interface ProfileSettingsLabels {\n personalInfo: string;\n firstName: string;\n middleName: string;\n lastName: string;\n displayName: string;\n displayNamePlaceholder: string;\n saveChanges: string;\n email: string;\n saveFailed: string;\n}\n\nexport interface ProfileSettingsValues {\n name: string;\n firstName: string;\n middleName: string;\n lastName: string;\n email?: string;\n}\n\n/**\n * Host-owned write path. The module never calls fetch or a toast library: the\n * host persists the values and decides how to report the outcome.\n */\nexport interface ProfileSettingsProps {\n labels: ProfileSettingsLabels;\n /** Current account values; the form re-seeds when these change. */\n profile: ProfileSettingsValues;\n /** Persist the edited values; the host toasts and refreshes its cache. */\n onSave(values: ProfileSettingsValues): Promise<void>;\n}\n",
|
|
47
47
|
"type": "registry:block"
|
|
48
48
|
},
|
|
49
49
|
{
|
|
50
|
-
"path": "src/
|
|
50
|
+
"path": "src/features/profile-settings/profile-settings.tsx",
|
|
51
51
|
"content": "\"use client\";\n\nimport { useState } from \"react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport type { ProfileSettingsProps, ProfileSettingsValues } from \"./types\";\n\nfunction Spinner() {\n return (\n <span\n aria-hidden=\"true\"\n className=\"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent\"\n />\n );\n}\n\nfunction SaveIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2Z\" />\n <path d=\"M17 21v-8H7v8M7 3v5h8\" />\n </svg>\n );\n}\n\nfunction sameValues(left: ProfileSettingsValues, right: ProfileSettingsValues): boolean {\n return (\n left.name === right.name &&\n left.firstName === right.firstName &&\n left.middleName === right.middleName &&\n left.lastName === right.lastName &&\n left.email === right.email\n );\n}\n\n/**\n * Account profile card: first/middle/last name plus the display name. The host\n * owns data loading, persistence and toasts; the module only edits the values.\n */\nexport function ProfileSettings({ labels, profile, onSave }: ProfileSettingsProps) {\n const [form, setForm] = useState<ProfileSettingsValues>(profile);\n // Re-seed when the host supplies a different account, comparing values (not\n // object identity) so a parent re-render never overwrites in-progress edits.\n const [seed, setSeed] = useState<ProfileSettingsValues>(profile);\n if (!sameValues(profile, seed)) {\n setSeed(profile);\n setForm(profile);\n }\n\n const [pending, setPending] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n function updateField(field: keyof ProfileSettingsValues, value: string): void {\n setForm((prev) => ({ ...prev, [field]: value }));\n }\n\n async function handleSave(): Promise<void> {\n if (pending) return;\n setPending(true);\n setError(null);\n try {\n await onSave(form);\n } catch {\n setError(labels.saveFailed);\n } finally {\n setPending(false);\n }\n }\n\n return (\n <Card>\n <CardHeader>\n <CardTitle className=\"text-base\">{labels.personalInfo}</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <div className=\"grid gap-4 sm:grid-cols-3\">\n <div className=\"space-y-2\">\n <Label htmlFor=\"profile-settings-first-name\">{labels.firstName}</Label>\n <Input\n id=\"profile-settings-first-name\"\n value={form.firstName}\n onChange={(event) => updateField(\"firstName\", event.target.value)}\n placeholder={labels.firstName}\n />\n </div>\n <div className=\"space-y-2\">\n <Label htmlFor=\"profile-settings-middle-name\">{labels.middleName}</Label>\n <Input\n id=\"profile-settings-middle-name\"\n value={form.middleName}\n onChange={(event) => updateField(\"middleName\", event.target.value)}\n placeholder={labels.middleName}\n />\n </div>\n <div className=\"space-y-2\">\n <Label htmlFor=\"profile-settings-last-name\">{labels.lastName}</Label>\n <Input\n id=\"profile-settings-last-name\"\n value={form.lastName}\n onChange={(event) => updateField(\"lastName\", event.target.value)}\n placeholder={labels.lastName}\n />\n </div>\n </div>\n\n <div className=\"space-y-2\">\n <Label htmlFor=\"profile-settings-name\">{labels.displayName}</Label>\n <Input\n id=\"profile-settings-name\"\n value={form.name}\n onChange={(event) => updateField(\"name\", event.target.value)}\n placeholder={labels.displayNamePlaceholder}\n />\n </div>\n\n {error && <p className=\"text-sm text-destructive\">{error}</p>}\n\n <div className=\"flex items-center gap-3 border-t pt-4\">\n <Button type=\"button\" onClick={() => void handleSave()} disabled={pending}>\n {pending ? <Spinner /> : <SaveIcon />}\n {labels.saveChanges}\n </Button>\n <p className=\"text-xs text-muted-foreground\">\n {labels.email}: {profile.email ?? \"—\"}\n </p>\n </div>\n </CardContent>\n </Card>\n );\n}\n",
|
|
52
52
|
"type": "registry:block"
|
|
53
53
|
}
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"x-fewbie.contract": {
|
|
9
9
|
"version": "1.0.0",
|
|
10
10
|
"framework": "^1.7.0",
|
|
11
|
-
"entry": "src/
|
|
11
|
+
"entry": "src/features/security-settings/index.ts",
|
|
12
12
|
"labels": [
|
|
13
13
|
"activeSessions",
|
|
14
14
|
"loadingSessions",
|
|
@@ -59,18 +59,18 @@
|
|
|
59
59
|
},
|
|
60
60
|
"files": [
|
|
61
61
|
{
|
|
62
|
-
"path": "src/
|
|
62
|
+
"path": "src/features/security-settings/index.ts",
|
|
63
63
|
"content": "export { SecuritySettings } from \"./security-settings\";\nexport type {\n SecuritySession,\n SecuritySettingsLabels,\n SecuritySettingsPort,\n SecuritySettingsProps,\n SecurityTwoFactorSetup,\n} from \"./types\";\n",
|
|
64
64
|
"type": "registry:block"
|
|
65
65
|
},
|
|
66
66
|
{
|
|
67
|
-
"path": "src/
|
|
67
|
+
"path": "src/features/security-settings/types.ts",
|
|
68
68
|
"content": "/**\n * Every string the cards render. The host supplies translated copy.\n */\nexport interface SecuritySettingsLabels {\n activeSessions: string;\n loadingSessions: string;\n loadSessionsFailed: string;\n noSessions: string;\n unknownDevice: string;\n thisDevice: string;\n signOutSession: string;\n twoFactorTitle: string;\n statusEnabled: string;\n statusDisabled: string;\n twoFactorDesc: string;\n qrAlt: string;\n scanQr: string;\n enterCode: string;\n confirmEnable: string;\n currentPassword: string;\n passwordPlaceholder: string;\n or: string;\n authenticatorCode: string;\n disable: string;\n disableTwoFactor: string;\n setupWithApp: string;\n cancel: string;\n retry: string;\n actionFailed: string;\n}\n\n/** One active session row, trimmed to what the card displays. */\nexport interface SecuritySession {\n id: number;\n browser?: string;\n operatingSystem?: string;\n isCurrentSession?: boolean;\n ipAddress?: string;\n city?: string;\n region?: string;\n countryCode?: string;\n createdAt: string;\n}\n\nexport interface SecurityTwoFactorSetup {\n qrCodeDataUrl: string;\n secret: string;\n}\n\n/**\n * Host-owned transport. The module never calls fetch or a query library: the\n * host decides how to reach its backend and what to do after each mutation.\n */\nexport interface SecuritySettingsPort {\n listSessions(): Promise<{ records: SecuritySession[] }>;\n revokeSession(id: number): Promise<void>;\n setupTwoFactor(): Promise<SecurityTwoFactorSetup>;\n enableTwoFactor(code: string): Promise<void>;\n disableTwoFactor(input: { password?: string; code?: string }): Promise<void>;\n}\n\nexport interface SecuritySettingsProps {\n labels: SecuritySettingsLabels;\n /** True when the account already has an authenticator app enrolled. */\n twoFactorEnabled: boolean;\n /**\n * Formats a session timestamp for display. The host owns locale formatting;\n * the module falls back to `toLocaleString` when omitted.\n */\n formatDateTime?: (iso: string) => string;\n port: SecuritySettingsPort;\n /** Called after a session was revoked so the host can refresh its cache. */\n onSessionsChanged?: () => void;\n /** Called after two-factor was enabled or disabled so the host can refresh. */\n onTwoFactorChanged?: () => void;\n}\n",
|
|
69
69
|
"type": "registry:block"
|
|
70
70
|
},
|
|
71
71
|
{
|
|
72
|
-
"path": "src/
|
|
73
|
-
"content": "\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport type { SecuritySession, SecuritySettingsProps, SecurityTwoFactorSetup } from \"./types\";\n\nconst CODE_LENGTH = 6;\n\nfunction Spinner() {\n return (\n <span\n aria-hidden=\"true\"\n className=\"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent\"\n />\n );\n}\n\nfunction MonitorIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <rect x=\"2\" y=\"3\" width=\"20\" height=\"14\" rx=\"2\" />\n <path d=\"M8 21h8M12 17v4\" />\n </svg>\n );\n}\n\nfunction ShieldCheckIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4 text-green-600\"\n >\n <path d=\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z\" />\n <path d=\"m9 12 2 2 4-4\" />\n </svg>\n );\n}\n\nfunction ShieldOffIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z\" />\n <path d=\"m4 4 16 16\" />\n </svg>\n );\n}\n\nfunction TrashIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6M10 11v5M14 11v5\" />\n </svg>\n );\n}\n\n/** Format the location parts carried on a session row. */\nfunction formatLocation(session: SecuritySession): string {\n return [session.city, session.region, session.countryCode].filter(Boolean).join(\", \");\n}\n\n/**\n * Account security cards: active sessions with per-row sign-out, and\n * authenticator-app enrollment. The host owns transport, cache invalidation\n * and toasts; the module only renders and reports through callbacks.\n */\nexport function SecuritySettings({\n labels,\n twoFactorEnabled,\n formatDateTime,\n port,\n onSessionsChanged,\n onTwoFactorChanged,\n}: SecuritySettingsProps) {\n // Keep the port reachable from the mount effect without re-running it when\n // the host re-creates its callback objects on every render.\n const portRef = useRef(port);\n useEffect(() => {\n portRef.current = port;\n }, [port]);\n\n const [sessions, setSessions] = useState<SecuritySession[] | null>(null);\n const [sessionsPending, setSessionsPending] = useState(true);\n const [sessionsFailed, setSessionsFailed] = useState(false);\n const [revokingId, setRevokingId] = useState<number | null>(null);\n const [actionError, setActionError] = useState<string | null>(null);\n\n const [setupData, setSetupData] = useState<SecurityTwoFactorSetup | null>(null);\n const [setupPending, setSetupPending] = useState(false);\n const [enableCode, setEnableCode] = useState(\"\");\n const [enablePending, setEnablePending] = useState(false);\n const [disableMode, setDisableMode] = useState(false);\n const [disablePassword, setDisablePassword] = useState(\"\");\n const [disableCode, setDisableCode] = useState(\"\");\n const [disablePending, setDisablePending] = useState(false);\n\n const loadSessions = useCallback(async (): Promise<void> => {\n try {\n const result = await portRef.current.listSessions();\n setSessions(result.records);\n setSessionsFailed(false);\n } catch {\n setSessionsFailed(true);\n } finally {\n setSessionsPending(false);\n }\n }, []);\n\n useEffect(() => {\n void loadSessions();\n }, [loadSessions]);\n\n function retrySessions(): void {\n setSessionsPending(true);\n setSessionsFailed(false);\n void loadSessions();\n }\n\n const formatDate = formatDateTime ?? ((iso: string) => new Date(iso).toLocaleString());\n\n async function handleRevoke(id: number): Promise<void> {\n if (revokingId !== null) return;\n setRevokingId(id);\n setActionError(null);\n try {\n await port.revokeSession(id);\n onSessionsChanged?.();\n await loadSessions();\n } catch {\n setActionError(labels.actionFailed);\n } finally {\n setRevokingId(null);\n }\n }\n\n async function handleSetup(): Promise<void> {\n if (setupPending) return;\n setSetupPending(true);\n setActionError(null);\n try {\n setSetupData(await port.setupTwoFactor());\n } catch {\n setActionError(labels.actionFailed);\n } finally {\n setSetupPending(false);\n }\n }\n\n async function handleEnable(): Promise<void> {\n if (enablePending) return;\n setEnablePending(true);\n setActionError(null);\n try {\n await port.enableTwoFactor(enableCode);\n setSetupData(null);\n setEnableCode(\"\");\n onTwoFactorChanged?.();\n } catch {\n setActionError(labels.actionFailed);\n } finally {\n setEnablePending(false);\n }\n }\n\n async function handleDisable(): Promise<void> {\n if (disablePending) return;\n setDisablePending(true);\n setActionError(null);\n try {\n await port.disableTwoFactor(disablePassword ? { password: disablePassword } : { code: disableCode });\n setDisableMode(false);\n setDisablePassword(\"\");\n setDisableCode(\"\");\n onTwoFactorChanged?.();\n } catch {\n setActionError(labels.actionFailed);\n } finally {\n setDisablePending(false);\n }\n }\n\n return (\n <div className=\"grid max-w-3xl gap-6\">\n <Card>\n <CardHeader>\n <CardTitle className=\"flex items-center gap-2 text-base\">\n <MonitorIcon />\n {labels.activeSessions}\n </CardTitle>\n </CardHeader>\n <CardContent>\n {sessionsPending ? (\n <div className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n <Spinner />\n {labels.loadingSessions}\n </div>\n ) : sessionsFailed ? (\n <div className=\"flex flex-wrap items-center gap-2 text-sm text-destructive\">\n {labels.loadSessionsFailed}\n <Button type=\"button\" variant=\"link\" size=\"sm\" className=\"h-auto p-0\" onClick={retrySessions}>\n {labels.retry}\n </Button>\n </div>\n ) : !sessions?.length ? (\n <p className=\"text-sm text-muted-foreground\">{labels.noSessions}</p>\n ) : (\n <ul className=\"divide-y\">\n {sessions.map((session) => (\n <li key={session.id} className=\"flex items-center justify-between gap-4 py-3 first:pt-0 last:pb-0\">\n <div className=\"min-w-0\">\n <div className=\"flex items-center gap-2\">\n <p className=\"truncate text-sm font-medium\">\n {[session.browser, session.operatingSystem].filter(Boolean).join(\" · \") || labels.unknownDevice}\n </p>\n {session.isCurrentSession && (\n <Badge variant=\"outline\" className=\"border-green-200 bg-green-50 text-green-700\">\n {labels.thisDevice}\n </Badge>\n )}\n </div>\n <p className=\"mt-0.5 truncate text-xs text-muted-foreground\">\n {[session.ipAddress, formatLocation(session)].filter(Boolean).join(\" · \")} ·{\" \"}\n {formatDate(session.createdAt)}\n </p>\n </div>\n {!session.isCurrentSession && (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon\"\n aria-label={labels.signOutSession}\n disabled={revokingId !== null}\n onClick={() => void handleRevoke(session.id)}\n >\n {revokingId === session.id ? <Spinner /> : <TrashIcon />}\n </Button>\n )}\n </li>\n ))}\n </ul>\n )}\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"flex items-center justify-between gap-2 text-base\">\n <span className=\"flex items-center gap-2\">\n {twoFactorEnabled ? <ShieldCheckIcon /> : <ShieldOffIcon />}\n {labels.twoFactorTitle}\n </span>\n <Badge variant={twoFactorEnabled ? \"default\" : \"outline\"}>\n {twoFactorEnabled ? labels.statusEnabled : labels.statusDisabled}\n </Badge>\n </CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">{labels.twoFactorDesc}</p>\n\n {/* Enrollment flow: QR code plus code confirmation */}\n {setupData && (\n <div className=\"space-y-4 rounded-md border bg-muted/30 p-4\">\n <div className=\"flex flex-col items-center gap-3 sm:flex-row sm:items-start\">\n {/* eslint-disable-next-line @next/next/no-img-element */}\n <img\n src={setupData.qrCodeDataUrl}\n alt={labels.qrAlt}\n className=\"h-40 w-40 rounded-md border bg-white p-2\"\n />\n <div className=\"min-w-0 space-y-2\">\n <p className=\"text-xs text-muted-foreground\">{labels.scanQr}</p>\n <p className=\"break-all rounded bg-background p-2 font-mono text-xs\">{setupData.secret}</p>\n </div>\n </div>\n <div className=\"space-y-2\">\n <Label htmlFor=\"security-settings-enable-code\">{labels.enterCode}</Label>\n <Input\n id=\"security-settings-enable-code\"\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n value={enableCode}\n onChange={(event) => setEnableCode(event.target.value.replace(/\\D/g, \"\").slice(0, CODE_LENGTH))}\n placeholder=\"123456\"\n />\n </div>\n <div className=\"flex justify-end gap-2\">\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => {\n setSetupData(null);\n setEnableCode(\"\");\n }}\n disabled={enablePending}\n >\n {labels.cancel}\n </Button>\n <Button\n type=\"button\"\n onClick={() => void handleEnable()}\n disabled={enablePending || enableCode.length !== CODE_LENGTH}\n >\n {enablePending ? <Spinner /> : labels.confirmEnable}\n </Button>\n </div>\n </div>\n )}\n\n {/* Disable flow: prove identity with password or a current code */}\n {disableMode && (\n <div className=\"space-y-4 rounded-md border bg-muted/30 p-4\">\n <div className=\"space-y-2\">\n <Label htmlFor=\"security-settings-disable-password\">{labels.currentPassword}</Label>\n <Input\n id=\"security-settings-disable-password\"\n type=\"password\"\n autoComplete=\"current-password\"\n value={disablePassword}\n onChange={(event) => {\n setDisablePassword(event.target.value);\n setDisableCode(\"\");\n }}\n placeholder={labels.passwordPlaceholder}\n />\n </div>\n <p className=\"text-center text-xs text-muted-foreground\">{labels.or}</p>\n <div className=\"space-y-2\">\n <Label htmlFor=\"security-settings-disable-code\">{labels.authenticatorCode}</Label>\n <Input\n id=\"security-settings-disable-code\"\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n value={disableCode}\n onChange={(event) => {\n setDisableCode(event.target.value.replace(/\\D/g, \"\").slice(0, CODE_LENGTH));\n setDisablePassword(\"\");\n }}\n placeholder=\"123456\"\n />\n </div>\n <div className=\"flex justify-end gap-2\">\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => {\n setDisableMode(false);\n setDisablePassword(\"\");\n setDisableCode(\"\");\n }}\n disabled={disablePending}\n >\n {labels.cancel}\n </Button>\n <Button\n type=\"button\"\n variant=\"destructive\"\n onClick={() => void handleDisable()}\n disabled={disablePending || (!disablePassword && disableCode.length !== CODE_LENGTH)}\n >\n {disablePending ? <Spinner /> : labels.disable}\n </Button>\n </div>\n </div>\n )}\n\n {actionError && <p className=\"text-sm text-destructive\">{actionError}</p>}\n\n {/* Idle actions */}\n {!setupData && !disableMode && (\n <div>\n {twoFactorEnabled ? (\n <Button type=\"button\" variant=\"outline\" onClick={() => setDisableMode(true)}>\n {labels.disableTwoFactor}\n </Button>\n ) : (\n <Button type=\"button\" onClick={() => void handleSetup()} disabled={setupPending}>\n {setupPending ? <Spinner /> : labels.setupWithApp}\n </Button>\n )}\n </div>\n )}\n </CardContent>\n </Card>\n </div>\n );\n}\n",
|
|
72
|
+
"path": "src/features/security-settings/security-settings.tsx",
|
|
73
|
+
"content": "\"use client\";\n\nimport { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport { Badge } from \"@/components/ui/badge\";\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent, CardHeader, CardTitle } from \"@/components/ui/card\";\nimport { Input } from \"@/components/ui/input\";\nimport { Label } from \"@/components/ui/label\";\nimport type { SecuritySession, SecuritySettingsProps, SecurityTwoFactorSetup } from \"./types\";\n\nconst CODE_LENGTH = 6;\n\n/** SSR-safe date fallback: fixed locale and zone, so both renders agree. */\nconst DEFAULT_DATE_FORMATTER = new Intl.DateTimeFormat(\"en-US\", {\n dateStyle: \"medium\",\n timeStyle: \"short\",\n timeZone: \"UTC\",\n});\n\nfunction Spinner() {\n return (\n <span\n aria-hidden=\"true\"\n className=\"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent\"\n />\n );\n}\n\nfunction MonitorIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <rect x=\"2\" y=\"3\" width=\"20\" height=\"14\" rx=\"2\" />\n <path d=\"M8 21h8M12 17v4\" />\n </svg>\n );\n}\n\nfunction ShieldCheckIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4 text-green-600 dark:text-green-500\"\n >\n <path d=\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z\" />\n <path d=\"m9 12 2 2 4-4\" />\n </svg>\n );\n}\n\nfunction ShieldOffIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z\" />\n <path d=\"m4 4 16 16\" />\n </svg>\n );\n}\n\nfunction TrashIcon() {\n return (\n <svg\n aria-hidden=\"true\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"h-4 w-4\"\n >\n <path d=\"M3 6h18M8 6V4h8v2M19 6l-1 14H6L5 6M10 11v5M14 11v5\" />\n </svg>\n );\n}\n\n/** Format the location parts carried on a session row. */\nfunction formatLocation(session: SecuritySession): string {\n return [session.city, session.region, session.countryCode].filter(Boolean).join(\", \");\n}\n\n/**\n * Account security cards: active sessions with per-row sign-out, and\n * authenticator-app enrollment. The host owns transport, cache invalidation\n * and toasts; the module only renders and reports through callbacks.\n */\nexport function SecuritySettings({\n labels,\n twoFactorEnabled,\n formatDateTime,\n port,\n onSessionsChanged,\n onTwoFactorChanged,\n}: SecuritySettingsProps) {\n // Keep the port reachable from the mount effect without re-running it when\n // the host re-creates its callback objects on every render.\n const portRef = useRef(port);\n useEffect(() => {\n portRef.current = port;\n }, [port]);\n\n const [sessions, setSessions] = useState<SecuritySession[] | null>(null);\n const [sessionsPending, setSessionsPending] = useState(true);\n const [sessionsFailed, setSessionsFailed] = useState(false);\n const [revokingId, setRevokingId] = useState<number | null>(null);\n const [actionError, setActionError] = useState<string | null>(null);\n\n const [setupData, setSetupData] = useState<SecurityTwoFactorSetup | null>(null);\n const [setupPending, setSetupPending] = useState(false);\n const [enableCode, setEnableCode] = useState(\"\");\n const [enablePending, setEnablePending] = useState(false);\n const [disableMode, setDisableMode] = useState(false);\n const [disablePassword, setDisablePassword] = useState(\"\");\n const [disableCode, setDisableCode] = useState(\"\");\n const [disablePending, setDisablePending] = useState(false);\n\n const loadSessions = useCallback(async (): Promise<void> => {\n try {\n const result = await portRef.current.listSessions();\n setSessions(result.records);\n setSessionsFailed(false);\n } catch {\n setSessionsFailed(true);\n } finally {\n setSessionsPending(false);\n }\n }, []);\n\n useEffect(() => {\n void loadSessions();\n }, [loadSessions]);\n\n function retrySessions(): void {\n setSessionsPending(true);\n setSessionsFailed(false);\n void loadSessions();\n }\n\n // Deterministic fallback: a locale/timezone-sensitive formatter would render\n // differently on the server and in the browser (R84-10). Hosts pass\n // `formatDateTime` to localize.\n const formatDate = formatDateTime ?? ((iso: string) => DEFAULT_DATE_FORMATTER.format(new Date(iso)));\n\n async function handleRevoke(id: number): Promise<void> {\n if (revokingId !== null) return;\n setRevokingId(id);\n setActionError(null);\n try {\n await port.revokeSession(id);\n onSessionsChanged?.();\n await loadSessions();\n } catch {\n setActionError(labels.actionFailed);\n } finally {\n setRevokingId(null);\n }\n }\n\n async function handleSetup(): Promise<void> {\n if (setupPending) return;\n setSetupPending(true);\n setActionError(null);\n try {\n setSetupData(await port.setupTwoFactor());\n } catch {\n setActionError(labels.actionFailed);\n } finally {\n setSetupPending(false);\n }\n }\n\n async function handleEnable(): Promise<void> {\n if (enablePending) return;\n setEnablePending(true);\n setActionError(null);\n try {\n await port.enableTwoFactor(enableCode);\n setSetupData(null);\n setEnableCode(\"\");\n onTwoFactorChanged?.();\n } catch {\n setActionError(labels.actionFailed);\n } finally {\n setEnablePending(false);\n }\n }\n\n async function handleDisable(): Promise<void> {\n if (disablePending) return;\n setDisablePending(true);\n setActionError(null);\n try {\n await port.disableTwoFactor(disablePassword ? { password: disablePassword } : { code: disableCode });\n setDisableMode(false);\n setDisablePassword(\"\");\n setDisableCode(\"\");\n onTwoFactorChanged?.();\n } catch {\n setActionError(labels.actionFailed);\n } finally {\n setDisablePending(false);\n }\n }\n\n return (\n <div className=\"grid max-w-3xl gap-6\">\n <Card>\n <CardHeader>\n <CardTitle className=\"flex items-center gap-2 text-base\">\n <MonitorIcon />\n {labels.activeSessions}\n </CardTitle>\n </CardHeader>\n <CardContent>\n {sessionsPending ? (\n <div className=\"flex items-center gap-2 text-sm text-muted-foreground\">\n <Spinner />\n {labels.loadingSessions}\n </div>\n ) : sessionsFailed ? (\n <div className=\"flex flex-wrap items-center gap-2 text-sm text-destructive\">\n {labels.loadSessionsFailed}\n <Button type=\"button\" variant=\"link\" size=\"sm\" className=\"h-auto p-0\" onClick={retrySessions}>\n {labels.retry}\n </Button>\n </div>\n ) : !sessions?.length ? (\n <p className=\"text-sm text-muted-foreground\">{labels.noSessions}</p>\n ) : (\n <ul className=\"divide-y\">\n {sessions.map((session) => (\n <li key={session.id} className=\"flex items-center justify-between gap-4 py-3 first:pt-0 last:pb-0\">\n <div className=\"min-w-0\">\n <div className=\"flex items-center gap-2\">\n <p className=\"truncate text-sm font-medium\">\n {[session.browser, session.operatingSystem].filter(Boolean).join(\" · \") || labels.unknownDevice}\n </p>\n {session.isCurrentSession && (\n <Badge\n variant=\"outline\"\n className=\"border-green-200 bg-green-50 text-green-700 dark:border-green-900 dark:bg-green-950 dark:text-green-400\"\n >\n {labels.thisDevice}\n </Badge>\n )}\n </div>\n <p className=\"mt-0.5 truncate text-xs text-muted-foreground\">\n {[session.ipAddress, formatLocation(session)].filter(Boolean).join(\" · \")} ·{\" \"}\n {formatDate(session.createdAt)}\n </p>\n </div>\n {!session.isCurrentSession && (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"icon\"\n aria-label={labels.signOutSession}\n disabled={revokingId !== null}\n onClick={() => void handleRevoke(session.id)}\n >\n {revokingId === session.id ? <Spinner /> : <TrashIcon />}\n </Button>\n )}\n </li>\n ))}\n </ul>\n )}\n </CardContent>\n </Card>\n\n <Card>\n <CardHeader>\n <CardTitle className=\"flex items-center justify-between gap-2 text-base\">\n <span className=\"flex items-center gap-2\">\n {twoFactorEnabled ? <ShieldCheckIcon /> : <ShieldOffIcon />}\n {labels.twoFactorTitle}\n </span>\n <Badge variant={twoFactorEnabled ? \"default\" : \"outline\"}>\n {twoFactorEnabled ? labels.statusEnabled : labels.statusDisabled}\n </Badge>\n </CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <p className=\"text-sm text-muted-foreground\">{labels.twoFactorDesc}</p>\n\n {/* Enrollment flow: QR code plus code confirmation */}\n {setupData && (\n <div className=\"space-y-4 rounded-md border bg-muted/30 p-4\">\n <div className=\"flex flex-col items-center gap-3 sm:flex-row sm:items-start\">\n {/* eslint-disable-next-line @next/next/no-img-element */}\n <img\n src={setupData.qrCodeDataUrl}\n alt={labels.qrAlt}\n className=\"h-40 w-40 rounded-md border bg-white p-2\"\n />\n <div className=\"min-w-0 space-y-2\">\n <p className=\"text-xs text-muted-foreground\">{labels.scanQr}</p>\n <p className=\"break-all rounded bg-background p-2 font-mono text-xs\">{setupData.secret}</p>\n </div>\n </div>\n <div className=\"space-y-2\">\n <Label htmlFor=\"security-settings-enable-code\">{labels.enterCode}</Label>\n <Input\n id=\"security-settings-enable-code\"\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n value={enableCode}\n onChange={(event) => setEnableCode(event.target.value.replace(/\\D/g, \"\").slice(0, CODE_LENGTH))}\n placeholder=\"123456\"\n />\n </div>\n <div className=\"flex justify-end gap-2\">\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => {\n setSetupData(null);\n setEnableCode(\"\");\n }}\n disabled={enablePending}\n >\n {labels.cancel}\n </Button>\n <Button\n type=\"button\"\n onClick={() => void handleEnable()}\n disabled={enablePending || enableCode.length !== CODE_LENGTH}\n >\n {enablePending ? <Spinner /> : labels.confirmEnable}\n </Button>\n </div>\n </div>\n )}\n\n {/* Disable flow: prove identity with password or a current code */}\n {disableMode && (\n <div className=\"space-y-4 rounded-md border bg-muted/30 p-4\">\n <div className=\"space-y-2\">\n <Label htmlFor=\"security-settings-disable-password\">{labels.currentPassword}</Label>\n <Input\n id=\"security-settings-disable-password\"\n type=\"password\"\n autoComplete=\"current-password\"\n value={disablePassword}\n onChange={(event) => {\n setDisablePassword(event.target.value);\n setDisableCode(\"\");\n }}\n placeholder={labels.passwordPlaceholder}\n />\n </div>\n <p className=\"text-center text-xs text-muted-foreground\">{labels.or}</p>\n <div className=\"space-y-2\">\n <Label htmlFor=\"security-settings-disable-code\">{labels.authenticatorCode}</Label>\n <Input\n id=\"security-settings-disable-code\"\n inputMode=\"numeric\"\n autoComplete=\"one-time-code\"\n value={disableCode}\n onChange={(event) => {\n setDisableCode(event.target.value.replace(/\\D/g, \"\").slice(0, CODE_LENGTH));\n setDisablePassword(\"\");\n }}\n placeholder=\"123456\"\n />\n </div>\n <div className=\"flex justify-end gap-2\">\n <Button\n type=\"button\"\n variant=\"outline\"\n onClick={() => {\n setDisableMode(false);\n setDisablePassword(\"\");\n setDisableCode(\"\");\n }}\n disabled={disablePending}\n >\n {labels.cancel}\n </Button>\n <Button\n type=\"button\"\n variant=\"destructive\"\n onClick={() => void handleDisable()}\n disabled={disablePending || (!disablePassword && disableCode.length !== CODE_LENGTH)}\n >\n {disablePending ? <Spinner /> : labels.disable}\n </Button>\n </div>\n </div>\n )}\n\n {actionError && <p className=\"text-sm text-destructive\">{actionError}</p>}\n\n {/* Idle actions */}\n {!setupData && !disableMode && (\n <div>\n {twoFactorEnabled ? (\n <Button type=\"button\" variant=\"outline\" onClick={() => setDisableMode(true)}>\n {labels.disableTwoFactor}\n </Button>\n ) : (\n <Button type=\"button\" onClick={() => void handleSetup()} disabled={setupPending}>\n {setupPending ? <Spinner /> : labels.setupWithApp}\n </Button>\n )}\n </div>\n )}\n </CardContent>\n </Card>\n </div>\n );\n}\n",
|
|
74
74
|
"type": "registry:block"
|
|
75
75
|
}
|
|
76
76
|
]
|
|
@@ -1,18 +1,17 @@
|
|
|
1
1
|
{
|
|
2
|
-
"version": "1.
|
|
2
|
+
"version": "1.1.0",
|
|
3
3
|
"framework": "^1.7.0",
|
|
4
|
-
"entry": "src/
|
|
4
|
+
"entry": "src/features/settings-required-state/index.ts",
|
|
5
5
|
"labels": [
|
|
6
6
|
"actionLabel"
|
|
7
7
|
],
|
|
8
|
-
"ports": [
|
|
9
|
-
"onOpenSettings"
|
|
10
|
-
],
|
|
8
|
+
"ports": [],
|
|
11
9
|
"ui": [
|
|
12
10
|
"button",
|
|
13
11
|
"card"
|
|
14
12
|
],
|
|
15
13
|
"states": [
|
|
14
|
+
"loading",
|
|
16
15
|
"ready"
|
|
17
16
|
]
|
|
18
17
|
}
|
|
@@ -4,39 +4,38 @@
|
|
|
4
4
|
"type": "registry:block",
|
|
5
5
|
"title": "Settings required state",
|
|
6
6
|
"description": "Empty state shown when required configuration is missing, with a call-to-action whose navigation stays in the host.",
|
|
7
|
-
"postInstall": "Render <SettingsRequiredState labels={...} title={...} settingsHref={...} onOpenSettings={...} />
|
|
7
|
+
"postInstall": "Render <SettingsRequiredState labels={...} title={...} settingsHref={...} onOpenSettings={...} /> for the navigate-to-settings variant, or pass onAction (plus actionPending) for an in-place action. The host supplies the translated action label, the in-app settings path and either callback. Requires the shadcn ui primitives button and card.",
|
|
8
8
|
"x-fewbie.contract": {
|
|
9
|
-
"version": "1.
|
|
9
|
+
"version": "1.1.0",
|
|
10
10
|
"framework": "^1.7.0",
|
|
11
|
-
"entry": "src/
|
|
11
|
+
"entry": "src/features/settings-required-state/index.ts",
|
|
12
12
|
"labels": [
|
|
13
13
|
"actionLabel"
|
|
14
14
|
],
|
|
15
|
-
"ports": [
|
|
16
|
-
"onOpenSettings"
|
|
17
|
-
],
|
|
15
|
+
"ports": [],
|
|
18
16
|
"ui": [
|
|
19
17
|
"button",
|
|
20
18
|
"card"
|
|
21
19
|
],
|
|
22
20
|
"states": [
|
|
21
|
+
"loading",
|
|
23
22
|
"ready"
|
|
24
23
|
]
|
|
25
24
|
},
|
|
26
25
|
"files": [
|
|
27
26
|
{
|
|
28
|
-
"path": "src/
|
|
27
|
+
"path": "src/features/settings-required-state/index.ts",
|
|
29
28
|
"content": "export { SettingsRequiredState } from \"./settings-required-state\";\nexport type { SettingsRequiredStateLabels, SettingsRequiredStateProps } from \"./types\";\n",
|
|
30
29
|
"type": "registry:block"
|
|
31
30
|
},
|
|
32
31
|
{
|
|
33
|
-
"path": "src/
|
|
34
|
-
"content": "import type { ReactNode } from \"react\";\n\n/**\n * Every string the state renders. The headline and description are already\n * host-supplied props, so only the call-to-action label lives here.\n */\nexport interface SettingsRequiredStateLabels {\n actionLabel: string;\n}\n\nexport interface SettingsRequiredStateProps {\n labels: SettingsRequiredStateLabels;\n /** Short headline shown below the icon, e.g. \"AWS credential required\". */\n title: string;\n /** Explanation of which setting is missing and why it is needed. */\n description?: ReactNode;\n /** Destination of the settings call-to-action
|
|
32
|
+
"path": "src/features/settings-required-state/types.ts",
|
|
33
|
+
"content": "import type { ReactNode } from \"react\";\n\n/**\n * Every string the state renders. The headline and description are already\n * host-supplied props, so only the call-to-action label lives here.\n */\nexport interface SettingsRequiredStateLabels {\n actionLabel: string;\n}\n\nexport interface SettingsRequiredStateProps {\n labels: SettingsRequiredStateLabels;\n /** Short headline shown below the icon, e.g. \"AWS credential required\". */\n title: string;\n /** Explanation of which setting is missing and why it is needed. */\n description?: ReactNode;\n /** Destination of the settings call-to-action. Required unless `onAction` is provided. */\n settingsHref?: string;\n /** Called with settingsHref; the host performs the client-side navigation. */\n onOpenSettings?: (href: string) => void;\n /** In-place action (e.g. one-click initialization); takes precedence over the settings link. */\n onAction?: () => void;\n /** Shows a spinner and disables the action while the in-place action runs. */\n actionPending?: boolean;\n /** Optional custom icon rendered inside the tinted badge. */\n icon?: ReactNode;\n /** Stretch the state to fill the parent height (used by full-screen panels). */\n fullHeight?: boolean;\n /** Allow callers to tweak the outer container when needed. */\n className?: string;\n}\n",
|
|
35
34
|
"type": "registry:block"
|
|
36
35
|
},
|
|
37
36
|
{
|
|
38
|
-
"path": "src/
|
|
39
|
-
"content": "\"use client\";\n\nimport { ArrowRight, Settings2 } from \"lucide-react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent } from \"@/components/ui/card\";\nimport { cn } from \"@/lib/utils\";\n\nimport type { SettingsRequiredStateProps } from \"./types\";\n\n/**\n * Unified \"required settings are missing\" state. Feature modules render this\n * when their backing configuration has not been set up yet, so the\n * empty-state visuals and the settings entry point stay consistent.\n */\nexport function SettingsRequiredState({\n labels,\n title,\n description,\n settingsHref,\n onOpenSettings,\n icon,\n fullHeight = false,\n className,\n}: SettingsRequiredStateProps) {\n return (\n <div className={cn(\"flex w-full items-center justify-center\", fullHeight ? \"h-full\" : \"py-8 md:py-16\", className)}>\n <Card className=\"w-full max-w-xl text-center\">\n <CardContent className=\"flex flex-col items-center px-6 py-10 md:px-12\">\n {/* Tinted icon badge */}\n <div className=\"mb-4 flex size-16 items-center justify-center rounded-full bg-primary/10 text-primary\">\n {icon ?? <Settings2 className=\"size-8\" />}\n </div>\n\n <h2 className=\"text-lg font-semibold text-foreground\">{title}</h2>\n\n {description ? <p className=\"mt-2 max-w-md text-sm leading-7 text-muted-foreground\">{description}</p> : null}\n\n <Button className=\"mt-6\" onClick={() => onOpenSettings(settingsHref)}>\n
|
|
37
|
+
"path": "src/features/settings-required-state/settings-required-state.tsx",
|
|
38
|
+
"content": "\"use client\";\n\nimport { ArrowRight, LoaderCircle, Settings2 } from \"lucide-react\";\n\nimport { Button } from \"@/components/ui/button\";\nimport { Card, CardContent } from \"@/components/ui/card\";\nimport { cn } from \"@/lib/utils\";\n\nimport type { SettingsRequiredStateProps } from \"./types\";\n\n/**\n * Unified \"required settings are missing\" state. Feature modules render this\n * when their backing configuration has not been set up yet, so the\n * empty-state visuals and the settings entry point stay consistent.\n */\nexport function SettingsRequiredState({\n labels,\n title,\n description,\n settingsHref,\n onOpenSettings,\n onAction,\n actionPending = false,\n icon,\n fullHeight = false,\n className,\n}: SettingsRequiredStateProps) {\n return (\n <div className={cn(\"flex w-full items-center justify-center\", fullHeight ? \"h-full\" : \"py-8 md:py-16\", className)}>\n <Card className=\"w-full max-w-xl text-center\">\n <CardContent className=\"flex flex-col items-center px-6 py-10 md:px-12\">\n {/* Tinted icon badge */}\n <div className=\"mb-4 flex size-16 items-center justify-center rounded-full bg-primary/10 text-primary\">\n {icon ?? <Settings2 className=\"size-8\" />}\n </div>\n\n <h2 className=\"text-lg font-semibold text-foreground\">{title}</h2>\n\n {description ? <p className=\"mt-2 max-w-md text-sm leading-7 text-muted-foreground\">{description}</p> : null}\n\n {onAction ? (\n <Button className=\"mt-6\" onClick={onAction} disabled={actionPending}>\n {actionPending ? <LoaderCircle className=\"size-4 animate-spin\" /> : null}\n {labels.actionLabel}\n </Button>\n ) : settingsHref && onOpenSettings ? (\n <Button className=\"mt-6\" onClick={() => onOpenSettings(settingsHref)}>\n {labels.actionLabel}\n <ArrowRight className=\"size-4\" />\n </Button>\n ) : null}\n </CardContent>\n </Card>\n </div>\n );\n}\n",
|
|
40
39
|
"type": "registry:block"
|
|
41
40
|
}
|
|
42
41
|
]
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
"files": [
|
|
9
9
|
{
|
|
10
10
|
"path": "src/lib/sse-stream.ts",
|
|
11
|
-
"content": "/**\n * Minimal Server-Sent Events transport over fetch.\n *\n * `postSse` covers endpoints that EventSource cannot serve (POST bodies,\n * custom headers): it POSTs a JSON body, then decodes the response stream.\n * `consumeSseStream` is the lower-level decoder for callers that already\n * hold a fetch Response.\n *\n * The wire format handled is standard SSE:\n *\n * event: <name>\\n\n * data: <json>\\n\n * \\n\n *\n * with `: keepalive` comment lines during quiet periods. This layer is\n * transport-text only; JSON decoding of the data line is the caller's job.\n */\n\nexport interface SseFrame {\n event: string;\n data: string;\n}\n\n/** HTTP-level failure of a POST-initiated SSE request (non-2xx or no body). */\nexport class SseStreamError extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(message);\n this.name = \"SseStreamError\";\n }\n}\n\nconst
|
|
11
|
+
"content": "/**\n * Minimal Server-Sent Events transport over fetch.\n *\n * `postSse` covers endpoints that EventSource cannot serve (POST bodies,\n * custom headers): it POSTs a JSON body, then decodes the response stream.\n * `consumeSseStream` is the lower-level decoder for callers that already\n * hold a fetch Response.\n *\n * The wire format handled is standard SSE:\n *\n * event: <name>\\n\n * data: <json>\\n\n * \\n\n *\n * with `: keepalive` comment lines during quiet periods. This layer is\n * transport-text only; JSON decoding of the data line is the caller's job.\n */\n\nexport interface SseFrame {\n event: string;\n data: string;\n}\n\n/** HTTP-level failure of a POST-initiated SSE request (non-2xx or no body). */\nexport class SseStreamError extends Error {\n constructor(\n readonly status: number,\n message: string,\n ) {\n super(message);\n this.name = \"SseStreamError\";\n }\n}\n\nconst NEVER_ABORTED = new AbortController().signal;\n\nexport interface PostSseOptions {\n /** JSON-encoded request body; omit to POST without a body. */\n body?: unknown;\n /** Extra request headers (e.g. Authorization). Content-Type and Accept are set automatically. */\n headers?: Record<string, string>;\n /** Aborting stops reading immediately; already received frames are retained by the caller. */\n signal?: AbortSignal;\n /** Called for every decoded frame, in arrival order. */\n onFrame: (frame: SseFrame) => void;\n}\n\n/**\n * POST-initiated SSE request: the standard workaround for EventSource's\n * inability to send POST bodies or custom headers. Resolves after the server\n * closes the stream; rejects with SseStreamError on HTTP-level failures.\n * Stream errors during reading propagate from the underlying reader.\n */\nexport async function postSse(url: string, options: PostSseOptions): Promise<void> {\n const { body, headers, signal = NEVER_ABORTED, onFrame } = options;\n\n const response = await fetch(url, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Accept: \"text/event-stream\",\n ...headers,\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal,\n });\n\n if (!response.ok || !response.body) {\n const detail = await response.text().catch(() => \"\");\n throw new SseStreamError(\n response.status,\n `SSE request failed with ${response.status}${detail ? `: ${detail}` : \"\"}`,\n );\n }\n\n await consumeSseStream(response.body, signal, onFrame);\n}\n\n/**\n * Consume a fetch Response.body stream until the server closes it.\n *\n * Partial multibyte sequences and frames split across chunks are buffered, so\n * callers may invoke this directly on response.body without any framing\n * assumptions. Aborting `signal` stops reading immediately; the already\n * received frames are retained by the caller.\n */\nexport async function consumeSseStream(\n body: ReadableStream<Uint8Array>,\n signal: AbortSignal,\n onFrame: (frame: SseFrame) => void,\n): Promise<void> {\n const reader = body.getReader();\n // A decoder per call: `{ stream: true }` keeps an incomplete multibyte\n // sequence inside this instance, so a shared one would let concurrent\n // streams steal each other's bytes (R84-02).\n const decoder = new TextDecoder();\n let buffer = \"\";\n\n const onAbort = (): void => {\n reader.cancel(\"aborted\").catch(() => {});\n };\n if (signal.aborted) {\n onAbort();\n } else {\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n\n let separatorIndex: number;\n // SSE dispatches on a blank line; tolerate CRLF.\n while ((separatorIndex = findFrameBoundary(buffer)) !== -1) {\n const rawFrame = buffer.slice(0, separatorIndex);\n buffer = buffer.slice(separatorIndex).replace(/^(\\r?\\n){2}/, \"\");\n const frame = parseFrame(rawFrame);\n if (frame) onFrame(frame);\n }\n }\n\n // Flush any complete sequence still buffered in the decoder.\n buffer += decoder.decode();\n\n const tail = buffer.trim();\n if (tail) {\n const frame = parseFrame(tail);\n if (frame) onFrame(frame);\n }\n } finally {\n signal.removeEventListener(\"abort\", onAbort);\n try {\n reader.releaseLock();\n } catch {\n // A lock held by a racing cancel() releases on its own.\n }\n }\n}\n\n/** Normalize the two possible blank-line styles (\\n\\n and \\r\\n\\r\\n). */\nfunction findFrameBoundary(buffer: string): number {\n const lf = buffer.indexOf(\"\\n\\n\");\n const crlf = buffer.indexOf(\"\\r\\n\\r\\n\");\n if (lf === -1) return crlf;\n if (crlf === -1) return lf;\n return Math.min(lf, crlf);\n}\n\nfunction parseFrame(rawFrame: string): SseFrame | null {\n let event = \"message\";\n const dataLines: string[] = [];\n\n for (const rawLine of rawFrame.split(/\\r?\\n/)) {\n const line = rawLine.replace(/\\r$/, \"\");\n if (!line || line.startsWith(\":\")) continue; // comments / keepalive\n if (line.startsWith(\"event:\")) {\n event = line.slice(\"event:\".length).trim();\n } else if (line.startsWith(\"data:\")) {\n dataLines.push(line.slice(\"data:\".length).trimStart());\n }\n }\n\n if (dataLines.length === 0) return null;\n return { event, data: dataLines.join(\"\\n\") };\n}\n",
|
|
12
12
|
"type": "registry:lib"
|
|
13
13
|
}
|
|
14
14
|
]
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
},
|
|
17
17
|
{
|
|
18
18
|
"path": "src/components/theme-toggle.tsx",
|
|
19
|
-
"content": "\"use client\";\n\nimport { Moon, Sun } from \"lucide-react\";\nimport { useTheme } from \"next-themes\";\n\nimport { Button } from \"@/components/ui/button\";\n\nexport function ThemeToggle() {\n const { resolvedTheme, setTheme } = useTheme();\n\n return (\n <Button\n variant=\"outline\"\n size=\"icon\"\n aria-label
|
|
19
|
+
"content": "\"use client\";\n\nimport { Moon, Sun } from \"lucide-react\";\nimport { useTheme } from \"next-themes\";\n\nimport { Button } from \"@/components/ui/button\";\n\nexport interface ThemeToggleProps {\n /** Accessible name of the button; the host passes its translated copy. */\n label?: string;\n}\n\nexport function ThemeToggle({ label = \"Toggle theme\" }: ThemeToggleProps = {}) {\n const { resolvedTheme, setTheme } = useTheme();\n\n return (\n <Button\n variant=\"outline\"\n size=\"icon\"\n aria-label={label}\n onClick={() => setTheme(resolvedTheme === \"dark\" ? \"light\" : \"dark\")}\n >\n <Sun className=\"size-5 scale-100 rotate-0 transition-all dark:scale-0 dark:-rotate-90\" />\n <Moon className=\"absolute size-5 scale-0 rotate-90 transition-all dark:scale-100 dark:rotate-0\" />\n </Button>\n );\n}\n",
|
|
20
20
|
"type": "registry:component"
|
|
21
21
|
}
|
|
22
22
|
]
|