statocysts 0.0.5 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,9 @@
1
+ import { a as DEFAULT_EXTRACTOR, c as ServiceProvider, i as buildSenderRegistry, l as defineProvider, n as SenderRegistry, o as DefineProviderContext, r as SenderUrl, s as DefineProviderOptions, t as Sender } from "./shared-CR_VTatP.js";
2
+ import { FetchOptions } from "ofetch";
3
+
4
+ //#region src/browser.d.ts
5
+ declare const senderRegistry: SenderRegistry;
6
+ declare function createSender(urls: SenderUrl[]): Sender;
7
+ declare function send(url: string | URL, message: string, options?: FetchOptions): Promise<void>;
8
+ //#endregion
9
+ export { DEFAULT_EXTRACTOR, DefineProviderContext, DefineProviderOptions, Sender, SenderRegistry, SenderUrl, ServiceProvider, buildSenderRegistry, createSender, defineProvider, send, senderRegistry };
@@ -0,0 +1,17 @@
1
+ import { a as defineProvider, i as DEFAULT_EXTRACTOR, n as json, o as assert, r as slack, t as buildSenderRegistry } from "./shared-BiiZsNzb.js";
2
+ import { ofetch } from "ofetch";
3
+
4
+ //#region src/browser.ts
5
+ const senderRegistry = buildSenderRegistry([json, slack]);
6
+ function createSender(urls) {
7
+ return senderRegistry(urls);
8
+ }
9
+ async function send(url, message, options) {
10
+ const _url = typeof url === "string" ? new URL(url) : url;
11
+ const provider = senderRegistry.resolveProvider(_url);
12
+ assert(provider, `Unsupported protocol ${_url.protocol}`);
13
+ await ofetch(provider.buildRequest(_url.toString(), message, options), options);
14
+ }
15
+
16
+ //#endregion
17
+ export { DEFAULT_EXTRACTOR, buildSenderRegistry, createSender, defineProvider, send, senderRegistry };
package/dist/index.d.ts CHANGED
@@ -1,31 +1,9 @@
1
+ import { a as DEFAULT_EXTRACTOR, c as ServiceProvider, i as buildSenderRegistry, l as defineProvider, n as SenderRegistry, o as DefineProviderContext, r as SenderUrl, s as DefineProviderOptions, t as Sender } from "./shared-CR_VTatP.js";
1
2
  import { FetchOptions } from "ofetch";
2
- import { z } from "zod";
3
3
 
4
- //#region src/sender.d.ts
5
- type Protocol = 'generic:' | 'slack:';
6
- declare const SUPPORTED_PROTOCOLS: string[];
4
+ //#region src/index.d.ts
5
+ declare const senderRegistry: SenderRegistry;
6
+ declare function createSender(urls: SenderUrl[]): Sender;
7
7
  declare function send(url: string | URL, message: string, options?: FetchOptions): Promise<void>;
8
8
  //#endregion
9
- //#region src/services/chat/slack.d.ts
10
- declare const slackOptionsSchema: z.ZodObject<{
11
- botname: z.ZodOptional<z.ZodString>;
12
- icon: z.ZodOptional<z.ZodString>;
13
- color: z.ZodOptional<z.ZodString>;
14
- title: z.ZodOptional<z.ZodString>;
15
- thread_ts: z.ZodOptional<z.ZodString>;
16
- }, z.core.$strip>;
17
- type SlackOptions = z.infer<typeof slackOptionsSchema>;
18
- declare function buildSlackRequest(url: URL, message: string): Request;
19
- //#endregion
20
- //#region src/services/specialized/generic.d.ts
21
- declare const genericOptionsSchema: z.ZodObject<{
22
- template: z.ZodDefault<z.ZodOptional<z.ZodEnum<{
23
- json: "json";
24
- plaintext: "plaintext";
25
- }>>>;
26
- method: z.ZodDefault<z.ZodOptional<z.ZodString>>;
27
- }, z.core.$strip>;
28
- type GenericOptions = z.infer<typeof genericOptionsSchema>;
29
- declare function buildGenericRequest(url: URL, message: string): Request;
30
- //#endregion
31
- export { GenericOptions, Protocol, SUPPORTED_PROTOCOLS, SlackOptions, buildGenericRequest, buildSlackRequest, send };
9
+ export { DEFAULT_EXTRACTOR, DefineProviderContext, DefineProviderOptions, Sender, SenderRegistry, SenderUrl, ServiceProvider, buildSenderRegistry, createSender, defineProvider, send, senderRegistry };
package/dist/index.js CHANGED
@@ -1,145 +1,17 @@
1
+ import { a as defineProvider, i as DEFAULT_EXTRACTOR, n as json, o as assert, r as slack, t as buildSenderRegistry } from "./shared-BiiZsNzb.js";
1
2
  import { ofetch } from "ofetch";
