@blackbelt-technology/pi-dashboard-gmail-plugin 0.8.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.
@@ -0,0 +1,471 @@
1
+ /**
2
+ * Gmail settings section (design D7 wizard + accounts panel). Renders the
3
+ * 6-step Google Cloud setup wizard (deep links, copyable gcloud commands,
4
+ * client-JSON upload, sign-in error → step mapping) and the accounts panel
5
+ * (add / re-auth / level / alias / revoke, status badges, honest scope limit).
6
+ * Sign-in flows render through the host `ui:oauth-flow` primitive.
7
+ * See change: add-gmail-plugin.
8
+ */
9
+ import { oauthFlowClient, useT, useUiPrimitive } from "@blackbelt-technology/dashboard-plugin-runtime";
10
+ import type React from "react";
11
+ import { useCallback, useEffect, useRef, useState } from "react";
12
+ import { validateClientJson } from "../shared/client-json.js";
13
+ import type { AccountInfo } from "../shared/protocol.js";
14
+ import { TIERS, type Tier } from "../shared/scopes.js";
15
+ import { consoleLinks, errorStep, gcloudCommands, type WizardStep } from "./wizard.js";
16
+
17
+ const API = "/api/plugins/gmail";
18
+
19
+ interface GmailState {
20
+ client: { configured: boolean; clientId?: string; projectId?: string };
21
+ accounts: AccountInfo[];
22
+ }
23
+
24
+ type FlowState = React.ComponentProps<ReturnType<typeof useUiPrimitive<"ui:oauth-flow">>>["flow"];
25
+ type FlowStatus = NonNullable<FlowState["status"]>;
26
+
27
+ async function api<T>(path: string, init?: RequestInit): Promise<T> {
28
+ const res = await fetch(`${API}${path}`, {
29
+ ...init,
30
+ headers: init?.body ? { "content-type": "application/json" } : undefined,
31
+ });
32
+ const body = (await res.json().catch(() => ({}))) as T & { error?: string };
33
+ if (!res.ok) throw Object.assign(new Error(body.error ?? `HTTP ${res.status}`), { code: body.error });
34
+ return body;
35
+ }
36
+
37
+ const btn =
38
+ "rounded border border-[var(--border)] px-2 py-0.5 text-[12px] hover:bg-[var(--bg-hover)] disabled:opacity-50";
39
+ const muted = "text-[12px] text-[var(--text-muted)]";
40
+
41
+ /** Poll a flow every 500 ms until terminal. */
42
+ function useFlowPoll(flowId: string | undefined, onPending: (s: FlowStatus) => void, onDone: (err: string | null) => void) {
43
+ const pending = useRef(onPending);
44
+ const done = useRef(onDone);
45
+ pending.current = onPending;
46
+ done.current = onDone;
47
+ useEffect(() => {
48
+ if (!flowId) return;
49
+ let stopped = false;
50
+ const timer = setInterval(() => {
51
+ oauthFlowClient.status(flowId).then(
52
+ (s) => {
53
+ if (stopped) return;
54
+ if (s.status === "pending") pending.current(s);
55
+ else done.current(s.status === "complete" ? null : (s.error ?? s.status));
56
+ },
57
+ (err: unknown) => {
58
+ if (!stopped) done.current(err instanceof Error ? err.message : String(err));
59
+ },
60
+ );
61
+ }, 500);
62
+ return () => {
63
+ stopped = true;
64
+ clearInterval(timer);
65
+ };
66
+ }, [flowId]);
67
+ }
68
+
69
+ function Copyable({ value }: { value: string }) {
70
+ const t = useT();
71
+ return (
72
+ <div className="flex items-center gap-2">
73
+ <code className="flex-1 overflow-x-auto rounded bg-[var(--bg-subtle)] px-2 py-1 text-[12px]">{value}</code>
74
+ <button type="button" className={btn} onClick={() => void navigator.clipboard?.writeText(value)}>
75
+ {t("copy", undefined, "Copy")}
76
+ </button>
77
+ </div>
78
+ );
79
+ }
80
+
81
+ function StepLink({ href, label }: { href: string; label: string }) {
82
+ return (
83
+ <a href={href} target="_blank" rel="noopener noreferrer" className="text-[12px] text-[var(--accent)] underline">
84
+ {label}
85
+ </a>
86
+ );
87
+ }
88
+
89
+ export function SetupWizard({
90
+ state,
91
+ highlight,
92
+ onUploaded,
93
+ }: {
94
+ state: GmailState;
95
+ highlight: WizardStep | null;
96
+ onUploaded: () => void;
97
+ }) {
98
+ const t = useT();
99
+ const [projectId, setProjectId] = useState(state.client.projectId ?? "");
100
+ const [uploadError, setUploadError] = useState<{ code: string; step: WizardStep } | null>(null);
101
+ const links = consoleLinks(projectId.trim());
102
+ const [cmdCreate, cmdEnable] = gcloudCommands(projectId.trim());
103
+ const [focus, setFocus] = useState<WizardStep | null>(highlight);
104
+ useEffect(() => setFocus(highlight ?? uploadError?.step ?? null), [highlight, uploadError]);
105
+
106
+ const upload = async (file: File) => {
107
+ setUploadError(null);
108
+ const textContent = await file.text();
109
+ const local = validateClientJson(textContent);
110
+ if (!local.ok) {
111
+ setUploadError({ code: local.error.code, step: local.error.step });
112
+ return;
113
+ }
114
+ try {
115
+ await api("/client", { method: "PUT", body: JSON.stringify({ json: JSON.parse(textContent) }) });
116
+ if (local.client.projectId && !projectId) setProjectId(local.client.projectId);
117
+ onUploaded();
118
+ } catch (err) {
119
+ const code = (err as { code?: string }).code ?? "upload_failed";
120
+ setUploadError({ code, step: errorStep(code) ?? 5 });
121
+ }
122
+ };
123
+
124
+ const stepClass = (n: WizardStep) =>
125
+ `rounded border p-2 ${focus === n ? "border-[var(--warning)]" : "border-[var(--border)]"}`;
126
+ const uploadMsg: Record<string, string> = {
127
+ not_json: t("errNotJson", undefined, "That file is not valid JSON. Upload the client_secret_*.json you downloaded (step 5)."),
128
+ web_client: t("errWebClient", undefined, "This is a Web application client. Create a Desktop app client instead (step 4)."),
129
+ not_installed: t("errNotInstalled", undefined, "No Desktop (`installed`) client in this file. Create a Desktop app client (step 4)."),
130
+ bad_client_id: t("errBadClientId", undefined, "The client id does not end in .apps.googleusercontent.com (step 4)."),
131
+ client_in_use: t(
132
+ "errClientInUse",
133
+ undefined,
134
+ "Accounts are connected with the current client. Revoke them first, then upload a different client.",
135
+ ),
136
+ missing_secret: t("errMissingSecret", undefined, "The file has no client secret. Download it again from the client page (step 5)."),
137
+ };
138
+
139
+ return (
140
+ <ol className="flex flex-col gap-2" data-testid="gmail-wizard">
141
+ <li className={stepClass(1)} data-testid="gmail-step-1">
142
+ <div className="font-medium text-[13px]">{t("step1", undefined, "1. Google Cloud project + Gmail API")}</div>
143
+ <label className={`${muted} flex items-center gap-2`}>
144
+ {t("projectId", undefined, "Project id")}
145
+ <input
146
+ data-testid="gmail-project-id"
147
+ className="rounded border border-[var(--border)] bg-transparent px-1 text-[12px]"
148
+ value={projectId}
149
+ onChange={(e) => setProjectId(e.target.value)}
150
+ placeholder="my-gmail-agent"
151
+ />
152
+ </label>
153
+ <div className={muted}>{t("withoutGcloud", undefined, "Without gcloud:")}</div>
154
+ <div className="flex gap-3">
155
+ <StepLink href={links.projectCreate} label={t("createProject", undefined, "Create project")} />
156
+ <StepLink href={links.gmailApi} label={t("enableGmail", undefined, "Enable the Gmail API")} />
157
+ </div>
158
+ <div className={muted}>{t("withGcloud", undefined, "With gcloud (run it yourself):")}</div>
159
+ <Copyable value={cmdCreate as string} />
160
+ <Copyable value={cmdEnable as string} />
161
+ </li>
162
+ <li className={stepClass(2)} data-testid="gmail-step-2">
163
+ <div className="font-medium text-[13px]">{t("step2", undefined, "2. Branding")}</div>
164
+ <StepLink href={links.branding} label={t("openBranding", undefined, "Open Branding")} />
165
+ <div className={muted}>{t("fallback2", undefined, "If the link moved: APIs & Services → OAuth consent screen.")}</div>
166
+ </li>
167
+ <li className={stepClass(3)} data-testid="gmail-step-3">
168
+ <div className="font-medium text-[13px]">{t("step3", undefined, "3. Audience + test users")}</div>
169
+ <StepLink href={links.audience} label={t("openAudience", undefined, "Open Audience")} />
170
+ <div className={muted}>
171
+ {t(
172
+ "audienceHelp",
173
+ undefined,
174
+ "Workspace org: choose Internal. Otherwise External, and add every Gmail address you will connect as a test user. In Testing, tokens expire after 7 days; “Publish app” gives longer-lived tokens with an unverified-app warning.",
175
+ )}
176
+ </div>
177
+ </li>
178
+ <li className={stepClass(4)} data-testid="gmail-step-4">
179
+ <div className="font-medium text-[13px]">{t("step4", undefined, "4. Desktop OAuth client")}</div>
180
+ <StepLink href={links.clientCreate} label={t("openClients", undefined, "Create client")} />
181
+ <div className={muted}>
182
+ {t("clientHelp", undefined, "Application type: Desktop app. Download the JSON. If the link moved: APIs & Services → Credentials.")}
183
+ </div>
184
+ </li>
185
+ <li className={stepClass(5)} data-testid="gmail-step-5">
186
+ <div className="font-medium text-[13px]">{t("step5", undefined, "5. Upload client_secret_*.json")}</div>
187
+ <input
188
+ type="file"
189
+ accept="application/json,.json"
190
+ data-testid="gmail-client-upload"
191
+ aria-label={t("uploadLabel", undefined, "Upload the OAuth client JSON")}
192
+ onChange={(e) => {
193
+ const f = e.target.files?.[0];
194
+ if (f) void upload(f);
195
+ }}
196
+ />
197
+ {state.client.configured && (
198
+ <div className={muted} data-testid="gmail-client-ok">
199
+ ✓ {state.client.clientId}
200
+ </div>
201
+ )}
202
+ {uploadError && (
203
+ <div role="alert" className="text-[12px] text-[var(--error)]" data-testid="gmail-upload-error" data-step={uploadError.step}>
204
+ {uploadMsg[uploadError.code] ?? uploadError.code}
205
+ </div>
206
+ )}
207
+ </li>
208
+ <li className={stepClass(6)} data-testid="gmail-step-6">
209
+ <div className="font-medium text-[13px]">{t("step6", undefined, "6. Test sign-in")}</div>
210
+ <div className={muted}>{t("step6Help", undefined, "Add your first account below — that is the test sign-in.")}</div>
211
+ </li>
212
+ </ol>
213
+ );
214
+ }
215
+
216
+ const TIER_LABEL: Record<Tier, string> = { readonly: "readonly", draft: "draft", send: "send" };
217
+
218
+ function AccountRow({
219
+ acct,
220
+ onChanged,
221
+ onFlow,
222
+ onRevoked,
223
+ }: {
224
+ acct: AccountInfo;
225
+ onChanged: () => void;
226
+ onFlow: (flowId: string) => void;
227
+ onRevoked: (email: string, remoteRevoked: boolean) => void;
228
+ }) {
229
+ const t = useT();
230
+ const [alias, setAlias] = useState(acct.alias ?? "");
231
+ const [msg, setMsg] = useState<string | null>(null);
232
+ const run = async (fn: () => Promise<void>) => {
233
+ setMsg(null);
234
+ try {
235
+ await fn();
236
+ } catch (err) {
237
+ setMsg((err as { code?: string }).code ?? (err as Error).message);
238
+ }
239
+ };
240
+ const setLevel = (tier: Tier) =>
241
+ run(async () => {
242
+ const r = await api<{ applied?: boolean; flowId?: string }>(`/accounts/${encodeURIComponent(acct.sub)}/level`, {
243
+ method: "POST",
244
+ body: JSON.stringify({ tier }),
245
+ });
246
+ if (r.flowId) onFlow(r.flowId);
247
+ else onChanged();
248
+ });
249
+ return (
250
+ <li className="flex flex-wrap items-center gap-2 rounded border border-[var(--border)] p-2" data-testid="gmail-account-row" data-email={acct.email}>
251
+ <span className="font-medium text-[13px]" data-testid="gmail-account-email">
252
+ {acct.email}
253
+ </span>
254
+ {acct.status === "ok" ? (
255
+ <span className="rounded bg-[var(--success-bg)] px-1 text-[11px]" data-testid="gmail-account-status" data-status="ok">
256
+ {t("statusOk", undefined, "ok")}
257
+ </span>
258
+ ) : (
259
+ <span className="rounded bg-[var(--warning-bg)] px-1 text-[11px]" data-testid="gmail-account-status" data-status="reauth_required">
260
+ {t("statusReauth", undefined, "re-auth needed")}
261
+ </span>
262
+ )}
263
+ {acct.testingHint && (
264
+ <span className={muted} title={t("testingHint", undefined, "Testing-mode app: Google expires this grant after 7 days.")}>
265
+ {t("testingBadge", undefined, "testing: 7-day")}
266
+ </span>
267
+ )}
268
+ <label className={muted}>
269
+ {t("level", undefined, "Level")}{" "}
270
+ <select
271
+ data-testid="gmail-account-level"
272
+ value={acct.tier}
273
+ onChange={(e) => void setLevel(e.target.value as Tier)}
274
+ className="rounded border border-[var(--border)] bg-transparent text-[12px]"
275
+ >
276
+ {TIERS.map((tier) => (
277
+ <option key={tier} value={tier}>
278
+ {TIER_LABEL[tier]}
279
+ </option>
280
+ ))}
281
+ </select>
282
+ </label>
283
+ <input
284
+ aria-label={t("aliasLabel", undefined, "Alias")}
285
+ data-testid="gmail-account-alias"
286
+ className="w-24 rounded border border-[var(--border)] bg-transparent px-1 text-[12px]"
287
+ value={alias}
288
+ placeholder={t("aliasPlaceholder", undefined, "alias")}
289
+ onChange={(e) => setAlias(e.target.value)}
290
+ onBlur={() =>
291
+ alias !== (acct.alias ?? "") &&
292
+ void run(async () => {
293
+ await api(`/accounts/${encodeURIComponent(acct.sub)}`, { method: "PATCH", body: JSON.stringify({ alias: alias || null }) });
294
+ onChanged();
295
+ })
296
+ }
297
+ />
298
+ <button type="button" className={btn} data-testid="gmail-account-reauth" onClick={() =>
299
+ void run(async () => {
300
+ // Force a fresh consent at the current level (status reset on persist).
301
+ const r = await api<{ flowId?: string }>(`/accounts/${encodeURIComponent(acct.sub)}/reauth`, { method: "POST" });
302
+ if (r.flowId) onFlow(r.flowId);
303
+ })
304
+ }>
305
+ {t("reauth", undefined, "Re-authenticate")}
306
+ </button>
307
+ <button
308
+ type="button"
309
+ className={btn}
310
+ data-testid="gmail-account-revoke"
311
+ onClick={() =>
312
+ void run(async () => {
313
+ const r = await api<{ remoteRevoked: boolean }>(`/accounts/${encodeURIComponent(acct.sub)}`, { method: "DELETE" });
314
+ onRevoked(acct.email, r.remoteRevoked);
315
+ onChanged();
316
+ })
317
+ }
318
+ >
319
+ {t("revoke", undefined, "Revoke")}
320
+ </button>
321
+ {msg && (
322
+ <span role="alert" className="text-[12px] text-[var(--error)]">
323
+ {msg}
324
+ </span>
325
+ )}
326
+ </li>
327
+ );
328
+ }
329
+
330
+ export function GmailSettings() {
331
+ const t = useT();
332
+ const OAuthFlow = useUiPrimitive("ui:oauth-flow");
333
+ const [state, setState] = useState<GmailState | null>(null);
334
+ const [loadError, setLoadError] = useState<string | null>(null);
335
+ const [flow, setFlow] = useState<FlowState | null>(null);
336
+ const [flowError, setFlowError] = useState<string | null>(null);
337
+ const [lastRevoke, setLastRevoke] = useState<string | null>(null);
338
+ const [newTier, setNewTier] = useState<Tier>("readonly");
339
+
340
+ const refresh = useCallback(async () => {
341
+ try {
342
+ setState(await api<GmailState>("/state"));
343
+ setLoadError(null);
344
+ } catch (err) {
345
+ setLoadError((err as Error).message);
346
+ }
347
+ }, []);
348
+ useEffect(() => {
349
+ void refresh();
350
+ }, [refresh]);
351
+
352
+ const startFlow = async (flowId: string) => {
353
+ setFlowError(null);
354
+ try {
355
+ setFlow({ phase: "waiting", status: await oauthFlowClient.status(flowId) });
356
+ } catch (err) {
357
+ setFlow(null);
358
+ setFlowError(err instanceof Error ? err.message : String(err));
359
+ }
360
+ };
361
+ useFlowPoll(
362
+ flow?.status?.flowId,
363
+ (status) => setFlow({ phase: "waiting", status }),
364
+ (err) => {
365
+ setFlow(null);
366
+ setFlowError(err);
367
+ void refresh();
368
+ },
369
+ );
370
+
371
+ const addAccount = async () => {
372
+ setFlowError(null);
373
+ setFlow({ phase: "starting" });
374
+ try {
375
+ const r = await api<{ flowId: string }>("/accounts", { method: "POST", body: JSON.stringify({ tier: newTier }) });
376
+ await startFlow(r.flowId);
377
+ } catch (err) {
378
+ setFlow(null);
379
+ setFlowError((err as { code?: string }).code ?? (err as Error).message);
380
+ }
381
+ };
382
+
383
+ if (loadError) return <div role="alert" className="text-[12px] text-[var(--error)]">{loadError}</div>;
384
+ if (!state) return <div className={muted}>{t("loading", undefined, "Loading…")}</div>;
385
+
386
+ const step = errorStep(flowError);
387
+ return (
388
+ <section className="flex flex-col gap-3" data-testid="gmail-settings" aria-labelledby="gmail-settings-title">
389
+ <h3 id="gmail-settings-title" className="font-semibold text-[14px]">
390
+ {t("title", undefined, "Gmail")}
391
+ </h3>
392
+ <details open={!state.client.configured || state.accounts.length === 0 || step !== null}>
393
+ <summary className="cursor-pointer text-[13px]">{t("setup", undefined, "Google Cloud setup")}</summary>
394
+ <SetupWizard state={state} highlight={step} onUploaded={() => void refresh()} />
395
+ </details>
396
+
397
+ <div className="flex flex-col gap-2" data-testid="gmail-accounts">
398
+ <div className="font-medium text-[13px]">{t("accounts", undefined, "Accounts")}</div>
399
+ <p className={muted} data-testid="gmail-level-help">
400
+ {t(
401
+ "levelHelp",
402
+ undefined,
403
+ "Levels: readonly = read; draft = + drafts; send = + send, reply, labels, archive, trash. Levels are enforced by this plugin, not by Google: a token carries every scope Google granted (draft-level compose access could technically send), so a level controls what the agent's tools may do. Any session on this dashboard can use every account within its level.",
404
+ )}
405
+ </p>
406
+ {state.accounts.length === 0 && <div className={muted}>{t("noAccounts", undefined, "No accounts connected.")}</div>}
407
+ <ul className="flex flex-col gap-2">
408
+ {state.accounts.map((a) => (
409
+ <AccountRow
410
+ key={a.sub}
411
+ acct={a}
412
+ onChanged={() => void refresh()}
413
+ onFlow={(id) => void startFlow(id)}
414
+ onRevoked={(email, remote) =>
415
+ setLastRevoke(
416
+ remote
417
+ ? t("revokedOk", { email }, `${email} removed and access revoked at Google.`)
418
+ : t(
419
+ "revokeManual",
420
+ { email },
421
+ `${email} removed locally, but Google could not be reached. Revoke access at myaccount.google.com/permissions.`,
422
+ ),
423
+ )
424
+ }
425
+ />
426
+ ))}
427
+ </ul>
428
+ {flow ? (
429
+ <OAuthFlow
430
+ flow={flow}
431
+ onSendInput={(id, value) => oauthFlowClient.input(id, value)}
432
+ onCancel={(id) => {
433
+ void oauthFlowClient.cancel(id);
434
+ }}
435
+ />
436
+ ) : (
437
+ <div className="flex items-center gap-2">
438
+ <select
439
+ aria-label={t("newLevel", undefined, "Level for the new account")}
440
+ data-testid="gmail-new-level"
441
+ value={newTier}
442
+ onChange={(e) => setNewTier(e.target.value as Tier)}
443
+ className="rounded border border-[var(--border)] bg-transparent text-[12px]"
444
+ >
445
+ {TIERS.map((tier) => (
446
+ <option key={tier} value={tier}>
447
+ {TIER_LABEL[tier]}
448
+ </option>
449
+ ))}
450
+ </select>
451
+ <button type="button" className={btn} data-testid="gmail-add-account" disabled={!state.client.configured} onClick={() => void addAccount()}>
452
+ {t("addAccount", undefined, "Add account")}
453
+ </button>
454
+ </div>
455
+ )}
456
+ {flowError && (
457
+ <div role="alert" className="text-[12px] text-[var(--error)]" data-testid="gmail-flow-error" data-step={step ?? ""}>
458
+ {step
459
+ ? t("flowErrorStep", { error: flowError, step }, `Sign-in failed (${flowError}). Fix wizard step ${step}.`)
460
+ : t("flowError", { error: flowError }, `Sign-in failed: ${flowError}`)}
461
+ </div>
462
+ )}
463
+ {lastRevoke && (
464
+ <div role="status" className={muted} data-testid="gmail-revoke-result">
465
+ {lastRevoke}
466
+ </div>
467
+ )}
468
+ </div>
469
+ </section>
470
+ );
471
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Client barrel. `GmailSettings` is a thin wrapper owning its own `Suspense`
3
+ * around a `lazy()` import, so the wizard + panel code stays OFF the cold
4
+ * landing entry chunk (mdi-chunk-size cap) and loads only when the Gmail
5
+ * settings page renders. The i18n catalog stays eager (tiny, merged at boot).
6
+ * See change: add-gmail-plugin.
7
+ */
8
+ import { lazy, Suspense } from "react";
9
+
10
+ export { catalog } from "../i18n.js";
11
+
12
+ const GmailSettingsImpl = lazy(() => import("./GmailSettings.js").then((m) => ({ default: m.GmailSettings })));
13
+
14
+ export function GmailSettings() {
15
+ return (
16
+ <Suspense fallback={null}>
17
+ <GmailSettingsImpl />
18
+ </Suspense>
19
+ );
20
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Setup-wizard data (design D7): console deep links, copyable gcloud commands
3
+ * and the sign-in-error → wizard-step map. Pure — the server never executes
4
+ * the commands. See change: add-gmail-plugin.
5
+ */
6
+
7
+ export type WizardStep = 1 | 2 | 3 | 4 | 5 | 6;
8
+
9
+ const CONSOLE = "https://console.cloud.google.com";
10
+
11
+ export interface ConsoleLinks {
12
+ projectCreate: string;
13
+ gmailApi: string;
14
+ branding: string;
15
+ audience: string;
16
+ clientCreate: string;
17
+ }
18
+
19
+ /** Deep links carrying `?project=<id>` (encoded). */
20
+ export function consoleLinks(projectId: string): ConsoleLinks {
21
+ const q = projectId ? `?project=${encodeURIComponent(projectId)}` : "";
22
+ return {
23
+ projectCreate: `${CONSOLE}/projectcreate`,
24
+ gmailApi: `${CONSOLE}/apis/library/gmail.googleapis.com${q}`,
25
+ branding: `${CONSOLE}/auth/branding${q}`,
26
+ audience: `${CONSOLE}/auth/audience${q}`,
27
+ clientCreate: `${CONSOLE}/auth/clients/create${q}`,
28
+ };
29
+ }
30
+
31
+ const PROJECT_ID_RE = /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/;
32
+
33
+ function isValidProjectId(id: string): boolean {
34
+ return PROJECT_ID_RE.test(id);
35
+ }
36
+
37
+ /** Copyable gcloud commands (only for a syntactically valid project id). */
38
+ export function gcloudCommands(projectId: string): string[] {
39
+ const id = isValidProjectId(projectId) ? projectId : "<project-id>";
40
+ return [`gcloud projects create ${id}`, `gcloud services enable gmail.googleapis.com --project ${id}`];
41
+ }
42
+
43
+ /** Map a sign-in / upload error code to the wizard step that fixes it. */
44
+ export function errorStep(code: string | undefined | null): WizardStep | null {
45
+ switch (code) {
46
+ case "access_denied":
47
+ case "org_internal":
48
+ return 3;
49
+ case "redirect_uri_mismatch":
50
+ case "web_client":
51
+ case "not_installed":
52
+ case "bad_client_id":
53
+ return 4;
54
+ case "invalid_client":
55
+ case "missing_secret":
56
+ case "not_json":
57
+ case "no_client":
58
+ case "client_in_use":
59
+ return 5;
60
+ default:
61
+ return null;
62
+ }
63
+ }
@@ -0,0 +1 @@
1
+ {"type":"object","properties":{},"additionalProperties":false}
package/src/i18n.ts ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Gmail plugin i18n catalog — UNPREFIXED leaf keys, merged by the shell under
3
+ * `plugin.gmail.*`; components resolve via the scoped `useT()`. English lives
4
+ * at the call sites as the fallback. `zh-CN` and `hu` MUST keep identical key
5
+ * sets (scripts/i18n-parity). See change: add-gmail-plugin.
6
+ */
7
+ export const catalog = {
8
+ "zh-CN": {
9
+ accounts: "账户",
10
+ addAccount: "添加账户",
11
+ aliasLabel: "别名",
12
+ aliasPlaceholder: "别名",
13
+ audienceHelp:
14
+ "Workspace 组织:选择“内部”。否则选择“外部”,并将要连接的每个 Gmail 地址添加为测试用户。测试模式下令牌 7 天后过期;“发布应用”可获得更长期的令牌,但会显示未验证应用警告。",
15
+ clientHelp: "应用类型:桌面应用。下载 JSON。若链接已变更:API 和服务 → 凭据。",
16
+ copy: "复制",
17
+ createProject: "创建项目",
18
+ enableGmail: "启用 Gmail API",
19
+ errBadClientId: "客户端 ID 不以 .apps.googleusercontent.com 结尾(第 4 步)。",
20
+ errClientInUse: "当前客户端下已连接账户。请先撤销它们,再上传其他客户端。",
21
+ errMissingSecret: "文件中没有客户端密钥。请从客户端页面重新下载(第 5 步)。",
22
+ errNotInstalled: "此文件中没有桌面(installed)客户端。请创建桌面应用客户端(第 4 步)。",
23
+ errNotJson: "该文件不是有效的 JSON。请上传你下载的 client_secret_*.json(第 5 步)。",
24
+ errWebClient: "这是 Web 应用客户端。请改为创建桌面应用客户端(第 4 步)。",
25
+ fallback2: "若链接已变更:API 和服务 → OAuth 同意屏幕。",
26
+ flowError: "登录失败:{error}",
27
+ flowErrorStep: "登录失败({error})。请修正向导第 {step} 步。",
28
+ level: "级别",
29
+ levelHelp:
30
+ "级别:readonly = 读取;draft = + 草稿;send = + 发送、回复、标签、归档、删除。级别由本插件执行,而非 Google:令牌带有 Google 授予的全部范围(draft 级的撰写权限理论上也能发送),因此级别控制的是代理工具可以做什么。此仪表盘上的任何会话都可以在级别范围内使用每个账户。",
31
+ loading: "加载中…",
32
+ newLevel: "新账户的级别",
33
+ noAccounts: "尚未连接账户。",
34
+ openAudience: "打开“目标对象”",
35
+ openBranding: "打开“品牌”",
36
+ openClients: "创建客户端",
37
+ projectId: "项目 ID",
38
+ reauth: "重新验证",
39
+ revoke: "撤销",
40
+ revokedOk: "{email} 已移除,并已在 Google 撤销访问权限。",
41
+ revokeManual: "{email} 已在本地移除,但无法连接 Google。请在 myaccount.google.com/permissions 撤销访问权限。",
42
+ setup: "Google Cloud 设置",
43
+ statusOk: "正常",
44
+ statusReauth: "需要重新验证",
45
+ step1: "1. Google Cloud 项目 + Gmail API",
46
+ step2: "2. 品牌",
47
+ step3: "3. 目标对象 + 测试用户",
48
+ step4: "4. 桌面 OAuth 客户端",
49
+ step5: "5. 上传 client_secret_*.json",
50
+ step6: "6. 测试登录",
51
+ step6Help: "在下方添加第一个账户 —— 这就是测试登录。",
52
+ testingBadge: "测试:7 天",
53
+ testingHint: "测试模式应用:Google 会在 7 天后使此授权过期。",
54
+ title: "Gmail",
55
+ uploadLabel: "上传 OAuth 客户端 JSON",
56
+ withGcloud: "使用 gcloud(请自行运行):",
57
+ withoutGcloud: "不使用 gcloud:",
58
+ },
59
+ hu: {
60
+ accounts: "Fiókok",
61
+ addAccount: "Fiók hozzáadása",
62
+ aliasLabel: "Álnév",
63
+ aliasPlaceholder: "álnév",
64
+ audienceHelp:
65
+ "Workspace-szervezet: válaszd a Belső lehetőséget. Egyébként Külső, és vedd fel tesztfelhasználóként minden csatlakoztatandó Gmail-címet. Tesztelés módban a tokenek 7 nap után lejárnak; az „Alkalmazás közzététele” hosszabb életű tokeneket ad, nem ellenőrzött alkalmazás figyelmeztetéssel.",
66
+ clientHelp: "Alkalmazástípus: Asztali alkalmazás. Töltsd le a JSON-t. Ha a link elköltözött: API-k és szolgáltatások → Hitelesítő adatok.",
67
+ copy: "Másolás",
68
+ createProject: "Projekt létrehozása",
69
+ enableGmail: "Gmail API engedélyezése",
70
+ errBadClientId: "Az ügyfél-azonosító nem .apps.googleusercontent.com végződésű (4. lépés).",
71
+ errClientInUse: "A jelenlegi ügyféllel fiókok vannak csatlakoztatva. Előbb vond vissza őket, majd tölts fel másik ügyfelet.",
72
+ errMissingSecret: "A fájlban nincs ügyféltitok. Töltsd le újra az ügyfél oldaláról (5. lépés).",
73
+ errNotInstalled: "A fájlban nincs asztali (installed) ügyfél. Hozz létre asztali alkalmazás ügyfelet (4. lépés).",
74
+ errNotJson: "A fájl nem érvényes JSON. Töltsd fel a letöltött client_secret_*.json fájlt (5. lépés).",
75
+ errWebClient: "Ez webalkalmazás-ügyfél. Hozz létre helyette asztali alkalmazás ügyfelet (4. lépés).",
76
+ fallback2: "Ha a link elköltözött: API-k és szolgáltatások → OAuth-hozzájárulási képernyő.",
77
+ flowError: "A bejelentkezés sikertelen: {error}",
78
+ flowErrorStep: "A bejelentkezés sikertelen ({error}). Javítsd a varázsló {step}. lépését.",
79
+ level: "Szint",
80
+ levelHelp:
81
+ "Szintek: readonly = olvasás; draft = + piszkozatok; send = + küldés, válasz, címkék, archiválás, kuka. A szinteket ez a bővítmény érvényesíti, nem a Google: a token a Google által megadott összes hatókört hordozza (a draft szintű írási jog technikailag küldhetne is), így a szint azt szabályozza, mit tehetnek az ügynök eszközei. A dashboard bármely munkamenete használhat minden fiókot a saját szintjén belül.",
82
+ loading: "Betöltés…",
83
+ newLevel: "Az új fiók szintje",
84
+ noAccounts: "Nincs csatlakoztatott fiók.",
85
+ openAudience: "Célközönség megnyitása",
86
+ openBranding: "Arculat megnyitása",
87
+ openClients: "Ügyfél létrehozása",
88
+ projectId: "Projektazonosító",
89
+ reauth: "Újrahitelesítés",
90
+ revoke: "Visszavonás",
91
+ revokedOk: "{email} eltávolítva, a hozzáférés a Google-nál visszavonva.",
92
+ revokeManual:
93
+ "{email} helyben eltávolítva, de a Google nem volt elérhető. Vond vissza a hozzáférést a myaccount.google.com/permissions oldalon.",
94
+ setup: "Google Cloud beállítás",
95
+ statusOk: "rendben",
96
+ statusReauth: "újrahitelesítés szükséges",
97
+ step1: "1. Google Cloud projekt + Gmail API",
98
+ step2: "2. Arculat",
99
+ step3: "3. Célközönség + tesztfelhasználók",
100
+ step4: "4. Asztali OAuth-ügyfél",
101
+ step5: "5. client_secret_*.json feltöltése",
102
+ step6: "6. Próba-bejelentkezés",
103
+ step6Help: "Add hozzá lent az első fiókot — ez a próba-bejelentkezés.",
104
+ testingBadge: "teszt: 7 nap",
105
+ testingHint: "Tesztelés módú alkalmazás: a Google 7 nap után lejártatja ezt a hozzáférést.",
106
+ title: "Gmail",
107
+ uploadLabel: "OAuth-ügyfél JSON feltöltése",
108
+ withGcloud: "gcloud-dal (futtasd magad):",
109
+ withoutGcloud: "gcloud nélkül:",
110
+ },
111
+ };