@sirenodeck/sirenodeck 0.2.10 → 0.4.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.
Files changed (59) hide show
  1. package/dist/main.mjs +1089 -626
  2. package/dist/{windows-CRWdUgCn.mjs → windows-BCvfQ3PA.mjs} +4 -4
  3. package/frontend/src/App.tsx +3 -0
  4. package/frontend/src/components/Deck.tsx +13 -2
  5. package/package.json +10 -1
  6. package/src/addon/api.ts +24 -1
  7. package/src/addon/data-directory.ts +52 -0
  8. package/src/api/protocol-internal.ts +1 -0
  9. package/src/builtin-addons/index.ts +0 -1
  10. package/src/builtin-addons/internal-settings/backend.ts +1 -1
  11. package/src/builtin-addons/internal-settings/buttons/brightness/common/frontend.tsx +14 -3
  12. package/src/builtin-addons/internal-settings/buttons/brightness-compact/frontend.tsx +6 -0
  13. package/src/builtin-addons/internal-settings/index.ts +15 -0
  14. package/src/builtin-addons/register-builtins.ts +0 -3
  15. package/src/cli/commands/addon-decks.ts +1 -0
  16. package/src/cli/commands/addon-setup-config.ts +85 -0
  17. package/src/cli/commands/addon-setup.ts +134 -0
  18. package/src/cli/commands/run.ts +53 -11
  19. package/src/cli/commands/service-manager.ts +3 -5
  20. package/src/cli/commands/start.ts +14 -81
  21. package/src/cli/commands/stop.ts +4 -0
  22. package/src/cli/index.ts +2 -0
  23. package/src/config/environment.ts +44 -0
  24. package/src/config/loader.ts +17 -1
  25. package/src/config/schemas.ts +2 -1
  26. package/src/config/validation.ts +5 -1
  27. package/src/deck/addon-handler-bridge.ts +105 -6
  28. package/src/deck/addon-settings.ts +94 -0
  29. package/src/deck/deck-config.ts +1 -0
  30. package/src/deck/inject-config-ui-button.ts +25 -14
  31. package/src/deck/runtime/runtime.ts +175 -3
  32. package/src/deck/system-back-injection.ts +2 -0
  33. package/src/deck/system-buttons/registry.tsx +1 -0
  34. package/src/deck/system-buttons/types.ts +1 -0
  35. package/src/system/credentials/native.ts +74 -0
  36. package/src/system/credentials/store.ts +77 -0
  37. package/src/system/providers/notification/windows.ts +4 -4
  38. package/src/themes/default/sirenodeck.json +1 -0
  39. package/src/themes/light/sirenodeck.json +1 -0
  40. package/src/themes/manifest.ts +1 -0
  41. package/src/ui/primitives/Chip.tsx +1 -0
  42. package/src/ui/primitives/StatusIndicator.tsx +36 -0
  43. package/src/ui/primitives/index.ts +1 -0
  44. package/src/ui/surfaces/BinaryToggleSurface.tsx +52 -0
  45. package/src/ui/surfaces/LoadingSurface.tsx +34 -0
  46. package/src/ui/surfaces/index.ts +2 -0
  47. package/src/builtin-addons/brightness/README.md +0 -51
  48. package/src/builtin-addons/brightness/buttons/brightness/backend.ts +0 -13
  49. package/src/builtin-addons/brightness/buttons/brightness/config.ts +0 -20
  50. package/src/builtin-addons/brightness/buttons/brightness/frontend.tsx +0 -50
  51. package/src/builtin-addons/brightness/domain/macos.ts +0 -46
  52. package/src/builtin-addons/brightness/index.d.ts +0 -5
  53. package/src/builtin-addons/brightness/index.ts +0 -20
  54. package/src/builtin-addons/brightness/poller.ts +0 -27
  55. package/src/builtin-addons/brightness/sirenodeck.json +0 -6
  56. /package/src/builtin-addons/{brightness/providers → internal-settings/brightness-providers}/darwin.ts +0 -0
  57. /package/src/builtin-addons/{brightness/providers → internal-settings/brightness-providers}/index.ts +0 -0
  58. /package/src/builtin-addons/{brightness/providers → internal-settings/brightness-providers}/linux.ts +0 -0
  59. /package/src/builtin-addons/{brightness/providers → internal-settings/brightness-providers}/windows.ts +0 -0
