@kamilio/wire 0.1.13 → 0.1.15
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 +13 -0
- package/dist/adapters/root.d.ts +2 -2
- package/dist/adapters/root.d.ts.map +1 -1
- package/dist/adapters/root.js +25 -6
- package/dist/adapters/root.js.map +1 -1
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +9 -5
- package/dist/cli.js.map +1 -1
- package/dist/executable.d.ts.map +1 -1
- package/dist/executable.js +3 -2
- package/dist/executable.js.map +1 -1
- package/node_modules/provider-notion/dist/index.d.ts +1 -0
- package/node_modules/provider-notion/dist/index.d.ts.map +1 -1
- package/node_modules/provider-notion/dist/index.js +1 -0
- package/node_modules/provider-notion/dist/index.js.map +1 -1
- package/node_modules/provider-notion/dist/notion-sync.d.ts +3 -1
- package/node_modules/provider-notion/dist/notion-sync.d.ts.map +1 -1
- package/node_modules/provider-notion/dist/notion-sync.js +153 -22
- package/node_modules/provider-notion/dist/notion-sync.js.map +1 -1
- package/node_modules/provider-notion/src/index.ts +2 -0
- package/node_modules/provider-notion/src/notion-sync.ts +139 -23
- package/node_modules/provider-slack/dist/index.d.ts +1 -1
- package/node_modules/provider-slack/dist/index.d.ts.map +1 -1
- package/node_modules/provider-slack/dist/index.js +1 -1
- package/node_modules/provider-slack/dist/index.js.map +1 -1
- package/node_modules/provider-slack/dist/slack.d.ts +3 -0
- package/node_modules/provider-slack/dist/slack.d.ts.map +1 -1
- package/node_modules/provider-slack/dist/slack.js +111 -20
- package/node_modules/provider-slack/dist/slack.js.map +1 -1
- package/node_modules/provider-slack/src/index.ts +1 -1
- package/node_modules/provider-slack/src/slack.ts +101 -19
- package/package.json +1 -1
- package/src/adapters/root.ts +26 -7
- package/src/cli.ts +5 -3
- package/src/executable.ts +4 -2
|
@@ -11,6 +11,7 @@ export type NotionOperation = Readonly<{ pointer: JsonObject; path: readonly Jso
|
|
|
11
11
|
export type NotionSidecarBlock = Readonly<{ id: string; path: readonly number[]; type: string; hash: string; snapshot: JsonObject }>;
|
|
12
12
|
export type NotionDiffSummary = Readonly<{ inserted: number; updated: number; deleted: number; moved: number }>;
|
|
13
13
|
type UserMentions = Readonly<Record<string, string>>;
|
|
14
|
+
type EmailMentions = Record<string, string>;
|
|
14
15
|
|
|
15
16
|
function object(value: JsonValue): JsonObject { return value as JsonObject; }
|
|
16
17
|
function array(value: JsonValue): JsonValue[] { return value as JsonValue[]; }
|
|
@@ -250,8 +251,8 @@ function baseUserMentions(base: JsonObject): UserMentions | undefined {
|
|
|
250
251
|
return base["user_mentions"] as UserMentions | undefined;
|
|
251
252
|
}
|
|
252
253
|
|
|
253
|
-
function notionData(pageId: string, markdown: string, tree: NotionTree, mentions: UserMentions | undefined): JsonObject {
|
|
254
|
-
return
|
|
254
|
+
function notionData(pageId: string, markdown: string, tree: NotionTree, mentions: UserMentions | undefined, emailMentions: EmailMentions = {}): JsonObject {
|
|
255
|
+
return { page_id: pageId, markdown, blocks: sidecarBlocksFromNotionTree(tree), ...(mentions === undefined ? {} : { user_mentions: mentions }), ...(Object.keys(emailMentions).length === 0 ? {} : { email_mentions: emailMentions }) };
|
|
255
256
|
}
|
|
256
257
|
|
|
257
258
|
function lineIndent(line: string): number { return Math.floor(line.match(/^ */)![0].length / 2); }
|
|
@@ -830,14 +831,15 @@ function renderNode(tree: NotionTree, indent: number, parentType = ""): string[]
|
|
|
830
831
|
return title.split("\n").map((line) => `${prefix}${escapeBlockMarkdownLine(line)}`);
|
|
831
832
|
}
|
|
832
833
|
|
|
833
|
-
export function renderNotionTreeToMarkdown(tree: NotionTree, mentions?: UserMentions): string {
|
|
834
|
+
export function renderNotionTreeToMarkdown(tree: NotionTree, mentions?: UserMentions, emailMentions: EmailMentions = {}): string {
|
|
834
835
|
const title = renderRichText(object(tree.block["properties"]!)["title"]!);
|
|
835
836
|
const compactTypes = new Set(["bulleted_list", "numbered_list", "to_do"]);
|
|
836
837
|
const body = tree.children.flatMap((child, index) => [
|
|
837
838
|
...(index === 0 || (tree.children[index - 1]!.block["type"] === child.block["type"] && compactTypes.has(child.block["type"] as string)) ? [] : [""]),
|
|
838
839
|
...renderNode(child, 0),
|
|
839
840
|
]);
|
|
840
|
-
|
|
841
|
+
let markdown = [`# ${title}`, ...body.length === 0 ? [] : ["", ...body]].join("\n").trim();
|
|
842
|
+
for (const [id, link] of Object.entries(emailMentions)) markdown = markdown.replace(new RegExp(`<span data-notion-mention="u" data-notion-id="${escapeRegExp(escapeHtml(id))}">.*?</span>`, "g"), () => link);
|
|
841
843
|
return mentions === undefined ? markdown : renderUserMentions(markdown, mentions);
|
|
842
844
|
}
|
|
843
845
|
|
|
@@ -847,7 +849,118 @@ async function notionPost(runtime: RuntimeCapabilities, path: string, cookie: st
|
|
|
847
849
|
return await response.json() as JsonObject;
|
|
848
850
|
}
|
|
849
851
|
|
|
850
|
-
async function
|
|
852
|
+
async function findNotionUsers(runtime: RuntimeCapabilities, query: string, cookie: string, spaceId: string, headers: HeadersInit): Promise<readonly JsonObject[]> {
|
|
853
|
+
query = query.trim();
|
|
854
|
+
if (query === "") throw new Error("Notion user lookup requires an email or name");
|
|
855
|
+
const response = await notionPost(runtime, "getVisibleUsers", cookie, { spaceId }, headers);
|
|
856
|
+
const users = response["users"] as readonly JsonObject[];
|
|
857
|
+
if (/^[^@\s]+@[^@\s]+$/.test(query)) return users.filter((user) => (user["aliases"] as readonly string[] | undefined)?.some((email) => email.toLowerCase() === query.toLowerCase()));
|
|
858
|
+
if (users.length === 0) return [];
|
|
859
|
+
const records = await notionPost(runtime, "getRecordValues", cookie, { requests: users.map((user) => ({ table: "notion_user", id: user["userId"]! })) }, headers);
|
|
860
|
+
const results = records["results"] as readonly JsonObject[];
|
|
861
|
+
return users.flatMap((user, index) => {
|
|
862
|
+
const profile = results[index]?.["value"] as JsonObject | undefined;
|
|
863
|
+
const name = profile?.["name"] as string | undefined ?? "";
|
|
864
|
+
const names = [name, ...(user["aliases"] as readonly string[] | undefined ?? [])];
|
|
865
|
+
return query.toLowerCase().split(/\s+/).every((word) => names.some((value) => value.toLowerCase().includes(word))) ? [{ ...user, name }] : [];
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
export async function lookupNotionUsers(runtime: RuntimeCapabilities, query: string): Promise<readonly JsonObject[]> {
|
|
870
|
+
const cookies = await runtime.cookies.loadSaved("notion");
|
|
871
|
+
if (cookies === null) throw notionAuthError();
|
|
872
|
+
const cookie = cookies.map((value) => `${value.name}=${value.value}`).join("; ");
|
|
873
|
+
const userId = cookies.find((value) => value.name === "notion_user_id")!.value;
|
|
874
|
+
const spaces = await notionPost(runtime, "getSpaces", cookie, {}, {});
|
|
875
|
+
const spaceView = object(object(spaces[userId]!)["space_view"]!);
|
|
876
|
+
const ids = [...new Set(Object.values(spaceView).map((value) => object(value)["spaceId"] as string))];
|
|
877
|
+
const users: JsonObject[] = [];
|
|
878
|
+
for (const spaceId of ids) users.push(...await findNotionUsers(runtime, query, cookie, spaceId, { "x-notion-active-user-header": userId, "x-notion-space-id": spaceId }));
|
|
879
|
+
return [...new Map(users.map((user) => [user["userId"], user])).values()];
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
async function resolveNotionEmailMentions(runtime: RuntimeCapabilities, blocks: readonly NotionBlock[], cookie: string, spaceId: string, headers: HeadersInit, mentions: EmailMentions): Promise<void> {
|
|
883
|
+
const segments: NotionRichText = [];
|
|
884
|
+
const visit = (value: JsonValue): void => {
|
|
885
|
+
if (Array.isArray(value)) {
|
|
886
|
+
if (typeof value[0] === "string" && value[0].startsWith("@") && Array.isArray(value[1]) && value[1].some((mark) => Array.isArray(mark) && mark[0] === "a" && typeof mark[1] === "string" && mark[1].startsWith("mailto:"))) segments.push(value);
|
|
887
|
+
else for (const child of value) visit(child);
|
|
888
|
+
} else if (value !== null && typeof value === "object") for (const child of Object.values(value)) visit(child);
|
|
889
|
+
};
|
|
890
|
+
for (const block of blocks) {
|
|
891
|
+
if (block.type === "code" || block.properties["notion_opaque"] !== undefined) continue;
|
|
892
|
+
visit(block.rich_text);
|
|
893
|
+
visit(block.properties);
|
|
894
|
+
}
|
|
895
|
+
if (segments.length === 0) return;
|
|
896
|
+
const response = await notionPost(runtime, "getVisibleUsers", cookie, { spaceId }, headers);
|
|
897
|
+
const users = response["users"] as readonly JsonObject[];
|
|
898
|
+
for (const segment of segments) {
|
|
899
|
+
const marks = segment[1] as JsonValue[][];
|
|
900
|
+
const link = marks.find((mark) => mark[0] === "a" && (mark[1] as string).startsWith("mailto:"))!;
|
|
901
|
+
const email = decodeURIComponent((link[1] as string).slice(7));
|
|
902
|
+
if (!/^[^@\s?]+@[^@\s?]+$/.test(email)) throw new Error(`Invalid mention email: ${email}`);
|
|
903
|
+
const matches = users.filter((user) => (user["aliases"] as readonly string[] | undefined)?.some((alias) => alias.toLowerCase() === email.toLowerCase()));
|
|
904
|
+
if (matches.length !== 1) throw new Error(`Expected one Notion user for ${email}, found ${matches.length}`);
|
|
905
|
+
const id = matches[0]!["userId"] as string;
|
|
906
|
+
mentions[id] = `[${escapeInlineMarkdown(segment[0] as string)}](mailto:${email})`;
|
|
907
|
+
segment[0] = "‣";
|
|
908
|
+
link[0] = "u";
|
|
909
|
+
link[1] = id;
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
async function fetchComments(runtime: RuntimeCapabilities, tree: NotionTree, spaceId: string, cookie: string, headers: HeadersInit): Promise<string> {
|
|
914
|
+
const records: Record<string, Map<string, JsonObject>> = { discussion: new Map(), comment: new Map(), notion_user: new Map() };
|
|
915
|
+
let startingAfterId: string | undefined;
|
|
916
|
+
while (true) {
|
|
917
|
+
const data = await notionPost(runtime, "getActivityLog", cookie, { spaceId, navigableBlock: { id: tree.id }, limit: 100, ...(startingAfterId === undefined ? {} : { startingAfterId }) }, headers);
|
|
918
|
+
const recordMap = object(data["recordMap"]!);
|
|
919
|
+
for (const table of Object.keys(records)) {
|
|
920
|
+
if (recordMap[table] === undefined) continue;
|
|
921
|
+
for (const [id, wrapper] of Object.entries(object(recordMap[table]!))) {
|
|
922
|
+
const value = object(object(object(wrapper)["value"]!)["value"]!);
|
|
923
|
+
const previous = records[table]!.get(id);
|
|
924
|
+
if (previous === undefined || (value["version"] as number) >= (previous["version"] as number)) records[table]!.set(id, value);
|
|
925
|
+
}
|
|
926
|
+
}
|
|
927
|
+
const activityIds = data["activityIds"] as string[];
|
|
928
|
+
if (activityIds.length < 100) break;
|
|
929
|
+
startingAfterId = activityIds[activityIds.length - 1]!;
|
|
930
|
+
}
|
|
931
|
+
const blockIds = new Set(sidecarBlocksFromNotionTree(tree).map((block) => block.id));
|
|
932
|
+
const discussions = [...records["discussion"]!.values()].filter((discussion) => blockIds.has(discussion["parent_id"] as string) && discussion["alive"] !== false);
|
|
933
|
+
for (const table of ["comment", "notion_user"]) {
|
|
934
|
+
const ids = table === "comment" ? discussions.flatMap((discussion) => discussion["comments"] as string[]) : [...records["comment"]!.values()].filter((comment) => comment["alive"] === true).map((comment) => comment["created_by_id"] as string);
|
|
935
|
+
const missing = [...new Set(ids)].filter((id) => !records[table]!.has(id));
|
|
936
|
+
if (missing.length === 0) continue;
|
|
937
|
+
const data = await notionPost(runtime, "getRecordValues", cookie, { requests: missing.map((id) => ({ table, id })) }, headers);
|
|
938
|
+
for (const [index, result] of (data["results"] as JsonObject[]).entries()) records[table]!.set(missing[index]!, object(result["value"]!));
|
|
939
|
+
}
|
|
940
|
+
const threads = discussions.map((discussion) => {
|
|
941
|
+
const comments = (discussion["comments"] as string[]).map((id) => records["comment"]!.get(id)!).filter((comment) => comment["alive"] === true);
|
|
942
|
+
if (comments.length === 0) return "";
|
|
943
|
+
const context = discussion["context"] === undefined ? "" : renderRichText(discussion["context"]!);
|
|
944
|
+
const link = `https://www.notion.so/${tree.id.replaceAll("-", "")}#${(discussion["parent_id"] as string).replaceAll("-", "")}`;
|
|
945
|
+
return [
|
|
946
|
+
`### [${discussion["parent_id"] === tree.id ? "Page comment" : "Inline comment"}](${link})${discussion["resolved"] === true ? " (resolved)" : ""}`,
|
|
947
|
+
...(context === "" ? [] : [context.split("\n").map((line) => `> ${line}`).join("\n")]),
|
|
948
|
+
...comments.map((comment) => `**${escapeInlineMarkdown(records["notion_user"]!.get(comment["created_by_id"] as string)!["name"] as string)}** — ${new Date(comment["created_time"] as number).toISOString()}\n\n${renderRichText(comment["text"]!)}`),
|
|
949
|
+
].join("\n\n");
|
|
950
|
+
}).filter((thread) => thread !== "");
|
|
951
|
+
return threads.length === 0 ? "" : `\n\n<!-- wire:notion-comments -->\n\n## Comments (read-only)\n\n${threads.join("\n\n")}\n\n<!-- /wire:notion-comments -->`;
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
function withoutComments(markdown: string): string {
|
|
955
|
+
return markdown.replace(/\n\n<!-- wire:notion-comments -->[\s\S]*?<!-- \/wire:notion-comments -->/g, "");
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
function notionDocument(pageId: string, tree: NotionTree, mentions: UserMentions | undefined, emailMentions: EmailMentions, comments: string): FetchedDocument {
|
|
959
|
+
const markdown = renderNotionTreeToMarkdown(tree, mentions, emailMentions) + comments;
|
|
960
|
+
return { title: markdown.split("\n")[0]!.replace(/^# */, ""), markdown, data: notionData(pageId, markdown, tree, mentions, emailMentions) };
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
async function fetchTree(runtime: RuntimeCapabilities, url: string, source: Source): Promise<Readonly<{ tree: NotionTree; userId: string; spaceId: string; cookie: string; headers: HeadersInit; comments: string }>> {
|
|
851
964
|
const cookies = await runtime.cookies.loadSaved("notion");
|
|
852
965
|
if (cookies === null) throw notionAuthError();
|
|
853
966
|
const cookie = cookies.map((value) => `${value.name}=${value.value}`).join("; ");
|
|
@@ -893,17 +1006,18 @@ async function fetchTree(runtime: RuntimeCapabilities, url: string, source: Sour
|
|
|
893
1006
|
if (idValue !== pageId && block["type"] === "page") return { id: idValue, block, children: [] };
|
|
894
1007
|
return { id: idValue, block, children: (block["content"] as readonly string[] | undefined ?? []).filter((child) => blocks.get(child)?.["alive"] !== false).map(build) };
|
|
895
1008
|
};
|
|
896
|
-
|
|
1009
|
+
const tree = build(pageId);
|
|
1010
|
+
const comments = await fetchComments(runtime, tree, spaceId, cookie, headers);
|
|
1011
|
+
return { tree, userId, spaceId, cookie, headers, comments };
|
|
897
1012
|
}
|
|
898
1013
|
|
|
899
1014
|
export async function fetchNotionDocument(runtime: RuntimeCapabilities, url: string, source: Source): Promise<FetchedDocument> {
|
|
900
|
-
const { tree } = await fetchTree(runtime, url, source);
|
|
901
|
-
|
|
902
|
-
return { title: markdown.split("\n")[0]!.replace(/^# */, ""), markdown, data: notionData(source.identifier, markdown, tree, undefined) };
|
|
1015
|
+
const { tree, comments } = await fetchTree(runtime, url, source);
|
|
1016
|
+
return notionDocument(source.identifier, tree, undefined, {}, comments);
|
|
903
1017
|
}
|
|
904
1018
|
|
|
905
1019
|
export async function uploadNotionDocument(runtime: RuntimeCapabilities, markdown: string, _markdownPath: string): Promise<UploadedDocument> {
|
|
906
|
-
const split = splitTitle(markdown);
|
|
1020
|
+
const split = splitTitle(withoutComments(markdown));
|
|
907
1021
|
if (split.title === "") throw new Error("Markdown document requires a first heading");
|
|
908
1022
|
const cookies = await runtime.cookies.loadSaved("notion");
|
|
909
1023
|
if (cookies === null) throw notionAuthError();
|
|
@@ -940,6 +1054,8 @@ export async function uploadNotionDocument(runtime: RuntimeCapabilities, markdow
|
|
|
940
1054
|
},
|
|
941
1055
|
};
|
|
942
1056
|
const localBlocks = parseNotionMarkdown(split.body);
|
|
1057
|
+
const emailMentions: EmailMentions = {};
|
|
1058
|
+
await resolveNotionEmailMentions(runtime, localBlocks, cookie, spaceId, headers, emailMentions);
|
|
943
1059
|
const operations = [pageOperation, ...buildNotionCreateOperations(localBlocks, pageId, spaceId, userId, currentTime).operations];
|
|
944
1060
|
await notionPost(runtime, "saveTransactionsFanout", cookie, { requestId: randomUUID(), transactions: [{ id: randomUUID(), spaceId, operations }] }, headers);
|
|
945
1061
|
const pageTree: NotionTree = {
|
|
@@ -947,8 +1063,8 @@ export async function uploadNotionDocument(runtime: RuntimeCapabilities, markdow
|
|
|
947
1063
|
block: pageOperation.args as JsonObject,
|
|
948
1064
|
children: localTree(localBlocks).map((node) => outputNode(node, undefined, pageId, { spaceId, userId }, currentTime)),
|
|
949
1065
|
};
|
|
950
|
-
const output = renderNotionTreeToMarkdown(pageTree);
|
|
951
|
-
return { url: `https://www.notion.so/${compactPageId}`, title: split.title, markdown: output, data: notionData(compactPageId, output, pageTree, undefined) };
|
|
1066
|
+
const output = renderNotionTreeToMarkdown(pageTree, undefined, emailMentions);
|
|
1067
|
+
return { url: `https://www.notion.so/${compactPageId}`, title: split.title, markdown: output, data: notionData(compactPageId, output, pageTree, undefined, emailMentions) };
|
|
952
1068
|
}
|
|
953
1069
|
|
|
954
1070
|
function splitTitle(markdown: string): Readonly<{ title: string; body: string }> {
|
|
@@ -963,9 +1079,10 @@ export async function synchronizeNotionDocument(runtime: RuntimeCapabilities, ur
|
|
|
963
1079
|
const remote = await fetchTree(runtime, url, source);
|
|
964
1080
|
const baseObject = object(base);
|
|
965
1081
|
const mentions = baseUserMentions(baseObject);
|
|
966
|
-
const
|
|
967
|
-
const
|
|
968
|
-
|
|
1082
|
+
const emailMentions = { ...(baseObject["email_mentions"] as EmailMentions | undefined) };
|
|
1083
|
+
const currentMarkdown = renderNotionTreeToMarkdown(remote.tree, mentions, emailMentions);
|
|
1084
|
+
const baseMarkdown = baseObject["markdown"] === undefined ? undefined : withoutComments(baseObject["markdown"] as string);
|
|
1085
|
+
let split = splitTitle(withoutComments(markdown));
|
|
969
1086
|
const currentSplit = splitTitle(currentMarkdown);
|
|
970
1087
|
const baseSplit = baseMarkdown === undefined ? undefined : splitTitle(baseMarkdown);
|
|
971
1088
|
let fieldMerged = false;
|
|
@@ -985,26 +1102,26 @@ export async function synchronizeNotionDocument(runtime: RuntimeCapabilities, ur
|
|
|
985
1102
|
if (baseSplit !== undefined) {
|
|
986
1103
|
const localTitleChanged = baseSplit.title !== split.title;
|
|
987
1104
|
const remoteTitleChanged = baseSplit.title !== currentSplit.title;
|
|
988
|
-
if (!localTitleChanged && remoteTitleChanged) return
|
|
1105
|
+
if (!localTitleChanged && remoteTitleChanged) return notionDocument(remote.tree.id, remote.tree, mentions, emailMentions, remote.comments);
|
|
989
1106
|
if (localTitleChanged && remoteTitleChanged && split.title !== currentSplit.title) throw new Error("Markdown and Notion changed since last sync");
|
|
990
|
-
if (localTitleChanged && remoteTitleChanged) return
|
|
1107
|
+
if (localTitleChanged && remoteTitleChanged) return notionDocument(remote.tree.id, remote.tree, mentions, emailMentions, remote.comments);
|
|
991
1108
|
}
|
|
992
1109
|
const titleRich = split.title === "" ? object(remote.tree.block["properties"]!)["title"]! as NotionRichText : titleRichText(split.title);
|
|
993
1110
|
const titleChanged = split.title !== "" && compact(object(remote.tree.block["properties"]!)["title"]!) !== compact(titleRich);
|
|
994
1111
|
if (titleChanged) await notionPost(runtime, "saveTransactionsFanout", remote.cookie, { requestId: randomUUID(), transactions: [{ id: randomUUID(), spaceId: remote.spaceId, operations: [{ pointer: pointer(remote.tree.id, remote.spaceId), path: ["properties", "title"], command: "updateBlockPropertyValue", args: { primitiveOp: { command: "set", args: titleRich } } }, { pointer: pointer(remote.tree.id, remote.spaceId), path: ["last_edited_time"], command: "set", args: runtime.clock.now().getTime() }] }] }, remote.headers);
|
|
995
1112
|
const outputTree: NotionTree = { ...remote.tree, block: { ...remote.tree.block, properties: { ...object(remote.tree.block["properties"]!), title: titleRich } } };
|
|
996
|
-
|
|
997
|
-
return { title: output.split("\n")[0]!.replace(/^# */, ""), markdown: output, data: notionData(remote.tree.id, output, outputTree, mentions) };
|
|
1113
|
+
return notionDocument(remote.tree.id, outputTree, mentions, emailMentions, remote.comments);
|
|
998
1114
|
}
|
|
999
1115
|
if (baseMarkdown !== undefined) {
|
|
1000
1116
|
const localChanged = baseMarkdown !== targetMarkdown;
|
|
1001
1117
|
const remoteChanged = baseMarkdown !== currentMarkdown;
|
|
1002
|
-
if (!localChanged && remoteChanged) return
|
|
1118
|
+
if (!localChanged && remoteChanged) return notionDocument(remote.tree.id, remote.tree, mentions, emailMentions, remote.comments);
|
|
1003
1119
|
if (localChanged && remoteChanged && targetMarkdown !== currentMarkdown && !fieldMerged) throw new Error("Markdown and Notion changed since last sync");
|
|
1004
|
-
if (localChanged && remoteChanged && targetMarkdown === currentMarkdown) return
|
|
1120
|
+
if (localChanged && remoteChanged && targetMarkdown === currentMarkdown) return notionDocument(remote.tree.id, remote.tree, mentions, emailMentions, remote.comments);
|
|
1005
1121
|
}
|
|
1006
1122
|
const localBody = mentions === undefined ? split.body : hydrateUserMentions(split.body, mentions);
|
|
1007
1123
|
const localBlocks = parseNotionMarkdown(localBody);
|
|
1124
|
+
await resolveNotionEmailMentions(runtime, localBlocks, remote.cookie, remote.spaceId, remote.headers, emailMentions);
|
|
1008
1125
|
const ambient = { spaceId: remote.spaceId, userId: remote.userId, currentTime: runtime.clock.now().getTime() };
|
|
1009
1126
|
const diffResult = diffNotionBlockTrees(remote.tree, localBlocks, sidecarBlocksFromNotionTree(remote.tree), ambient);
|
|
1010
1127
|
const operations = [...diffResult.operations];
|
|
@@ -1012,6 +1129,5 @@ export async function synchronizeNotionDocument(runtime: RuntimeCapabilities, ur
|
|
|
1012
1129
|
if (split.title !== "" && compact(object(remote.tree.block["properties"]!)["title"]!) !== compact(titleRich)) operations.unshift({ pointer: pointer(remote.tree.id, remote.spaceId), path: ["properties", "title"], command: "updateBlockPropertyValue", args: { primitiveOp: { command: "set", args: titleRich } } });
|
|
1013
1130
|
if (operations.length > 0) await notionPost(runtime, "saveTransactionsFanout", remote.cookie, { requestId: randomUUID(), transactions: [{ id: randomUUID(), spaceId: remote.spaceId, operations }] }, remote.headers);
|
|
1014
1131
|
const outputTree: NotionTree = { id: remote.tree.id, block: { ...remote.tree.block, properties: { ...object(remote.tree.block["properties"]!), title: titleRich } }, children: localTree(localBlocks).map((node, index) => outputNode(node, remote.tree.children[index], remote.tree.id, remote, ambient.currentTime)) };
|
|
1015
|
-
|
|
1016
|
-
return { title: output.split("\n")[0]!.replace(/^# */, ""), markdown: output, data: notionData(remote.tree.id, output, outputTree, mentions) };
|
|
1132
|
+
return notionDocument(remote.tree.id, outputTree, mentions, emailMentions, remote.comments);
|
|
1017
1133
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { slackService, markdownToSlackBlocks, slackBlocksToMarkdown, sendSlackMessage, type SlackSentMessage } from "./slack.js";
|
|
1
|
+
export { slackService, markdownToSlackBlocks, slackBlocksToMarkdown, sendSlackMessage, editSlackMessage, lookupSlackUsers, type SlackSentMessage } from "./slack.js";
|
|
2
2
|
export declare const slackProvider: Readonly<{
|
|
3
3
|
services: readonly [Readonly<{
|
|
4
4
|
name: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,KAAK,gBAAgB,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,KAAK,gBAAgB,EAAE,MAAM,YAAY,CAAC;AACrK,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAExB,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { slackService } from "./slack.js";
|
|
2
|
-
export { slackService, markdownToSlackBlocks, slackBlocksToMarkdown, sendSlackMessage } from "./slack.js";
|
|
2
|
+
export { slackService, markdownToSlackBlocks, slackBlocksToMarkdown, sendSlackMessage, editSlackMessage, lookupSlackUsers } from "./slack.js";
|
|
3
3
|
export const slackProvider = Object.freeze({
|
|
4
4
|
services: [slackService],
|
|
5
5
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1C,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,gBAAgB,EAAyB,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE1C,OAAO,EAAE,YAAY,EAAE,qBAAqB,EAAE,qBAAqB,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,gBAAgB,EAAyB,MAAM,YAAY,CAAC;AACrK,MAAM,CAAC,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CAAC;IACzC,QAAQ,EAAE,CAAC,YAAY,CAAU;CAClC,CAAC,CAAC"}
|
|
@@ -2,13 +2,16 @@ import type { JsonObject } from "wire-core";
|
|
|
2
2
|
import type { RuntimeCapabilities } from "wire-core";
|
|
3
3
|
export declare function markdownToSlackBlocks(markdown: string): readonly JsonObject[];
|
|
4
4
|
export declare function slackBlocksToMarkdown(blocks: readonly JsonObject[], users: ReadonlyMap<string, string>): string;
|
|
5
|
+
export declare function lookupSlackUsers(runtime: RuntimeCapabilities, query: string): Promise<readonly JsonObject[]>;
|
|
5
6
|
export type SlackSentMessage = Readonly<{
|
|
6
7
|
channel: string;
|
|
7
8
|
ts: string;
|
|
8
9
|
url: string;
|
|
9
10
|
thread_ts?: string;
|
|
11
|
+
replies?: readonly SlackSentMessage[];
|
|
10
12
|
}>;
|
|
11
13
|
export declare function sendSlackMessage(runtime: RuntimeCapabilities, destination: string, markdown: string): Promise<SlackSentMessage>;
|
|
14
|
+
export declare function editSlackMessage(runtime: RuntimeCapabilities, url: string, markdown: string): Promise<SlackSentMessage>;
|
|
12
15
|
export declare const slackService: Readonly<{
|
|
13
16
|
name: string;
|
|
14
17
|
matches(url: URL): boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"slack.d.ts","sourceRoot":"","sources":["../src/slack.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"slack.d.ts","sourceRoot":"","sources":["../src/slack.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAC5C,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAwIrD,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,SAAS,UAAU,EAAE,CAO7E;AAsCD,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,SAAS,UAAU,EAAE,EAAE,KAAK,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,MAAM,CAmC/G;AA+CD,wBAAsB,gBAAgB,CAAC,OAAO,EAAE,mBAAmB,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,UAAU,EAAE,CAAC,CAmBlH;AA2CD,MAAM,MAAM,gBAAgB,GAAG,QAAQ,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAAC,OAAO,CAAC,EAAE,SAAS,gBAAgB,EAAE,CAAA;CAAE,CAAC,CAAC;AAEjJ,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAE/H;AAED,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,mBAAmB,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAEvH;AAoED,eAAO,MAAM,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAwGvB,CAAC"}
|
|
@@ -39,6 +39,8 @@ function inlinePlain(nodes) {
|
|
|
39
39
|
return node.alt;
|
|
40
40
|
if (node.type === "break")
|
|
41
41
|
return "\n";
|
|
42
|
+
if (node.type === "thematicBreak")
|
|
43
|
+
return "──────────";
|
|
42
44
|
if (node.type === "footnoteReference")
|
|
43
45
|
return `[${node.label}]`;
|
|
44
46
|
throw new Error(`Unsupported Slack inline node: ${node.type}`);
|
|
@@ -313,12 +315,95 @@ async function slackSession(runtime) {
|
|
|
313
315
|
const metadata = await runtime.cookies.metadata("slack");
|
|
314
316
|
return { origin: metadata["origin"], token: metadata["token"], cookie: cookies.map((value) => `${value.name}=${value.value}`).join("; ") };
|
|
315
317
|
}
|
|
316
|
-
export async function
|
|
317
|
-
|
|
318
|
+
export async function lookupSlackUsers(runtime, query) {
|
|
319
|
+
query = query.trim();
|
|
320
|
+
if (query === "")
|
|
321
|
+
throw new Error("Slack user lookup requires an email or name");
|
|
322
|
+
const session = await slackSession(runtime);
|
|
323
|
+
const request = (method, parameters) => api(runtime, session.origin, session.token, session.cookie, method, parameters);
|
|
324
|
+
const email = /^[^@\s]+@[^@\s]+$/.test(query);
|
|
325
|
+
const found = [];
|
|
326
|
+
let cursor;
|
|
327
|
+
do {
|
|
328
|
+
const response = await request("users.list", { limit: "200", ...(cursor === undefined ? {} : { cursor }) });
|
|
329
|
+
for (const member of response["members"]) {
|
|
330
|
+
if (member["deleted"] === true)
|
|
331
|
+
continue;
|
|
332
|
+
const profile = member["profile"];
|
|
333
|
+
const names = [member["name"], member["real_name"], profile?.["display_name"], profile?.["real_name"], profile?.["email"]].filter((value) => typeof value === "string");
|
|
334
|
+
if (email ? profile?.["email"]?.toLowerCase() === query.toLowerCase() : query.startsWith("@") ? member["name"] === query.slice(1) : query.toLowerCase().split(/\s+/).every((word) => names.some((name) => name.toLowerCase().includes(word))))
|
|
335
|
+
found.push(member);
|
|
336
|
+
}
|
|
337
|
+
cursor = response["response_metadata"]?.["next_cursor"];
|
|
338
|
+
} while (cursor !== undefined && cursor !== "");
|
|
339
|
+
return found;
|
|
340
|
+
}
|
|
341
|
+
function slackMessageParts(markdown) {
|
|
342
|
+
const ast = parse(markdown).ast;
|
|
343
|
+
if (ast.type !== "root")
|
|
344
|
+
throw new Error("Expected Markdown document");
|
|
345
|
+
const bytes = Buffer.from(markdown);
|
|
346
|
+
const parts = [];
|
|
347
|
+
let start = 0;
|
|
348
|
+
for (const node of ast.children) {
|
|
349
|
+
if (node.type !== "thematicBreak" || bytes.subarray(node.range.start, node.range.end).toString().trim() !== "---")
|
|
350
|
+
continue;
|
|
351
|
+
parts.push(bytes.subarray(start, node.range.start).toString().trim());
|
|
352
|
+
start = node.range.end;
|
|
353
|
+
}
|
|
354
|
+
parts.push(bytes.subarray(start).toString().trim());
|
|
355
|
+
if (parts.some((part) => part === ""))
|
|
356
|
+
throw new Error("Slack thread sections must not be empty");
|
|
357
|
+
return parts;
|
|
358
|
+
}
|
|
359
|
+
async function resolveSlackEmailMentions(runtime, blocks, users) {
|
|
360
|
+
const resolve = async (element) => {
|
|
361
|
+
if (element["type"] === "link" && typeof element["text"] === "string" && element["text"].startsWith("@") && typeof element["url"] === "string" && element["url"].startsWith("mailto:")) {
|
|
362
|
+
const email = decodeURIComponent(element["url"].slice(7));
|
|
363
|
+
if (!/^[^@\s?]+@[^@\s?]+$/.test(email))
|
|
364
|
+
throw new Error(`Invalid mention email: ${email}`);
|
|
365
|
+
const key = email.toLowerCase();
|
|
366
|
+
if (!users.has(key)) {
|
|
367
|
+
const matches = await lookupSlackUsers(runtime, email);
|
|
368
|
+
if (matches.length !== 1)
|
|
369
|
+
throw new Error(`Expected one Slack user for ${email}, found ${matches.length}`);
|
|
370
|
+
users.set(key, matches[0]["id"]);
|
|
371
|
+
}
|
|
372
|
+
return { type: "user", user_id: users.get(key), ...(element["style"] === undefined ? {} : { style: element["style"] }) };
|
|
373
|
+
}
|
|
374
|
+
if (Array.isArray(element["elements"])) {
|
|
375
|
+
const elements = [];
|
|
376
|
+
for (const child of element["elements"])
|
|
377
|
+
elements.push(await resolve(child));
|
|
378
|
+
return { ...element, elements };
|
|
379
|
+
}
|
|
380
|
+
return element;
|
|
381
|
+
};
|
|
382
|
+
const result = [];
|
|
383
|
+
for (const block of blocks)
|
|
384
|
+
result.push(await resolve(block));
|
|
385
|
+
return result;
|
|
386
|
+
}
|
|
387
|
+
export function sendSlackMessage(runtime, destination, markdown) {
|
|
388
|
+
return writeSlackMessage(runtime, destination, markdown, false);
|
|
389
|
+
}
|
|
390
|
+
export function editSlackMessage(runtime, url, markdown) {
|
|
391
|
+
return writeSlackMessage(runtime, url, markdown, true);
|
|
392
|
+
}
|
|
393
|
+
async function writeSlackMessage(runtime, destination, markdown, edit) {
|
|
394
|
+
markdown = markdown.replace(/\r\n?/g, "\n");
|
|
395
|
+
const parts = slackMessageParts(markdown);
|
|
396
|
+
const blocks = parts.map(markdownToSlackBlocks);
|
|
397
|
+
const users = new Map();
|
|
398
|
+
for (const [index, value] of blocks.entries())
|
|
399
|
+
blocks[index] = await resolveSlackEmailMentions(runtime, value, users);
|
|
400
|
+
if (edit && (!destination.startsWith("https://") || messageParts(new URL(destination)) === undefined))
|
|
401
|
+
throw new Error("Slack edit requires a message URL");
|
|
318
402
|
const session = await slackSession(runtime);
|
|
319
403
|
const request = (method, parameters) => api(runtime, session.origin, session.token, session.cookie, method, parameters);
|
|
320
404
|
let channel;
|
|
321
405
|
let thread;
|
|
406
|
+
let editTimestamp;
|
|
322
407
|
if (destination.startsWith("https://")) {
|
|
323
408
|
const url = new URL(destination);
|
|
324
409
|
const message = messageParts(url);
|
|
@@ -327,6 +412,8 @@ export async function sendSlackMessage(runtime, destination, markdown) {
|
|
|
327
412
|
throw new Error(`Unsupported Slack destination: ${destination}`);
|
|
328
413
|
if (message !== undefined) {
|
|
329
414
|
channel = message.channel;
|
|
415
|
+
if (edit)
|
|
416
|
+
editTimestamp = slackTimestamp(message.rawTimestamp);
|
|
330
417
|
thread = url.searchParams.has("thread_ts") ? url.searchParams.get("thread_ts") : slackTimestamp(message.rawTimestamp);
|
|
331
418
|
const response = await request("conversations.replies", { channel, ts: thread, limit: "1" });
|
|
332
419
|
const selected = response["messages"][0];
|
|
@@ -338,22 +425,13 @@ export async function sendSlackMessage(runtime, destination, markdown) {
|
|
|
338
425
|
}
|
|
339
426
|
else if (/^[CDG][A-Z0-9]+$/.test(destination))
|
|
340
427
|
channel = destination;
|
|
341
|
-
else if (/^[UW][A-Z0-9]+$/.test(destination) || destination.startsWith("@")) {
|
|
428
|
+
else if (/^[UW][A-Z0-9]+$/.test(destination) || destination.startsWith("@") || /^[^@\s]+@[^@\s]+$/.test(destination)) {
|
|
342
429
|
let user = destination;
|
|
343
|
-
if (destination
|
|
344
|
-
const
|
|
345
|
-
const found = [];
|
|
346
|
-
let cursor;
|
|
347
|
-
do {
|
|
348
|
-
const response = await request("users.list", { limit: "200", ...(cursor === undefined ? {} : { cursor }) });
|
|
349
|
-
for (const member of response["members"])
|
|
350
|
-
if (member["name"] === name && member["deleted"] !== true)
|
|
351
|
-
found.push(member["id"]);
|
|
352
|
-
cursor = response["response_metadata"]?.["next_cursor"];
|
|
353
|
-
} while (cursor !== undefined && cursor !== "");
|
|
430
|
+
if (!/^[UW][A-Z0-9]+$/.test(destination)) {
|
|
431
|
+
const found = await lookupSlackUsers(runtime, destination);
|
|
354
432
|
if (found.length !== 1)
|
|
355
|
-
throw new Error(`Expected one Slack user
|
|
356
|
-
user = found[0];
|
|
433
|
+
throw new Error(`Expected one Slack user for ${destination}, found ${found.length}; use an email or user ID`);
|
|
434
|
+
user = found[0]["id"];
|
|
357
435
|
}
|
|
358
436
|
const opened = await request("conversations.open", { users: user });
|
|
359
437
|
channel = opened["channel"]["id"];
|
|
@@ -375,10 +453,23 @@ export async function sendSlackMessage(runtime, destination, markdown) {
|
|
|
375
453
|
throw new Error(`Expected one Slack channel named #${name}, found ${found.length}; use a channel ID or URL`);
|
|
376
454
|
channel = found[0];
|
|
377
455
|
}
|
|
378
|
-
const
|
|
379
|
-
const
|
|
380
|
-
|
|
381
|
-
|
|
456
|
+
const sent = [];
|
|
457
|
+
for (const [index, part] of parts.entries()) {
|
|
458
|
+
try {
|
|
459
|
+
const updating = index === 0 && edit;
|
|
460
|
+
const posted = await request(updating ? "chat.update" : "chat.postMessage", { channel, text: part, blocks: JSON.stringify(blocks[index]), unfurl_links: "false", unfurl_media: "false", parse: "none", mrkdwn: "false", ...(updating ? { ts: editTimestamp } : thread === undefined ? {} : { thread_ts: thread }) });
|
|
461
|
+
const ts = posted["ts"];
|
|
462
|
+
const url = `${session.origin}/archives/${posted["channel"]}/p${ts.replace(".", "")}${thread === undefined ? "" : `?thread_ts=${thread}`}`;
|
|
463
|
+
sent.push({ channel: posted["channel"], ts, url, ...(thread === undefined ? {} : { thread_ts: thread }) });
|
|
464
|
+
thread ??= ts;
|
|
465
|
+
}
|
|
466
|
+
catch (error) {
|
|
467
|
+
if (sent.length === 0)
|
|
468
|
+
throw error;
|
|
469
|
+
throw new Error(`Slack thread stopped after ${sent.length} message(s): ${sent.map((message) => message.url).join(", ")}. ${error instanceof Error ? error.message : String(error)}`);
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
return { ...sent[0], ...(sent.length === 1 ? {} : { replies: sent.slice(1) }) };
|
|
382
473
|
}
|
|
383
474
|
export const slackService = defineService({
|
|
384
475
|
name: "slack",
|