pi-tsgw 2.0.0 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +31 -5
- package/extensions/config.ts +66 -0
- package/extensions/dav/calendar-write-schema.ts +50 -0
- package/extensions/dav/calendar-write.ts +170 -0
- package/extensions/dav/calendar.ts +137 -0
- package/extensions/dav/client.ts +105 -0
- package/extensions/dav/config.ts +35 -0
- package/extensions/dav/contact-action-schema.ts +37 -0
- package/extensions/dav/contact-actions.ts +108 -0
- package/extensions/dav/contacts.ts +59 -0
- package/extensions/dav/index.ts +18 -0
- package/extensions/dav/mutations.ts +38 -0
- package/extensions/dav/schema.ts +36 -0
- package/extensions/dav/tools.ts +103 -0
- package/extensions/dav/types.ts +37 -0
- package/extensions/email/config.ts +11 -70
- package/extensions/email/index.ts +6 -11
- package/extensions/email/smtp.ts +2 -1
- package/extensions/email/tools.ts +59 -16
- package/extensions/images/tool-schema.ts +3 -3
- package/extensions/images/tools.ts +3 -3
- package/extensions/models/catalog.ts +2 -3
- package/extensions/models/vendors/openai.ts +2 -2
- package/extensions/provider/catalog-state.ts +5 -5
- package/extensions/provider/status.ts +1 -1
- package/index.ts +2 -0
- package/package.json +5 -2
- package/skills/tsgw-email/SKILL.md +2 -0
- package/skills/tsgw-image-generation/SKILL.md +3 -3
- package/skills/tsgw-synology-dav/SKILL.md +25 -6
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# pi-tsgw
|
|
2
2
|
|
|
3
|
-
自用的 Pi 扩展,为 TOSSP AIH gateway 提供模型目录、请求适配、联网搜索、图片生成与编辑、分类模型及配套工作流,并提供可选的 IMAP/SMTP
|
|
3
|
+
自用的 Pi 扩展,为 TOSSP AIH gateway 提供模型目录、请求适配、联网搜索、图片生成与编辑、分类模型及配套工作流,并提供可选的 IMAP/SMTP 邮件与 DAV 日历、联系人组件。以 MIT 许可证公开。
|
|
4
4
|
|
|
5
5
|
## 安装
|
|
6
6
|
|
|
@@ -31,13 +31,15 @@ pi install npm:pi-tsgw
|
|
|
31
31
|
|
|
32
32
|
## 工具入口
|
|
33
33
|
|
|
34
|
-
|
|
34
|
+
图片、上传、代理搜索、邮件及 DAV 工具均为 `deferred` 注册,通过 codemode 按需发现和调用,不默认声明完整工具 schema。使用 `describeNamespace("tsgw_images")`、`describeNamespace("tsgw_upload")`、`describeNamespace("tsgw_search")` 、`describeNamespace("tsgw_email")` 或 `describeNamespace("tsgw_dav")` 查看对应能力。用法见[图片技能](skills/tsgw-image-generation/SKILL.md)、[上传技能](skills/tsgw-upload/SKILL.md)、[搜索技能](skills/tsgw-search/SKILL.md)、[邮件技能](skills/tsgw-email/SKILL.md)及[DAV 技能](skills/tsgw-synology-dav/SKILL.md)。
|
|
35
|
+
|
|
36
|
+
图片工具固定登记已接入的两款模型,不受 `tsgw.includeModels` / `excludeModels` 或网关模型目录缺席影响;仍复用宿主认证,由实际调用确认上游支持,失败不自动重试或换模型。
|
|
35
37
|
|
|
36
38
|
本地上传工具名为 `tsgw_upload_local_file`,不再提供旧名 `upload_local_file`;已有调用需更新。代理搜索仍遵守当前模型及可用目录限制,不因切换模型或刷新目录自动激活。
|
|
37
39
|
|
|
38
40
|
## 可选邮件配置
|
|
39
41
|
|
|
40
|
-
邮件能力需要 Pi 1.2
|
|
42
|
+
邮件能力需要 Pi 1.2+,工具始终通过 codemode 按需发现;调用缺配置时会提示所需字段。在宿主用户目录配置统一的 `tsgw.json`(权限 `0600`),顶层按 `imap`、`smtp` 等协议类型分组,每组为 ID 到配置的映射;不同类型可使用同名 ID,IMAP 与 SMTP 可独立配置。以下地址与密码均为占位内容:
|
|
41
43
|
|
|
42
44
|
```json
|
|
43
45
|
{
|
|
@@ -62,11 +64,35 @@ pi install npm:pi-tsgw
|
|
|
62
64
|
"fromAddress": "sender@example.invalid",
|
|
63
65
|
"allowSenderOverride": false
|
|
64
66
|
}
|
|
65
|
-
}
|
|
66
|
-
"defaultSmtp": "outbound"
|
|
67
|
+
}
|
|
67
68
|
}
|
|
68
69
|
```
|
|
69
70
|
|
|
71
|
+
发信未指定 SMTP 时默认使用 `smtp` 组按对象枚举顺序注册的首项,显式指定账户优先,失败不切换;文件中不再配置 `defaultSmtp`。旧 `tsgw-email.json` 不再读取,不会自动迁移或删除;迁移时保留原账户字段,并通过账户工具返回的 `defaultSmtp` 核对默认身份;纯数字 ID 按对象枚举规则排序,必要时显式指定 SMTP。首次配置可在提示后重试;已加载账户的修改通过 `/reload` 生效,不在启动时连接服务。密码仅在本地填写,不要贴进聊天。
|
|
72
|
+
|
|
70
73
|
`implicit` 表示连接即 TLS;`starttls` 必须成功升级 TLS,均校验证书。SMTP 可选 `fromName` 和 `envelopeFrom`;未配置后者时信封发件人跟随最终 From。`allowSenderOverride: true` 允许自定义发件地址和名称;可配非空 `allowedFromDomains` 数组限定最终 From 的域(含默认地址),忽略大小写,兼容 Unicode/Punycode,子域须单列;省略则不额外限制域,不影响已有配置。该字段不限制独立的 `envelopeFrom`,也不验证 SPF/DKIM/DMARC 或保证投递成功。邮件工具统一 `tsgw_email_` 前缀,通过 codemode 的 `describeNamespace("tsgw_email")` 按需发现,不直接声明或内联到模型上下文。无后台同步、磁盘缓存、自动重发、出口切换或发送后存档;读取不自动标已读。附件仅允许当前工作目录或系统临时目录,不允许访问宿主配置目录,符号链接按真实路径校验。超出读取预算、原始头部不是合法 UTF-8,或 inline 文本附件会被库转换字符集/flowed 格式时,会明确报告,不把截断或改写内容当作完整原文。
|
|
71
74
|
|
|
75
|
+
## 可选 DAV 配置
|
|
76
|
+
|
|
77
|
+
在同一 `tsgw.json` 的 `dav` 组按 ID 添加配置,不创建独立文件:
|
|
78
|
+
|
|
79
|
+
```json
|
|
80
|
+
{
|
|
81
|
+
"dav": {
|
|
82
|
+
"work": {
|
|
83
|
+
"url": "https://dav.example.invalid/",
|
|
84
|
+
"user": "<登录账号>",
|
|
85
|
+
"password": "<应用密码>",
|
|
86
|
+
"timeZone": "Asia/Shanghai"
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
`timeZone` 可省略,但事件展开必须在调用时明确时区;不用主机时区推断。密码为本地填写的普通字符串,不支持命令或环境变量占位符。根 URL 的服务发现使用标准 `/.well-known/caldav`/`carddav` 入口,最多跟随三次同源跳转;配置具体服务路径时按原路径发现,不探测其他端口或厂商私有路径。资源读取不跟随跳转,始终校验证书。
|
|
93
|
+
|
|
94
|
+
通过 codemode 发现 `tsgw_dav`,先 `accounts`,再以明确账户和类型调用 `collections`;列表须传实际集合,详情使用返回的资源 URL。提供账户、集合,日程/待办/日记/联系人的 list/get/create/update/delete,以及多字段 contact_search;创建、修改、删除均须明确授权。更新或删除先读取并核对调用方确认的强 ETag,冲突不重试;日历删除针对整资源,不是某次展开实例。日程读取所选日历全部事件资源,再由库按明确时区与窗口展开过滤,避免服务端时区不同导致漏项;代价是大日历读取量较大。待办与日记只返回已存储组件;默认摘要不包含原文,详情 `raw: true` 才返回源文本。读取和搜索超过结果预算会明确失败,不返回看似完整的截断列表。写工具只返回身份、版本与结果,不在内部回读;REMOTE_RESULT_UNKNOWN 表示可能已生效,应先核对目标,不能自动重发。
|
|
95
|
+
|
|
96
|
+
DAV 业务调用需要 Node.js 24+ 及可选依赖 `davkit`;Node.js 22 或省略 optional 依赖仍可加载插件并发现工具,调用 DAV 时返回环境指导,不影响其他能力,也不会自动安装依赖或改用旧 MCP。注册阶段不读配置或联网;DAV 配置按次调用加载,不自动迁移旧 DAV 凭据、切换账号或重试。
|
|
97
|
+
|
|
72
98
|
开发维护约定见 [AGENTS.md](https://github.com/tossp/pi-tsgw/blob/main/AGENTS.md)。
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { readFileSync, statSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { DavConfigError, parseDavAccounts, type DavAccountConfig } from "./dav/config.ts";
|
|
5
|
+
import {
|
|
6
|
+
EmailConfigError, parseImapAccounts, parseSmtpConfigs,
|
|
7
|
+
type ImapAccountConfig, type SmtpConfig,
|
|
8
|
+
} from "./email/config.ts";
|
|
9
|
+
|
|
10
|
+
export interface ConfigMap {
|
|
11
|
+
imap: ImapAccountConfig;
|
|
12
|
+
smtp: SmtpConfig;
|
|
13
|
+
dav: DavAccountConfig;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type ConfigResult<T> =
|
|
17
|
+
| { status: "missing" }
|
|
18
|
+
| { status: "invalid"; message: string }
|
|
19
|
+
| { status: "ready"; config: T };
|
|
20
|
+
|
|
21
|
+
const factories: { [K in keyof ConfigMap]: (raw: unknown) => Record<string, ConfigMap[K]> } = {
|
|
22
|
+
imap: parseImapAccounts,
|
|
23
|
+
smtp: parseSmtpConfigs,
|
|
24
|
+
dav: parseDavAccounts,
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
/** 只读统一文件并校验本次所需类型;不探测旧入口、不迁移、不联网。 */
|
|
28
|
+
export function readConfig<K extends keyof ConfigMap>(
|
|
29
|
+
kind: K,
|
|
30
|
+
agentDir?: string,
|
|
31
|
+
): ConfigResult<Record<string, ConfigMap[K]>> {
|
|
32
|
+
let text: string;
|
|
33
|
+
try {
|
|
34
|
+
const path = join(agentDir ?? getAgentDir(), "tsgw.json");
|
|
35
|
+
const stats = statSync(path);
|
|
36
|
+
if (!stats.isFile()) return { status: "invalid", message: "扩展配置路径不是普通文件。" };
|
|
37
|
+
if ((stats.mode & 0o777) !== 0o600)
|
|
38
|
+
return { status: "invalid", message: "扩展配置文件权限必须是 0600。" };
|
|
39
|
+
text = readFileSync(path, "utf8");
|
|
40
|
+
} catch (error) {
|
|
41
|
+
const code = (error as { code?: unknown } | null)?.code;
|
|
42
|
+
if (code === "ENOENT" || code === "ENOTDIR") return { status: "missing" };
|
|
43
|
+
return { status: "invalid", message: "扩展配置文件无法读取或定位。" };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
let raw: unknown;
|
|
47
|
+
try {
|
|
48
|
+
raw = JSON.parse(text.startsWith("\uFEFF") ? text.slice(1) : text);
|
|
49
|
+
} catch {
|
|
50
|
+
// 原始解析错误可能包含凭据片段,不能回显。
|
|
51
|
+
return { status: "invalid", message: "扩展配置文件不是有效的 JSON。" };
|
|
52
|
+
}
|
|
53
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw))
|
|
54
|
+
return { status: "invalid", message: "扩展配置顶层必须是 JSON 对象。" };
|
|
55
|
+
if (Object.keys(raw).some(key => !["imap", "smtp", "dav"].includes(key)))
|
|
56
|
+
return { status: "invalid", message: "扩展配置顶层包含不支持的字段。" };
|
|
57
|
+
if (!Object.hasOwn(raw, kind)) return { status: "missing" };
|
|
58
|
+
|
|
59
|
+
try {
|
|
60
|
+
const config = factories[kind]((raw as Record<string, unknown>)[kind]);
|
|
61
|
+
return Object.keys(config).length ? { status: "ready", config } : { status: "missing" };
|
|
62
|
+
} catch (error) {
|
|
63
|
+
return { status: "invalid", message: error instanceof EmailConfigError || error instanceof DavConfigError
|
|
64
|
+
? error.message : "扩展配置类型无效。" };
|
|
65
|
+
}
|
|
66
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { Type } from "typebox";
|
|
2
|
+
|
|
3
|
+
const options = { additionalProperties: false } as const;
|
|
4
|
+
const id = Type.String({ minLength: 1, pattern: "^[^\\u0000-\\u001f\\u007f]+$" });
|
|
5
|
+
const url = Type.String({ minLength: 1, description: "已发现的同源完整 URL;创建仅接受明确集合,不接受自定资源路径。" });
|
|
6
|
+
const basicTime = Type.String({ pattern: "^\\d{8}(?:T\\d{6}Z?)?$" });
|
|
7
|
+
const time = Type.Union([
|
|
8
|
+
basicTime,
|
|
9
|
+
Type.Object({ value: basicTime,
|
|
10
|
+
valueType: Type.Optional(Type.Union([Type.Literal("DATE"), Type.Literal("DATE-TIME")])),
|
|
11
|
+
tzid: Type.Optional(Type.String({ minLength: 1 })),
|
|
12
|
+
}, options),
|
|
13
|
+
], { description: "仅基本日历时间 YYYYMMDD / YYYYMMDDTHHmmss[Z],不支持 ISO;对象 DATE 须声明 valueType。创建不猜时区;更新字符串沿用原表示,新增时间属性须用对象。TZID 明确指定,不将当地重复系列固定转 UTC。" });
|
|
14
|
+
const nullableTime = Type.Optional(Type.Union([time, Type.Null()]));
|
|
15
|
+
const scalar = Type.Optional(Type.String());
|
|
16
|
+
const nullableScalar = Type.Optional(Type.Union([Type.String(), Type.Null()]));
|
|
17
|
+
const properties = Type.Optional(Type.Array(Type.String({ minLength: 1 }), {
|
|
18
|
+
description: "未折行的完整逻辑属性;更新按基本名整组替换,省略或 [] 不修改。不得与便捷字段冲突,不能设置 UID/VERSION/RECURRENCE-ID 或受管 DTSTAMP/LAST-MODIFIED/SEQUENCE。",
|
|
19
|
+
}));
|
|
20
|
+
const alarms = Type.Optional(Type.Array(Type.String({ minLength: 1 }), {
|
|
21
|
+
description: "完整 VALARM 块,由库验证依赖;省略保留,[] 清空。不支持日记提醒。",
|
|
22
|
+
}));
|
|
23
|
+
const create = { account: id, collectionUrl: url, summary: Type.String(),
|
|
24
|
+
description: scalar, location: scalar, status: scalar, properties };
|
|
25
|
+
const identity = { account: id, resourceUrl: url, uid: id,
|
|
26
|
+
etag: Type.String({ minLength: 1, description: "上次读取并确认的单个强 ETag;不接受弱标签、通配符或列表。" }) };
|
|
27
|
+
const update = { ...identity,
|
|
28
|
+
recurrenceId: Type.Optional(Type.String({ minLength: 1, description: "已有例外的完整 RECURRENCE-ID 逻辑行;省略只选主件,拒绝 RANGE,不隐式创建例外。" })),
|
|
29
|
+
summary: nullableScalar, description: nullableScalar, location: nullableScalar, status: nullableScalar,
|
|
30
|
+
properties,
|
|
31
|
+
removeProperties: Type.Optional(Type.Array(Type.String({ minLength: 1 }), {
|
|
32
|
+
description: "显式删除整组基本属性名;不能与同名字段/properties 混用,也不能删除身份或受管修订元数据。",
|
|
33
|
+
})),
|
|
34
|
+
};
|
|
35
|
+
const rrule = Type.Optional(Type.String({ minLength: 1, description: "RRULE 的完整值(不带 RRULE:);与 properties/removeProperties 的 RRULE 操作互斥。" }));
|
|
36
|
+
const deleteResource = Type.Object(identity, { ...options,
|
|
37
|
+
description: "删除整份资源而非单次发生项;GET 版本核对及整资源 kind/UID 校验后条件删除,不接受 recurrenceId。" });
|
|
38
|
+
|
|
39
|
+
export const calendarWriteSchemas = {
|
|
40
|
+
event_create: Type.Object({ ...create, start: time, end: Type.Optional(time), rrule, alarms }, options),
|
|
41
|
+
event_update: Type.Object({ ...update, start: nullableTime, end: nullableTime,
|
|
42
|
+
rrule: Type.Optional(Type.Union([Type.String({ minLength: 1 }), Type.Null()])), alarms }, options),
|
|
43
|
+
event_delete: deleteResource,
|
|
44
|
+
todo_create: Type.Object({ ...create, start: Type.Optional(time), due: Type.Optional(time), alarms }, options),
|
|
45
|
+
todo_update: Type.Object({ ...update, start: nullableTime, due: nullableTime, alarms }, options),
|
|
46
|
+
todo_delete: deleteResource,
|
|
47
|
+
journal_create: Type.Object({ ...create, date: time }, options),
|
|
48
|
+
journal_update: Type.Object({ ...update, date: nullableTime }, options),
|
|
49
|
+
journal_delete: deleteResource,
|
|
50
|
+
};
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
import type { CalendarComponent, CalendarComponentEdit, CalendarComponentKind, CalendarTimeInput } from "davkit/ical";
|
|
2
|
+
import { contentOperation, createResourceUrl, getVersionedResource, utcStamp } from "./mutations.ts";
|
|
3
|
+
import { DavToolError, type DavReadContext } from "./types.ts";
|
|
4
|
+
|
|
5
|
+
type Time = string | CalendarTimeInput;
|
|
6
|
+
interface Fields {
|
|
7
|
+
summary?: string | null;
|
|
8
|
+
description?: string | null;
|
|
9
|
+
location?: string | null;
|
|
10
|
+
status?: string | null;
|
|
11
|
+
start?: Time | null;
|
|
12
|
+
end?: Time | null;
|
|
13
|
+
due?: Time | null;
|
|
14
|
+
date?: Time | null;
|
|
15
|
+
rrule?: string | null;
|
|
16
|
+
properties?: string[];
|
|
17
|
+
alarms?: string[];
|
|
18
|
+
}
|
|
19
|
+
export interface CalendarCreateInput extends Fields { account: string; collectionUrl: string; summary: string }
|
|
20
|
+
export interface CalendarUpdateInput extends Fields {
|
|
21
|
+
account: string; resourceUrl: string; uid: string; etag: string;
|
|
22
|
+
recurrenceId?: string;
|
|
23
|
+
removeProperties?: string[];
|
|
24
|
+
}
|
|
25
|
+
export interface CalendarDeleteInput { account: string; resourceUrl: string; uid: string; etag: string }
|
|
26
|
+
|
|
27
|
+
const contentType = "text/calendar; charset=utf-8";
|
|
28
|
+
const protectedNames = new Set(["UID", "VERSION", "PRODID", "RECURRENCE-ID", "DTSTAMP", "LAST-MODIFIED", "SEQUENCE", "BEGIN", "END"]);
|
|
29
|
+
const scalarNames = { summary: "SUMMARY", description: "DESCRIPTION", location: "LOCATION", status: "STATUS",
|
|
30
|
+
start: "DTSTART", date: "DTSTART", end: "DTEND", due: "DUE", rrule: "RRULE" } as const;
|
|
31
|
+
|
|
32
|
+
function invalid(message: string): never { throw new DavToolError("INVALID_INPUT", message); }
|
|
33
|
+
|
|
34
|
+
/** 只识别调用方属性的基本名以检查业务冲突,完整语法仍交给库;不扫描源原文。 */
|
|
35
|
+
function inputPropertyName(line: string): string {
|
|
36
|
+
const match = /^(?:[a-z0-9-]+\.)?([a-z0-9-]+)(?=[;:])/i.exec(line);
|
|
37
|
+
if (!match || /[\r\n]/.test(line)) return invalid("properties 必须是未折行的完整逻辑属性。");
|
|
38
|
+
return match[1]!.toUpperCase();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function validateFields(input: Fields & { removeProperties?: string[] }, kind: CalendarComponentKind) {
|
|
42
|
+
if ((kind !== "VEVENT" && (input.end !== undefined || input.rrule !== undefined)) ||
|
|
43
|
+
(kind !== "VTODO" && input.due !== undefined) ||
|
|
44
|
+
(kind !== "VJOURNAL" && input.date !== undefined) ||
|
|
45
|
+
(kind === "VJOURNAL" && (input.start !== undefined || input.alarms !== undefined)))
|
|
46
|
+
invalid("字段不适用于指定日历类型;日记时间使用 date,提醒仅支持事件和待办。");
|
|
47
|
+
const names = new Set((input.properties ?? []).map(inputPropertyName));
|
|
48
|
+
const removals = new Set((input.removeProperties ?? []).map(name => {
|
|
49
|
+
if (!/^[a-z0-9-]+$/i.test(name)) return invalid("removeProperties 仅接受基本属性名。");
|
|
50
|
+
return name.toUpperCase();
|
|
51
|
+
}));
|
|
52
|
+
for (const name of [...names, ...removals]) {
|
|
53
|
+
if (protectedNames.has(name)) invalid("不能直接设置或删除身份、版本及受管修订元数据。");
|
|
54
|
+
if (names.has(name) && removals.has(name)) invalid("同名属性不能同时设置和删除。");
|
|
55
|
+
}
|
|
56
|
+
for (const [key, name] of Object.entries(scalarNames)) {
|
|
57
|
+
if (input[key as keyof typeof scalarNames] !== undefined && (names.has(name) || removals.has(name)))
|
|
58
|
+
invalid("便捷字段与同名完整属性或删除操作冲突。");
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function createTime(context: DavReadContext, name: string, input: Time): string {
|
|
63
|
+
const value = typeof input === "string"
|
|
64
|
+
? { value: input, ...(/^\d{8}$/.test(input) ? { valueType: "DATE" as const } : {}) }
|
|
65
|
+
: input;
|
|
66
|
+
if (value.tzid !== undefined && !/^[a-z0-9_+\-/]+$/i.test(value.tzid))
|
|
67
|
+
invalid("TZID 必须是明确且可解析的时区标识。");
|
|
68
|
+
const time = context.ical.parseCalendarTime(value.value, value);
|
|
69
|
+
if (time.unresolvedReason !== null) invalid("时间或时区无法唯一解释,不能猜测当地时间。");
|
|
70
|
+
return `${name}${time.kind === "date" ? ";VALUE=DATE" : time.tzid ? `;TZID=${time.tzid}` : ""}:${time.value}`;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function recurrenceLine(value: string): string {
|
|
74
|
+
if (!value || /[\r\n]/.test(value)) invalid("rrule 只接收单行规则值,不包含 RRULE:。");
|
|
75
|
+
return `RRULE:${value}`;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function selector(input: CalendarUpdateInput, kind: CalendarComponentKind) {
|
|
79
|
+
if (input.recurrenceId !== undefined &&
|
|
80
|
+
(!/^RECURRENCE-ID[;:]/i.test(input.recurrenceId) || /[\r\n]/.test(input.recurrenceId)))
|
|
81
|
+
invalid("例外选择器必须是完整 RECURRENCE-ID 逻辑行,不能使用裸时间或展开实例身份。");
|
|
82
|
+
return { kind, uid: input.uid, ...(input.recurrenceId === undefined ? {} : { recurrenceId: input.recurrenceId }) };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function selectComponent(context: DavReadContext, raw: string, input: CalendarUpdateInput, kind: CalendarComponentKind) {
|
|
86
|
+
const components = contentOperation(() => context.ical.parseCalendar(raw), "DATA_INVALID").components
|
|
87
|
+
.filter(component => component.kind === kind && component.uid === input.uid &&
|
|
88
|
+
component.recurrenceId === (input.recurrenceId ?? null));
|
|
89
|
+
if (components.length > 1) throw new DavToolError("AMBIGUOUS_TARGET", "资源内目标组件不唯一,未执行写入。");
|
|
90
|
+
const component = components[0];
|
|
91
|
+
if (!component) throw new DavToolError("NOT_FOUND", "资源内未找到指定组件;不能隐式创建例外。");
|
|
92
|
+
if (component.properties.some(property => property.name === "RECURRENCE-ID" && property.parameters.RANGE !== undefined))
|
|
93
|
+
throw new DavToolError("RECURRENCE_UNSUPPORTED", "不支持 RECURRENCE-ID 带 RANGE 的目标。");
|
|
94
|
+
return component;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function nextSequence(component: CalendarComponent): number {
|
|
98
|
+
const values = component.properties.filter(property => property.name === "SEQUENCE");
|
|
99
|
+
if (values.length === 0) return 1;
|
|
100
|
+
const property = values[0]!;
|
|
101
|
+
const type = property.parameters.VALUE;
|
|
102
|
+
const sequence = Number(property.rawValue);
|
|
103
|
+
if (values.length !== 1 || (type && (type.length !== 1 || type[0]?.toUpperCase() !== "INTEGER")) ||
|
|
104
|
+
!/^\+?\d+$/.test(property.rawValue) || !Number.isSafeInteger(sequence) || sequence >= Number.MAX_SAFE_INTEGER)
|
|
105
|
+
throw new DavToolError("DATA_INVALID", "源 SEQUENCE 无效、重复或无法安全递增,未执行写入。");
|
|
106
|
+
return sequence + 1;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function createCalendar(context: DavReadContext, input: CalendarCreateInput, kind: CalendarComponentKind) {
|
|
110
|
+
validateFields(input, kind);
|
|
111
|
+
if (typeof input.summary !== "string") invalid("创建必须提供 summary。");
|
|
112
|
+
if (kind === "VEVENT" && input.start == null) invalid("创建事件必须提供 start。");
|
|
113
|
+
if (kind === "VJOURNAL" && input.date == null) invalid("创建日记必须明确提供 date,不使用默认当天。");
|
|
114
|
+
const raw = contentOperation(() => {
|
|
115
|
+
const properties = [...(input.properties ?? []), `LAST-MODIFIED:${utcStamp()}`, "SEQUENCE:0"];
|
|
116
|
+
for (const [field, name] of [["start", "DTSTART"], ["end", "DTEND"], ["due", "DUE"], ["date", "DTSTART"]] as const) {
|
|
117
|
+
const value = input[field];
|
|
118
|
+
if (value === null) invalid("创建时间字段不能为 null。");
|
|
119
|
+
if (value !== undefined) properties.push(createTime(context, name, value));
|
|
120
|
+
}
|
|
121
|
+
if (input.rrule === null) invalid("创建 rrule 不能为 null。");
|
|
122
|
+
if (input.rrule !== undefined) properties.push(recurrenceLine(input.rrule));
|
|
123
|
+
let data = context.ical.buildCalendarComponent({ kind, summary: input.summary, properties, alarms: input.alarms });
|
|
124
|
+
const component = context.ical.parseCalendar(data).components[0]!;
|
|
125
|
+
const edit: CalendarComponentEdit = {};
|
|
126
|
+
for (const field of ["description", "location", "status"] as const) {
|
|
127
|
+
if (input[field] === null) invalid("创建文字字段不能为 null。");
|
|
128
|
+
if (input[field] !== undefined) edit[field] = input[field];
|
|
129
|
+
}
|
|
130
|
+
data = context.ical.updateCalendarComponent(data, { kind, uid: component.uid }, edit);
|
|
131
|
+
return { data, uid: component.uid };
|
|
132
|
+
});
|
|
133
|
+
const resourceUrl = createResourceUrl(input.collectionUrl, "ics");
|
|
134
|
+
context.writeIdentity = { account: input.account, kind, uid: raw.uid };
|
|
135
|
+
const etag = await context.client.create(resourceUrl, raw.data, contentType);
|
|
136
|
+
return { account: input.account, kind, resourceUrl, uid: raw.uid, etag, outcome: "created" as const };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export async function updateCalendar(context: DavReadContext, input: CalendarUpdateInput, kind: CalendarComponentKind) {
|
|
140
|
+
validateFields(input, kind);
|
|
141
|
+
const target = selector(input, kind);
|
|
142
|
+
const resource = await getVersionedResource(context, input);
|
|
143
|
+
const component = selectComponent(context, resource.data, input, kind);
|
|
144
|
+
const edited = contentOperation(() => {
|
|
145
|
+
const edit: CalendarComponentEdit = { properties: [...(input.properties ?? [])],
|
|
146
|
+
removeProperties: [...(input.removeProperties ?? [])], alarms: input.alarms };
|
|
147
|
+
for (const field of ["summary", "description", "location", "status", "start", "end", "due"] as const) {
|
|
148
|
+
if (input[field] !== undefined) Object.assign(edit, { [field]: input[field] });
|
|
149
|
+
}
|
|
150
|
+
if (input.date !== undefined) edit.start = input.date;
|
|
151
|
+
if (input.rrule === null) edit.removeProperties!.push("RRULE");
|
|
152
|
+
else if (input.rrule !== undefined) edit.properties!.push(recurrenceLine(input.rrule));
|
|
153
|
+
return context.ical.updateCalendarComponent(resource.data, target, edit);
|
|
154
|
+
});
|
|
155
|
+
if (edited === resource.data)
|
|
156
|
+
return { account: input.account, kind, resourceUrl: input.resourceUrl, uid: input.uid, etag: input.etag, outcome: "unchanged" as const };
|
|
157
|
+
const sequence = nextSequence(component), stamp = utcStamp();
|
|
158
|
+
const data = contentOperation(() => context.ical.updateCalendarComponent(edited, target,
|
|
159
|
+
{ properties: [`DTSTAMP:${stamp}`, `LAST-MODIFIED:${stamp}`, `SEQUENCE:${sequence}`] }));
|
|
160
|
+
const etag = await context.client.update(input.resourceUrl, data, input.etag, contentType);
|
|
161
|
+
return { account: input.account, kind, resourceUrl: input.resourceUrl, uid: input.uid, etag, outcome: "updated" as const };
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
export async function deleteCalendar(context: DavReadContext, input: CalendarDeleteInput, kind: CalendarComponentKind) {
|
|
165
|
+
if ("recurrenceId" in input) invalid("删除针对整份资源,不接受 recurrenceId。");
|
|
166
|
+
const resource = await getVersionedResource(context, input);
|
|
167
|
+
contentOperation(() => context.ical.assertCalendarResourceIdentity(resource.data, { kind, uid: input.uid }), "DATA_INVALID");
|
|
168
|
+
await context.client.delete(input.resourceUrl, input.etag);
|
|
169
|
+
return { account: input.account, kind, resourceUrl: input.resourceUrl, uid: input.uid, etag: input.etag, outcome: "deleted" as const };
|
|
170
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import type { CalendarComponent, CalendarComponentKind, CalendarProperty } from "davkit/ical";
|
|
2
|
+
import { DavToolError, type CalendarGetInput, type CalendarListInput, type DavReadContext } from "./types.ts";
|
|
3
|
+
|
|
4
|
+
function invalidData(): never {
|
|
5
|
+
throw new DavToolError("DATA_INVALID", "日历源数据无效或无法完整解释,未返回部分结果");
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
function parse(context: DavReadContext, raw: string) {
|
|
9
|
+
try { return context.ical.parseCalendar(raw); }
|
|
10
|
+
catch { return invalidData(); }
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** 日期是否合法由公开库校验;Date 只转换显式 offset,不丢弃非零毫秒。 */
|
|
14
|
+
function windowTime(context: DavReadContext, value: string | undefined): { value: string; instant: number } {
|
|
15
|
+
try {
|
|
16
|
+
if (!value) throw new Error();
|
|
17
|
+
let basic = value;
|
|
18
|
+
if (basic.length !== 16 || !/^\d{8}T\d{6}Z$/.test(basic)) {
|
|
19
|
+
const iso = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.000)?(Z|[+-]\d{2}:\d{2})$/.exec(value);
|
|
20
|
+
if (!iso) throw new Error();
|
|
21
|
+
// Date 会把 2 月 30 日等输入归一化,须先验证原始墙钟字段。
|
|
22
|
+
context.ical.parseCalendarTime(`${iso[1]}${iso[2]}${iso[3]}T${iso[4]}${iso[5]}${iso[6]}`);
|
|
23
|
+
basic = new Date(value).toISOString().replace(/[-:]/g, "").replace(".000", "");
|
|
24
|
+
}
|
|
25
|
+
const time = context.ical.parseCalendarTime(basic);
|
|
26
|
+
if (time.kind !== "utc" || time.epochMilliseconds === null) throw new Error();
|
|
27
|
+
return { value: basic, instant: time.epochMilliseconds };
|
|
28
|
+
} catch {
|
|
29
|
+
throw new DavToolError("INVALID_INPUT", "事件时间窗须为有效的秒精度基本 UTC 时间或带显式 Z/offset 的 ISO 8601 时间");
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function eventWindow(context: DavReadContext, input: CalendarListInput) {
|
|
34
|
+
const start = windowTime(context, input.start), end = windowTime(context, input.end);
|
|
35
|
+
if (start.instant >= end.instant) throw new DavToolError("INVALID_INPUT", "事件时间窗的 start 必须早于 end");
|
|
36
|
+
const timeZone = input.timeZone ?? context.timeZone;
|
|
37
|
+
if (!timeZone) throw new DavToolError("TIMEZONE_REQUIRED", "事件展开需要显式指定 timeZone 或配置账户时区");
|
|
38
|
+
try { new Intl.DateTimeFormat("en-US", { timeZone }); }
|
|
39
|
+
catch { throw new DavToolError("INVALID_INPUT", "事件展开时区无效"); }
|
|
40
|
+
return { start: start.value, end: end.value, timeZone };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function rejectRange(component: CalendarComponent) {
|
|
44
|
+
if (component.properties.some(property => property.name === "RECURRENCE-ID" && property.parameters.RANGE !== undefined)) {
|
|
45
|
+
throw new DavToolError("RECURRENCE_UNSUPPORTED", "不支持 RECURRENCE-ID 带 RANGE 的目标");
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function matches(component: CalendarComponent, input: CalendarListInput, kind: CalendarComponentKind) {
|
|
50
|
+
return component.kind === kind && (input.uid === undefined || component.uid === input.uid) &&
|
|
51
|
+
(input.status === undefined || component.status?.toUpperCase() === input.status.toUpperCase());
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function summary(component: CalendarComponent) {
|
|
55
|
+
return { kind: component.kind, uid: component.uid, summary: component.summary,
|
|
56
|
+
location: component.location, status: component.status };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 存储组件只投影时间,不自行解释 floating/DATE 为某个时区的 instant。 */
|
|
60
|
+
function storedTimes(context: DavReadContext, component: CalendarComponent) {
|
|
61
|
+
const fields = { DTSTART: "start", DTEND: "end", DUE: "due", COMPLETED: "completed",
|
|
62
|
+
CREATED: "created", "LAST-MODIFIED": "lastModified", DTSTAMP: "dtstamp" } as const;
|
|
63
|
+
const times: Partial<Record<(typeof fields)[keyof typeof fields], ReturnType<DavReadContext["ical"]["parseCalendarTime"]>>> = {};
|
|
64
|
+
try {
|
|
65
|
+
for (const [name, field] of Object.entries(fields)) {
|
|
66
|
+
const found = component.properties.filter(property => property.name === name);
|
|
67
|
+
if (found.length > 1) return invalidData();
|
|
68
|
+
const property = found[0];
|
|
69
|
+
if (!property) continue;
|
|
70
|
+
const values = property.parameters.VALUE, zones = property.parameters.TZID;
|
|
71
|
+
const type = values?.[0]?.toUpperCase();
|
|
72
|
+
if ((values && values.length !== 1) || (zones && zones.length !== 1) ||
|
|
73
|
+
(type !== undefined && type !== "DATE" && type !== "DATE-TIME")) return invalidData();
|
|
74
|
+
const options: Parameters<DavReadContext["ical"]["parseCalendarTime"]>[1] = {};
|
|
75
|
+
if (type !== undefined) options.valueType = type;
|
|
76
|
+
if (zones) options.tzid = zones[0];
|
|
77
|
+
const time = context.ical.parseCalendarTime(property.rawValue, options);
|
|
78
|
+
if (time.unresolvedReason !== null) return invalidData();
|
|
79
|
+
times[field] = time;
|
|
80
|
+
}
|
|
81
|
+
return times;
|
|
82
|
+
} catch { return invalidData(); }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function propertyDetails({ raw: _raw, ...property }: CalendarProperty) { return property; }
|
|
86
|
+
|
|
87
|
+
export async function listCalendar(context: DavReadContext, input: CalendarListInput, kind: CalendarComponentKind) {
|
|
88
|
+
if (kind === "VEVENT") {
|
|
89
|
+
const window = eventWindow(context, input);
|
|
90
|
+
// 服务端解释 floating 的时区可能不同;只筛组件,避免时间窗预筛选漏项。
|
|
91
|
+
const resources = await context.client.query(input.collectionUrl, "calendar", { component: kind });
|
|
92
|
+
const items = resources.flatMap(resource => {
|
|
93
|
+
for (const component of parse(context, resource.data).components) {
|
|
94
|
+
if (component.kind === kind) rejectRange(component);
|
|
95
|
+
}
|
|
96
|
+
let occurrences: ReturnType<DavReadContext["ical"]["expandEvents"]>;
|
|
97
|
+
try { occurrences = context.ical.expandEvents(resource.data, window); }
|
|
98
|
+
catch { return invalidData(); }
|
|
99
|
+
return occurrences.filter(occurrence => matches(occurrence.component, input, kind)).map(occurrence => ({
|
|
100
|
+
resourceUrl: resource.url, etag: resource.etag, ...summary(occurrence.component),
|
|
101
|
+
// 展开身份仅是发生时间值;存储选择器是完整逻辑行,两者不可互换。
|
|
102
|
+
recurrenceId: occurrence.recurrenceId, storedRecurrenceId: occurrence.component.recurrenceId,
|
|
103
|
+
start: occurrence.start, end: occurrence.end,
|
|
104
|
+
startInstant: occurrence.startInstant, endInstant: occurrence.endInstant,
|
|
105
|
+
}));
|
|
106
|
+
});
|
|
107
|
+
items.sort((left, right) => left.startInstant - right.startInstant);
|
|
108
|
+
return { complete: true, account: input.account, collectionUrl: input.collectionUrl,
|
|
109
|
+
kind, expanded: true, start: window.start, end: window.end, timeZone: window.timeZone, items };
|
|
110
|
+
}
|
|
111
|
+
const resources = await context.client.query(input.collectionUrl, "calendar", { component: kind });
|
|
112
|
+
const items = resources.flatMap(resource => parse(context, resource.data).components
|
|
113
|
+
.filter(component => component.kind === kind)
|
|
114
|
+
.map(component => ({ component, times: storedTimes(context, component) }))
|
|
115
|
+
.filter(({ component }) => matches(component, input, kind))
|
|
116
|
+
.map(({ component, times }) => ({ resourceUrl: resource.url, etag: resource.etag, ...summary(component),
|
|
117
|
+
recurrenceId: component.recurrenceId, storedRecurrenceId: component.recurrenceId, ...times })));
|
|
118
|
+
return { complete: true, account: input.account, collectionUrl: input.collectionUrl, kind, storedComponents: true, items };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export async function getCalendar(context: DavReadContext, input: CalendarGetInput, kind: CalendarComponentKind) {
|
|
122
|
+
const resource = await context.client.get(input.resourceUrl);
|
|
123
|
+
const components = parse(context, resource.data).components.filter(component => component.kind === kind &&
|
|
124
|
+
component.uid === input.uid && component.recurrenceId === (input.recurrenceId ?? null));
|
|
125
|
+
if (components.length > 1) throw new DavToolError("AMBIGUOUS_TARGET", "资源内存在多个匹配组件,无法唯一选择目标");
|
|
126
|
+
const component = components[0];
|
|
127
|
+
if (!component) throw new DavToolError("NOT_FOUND", "资源内未找到指定的日历组件");
|
|
128
|
+
rejectRange(component);
|
|
129
|
+
const result = { account: input.account, resourceUrl: resource.url, etag: resource.etag,
|
|
130
|
+
...summary(component), recurrenceId: component.recurrenceId, description: component.description,
|
|
131
|
+
...storedTimes(context, component), properties: component.properties.map(propertyDetails),
|
|
132
|
+
alarms: component.alarms.map(alarm => ({ properties: alarm.properties.map(propertyDetails) })),
|
|
133
|
+
};
|
|
134
|
+
const response: typeof result & { raw?: string } = result;
|
|
135
|
+
if (input.raw === true) response.raw = resource.data;
|
|
136
|
+
return response;
|
|
137
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import type { DavKind } from "davkit/dav";
|
|
2
|
+
import type { DavAccountConfig } from "./config.ts";
|
|
3
|
+
import { DavToolError, type DavReadContext } from "./types.ts";
|
|
4
|
+
|
|
5
|
+
export function supportsDavNode(version: string): boolean {
|
|
6
|
+
return /^(\d+)\./.test(version) && Number(version.split(".")[0]) >= 24;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** 每次调用独立客户端与取消信号;记录写入确认状态,不缓存密码或自动重试。 */
|
|
10
|
+
export async function withDavAccount<T>(
|
|
11
|
+
config: DavAccountConfig,
|
|
12
|
+
signal: AbortSignal | undefined,
|
|
13
|
+
handler: (context: DavReadContext) => Promise<T>,
|
|
14
|
+
options: { discoveryKind?: DavKind; fetch?: typeof globalThis.fetch } = {},
|
|
15
|
+
): Promise<T> {
|
|
16
|
+
if (!supportsDavNode(process.versions.node))
|
|
17
|
+
throw new DavToolError("DAV_UNAVAILABLE", "DAV 业务调用需要 Node.js 24 或更新版本;其他插件能力不受影响。");
|
|
18
|
+
signal?.throwIfAborted();
|
|
19
|
+
const library = await loadLibrary();
|
|
20
|
+
const base = new URL(config.url);
|
|
21
|
+
// 根地址可能是管理门户,按标准协议入口发现;明确路径则按配置使用,不试探厂商私有路径。
|
|
22
|
+
const entry = options.discoveryKind && base.pathname === "/"
|
|
23
|
+
? new URL(`/.well-known/${options.discoveryKind === "calendar" ? "caldav" : "carddav"}`, base).href
|
|
24
|
+
: config.url;
|
|
25
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
26
|
+
const mutation: { method?: string; resourceUrl?: string; status?: number } = {};
|
|
27
|
+
const writeConfirmed = () => mutation.status !== undefined
|
|
28
|
+
&& (mutation.method === "PUT" ? [200, 201, 204] : [200, 204]).includes(mutation.status);
|
|
29
|
+
const makeClient = (baseUrl: string, observe?: (url: string, response: Response) => void) => new library.dav.DavClient({
|
|
30
|
+
baseUrl, basicAuth: { username: config.user, password: config.password },
|
|
31
|
+
fetch: async (url, init) => {
|
|
32
|
+
const signals = [signal, init?.signal].filter((value): value is AbortSignal => !!value);
|
|
33
|
+
const requestSignal = signals.length ? AbortSignal.any(signals) : undefined;
|
|
34
|
+
const writing = init?.method === "PUT" || init?.method === "DELETE";
|
|
35
|
+
if (writing) {
|
|
36
|
+
requestSignal?.throwIfAborted();
|
|
37
|
+
mutation.method = init.method;
|
|
38
|
+
mutation.resourceUrl = String(url);
|
|
39
|
+
}
|
|
40
|
+
const response = await fetchImpl(url, { ...init, signal: requestSignal, redirect: "manual" });
|
|
41
|
+
if (writing) mutation.status = response.status;
|
|
42
|
+
observe?.(String(url), response);
|
|
43
|
+
return response;
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
const client = makeClient(config.url);
|
|
47
|
+
if (options.discoveryKind) client.discover = async kind => {
|
|
48
|
+
let endpoint = entry;
|
|
49
|
+
for (let redirects = 0; ; redirects++) {
|
|
50
|
+
let next: string | undefined;
|
|
51
|
+
let invalid = false;
|
|
52
|
+
const discovery = makeClient(endpoint, (url, response) => {
|
|
53
|
+
if (![301, 302, 307, 308].includes(response.status)) return;
|
|
54
|
+
const location = response.headers.get("location");
|
|
55
|
+
try {
|
|
56
|
+
const target = location ? new URL(location, url) : undefined;
|
|
57
|
+
if (!target || redirects >= 3 || target.origin !== base.origin || target.username || target.password || target.hash) invalid = true;
|
|
58
|
+
else next = target.href;
|
|
59
|
+
} catch { invalid = true; }
|
|
60
|
+
});
|
|
61
|
+
try { return await discovery.discover(kind); }
|
|
62
|
+
catch (error) {
|
|
63
|
+
if (invalid) throw new DavToolError("DISCOVERY_FAILED", "DAV 发现跳转无效、过多或跨源;未转发认证。");
|
|
64
|
+
if (!next) throw error;
|
|
65
|
+
// 由库重新执行发现,确保相对 href 以新入口解析;资源 GET/REPORT 不跟随跳转。
|
|
66
|
+
endpoint = next;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
const context: DavReadContext = { client, ical: library.ical, vcard: library.vcard,
|
|
71
|
+
...(config.timeZone === undefined ? {} : { timeZone: config.timeZone }) };
|
|
72
|
+
try {
|
|
73
|
+
const data = await handler(context);
|
|
74
|
+
// 已确认的写入不因随后取消被降为失败;调用方不做写后回读。
|
|
75
|
+
if (!writeConfirmed()) signal?.throwIfAborted();
|
|
76
|
+
return data;
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (error instanceof DavToolError) throw error;
|
|
79
|
+
if (mutation.method && (mutation.status === undefined
|
|
80
|
+
|| (mutation.status >= 200 && mutation.status < 300 && !writeConfirmed())))
|
|
81
|
+
throw new DavToolError("REMOTE_RESULT_UNKNOWN", "写入请求已发出,但远端结果尚未确认;不能假定未生效。请先读取目标资源核对,不会自动重发或补偿。",
|
|
82
|
+
{ ...context.writeIdentity, method: mutation.method, resourceUrl: mutation.resourceUrl });
|
|
83
|
+
if (error instanceof library.dav.DavConflictError)
|
|
84
|
+
throw new DavToolError("CONFLICT", "条件写入发生版本或创建冲突,未自动重试;请重新读取并确认变更。");
|
|
85
|
+
if (error instanceof library.dav.DavError && (error.status !== null || !signal?.aborted)) {
|
|
86
|
+
const code = error.status === 401 || error.status === 403 ? "DAV_AUTH_FAILED"
|
|
87
|
+
: error.status === 404 ? "NOT_FOUND" : "DAV_FAILED";
|
|
88
|
+
const status = error.status === null ? "连接或响应读取失败" : `HTTP ${error.status}`;
|
|
89
|
+
throw new DavToolError(code, `DAV 请求失败(${status}),未自动重试;请核对服务入口、账户与权限。`);
|
|
90
|
+
}
|
|
91
|
+
if (signal?.aborted) throw new DavToolError("ABORTED", "DAV 操作已取消,未发出写入请求。");
|
|
92
|
+
if (error instanceof library.dav.DavProtocolError)
|
|
93
|
+
throw new DavToolError("DAV_PROTOCOL", "服务器未返回有效 DAV 数据;请核对服务入口,不把网页响应视为认证成功。");
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
async function loadLibrary() {
|
|
99
|
+
try {
|
|
100
|
+
const [dav, ical, vcard] = await Promise.all([import("davkit/dav"), import("davkit/ical"), import("davkit/vcard")]);
|
|
101
|
+
return { dav, ical, vcard };
|
|
102
|
+
} catch {
|
|
103
|
+
throw new DavToolError("DAV_UNAVAILABLE", "DAV 可选依赖不可用;请按正常包管理流程安装包含 optional 依赖的插件,不会自动安装或切换旧 MCP。");
|
|
104
|
+
}
|
|
105
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
export interface DavAccountConfig {
|
|
2
|
+
url: string;
|
|
3
|
+
user: string;
|
|
4
|
+
password: string;
|
|
5
|
+
timeZone?: string;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export class DavConfigError extends Error {}
|
|
9
|
+
|
|
10
|
+
/** 只校验 dav 组,不读文件或连接服务器;错误不得包含账户键值。 */
|
|
11
|
+
export function parseDavAccounts(raw: unknown): Record<string, DavAccountConfig> {
|
|
12
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw))
|
|
13
|
+
throw new DavConfigError("DAV 配置无效:dav 必须是账户 ID 到配置的映射对象。");
|
|
14
|
+
const entries: [string, DavAccountConfig][] = [];
|
|
15
|
+
for (const [id, value] of Object.entries(raw)) {
|
|
16
|
+
const fail = (): never => { throw new DavConfigError("DAV 配置无效:请核对账户 ID、HTTPS url、user、非空 password 及可选的 IANA timeZone;不要在聊天中提交密码。"); };
|
|
17
|
+
if (!id || /[\u0000-\u001f\u007f]/.test(id) || value === null || typeof value !== "object" || Array.isArray(value)) fail();
|
|
18
|
+
const item = value as Record<string, unknown>;
|
|
19
|
+
if (Object.keys(item).some(key => !["url", "user", "password", "timeZone"].includes(key))) fail();
|
|
20
|
+
const { url, user, password, timeZone } = item;
|
|
21
|
+
if (typeof url !== "string" || typeof user !== "string" || typeof password !== "string" || !password.length) fail();
|
|
22
|
+
if (!user || /[:\u0000-\u001f\u007f]/.test(user as string) || /[\s\u0000-\u001f\u007f]/.test(url as string)) fail();
|
|
23
|
+
try {
|
|
24
|
+
const address = new URL(url as string);
|
|
25
|
+
if (address.protocol !== "https:" || address.username || address.password || address.hash || address.search) fail();
|
|
26
|
+
if (timeZone !== undefined) {
|
|
27
|
+
if (typeof timeZone !== "string" || !timeZone) fail();
|
|
28
|
+
new Intl.DateTimeFormat("en", { timeZone: timeZone as string });
|
|
29
|
+
}
|
|
30
|
+
} catch { fail(); }
|
|
31
|
+
entries.push([id, { url: url as string, user: user as string, password: password as string,
|
|
32
|
+
...(timeZone === undefined ? {} : { timeZone: timeZone as string }) }]);
|
|
33
|
+
}
|
|
34
|
+
return Object.fromEntries(entries);
|
|
35
|
+
}
|