@@ -3,14 +3,14 @@ import { a as withTimeout } from "./main.mjs";
3
3
  const DEFAULT_TIMEOUT_MS = 5e3;
4
4
  const shellQuote = (value) => `'${value.replace(/'/g, "''").replace(/'/g, "'\\''")}'`;
5
5
  const buildToastScript = (title, body) => {
6
- const safeTitle = title.replace(/[`$"\\]/g, "\\$&");
7
- const safeBody = body.replace(/[`$"\\]/g, "\\$&");
6
+ const safeTitle = Buffer.from(title, "utf8").toString("base64");
7
+ const safeBody = Buffer.from(body, "utf8").toString("base64");
8
8
  return [
9
9
  "Add-Type -AssemblyName System.Windows.Forms | Out-Null",
10
10
  `$balloon = New-Object System.Windows.Forms.NotifyIcon`,
11
11
  `$balloon.Icon = [System.Drawing.SystemIcons]::Information`,
12
- `$balloon.BalloonTipTitle = "${safeTitle}"`,
13
- `$balloon.BalloonTipText = "${safeBody}"`,
12
+ `$balloon.BalloonTipTitle = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${safeTitle}'))`,
13
+ `$balloon.BalloonTipText = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${safeBody}'))`,
14
14
  `$balloon.Visible = $true`,
15
15
  `$balloon.ShowBalloonTip(5000)`,
16
16
  "Start-Sleep -Milliseconds 5500",
@@ -55,6 +55,7 @@ interface DeckState {
55
55
  id: string
56
56
  name: string
57
57
  buttons: DeckButton[]
58
+ isModal?: boolean
58
59
  isCompact?: boolean
59
60
  hasOverlayDeckAvailable?: boolean
60
61
  overlayDeckIcon?: string | null
@@ -379,6 +380,7 @@ const AppContent = () => {
379
380
  | "amber"
380
381
  | "lime"
381
382
  variant?: string
383
+ isModal?: boolean
382
384
  buttonErrors?: ButtonErrorState[]
383
385
  }
384
386
  >
@@ -391,6 +393,7 @@ const AppContent = () => {
391
393
  id: message.deckId,
392
394
  name: surface.name ?? message.deckId,
393
395
  buttons: surface.buttons,
396
+ isModal: surface.isModal === true,
394
397
  ...(surface.buttonColor !== undefined
395
398
  ? { buttonColor: surface.buttonColor }
396
399
  : {}),
@@ -45,6 +45,9 @@ import { ErrorBoundary } from "./ErrorBoundary"
45
45
  ;(
46
46
  globalThis as { __codingAgentsUseAddonChannel?: typeof useAddonChannel }
47
47
  ).__codingAgentsUseAddonChannel = useAddonChannel
48
+ ;(
49
+ globalThis as { __calendarUseAddonChannel?: typeof useAddonChannel }
50
+ ).__calendarUseAddonChannel = useAddonChannel
48
51
 
49
52
  const BUTTON_SIZE = BUTTON_SIZE_PX
50
53
  export interface DeckButton {
@@ -63,6 +66,7 @@ export interface Deck {
63
66
  id: string
64
67
  name: string
65
68
  buttons: DeckButton[]
69
+ isModal?: boolean
66
70
  buttonColor?:
67
71
  | "blue"
68
72
  | "green"
@@ -381,7 +385,8 @@ export const Deck = ({
381
385
  const width = columns * BUTTON_SIZE + (columns - 1) * resolvedGap + pad * 2
382
386
  const height = rows * BUTTON_SIZE + (rows - 1) * resolvedGap + pad * 2
383
387
  const n1Position = model.keyCount - 1
384
- const splitAtN1 = deck.hasOverlayDeckAvailable === true
388
+ const splitAtN1 =
389
+ deck.hasOverlayDeckAvailable === true && deck.isModal !== true
385
390
  const errorPositions = new Set(
386
391
  (deck.buttonErrors ?? []).map((error) => error.position),
387
392
  )
@@ -413,7 +418,7 @@ export const Deck = ({
413
418
  .filter((p) => p < model.keyCount),
414
419
  )
415
420
  const emptyCells: ReactNode[] = []
416
- if (!compact) {
421
+ if (!compact && deck.isModal !== true) {
417
422
  for (let position = 0; position < model.keyCount; position += 1) {
418
423
  if (occupiedPositions.has(position)) continue
419
424
  const col = (position % columns) + 1
@@ -446,6 +451,12 @@ export const Deck = ({
446
451
  gap: `${resolvedGap}px`,
447
452
  width,
448
453
  height,
454
+ ...(deck.isModal
455
+ ? {
456
+ backgroundColor:
457
+ "var(--sireno-color-modal-deck-bgr, var(--sireno-variant-default-bg))",
458
+ }
459
+ : {}),
449
460
  } as CSSProperties
450
461
  }
451
462
  data-deck-id={deck.id}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sirenodeck/sirenodeck",
3
- "version": "0.2.10",
3
+ "version": "0.4.0",
4
4
  "description": "CLI for managing Elgato Stream Deck devices via a config-driven deck system.",
5
5
  "homepage": "https://deck.sireno.dev",
6
6
  "bugs": {
@@ -69,6 +69,14 @@
69
69
  "types": "./src/ui/surfaces/IconLabelSurface.tsx",
70
70
  "default": "./src/ui/surfaces/IconLabelSurface.tsx"
71
71
  },
72
+ "./ui/surfaces/BinaryToggleSurface": {
73
+ "types": "./src/ui/surfaces/BinaryToggleSurface.tsx",
74
+ "default": "./src/ui/surfaces/BinaryToggleSurface.tsx"
75
+ },
76
+ "./ui/surfaces/LoadingSurface": {
77
+ "types": "./src/ui/surfaces/LoadingSurface.tsx",
78
+ "default": "./src/ui/surfaces/LoadingSurface.tsx"
79
+ },
72
80
  "./ui/surfaces/IconLabelProgressSurface": {
73
81
  "types": "./src/ui/surfaces/IconLabelProgressSurface.tsx",
74
82
  "default": "./src/ui/surfaces/IconLabelProgressSurface.tsx"
@@ -108,6 +116,7 @@
108
116
  "@heroui/styles": "3.2.6",
109
117
  "@internationalized/date": "^3.12.4",
110
118
  "@meteocons/svg-static": "^0.1.0",
119
+ "@napi-rs/keyring": "2.1.2",
111
120
  "@react-aria/ssr": "^3.10.1",
112
121
  "@react-aria/utils": "^3.34.1",
113
122
  "@tailwindcss/vite": "^4.0.0",
package/src/addon/api.ts CHANGED
@@ -8,6 +8,7 @@ import type { GestureKind } from "@/core/gesture-state"
8
8
 
9
9
  export type { GestureKind }
10
10
  import type { Methods } from "@/deck/methods"
11
+ import type { AddonCredentials } from "@/system/credentials/store"
11
12
 
12
13
  /** The runtime manifest API version (`AddonManifestV1`). */
13
14
  export const SIRENO_ADDON_API_VERSION = 1 as const
@@ -269,6 +270,12 @@ export interface AddonManifestV1 {
269
270
  readonly kind?: AddonKind
270
271
  readonly buttonTypes: Readonly<Record<string, AddonButtonTypeDefAny>>
271
272
  readonly defaultButton?: string
273
+ /** Entry shown in the global Settings deck for this loaded addon. */
274
+ readonly settings?: {
275
+ readonly label: string
276
+ readonly icon: string
277
+ readonly deck: string
278
+ }
272
279
  readonly decks?: ReadonlyArray<AddonDeckEntry>
273
280
  readonly frontend?: AddonFrontend
274
281
  readonly poller?: {
@@ -310,7 +317,8 @@ export interface AddonGlobalService {
310
317
  // onLoad/onUnload accept an optional addon-specific config (typed as
311
318
  // `unknown` since the runtime doesn't know the addon's config shape).
312
319
  // Built-in addons ignore it; third-party / builtin addons that need
313
- // hydrated state can read it. The runtime calls these once per process.
320
+ // hydrated state can read addons[].config.service. Changes require restart;
321
+ // this ordinary config is not secure credential storage.
314
322
  readonly onLoad?: (
315
323
  ctx: AddonServiceContext,
316
324
  config?: unknown,
@@ -338,6 +346,21 @@ export interface AddonGlobalSubscription {
338
346
  }
339
347
 
340
348
  export interface AddonServiceContext {
349
+ /** Private persistent directory scoped by the host to this addon; not a credential store. */
350
+ getDataDirectory?: () => Promise<string>
351
+ /** Show an existing deck until released. Returns null if unavailable or locked.
352
+ * A newer interruption or navigation supersedes the returned release handle. */
353
+ interruptDeck?: (
354
+ deckId: string,
355
+ options?: { onBack?: () => void | Promise<void> },
356
+ ) => (() => void) | null
357
+ /** Queue a modal deck; OK closes it and invokes onOk. The returned handle cancels it. */
358
+ showModal?: (
359
+ deckId: string,
360
+ options?: { onOk?: () => void | Promise<void> },
361
+ ) => (() => void) | null
362
+ /** Namespaced credential store when supported by the host; addons are trusted code. */
363
+ credentials?: AddonCredentials
341
364
  /** Push data to the channel this poller/subscription is bound to. */
342
365
  publish: (data: unknown) => void
343
366
  /**
@@ -0,0 +1,52 @@
1
+ import { createHash } from "node:crypto"
2
+ import { chmod, lstat, mkdir } from "node:fs/promises"
3
+ import { homedir } from "node:os"
4
+ import { isAbsolute, join } from "node:path"
5
+
6
+ export const addonDataRoot = (): string => {
7
+ if (process.platform === "win32") {
8
+ const local = process.env["LOCALAPPDATA"]
9
+ if (!local || !isAbsolute(local))
10
+ throw new Error("LOCALAPPDATA is unavailable")
11
+ return join(local, "sirenodeck")
12
+ }
13
+ if (process.platform === "darwin") {
14
+ return join(homedir(), "Library", "Application Support", "sirenodeck")
15
+ }
16
+ const xdg = process.env["XDG_DATA_HOME"]
17
+ return join(
18
+ xdg && isAbsolute(xdg) ? xdg : join(homedir(), ".local", "share"),
19
+ "sirenodeck",
20
+ )
21
+ }
22
+
23
+ export const createAddonDataDirectory = (
24
+ name: string,
25
+ root?: string,
26
+ ): (() => Promise<string>) => {
27
+ let result: Promise<string> | undefined
28
+ return () => {
29
+ result ??= (async () => {
30
+ const base = root ?? addonDataRoot()
31
+ if (!isAbsolute(base)) throw new Error("Addon data root must be absolute")
32
+ const addons = join(base, "addons")
33
+ const directory = join(
34
+ addons,
35
+ createHash("sha256").update(name).digest("hex"),
36
+ )
37
+ await mkdir(base, { recursive: true, mode: 0o700 })
38
+ for (const path of [addons, directory]) {
39
+ await mkdir(path, { mode: 0o700 }).catch(
40
+ (error: NodeJS.ErrnoException) => {
41
+ if (error.code !== "EEXIST") throw error
42
+ },
43
+ )
44
+ if (!(await lstat(path)).isDirectory())
45
+ throw new Error(`Not a directory: ${path}`)
46
+ if (process.platform !== "win32") await chmod(path, 0o700)
47
+ }
48
+ return directory
49
+ })()
50
+ return result
51
+ }
52
+ }
@@ -86,6 +86,7 @@ export const deckConfigSurfaceSchema = z.object({
86
86
  id: z.string(),
87
87
  name: z.string(),
88
88
  buttons: z.array(deckConfigSurfaceButtonSchema),
89
+ isModal: z.boolean().optional(),
89
90
  buttonColor: z.string().optional(),
90
91
  variant: z.string().optional(),
91
92
  buttonErrors: z
@@ -1,5 +1,4 @@
1
1
  export { SYSTEM_BUTTON_TYPES } from "@/deck/system-buttons/types"
2
- export { default as brightnessAddon } from "./brightness/index"
3
2
  export { coreAddon } from "./core/index"
4
3
  export { default as dateTimeAddon } from "./date-time/index"
5
4
  export { default as emojiSelectorAddon } from "./emoji-selector/index"
@@ -4,7 +4,7 @@ import { AddonServiceContext, AddonGlobalService } from "@/addon/api"
4
4
  import {
5
5
  createBrightnessProvider,
6
6
  type BrightnessProvider,
7
- } from "@/builtin-addons/brightness/providers"
7
+ } from "./brightness-providers"
8
8
 
9
9
  let brightnessProvider: BrightnessProvider | null = null
10
10
 
@@ -6,7 +6,7 @@ import { useEffect, useRef, useState } from "react"
6
6
  const BRIGHTNESS_CHANNEL = "sireno:settings:brightness"
7
7
  const PROGRESS_VISIBLE_MS = 2000
8
8
 
9
- export type BrightnessVariant = "down" | "up"
9
+ export type BrightnessVariant = "down" | "up" | "compact"
10
10
 
11
11
  interface BrightnessButtonFrontendProps {
12
12
  readonly variant: BrightnessVariant
@@ -23,7 +23,12 @@ export const BrightnessButtonFrontend = ({
23
23
  const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
24
24
 
25
25
  useEffect(() => {
26
- if (gesture?.gesture !== "tap" && gesture?.gesture !== "dbl-tap") return
26
+ if (
27
+ gesture?.gesture !== "tap" &&
28
+ gesture?.gesture !== "dbl-tap" &&
29
+ gesture?.gesture !== "hold"
30
+ )
31
+ return
27
32
  setShowProgress(true)
28
33
  if (timerRef.current) clearTimeout(timerRef.current)
29
34
  timerRef.current = setTimeout(
@@ -42,7 +47,13 @@ export const BrightnessButtonFrontend = ({
42
47
  return (
43
48
  <IconLabelProgressSurface
44
49
  source={`icon://${variant === "down" ? "sun-dim" : "sun"}`}
45
- label={variant === "down" ? "Darker" : "Lighter"}
50
+ label={
51
+ variant === "compact"
52
+ ? "Tap + / Hold −"
53
+ : variant === "down"
54
+ ? "Darker"
55
+ : "Lighter"
56
+ }
46
57
  progress={progress}
47
58
  visible={showProgress}
48
59
  />
@@ -0,0 +1,6 @@
1
+ import type { AddonFrontendButton } from "@/addon/api"
2
+ import { BrightnessButtonFrontend } from "../brightness/common/frontend"
3
+
4
+ export const CompactBrightnessFrontend: AddonFrontendButton<unknown> = ({
5
+ gesture,
6
+ }) => <BrightnessButtonFrontend variant="compact" gesture={gesture ?? null} />
@@ -4,6 +4,7 @@ import appInfoBackend from "./buttons/app-info/backend"
4
4
  import appInfoFrontend from "./buttons/app-info/frontend"
5
5
  import brightnessDownBackend from "./buttons/brightness-down/backend"
6
6
  import brightnessDownFrontend from "./buttons/brightness-down/frontend"
7
+ import { CompactBrightnessFrontend } from "./buttons/brightness-compact/frontend"
7
8
  import brightnessUpBackend from "./buttons/brightness-up/backend"
8
9
  import brightnessUpFrontend from "./buttons/brightness-up/frontend"
9
10
  import settingsDeck from "./decks/settings"
@@ -31,6 +32,20 @@ export const manifest: AddonManifestV1 = {
31
32
  gestureHandlers: ["tap", "dbl-tap"] as const,
32
33
  },
33
34
  },
35
+ "internal-settings:compact-brightness": {
36
+ frontend: CompactBrightnessFrontend,
37
+ service: {
38
+ ...withInternal(brightnessUpBackend),
39
+ gestureHandlers: ["tap", "dbl-tap", "hold"] as const,
40
+ onHold: ({ coreMethods }) => {
41
+ coreMethods.adjustBrightness({ direction: "down" })
42
+ },
43
+ },
44
+ },
45
+ "internal-settings:compact-app-info": {
46
+ frontend: appInfoFrontend,
47
+ service: { internal: true },
48
+ },
34
49
  "internal-settings:app-info": {
35
50
  frontend: appInfoFrontend,
36
51
  service: {
@@ -4,7 +4,6 @@ import { registerBuiltInThemes, registerSiblingThemes } from "@/themes/loader"
4
4
 
5
5
  import { manifest as codingAgentsManifest } from "./coding-agents"
6
6
  import { registerCodingAgentsAddon } from "./coding-agents"
7
- import brightnessAddon from "./brightness/index"
8
7
  import { coreAddon } from "./core/index"
9
8
  import dateTimeAddon from "./date-time/index"
10
9
  import emojiSelectorAddon from "./emoji-selector/index"
@@ -27,7 +26,6 @@ export const registerBuiltins = (registry: AddonRegistry): void => {
27
26
  registry.load(systemStatusAddon)
28
27
  registry.load(valueDisplayAddon)
29
28
  registry.load(weatherAddon)
30
- registry.load(brightnessAddon)
31
29
  registerCodingAgentsAddon(registry)
32
30
  }
33
31
 
@@ -60,6 +58,5 @@ export const BUILTIN_MANIFESTS: ReadonlyMap<string, unknown> = new Map<
60
58
  ["system-status", systemStatusAddon],
61
59
  ["value-display", valueDisplayAddon],
62
60
  ["weather", weatherAddon],
63
- ["brightness", brightnessAddon],
64
61
  ["coding-agents", codingAgentsManifest],
65
62
  ])
@@ -239,6 +239,7 @@ export const collectAddonDefaultButtonConfig = (
239
239
  if (addon.defaultButton === undefined) continue
240
240
  let matchCount = 0
241
241
  for (const deck of userDecks) {
242
+ if (deck.addonOwner !== undefined) continue
242
243
  for (const btn of deck.buttons) {
243
244
  if (btn.type === addon.defaultButton || btn.type === addon.name) {
244
245
  if (matchCount > 0) {
@@ -0,0 +1,85 @@
1
+ import { basename, dirname, resolve } from "node:path"
2
+ import { existsSync, readFileSync } from "node:fs"
3
+ import { isMap, isScalar, isSeq, parseDocument } from "yaml"
4
+ import { createConfigMutationService } from "@/config/mutation"
5
+
6
+ export const saveAddonProvider = async (
7
+ path: string,
8
+ addonName: string,
9
+ provider: {
10
+ id: string
11
+ type: string
12
+ clientId: string
13
+ calendarIds: string[]
14
+ calendarColors?: Record<string, string>
15
+ },
16
+ ): Promise<void> => {
17
+ const mutation = createConfigMutationService({ configPath: path })
18
+ const candidates: Array<{ path: string; index: number }> = []
19
+ for (const source of mutation.sources()) {
20
+ const doc = parseDocument(readFileSync(source, "utf8"))
21
+ if (doc.errors.length) continue
22
+ const addons = doc.get("addons")
23
+ if (!isSeq(addons)) continue
24
+ addons.items.forEach((item, index) => {
25
+ const value = isMap(item)
26
+ ? item.get("src")
27
+ : isScalar(item)
28
+ ? item.value
29
+ : undefined
30
+ if (typeof value !== "string") return
31
+ const base = basename(value.replace(/\/$/, ""))
32
+ let name = base === addonName || base === `addon-${addonName}`
33
+ const manifestPath = resolve(dirname(source), value, "sirenodeck.json")
34
+ if (!name && existsSync(manifestPath)) {
35
+ try {
36
+ name =
37
+ JSON.parse(readFileSync(manifestPath, "utf8")).name === addonName
38
+ } catch {
39
+ /* ignore invalid manifests */
40
+ }
41
+ }
42
+ if (name) candidates.push({ path: source, index })
43
+ })
44
+ }
45
+ if (candidates.length !== 1)
46
+ throw new Error(
47
+ `Expected one ${addonName} addon entry; found ${candidates.length}`,
48
+ )
49
+ const target = candidates[0]!
50
+ const document = parseDocument(mutation.readSource(target.path), {
51
+ keepSourceTokens: true,
52
+ })
53
+ const addonPath = ["addons", target.index]
54
+ const item = document.getIn(addonPath)
55
+ if (!isMap(item)) {
56
+ const src =
57
+ typeof item === "string" ? item : isScalar(item) ? item.value : undefined
58
+ if (typeof src !== "string") throw new Error("Invalid addon entry")
59
+ document.setIn(addonPath, document.createNode({ src }))
60
+ }
61
+ const providersPath = [...addonPath, "config", "service", "providers"]
62
+ let providers = document.getIn(providersPath)
63
+ if (providers === undefined) {
64
+ document.setIn(providersPath, [])
65
+ providers = document.getIn(providersPath)
66
+ }
67
+ if (!isSeq(providers)) throw new Error("Calendar providers must be a list")
68
+ const matches = providers.items.filter(
69
+ (entry) => isMap(entry) && entry.get("id") === provider.id,
70
+ )
71
+ if (matches.length > 1)
72
+ throw new Error("Duplicate calendar account IDs in config")
73
+ if (matches.length === 1) {
74
+ const existing = matches[0]!
75
+ if (!isMap(existing) || existing.get("type") !== provider.type)
76
+ throw new Error("Account ID is already used by another provider")
77
+ for (const [key, value] of Object.entries(provider))
78
+ existing.set(key, value)
79
+ } else providers.add(provider)
80
+ await mutation.apply({
81
+ kind: "edit-source",
82
+ path: target.path,
83
+ content: document.toString(),
84
+ })
85
+ }
@@ -0,0 +1,134 @@
1
+ import { resolve } from "node:path"
2
+ import { styleText } from "node:util"
3
+ import { pathToFileURL } from "node:url"
4
+ import { confirm, isCancel, multiselect, password, text } from "@clack/prompts"
5
+ import type { CommandModule } from "yargs"
6
+ import { scopeCredentials } from "@/system/credentials/store"
7
+ import { createNativeCredentialBackend } from "@/system/credentials/native"
8
+ import { openBrowser } from "@/outputClient/open-browser"
9
+ import { createLogger } from "@/util/logger"
10
+ import { isRunning, readConfigPath, readPid } from "@/util/daemon"
11
+ import { resolveUserPath } from "@/cli/cwd"
12
+ import { saveAddonProvider } from "./addon-setup-config"
13
+
14
+ interface SetupModule {
15
+ addonName: string
16
+ setupAddon(ctx: {
17
+ credentials: ReturnType<typeof scopeCredentials>
18
+ openUrl(url: string): void
19
+ text(message: string, secret?: boolean): Promise<string>
20
+ selectMany(
21
+ message: string,
22
+ options: readonly {
23
+ value: string
24
+ label: string
25
+ hint?: string
26
+ color?: string
27
+ }[],
28
+ ): Promise<string[]>
29
+ confirm(message: string): Promise<boolean>
30
+ saveProvider(provider: {
31
+ id: string
32
+ type: string
33
+ clientId: string
34
+ calendarIds: string[]
35
+ calendarColors?: Record<string, string>
36
+ }): Promise<string | null>
37
+ print(message: string): void
38
+ }): Promise<void>
39
+ }
40
+
41
+ export const addonSetupCommand: CommandModule<object, { module: string }> = {
42
+ command: "addon-setup <module>",
43
+ describe: "Run an installed addon's interactive setup module",
44
+ builder: (yargs) =>
45
+ yargs.positional("module", {
46
+ type: "string",
47
+ demandOption: true,
48
+ description: "Path to the addon's setup module",
49
+ }),
50
+ handler: async ({ module }) => {
51
+ if (!process.stdin.isTTY || !process.stdout.isTTY)
52
+ throw new Error("Addon setup requires an interactive terminal")
53
+ const setup = (await import(
54
+ pathToFileURL(resolve(module)).href
55
+ )) as SetupModule
56
+ if (
57
+ !/^[a-z0-9][a-z0-9-]*$/.test(setup.addonName) ||
58
+ typeof setup.setupAddon !== "function"
59
+ )
60
+ throw new Error("Invalid addon setup module")
61
+ const logger = createLogger({})
62
+ const pid = readPid()
63
+ let configPath = pid !== null && isRunning(pid) ? readConfigPath() : null
64
+ await setup.setupAddon({
65
+ credentials: scopeCredentials(
66
+ createNativeCredentialBackend(),
67
+ setup.addonName,
68
+ ),
69
+ openUrl: (url) => {
70
+ console.log(`Open this URL if your browser does not start:\n${url}`)
71
+ openBrowser(url, logger)
72
+ },
73
+ text: async (message, secret) => {
74
+ const value = secret
75
+ ? await password({ message })
76
+ : await text({ message })
77
+ if (isCancel(value)) throw new Error("Addon setup cancelled")
78
+ return value
79
+ },
80
+ selectMany: async (message, options) => {
81
+ const value = await multiselect({
82
+ message,
83
+ options: options.map(({ color, ...option }) => {
84
+ const useColor =
85
+ process.stdout.isTTY &&
86
+ process.env["NO_COLOR"] === undefined &&
87
+ process.env["TERM"] !== "dumb"
88
+ const hex = /^#[0-9a-f]{6}$/i.test(color ?? "")
89
+ ? color!.slice(1)
90
+ : undefined
91
+ const rgb =
92
+ hex === undefined
93
+ ? undefined
94
+ : [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16))
95
+ const marker =
96
+ rgb && useColor ? `\x1b[38;2;${rgb.join(";")}m■\x1b[0m` : "■"
97
+ return {
98
+ ...option,
99
+ label: `${marker} ${useColor ? styleText("white", option.label) : option.label}`,
100
+ }
101
+ }),
102
+ required: true,
103
+ })
104
+ if (isCancel(value)) throw new Error("Addon setup cancelled")
105
+ return value
106
+ },
107
+ confirm: async (message) => {
108
+ const value = await confirm({ message, initialValue: false })
109
+ if (isCancel(value)) throw new Error("Addon setup cancelled")
110
+ return value
111
+ },
112
+ saveProvider: async (provider) => {
113
+ if (!configPath) {
114
+ const value = await text({
115
+ message: "Config file path (leave blank for manual instructions)",
116
+ })
117
+ if (isCancel(value)) throw new Error("Addon setup cancelled")
118
+ if (!value.trim()) return null
119
+ configPath = resolveUserPath(value.trim())
120
+ }
121
+ try {
122
+ await saveAddonProvider(configPath, setup.addonName, provider)
123
+ return configPath
124
+ } catch (error) {
125
+ console.error(
126
+ `Could not update config: ${error instanceof Error ? error.message : String(error)}`,
127
+ )
128
+ return null
129
+ }
130
+ },
131
+ print: (message) => console.log(message),
132
+ })
133
+ },
134
+ }