# 服务接口

桌面服务模块的默认导出是 `ServiceFactory`. 用法见 [服务](https://docs.dopame.ai/zh/guide/services.md).

```ts
type ServiceFactory = (context: ServiceContext) => ServiceInstance | Promise<ServiceInstance>

interface ServiceInstance {
  readonly api: Readonly<Record<string, object>>
  readonly sync?: readonly string[]
  close?(): unknown
}

interface ServiceContext {
  readonly name: string
  readonly package: string
  readonly state: string
  readonly native: Readonly<Record<string, unknown>> | null
  readonly env: Readonly<Record<string, string | undefined>>
  readonly inspect?: AcdeInspect
  log(line: string): void
  spawn(argv: readonly string[], options?: SpawnOptions): ServiceProcess
  import<K extends keyof ServiceModuleTypes>(specifier: `acde:${K}`): Promise<{ readonly default: ServiceModuleTypes[K] } & { readonly [N in K]: ServiceModuleTypes[K] }>
}

// ServiceModuleTypes: windows, packages, session, desktops, inspect, setDefault, 以及只有 apps() 的 desktop

interface SpawnOptions {
  readonly cwd?: string
  readonly env?: Readonly<Record<string, string>>
  onLine?(line: string): void
  onExit?(code: number | null, signal: number | null): void
}

interface ServiceProcess {
  readonly pid: number
  write(text: string): boolean
  end(): void
  kill(signal?: 'SIGTERM' | 'SIGKILL' | 'SIGINT' | 'SIGHUP'): boolean
}
```

- `api`: 命名空间 → 对象. 每个命名空间成为模块 `acde:<命名空间>`, 对象上的函数成为可调用的方法, 字符串 / 数字 / 布尔值成为只读字段.
- `sync`: `"命名空间.方法"` 的列表. 这些方法在页面启动时调一次, 结果缓存在页面里, 之后在页面里同步返回 (适合不变的配置).
- `close()`: 桌面停止时调用.
- 应用把**服务名** (桌面配置 `services` 的键) 列在自己的 `services` 里, 运行时就把这个服务的所有命名空间都给它. 导入的命名空间不是服务自己的名字时, `acdev check` 和 `acdev build` 让它通过, 带一条 `note:`, 因为它们没法知道一个服务有哪些命名空间 (见 [服务](https://docs.dopame.ai/zh/guide/services.md#调用)). 服务名不能是系统模块或能力的名字, 取了这种名字的命名空间会被略去.
- `import('acde:windows')`: 桌面把这个模块给了这个服务时, resolve 成这个模块 (`{ windows, default }`): 在 `acde.config.jsonc` 里写 `"services": { "clock": { "module": "services/clock.ts", "modules": ["windows"] } }`, `acdev build` 把它写进清单, 成为 `"services": [{ "name": "clock", "modules": ["windows"] }]` (见 [包清单](https://docs.dopame.ai/zh/reference/manifest.md#desktopmanifest)). 否则 reject, 错误信息是 `acde:windows is a shell module: list it in the modules of service "clock" in the desktop manifest`. 服务不能用静态 `import` 导入 `acde:` 模块 (构建会拒绝). 服务拿到的模块就是桌面页拿到的那些, 有两个例外: `acde:desktop` 只有 `apps()`, `acde:permissions` 不给. 类型里声明为 promise 的调用, 在服务里返回的也是 promise. 见 [服务](https://docs.dopame.ai/zh/guide/services.md#服务里的-shell-模块).