2
- import { z } from "zod";
3
3
 
4
- //#region src/utils/assert.ts
5
- function assert(condition, message) {
6
- if (!condition) throw typeof message === "string" ? new Error(message) : message;
4
+ //#region src/index.ts
5
+ const senderRegistry = buildSenderRegistry([json, slack]);
6
+ function createSender(urls) {
7
+ return senderRegistry(urls);
7
8
  }
8
-
9
- //#endregion
10
- //#region src/services/chat/slack.ts
11
- const slackOptionsSchema = z.object({
12
- botname: z.string().optional(),
13
- icon: z.string().optional(),
14
- color: z.string().optional(),
15
- title: z.string().optional(),
16
- thread_ts: z.string().optional()
17
- });
18
- function isBotApiFormat(url) {
19
- return url.username === "xoxb";
20
- }
21
- function isWebhookFormat(url) {
22
- return url.username === "hook";
23
- }
24
- function parseBotToken(url) {
25
- assert(url.password, "Bot token is required");
26
- return url.password;
27
- }
28
- function parseWebhookToken(url) {
29
- assert(url.password, "Webhook token is required");
30
- const parts = url.password.split("-");
31
- assert(parts.length === 3, "Invalid webhook token format");
32
- return {
33
- id: parts[0],
34
- token: parts[1],
35
- secret: parts[2]
36
- };
37
- }
38
- function buildBotApiRequest(url, message, options) {
39
- const token = parseBotToken(url);
40
- const body = {
41
- channel: url.hostname,
42
- text: message
43
- };
44
- if (options.botname) body.username = options.botname;
45
- if (options.icon) if (options.icon.startsWith(":") && options.icon.endsWith(":")) body.icon_emoji = options.icon;
46
- else body.icon_url = options.icon;
47
- if (options.thread_ts) body.thread_ts = options.thread_ts;
48
- const attachments = [];
49
- if (options.color || options.title) {
50
- const attachment = {};
51
- if (options.color) attachment.color = options.color.startsWith("%23") ? decodeURIComponent(options.color) : options.color;
52
- if (options.title) attachment.title = options.title;
53
- attachments.push(attachment);
54
- }
55
- if (attachments.length > 0) body.attachments = attachments;
56
- return new Request("https://slack.com/api/chat.postMessage", {
57
- method: "POST",
58
- headers: {
59
- "Authorization": `Bearer xoxb-${token}`,
60
- "Content-Type": "application/json"
61
- },
62
- body: JSON.stringify(body)
63
- });
64
- }
65
- function buildWebhookRequest(url, message, options) {
66
- const { id, token, secret } = parseWebhookToken(url);
67
- const body = { text: message };
68
- if (options.botname) body.username = options.botname;
69
- if (options.icon) if (options.icon.startsWith(":") && options.icon.endsWith(":")) body.icon_emoji = options.icon;
70
- else body.icon_url = options.icon;
71
- const attachments = [];
72
- if (options.color || options.title) {
73
- const attachment = {};
74
- if (options.color) attachment.color = options.color.startsWith("%23") ? decodeURIComponent(options.color) : options.color;
75
- if (options.title) attachment.title = options.title;
76
- attachments.push(attachment);
77
- }
78
- if (attachments.length > 0) body.attachments = attachments;
79
- return new Request(`https://hooks.slack.com/services/${id}/${token}/${secret}`, {
80
- method: "POST",
81
- headers: { "Content-Type": "application/json" },
82
- body: JSON.stringify(body)
83
- });
84
- }
85
- function buildSlackRequest(url, message) {
86
- assert(url.protocol === "slack:", `Unexpected protocol ${url.protocol}`);
87
- const params = new URLSearchParams(url.search);
88
- const options = slackOptionsSchema.parse(Object.fromEntries(params.entries()));
89
- if (isBotApiFormat(url)) return buildBotApiRequest(url, message, options);
90
- if (isWebhookFormat(url)) return buildWebhookRequest(url, message, options);
91
- throw new Error(`Unsupported Slack URL format: ${url.toString()}`);
92
- }
93
-
94
- //#endregion
95
- //#region src/services/specialized/generic.ts
96
- const genericOptionsSchema = z.object({
97
- template: z.enum(["json", "plaintext"]).optional().default("json"),
98
- method: z.string().optional().default("POST")
99
- });
100
- function isOptionParam(key) {
101
- return !key.startsWith("@") && !key.startsWith("$");
102
- }
103
- function buildGenericRequest(url, message) {
104
- assert(url.protocol === "generic:", `Unexpected protocol ${url.protocol}`);
105
- const params = new URLSearchParams(url.hash.slice(1));
106
- const allParamsEntries = Array.from(params.entries());
107
- const optionsParams = Object.fromEntries(allParamsEntries.filter(([key]) => isOptionParam(key)));
108
- const options = genericOptionsSchema.parse(optionsParams);
109
- const headers = Object.fromEntries(allParamsEntries.filter(([key]) => key.startsWith("@")).map(([key, value]) => [key.slice(1), value]));
110
- const dataProperties = Object.fromEntries(allParamsEntries.filter(([key]) => key.startsWith("$")).map(([key, value]) => [key.slice(1), value]));
111
- const targetUrl = new URL(url.host + url.pathname);
112
- return new Request(targetUrl.toString(), {
113
- method: options.method,
114
- headers: {
115
- "Content-Type": options.template === "json" ? "application/json" : "text/plain",
116
- ...headers
117
- },
118
- body: options.template === "json" ? JSON.stringify({
119
- ...dataProperties,
120
- message
121
- }) : message
122
- });
123
- }
124
-
125
- //#endregion
126
- //#region src/sender.ts
127
- const SUPPORTED_PROTOCOLS = ["generic:", "slack:"];
128
9
  async function send(url, message, options) {
129
10
  const _url = typeof url === "string" ? new URL(url) : url;
130
- assert(SUPPORTED_PROTOCOLS.includes(_url.protocol), `Unsupported protocol ${_url.protocol}`);
131
- let req;
132
- switch (_url.protocol) {
133
- case "generic:":
134
- req = buildGenericRequest(_url, message);
135
- break;
136
- case "slack:":
137
- req = buildSlackRequest(_url, message);
138
- break;
139
- default: throw new Error(`Unsupported protocol ${_url.protocol}`);
140
- }
141
- await ofetch(req, options);
11
+ const provider = senderRegistry.resolveProvider(_url);
12
+ assert(provider, `Unsupported protocol ${_url.protocol}`);
13
+ await ofetch(provider.buildRequest(_url.toString(), message, options), options);
142
14
  }
143
15
 
144
16
  //#endregion
145
- export { SUPPORTED_PROTOCOLS, buildGenericRequest, buildSlackRequest, send };
17
+ export { DEFAULT_EXTRACTOR, buildSenderRegistry, createSender, defineProvider, send, senderRegistry };
@@ -0,0 +1,135 @@
1
+ import defu from "defu";
2
+ import { withProtocol, withoutLeadingSlash } from "ufo";
3
+ import { ofetch } from "ofetch";
4
+
5
+ //#region src/utils/assert.ts
6
+ function assert(condition, message) {
7
+ if (!condition) throw typeof message === "string" ? new Error(message) : message;
8
+ }
9
+
10
+ //#endregion
11
+ //#region src/core/provider.ts
12
+ const DEFAULT_EXTRACTOR = (url) => Object.fromEntries(url.searchParams.entries());
13
+ function defineProvider(protocol, createOptions) {
14
+ const createOpt = defu(createOptions, { extractor: DEFAULT_EXTRACTOR });
15
+ const buildRequest = (protocolUrl, message, options) => {
16
+ const url = new URL(protocolUrl);
17
+ assert(url.protocol === protocol, `Unexpected protocol "${url.protocol}"`);
18
+ const ctx = {
19
+ data: createOpt.extractor(url),
20
+ url,
21
+ message
22
+ };
23
+ const opts = defu(createOptions.defaultOptions ?? {}, options ?? {});
24
+ return createOptions.createRequest.call(ctx, ctx, opts);
25
+ };
26
+ return {
27
+ get protocol() {
28
+ return protocol;
29
+ },
30
+ buildRequest,
31
+ get defaultOptions() {
32
+ return createOptions.defaultOptions;
33
+ },
34
+ $infer: {}
35
+ };
36
+ }
37
+
38
+ //#endregion
39
+ //#region src/services/chat/slack/index.ts
40
+ const slack = defineProvider("slack:", {
41
+ extractor: (url) => {
42
+ assert(url.hostname === "bot" || url.hostname === "webhook", `Invalid slack URL: ${url.toString()}`);
43
+ if (url.hostname === "bot") {
44
+ assert(url.username, "Channel ID is required");
45
+ assert(url.password, "Bot token is required");
46
+ } else assert(url.pathname.split("/").filter(Boolean).length === 3, "Webhook URL is invalid");
47
+ return { type: url.hostname };
48
+ },
49
+ defaultOptions: {
50
+ hookBaseUrl: "https://hooks.slack.com/",
51
+ botApiBaseUrl: "https://slack.com/"
52
+ },
53
+ createRequest(_, options) {
54
+ const { type } = this.data;
55
+ let url;
56
+ const headers = new Headers([["Content-Type", "application/json"]]);
57
+ const body = { text: this.message };
58
+ if (type === "bot") {
59
+ const { username: channel, password: token, searchParams } = this.url;
60
+ url = new URL("/api/chat.postMessage", options.botApiBaseUrl);
61
+ searchParams.forEach((value, key) => {
62
+ url.searchParams.set(key, value);
63
+ });
64
+ headers.set("Authorization", `Bearer ${token}`);
65
+ body.channel = channel;
66
+ } else {
67
+ const { searchParams } = this.url;
68
+ url = new URL(`/services/${withoutLeadingSlash(this.url.pathname)}`, options.hookBaseUrl);
69
+ searchParams.forEach((value, key) => {
70
+ url.searchParams.set(key, value);
71
+ });
72
+ }
73
+ return new Request(url, {
74
+ method: "POST",
75
+ headers,
76
+ body: JSON.stringify(options.body ?? body)
77
+ });
78
+ }
79
+ });
80
+
81
+ //#endregion
82
+ //#region src/services/specialized/json/index.ts
83
+ const json = defineProvider("json:", { createRequest() {
84
+ const url = new URL(this.url);
85
+ const headers = new Headers([["Content-Type", "application/json"]]);
86
+ const body = { message: this.message };
87
+ Array.from(url.searchParams.entries()).forEach(([key, value]) => {
88
+ if (key.startsWith(" ")) {
89
+ url.searchParams.delete(key);
90
+ const headerKey = key.slice(1);
91
+ if (headers.has(headerKey)) headers.set(headerKey, value);
92
+ else headers.append(headerKey, value);
93
+ } else if (key.startsWith(":")) {
94
+ url.searchParams.delete(key);
95
+ const propertyKey = key.slice(1);
96
+ body[propertyKey] = value;
97
+ }
98
+ });
99
+ const requestUrl = withProtocol(url.toString(), "https:");
100
+ return new Request(requestUrl, {
101
+ method: "POST",
102
+ body: JSON.stringify(body),
103
+ headers
104
+ });
105
+ } });
106
+
107
+ //#endregion
108
+ //#region src/core/sender.ts
109
+ function buildSenderRegistry(providers) {
110
+ const providersRegistry = /* @__PURE__ */ new Map();
111
+ providers.forEach((provider) => {
112
+ providersRegistry.set(provider.protocol, provider);
113
+ });
114
+ function resolveProvider(url) {
115
+ const _url = typeof url === "string" ? new URL(url) : url;
116
+ return providersRegistry.get(_url.protocol);
117
+ }
118
+ function createSender(urls) {
119
+ const registries = urls.map((url) => {
120
+ const provider = resolveProvider(url);
121
+ if (!provider) return;
122
+ return {
123
+ provider,
124
+ url
125
+ };
126
+ }).filter((p) => !!p);
127
+ return { async send(message, options) {
128
+ for (const registry of registries) await ofetch(registry.provider.buildRequest(registry.url.toString(), message), options);
129
+ } };
130
+ }
131
+ return Object.assign(createSender, { resolveProvider });
132
+ }
133
+
134
+ //#endregion
135
+ export { defineProvider as a, DEFAULT_EXTRACTOR as i, json as n, assert as o, slack as r, buildSenderRegistry as t };
@@ -0,0 +1,34 @@
1
+ import { FetchOptions } from "ofetch";
2
+
3
+ //#region src/core/provider.d.ts
4
+ interface ServiceProvider<Protocol extends string, Data = unknown, Options = unknown> {
5
+ readonly protocol: Protocol;
6
+ $infer: Data;
7
+ defaultOptions: Options | undefined;
8
+ buildRequest: (url: string, message: string, options?: Options) => Request;
9
+ }
10
+ interface DefineProviderContext<Data = unknown> {
11
+ url: URL;
12
+ message: string;
13
+ data: Data;
14
+ }
15
+ interface DefineProviderOptions<Data = unknown, Options = unknown> {
16
+ defaultOptions?: Options;
17
+ extractor?: (url: URL) => Data;
18
+ createRequest: (this: DefineProviderContext<Data>, ctx: DefineProviderContext<Data>, Options: Options) => Request;
19
+ }
20
+ declare const DEFAULT_EXTRACTOR: (url: URL) => unknown;
21
+ declare function defineProvider<const Protocol extends string, Data = unknown, Options = unknown>(protocol: Protocol, createOptions: DefineProviderOptions<Data, Options>): ServiceProvider<Protocol, Data, Options>;
22
+ //#endregion
23
+ //#region src/core/sender.d.ts
24
+ interface Sender {
25
+ send: (message: string, options?: FetchOptions) => Promise<void>;
26
+ }
27
+ type SenderUrl = string | URL;
28
+ interface SenderRegistry {
29
+ (urls: SenderUrl[]): Sender;
30
+ resolveProvider: (url: string | URL) => ServiceProvider<string> | undefined;
31
+ }
32
+ declare function buildSenderRegistry(providers: ServiceProvider<string, any, any>[]): SenderRegistry;
33
+ //#endregion
34
+ export { DEFAULT_EXTRACTOR as a, ServiceProvider as c, buildSenderRegistry as i, defineProvider as l, SenderRegistry as n, DefineProviderContext as o, SenderUrl as r, DefineProviderOptions as s, Sender as t };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "statocysts",
3
3
  "type": "module",
4
- "version": "0.0.5",
4
+ "version": "0.2.0",
5
5
  "description": "Notification library for JavaScript",
6
6
  "license": "MIT",
7
7
  "homepage": "https://github.com/octoplorer/statocysts",
@@ -17,12 +17,20 @@
17
17
  "shoutrrr"
18
18
  ],
19
19
  "exports": {
20
- ".": "./dist/index.js",
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js"
23
+ },
24
+ "./browser": {
25
+ "types": "./dist/browser.d.ts",
26
+ "import": "./dist/browser.js"
27
+ },
21
28
  "./package.json": "./package.json"
22
29
  },
23
30
  "main": "./dist/index.js",
24
31
  "module": "./dist/index.js",
25
32
  "types": "./dist/index.d.ts",
33
+ "browser": "./dist/browser.js",
26
34
  "files": [
27
35
  "dist"
28
36
  ],
@@ -33,12 +41,15 @@
33
41
  "node": ">=24.12.0"
34
42
  },
35
43
  "dependencies": {
44
+ "defu": "^6.1.4",
36
45
  "ofetch": "^1.5.1",
46
+ "ufo": "^1.6.1",
37
47
  "zod": "^4.2.1"
38
48
  },
39
49
  "devDependencies": {
40
50
  "@antfu/eslint-config": "^6.7.1",
41
51
  "@types/node": "^25.0.2",
52
+ "@vitest/coverage-v8": "4.0.15",
42
53
  "bumpp": "^10.3.2",
43
54
  "eslint": "^9.39.2",
44
55
  "eslint-plugin-format": "^1.1.0",