easy-ping 0.1.0 → 0.3.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 +44 -2
- package/dist/{adapter-f0OR2DhY.d.cts → adapter-BfLe2J0t.d.cts} +10 -0
- package/dist/{adapter-f0OR2DhY.d.ts → adapter-BfLe2J0t.d.ts} +10 -0
- package/dist/adapters/drizzle.cjs +6 -2
- package/dist/adapters/drizzle.cjs.map +1 -1
- package/dist/adapters/drizzle.d.cts +1 -1
- package/dist/adapters/drizzle.d.ts +1 -1
- package/dist/adapters/drizzle.js +6 -2
- package/dist/adapters/drizzle.js.map +1 -1
- package/dist/adapters/mongodb.cjs +3 -2
- package/dist/adapters/mongodb.cjs.map +1 -1
- package/dist/adapters/mongodb.d.cts +2 -2
- package/dist/adapters/mongodb.d.ts +2 -2
- package/dist/adapters/mongodb.js +3 -2
- package/dist/adapters/mongodb.js.map +1 -1
- package/dist/adapters/postgres.cjs +484 -0
- package/dist/adapters/postgres.cjs.map +1 -0
- package/dist/adapters/postgres.d.cts +81 -0
- package/dist/adapters/postgres.d.ts +81 -0
- package/dist/adapters/postgres.js +360 -0
- package/dist/adapters/postgres.js.map +1 -0
- package/dist/chunk-RBDW4S6F.js +199 -0
- package/dist/chunk-RBDW4S6F.js.map +1 -0
- package/dist/client.cjs +3 -5
- package/dist/client.cjs.map +1 -1
- package/dist/client.js +3 -5
- package/dist/client.js.map +1 -1
- package/dist/index.cjs +17 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -4
- package/dist/index.d.ts +6 -4
- package/dist/index.js +17 -11
- package/dist/index.js.map +1 -1
- package/dist/{plugin-bTJKmnlq.d.ts → plugin-CmPOFVmn.d.ts} +1 -1
- package/dist/{plugin-Bqj9xAOS.d.cts → plugin-f5KaFWSN.d.cts} +1 -1
- package/dist/plugins/digests.d.cts +2 -2
- package/dist/plugins/digests.d.ts +2 -2
- package/dist/plugins/preferences-client.d.cts +2 -2
- package/dist/plugins/preferences-client.d.ts +2 -2
- package/dist/plugins/preferences.d.cts +2 -2
- package/dist/plugins/preferences.d.ts +2 -2
- package/dist/plugins/push.cjs +25 -23
- package/dist/plugins/push.cjs.map +1 -1
- package/dist/plugins/push.d.cts +59 -3
- package/dist/plugins/push.d.ts +59 -3
- package/dist/plugins/push.js +25 -24
- package/dist/plugins/push.js.map +1 -1
- package/dist/providers/web-push.d.cts +2 -2
- package/dist/providers/web-push.d.ts +2 -2
- package/dist/react.cjs +3 -5
- package/dist/react.cjs.map +1 -1
- package/dist/react.js +3 -5
- package/dist/react.js.map +1 -1
- package/dist/schema.d.cts +2 -2
- package/dist/schema.d.ts +2 -2
- package/dist/schema.js +1 -197
- package/dist/schema.js.map +1 -1
- package/dist/testing.cjs +29 -0
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +1 -1
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +29 -0
- package/dist/testing.js.map +1 -1
- package/package.json +15 -11
package/dist/plugins/push.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { h as EasyPingPlugin } from '../plugin-
|
|
2
|
-
import '../adapter-
|
|
1
|
+
import { h as EasyPingPlugin } from '../plugin-CmPOFVmn.js';
|
|
2
|
+
import '../adapter-BfLe2J0t.js';
|
|
3
3
|
|
|
4
4
|
type PushSubscription = {
|
|
5
5
|
endpoint: string;
|
|
@@ -55,6 +55,62 @@ type PushOptions = {
|
|
|
55
55
|
* immediately: an unpruned registry accumulates dead subscriptions forever and
|
|
56
56
|
* every send slows down behind them.
|
|
57
57
|
*/
|
|
58
|
+
/**
|
|
59
|
+
* The tables this plugin owns, as a standalone value.
|
|
60
|
+
*
|
|
61
|
+
* Exported separately from `push()` so DDL can be rendered without building a
|
|
62
|
+
* plugin instance — otherwise creating the tables means inventing a provider
|
|
63
|
+
* and a render function you never intend to call.
|
|
64
|
+
*/
|
|
65
|
+
declare const pushSchema: {
|
|
66
|
+
readonly pushDevice: {
|
|
67
|
+
readonly tableName: "notification_push_device";
|
|
68
|
+
readonly fields: {
|
|
69
|
+
readonly id: {
|
|
70
|
+
readonly type: "string";
|
|
71
|
+
readonly required: true;
|
|
72
|
+
};
|
|
73
|
+
readonly userId: {
|
|
74
|
+
readonly type: "string";
|
|
75
|
+
readonly required: true;
|
|
76
|
+
};
|
|
77
|
+
readonly endpoint: {
|
|
78
|
+
readonly type: "string";
|
|
79
|
+
readonly required: true;
|
|
80
|
+
};
|
|
81
|
+
readonly p256dh: {
|
|
82
|
+
readonly type: "string";
|
|
83
|
+
readonly required: true;
|
|
84
|
+
};
|
|
85
|
+
readonly auth: {
|
|
86
|
+
readonly type: "string";
|
|
87
|
+
readonly required: true;
|
|
88
|
+
};
|
|
89
|
+
readonly userAgent: {
|
|
90
|
+
readonly type: "string";
|
|
91
|
+
};
|
|
92
|
+
readonly createdAt: {
|
|
93
|
+
readonly type: "date";
|
|
94
|
+
readonly required: true;
|
|
95
|
+
readonly defaultNow: true;
|
|
96
|
+
};
|
|
97
|
+
readonly lastSeenAt: {
|
|
98
|
+
readonly type: "date";
|
|
99
|
+
readonly required: true;
|
|
100
|
+
readonly defaultNow: true;
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
readonly primaryKey: readonly ["id"];
|
|
104
|
+
readonly indexes: readonly [{
|
|
105
|
+
readonly on: readonly ["userId"];
|
|
106
|
+
readonly name: "push_device_user_idx";
|
|
107
|
+
}, {
|
|
108
|
+
readonly on: readonly ["endpoint"];
|
|
109
|
+
readonly unique: true;
|
|
110
|
+
readonly name: "push_device_endpoint_idx";
|
|
111
|
+
}];
|
|
112
|
+
};
|
|
113
|
+
};
|
|
58
114
|
declare function push(options: PushOptions): EasyPingPlugin<"push">;
|
|
59
115
|
|
|
60
|
-
export { type PushDevice, type PushMessage, type PushOptions, type PushProvider, type PushSendResult, type PushSubscription, push };
|
|
116
|
+
export { type PushDevice, type PushMessage, type PushOptions, type PushProvider, type PushSendResult, type PushSubscription, push, pushSchema };
|
package/dist/plugins/push.js
CHANGED
|
@@ -1,5 +1,27 @@
|
|
|
1
1
|
// src/plugins/push/index.ts
|
|
2
2
|
var DEVICE = "notification_push_device";
|
|
3
|
+
var pushSchema = {
|
|
4
|
+
pushDevice: {
|
|
5
|
+
tableName: DEVICE,
|
|
6
|
+
fields: {
|
|
7
|
+
id: { type: "string", required: true },
|
|
8
|
+
userId: { type: "string", required: true },
|
|
9
|
+
endpoint: { type: "string", required: true },
|
|
10
|
+
p256dh: { type: "string", required: true },
|
|
11
|
+
auth: { type: "string", required: true },
|
|
12
|
+
userAgent: { type: "string" },
|
|
13
|
+
createdAt: { type: "date", required: true, defaultNow: true },
|
|
14
|
+
lastSeenAt: { type: "date", required: true, defaultNow: true }
|
|
15
|
+
},
|
|
16
|
+
primaryKey: ["id"],
|
|
17
|
+
indexes: [
|
|
18
|
+
{ on: ["userId"], name: "push_device_user_idx" },
|
|
19
|
+
// One row per endpoint: re-registering the same browser must update,
|
|
20
|
+
// not duplicate, or every send goes out N times to one device.
|
|
21
|
+
{ on: ["endpoint"], unique: true, name: "push_device_endpoint_idx" }
|
|
22
|
+
]
|
|
23
|
+
}
|
|
24
|
+
};
|
|
3
25
|
function push(options) {
|
|
4
26
|
let ctx;
|
|
5
27
|
const staleAfterDays = options.staleAfterDays ?? 180;
|
|
@@ -9,35 +31,14 @@ function push(options) {
|
|
|
9
31
|
init: (context) => {
|
|
10
32
|
ctx = context;
|
|
11
33
|
},
|
|
12
|
-
schema:
|
|
13
|
-
pushDevice: {
|
|
14
|
-
tableName: DEVICE,
|
|
15
|
-
fields: {
|
|
16
|
-
id: { type: "string", required: true },
|
|
17
|
-
userId: { type: "string", required: true },
|
|
18
|
-
endpoint: { type: "string", required: true },
|
|
19
|
-
p256dh: { type: "string", required: true },
|
|
20
|
-
auth: { type: "string", required: true },
|
|
21
|
-
userAgent: { type: "string" },
|
|
22
|
-
createdAt: { type: "date", required: true, defaultNow: true },
|
|
23
|
-
lastSeenAt: { type: "date", required: true, defaultNow: true }
|
|
24
|
-
},
|
|
25
|
-
primaryKey: ["id"],
|
|
26
|
-
indexes: [
|
|
27
|
-
{ on: ["userId"], name: "push_device_user_idx" },
|
|
28
|
-
// One row per endpoint: re-registering the same browser must update,
|
|
29
|
-
// not duplicate, or every send goes out N times to one device.
|
|
30
|
-
{ on: ["endpoint"], unique: true, name: "push_device_endpoint_idx" }
|
|
31
|
-
]
|
|
32
|
-
}
|
|
33
|
-
},
|
|
34
|
+
schema: pushSchema,
|
|
34
35
|
hooks: {
|
|
35
36
|
deliver: async (context) => {
|
|
36
37
|
const devices = await ctx.store.find(DEVICE, {
|
|
37
38
|
userId: context.notification.userId
|
|
38
39
|
});
|
|
39
40
|
if (devices.length === 0) {
|
|
40
|
-
return { result: "
|
|
41
|
+
return { result: "skipped", reason: "no registered devices" };
|
|
41
42
|
}
|
|
42
43
|
const content = options.render({
|
|
43
44
|
type: context.notification.type,
|
|
@@ -139,6 +140,6 @@ function push(options) {
|
|
|
139
140
|
};
|
|
140
141
|
}
|
|
141
142
|
|
|
142
|
-
export { push };
|
|
143
|
+
export { push, pushSchema };
|
|
143
144
|
//# sourceMappingURL=push.js.map
|
|
144
145
|
//# sourceMappingURL=push.js.map
|
package/dist/plugins/push.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/plugins/push/index.ts"],"names":[],"mappings":";AAGA,IAAM,MAAA,GAAS,0BAAA;AAqDR,SAAS,KAAK,OAAA,EAA8C;AACjE,EAAA,IAAI,GAAA;AACJ,EAAA,MAAM,cAAA,GAAiB,QAAQ,cAAA,IAAkB,GAAA;AAEjD,EAAA,OAAO;AAAA,IACL,EAAA,EAAI,MAAA;AAAA,IACJ,QAAA,EAAU,CAAC,MAAM,CAAA;AAAA,IAEjB,IAAA,EAAM,CAAC,OAAA,KAAY;AACjB,MAAA,GAAA,GAAM,OAAA;AAAA,IACR,CAAA;AAAA,IAEA,MAAA,EAAQ;AAAA,M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;AAAA,QACE,IAAA,EAAM,aAAA;AAAA,QACN,MAAA,EAAQ,MAAA;AAAA,QACR,KAAA,EAAO,EAAE,IAAA,EAAM,SAAA,EAAU;AAAA,QACzB,SAAS,YAAY;AACnB,UAAA,MAAM,SAAS,IAAI,IAAA,CAAK,KAAK,GAAA,EAAI,GAAI,iBAAiB,KAAU,CAAA;AAChE,UAAA,MAAM,OAAA,GAAU,MAAM,GAAA,CAAI,KAAA,CAAM,MAAA,CAAO,MAAA,EAAQ,EAAE,UAAA,EAAY,EAAE,EAAA,EAAI,MAAA,EAAO,EAAG,CAAA;AAC7E,UAAA,OAAO,QAAA,CAAS,IAAA,CAAK,EAAE,OAAA,EAAS,CAAA;AAAA,QAClC;AAAA;AACF;AACF,GACF;AACF","file":"push.js","sourcesContent":["import type { DeliveryOutcome } from \"../../core/adapter\";\nimport type { DeliverContext, EasyPingPlugin, PluginInitContext } from \"../../core/plugin\";\n\nconst DEVICE = \"notification_push_device\";\n\nexport type PushSubscription = {\n endpoint: string;\n keys: { p256dh: string; auth: string };\n};\n\nexport type PushMessage = {\n subscription: PushSubscription;\n title: string;\n body: string;\n data?: Record<string, unknown> | undefined;\n signal?: AbortSignal | undefined;\n};\n\nexport type PushSendResult = {\n /** True when the endpoint is permanently gone (404/410) and must be pruned. */\n expired?: boolean;\n retryable?: boolean;\n};\n\nexport type PushProvider = {\n name: string;\n send(message: PushMessage): Promise<PushSendResult>;\n};\n\nexport type PushDevice = {\n id: string;\n userId: string;\n endpoint: string;\n p256dh: string;\n auth: string;\n userAgent: string | null;\n createdAt: Date;\n lastSeenAt: Date;\n};\n\nexport type PushOptions = {\n provider: PushProvider;\n /** Builds the notification shown on the device. */\n render: (input: { type: string; payload: unknown }) => { title: string; body: string };\n /** Devices untouched for this long are pruned on next delivery. */\n staleAfterDays?: number;\n};\n\n/**\n * Web push over the device registry.\n *\n * Tokens are per device, not per user, so a delivery fans out and succeeds if\n * any endpoint accepts. Endpoints that report themselves gone are deleted\n * immediately: an unpruned registry accumulates dead subscriptions forever and\n * every send slows down behind them.\n */\nexport function push(options: PushOptions): EasyPingPlugin<\"push\"> {\n let ctx: PluginInitContext;\n const staleAfterDays = options.staleAfterDays ?? 180;\n\n return {\n id: \"push\",\n channels: [\"push\"],\n\n init: (context) => {\n ctx = context;\n },\n\n schema: {\n pushDevice: {\n tableName: DEVICE,\n fields: {\n id: { type: \"string\", required: true },\n userId: { type: \"string\", required: true },\n endpoint: { type: \"string\", required: true },\n p256dh: { type: \"string\", required: true },\n auth: { type: \"string\", required: true },\n userAgent: { type: \"string\" },\n createdAt: { type: \"date\", required: true, defaultNow: true },\n lastSeenAt: { type: \"date\", required: true, defaultNow: true },\n },\n primaryKey: [\"id\"],\n indexes: [\n { on: [\"userId\"], name: \"push_device_user_idx\" },\n // One row per endpoint: re-registering the same browser must update,\n // not duplicate, or every send goes out N times to one device.\n { on: [\"endpoint\"], unique: true, name: \"push_device_endpoint_idx\" },\n ],\n },\n },\n\n hooks: {\n deliver: async (context: DeliverContext): Promise<DeliveryOutcome> => {\n const devices = await ctx.store.find<PushDevice>(DEVICE, {\n userId: context.notification.userId,\n });\n\n if (devices.length === 0) {\n return { result: \"failed\", error: \"no registered devices\", retryable: false };\n }\n\n const content = options.render({\n type: context.notification.type,\n payload: context.notification.payload,\n });\n\n const expired: string[] = [];\n let delivered = 0;\n let retryable = false;\n let lastError = \"\";\n\n for (const device of devices) {\n try {\n const result = await options.provider.send({\n subscription: {\n endpoint: device.endpoint,\n keys: { p256dh: device.p256dh, auth: device.auth },\n },\n ...content,\n data: { notificationId: context.notification.id, type: context.notification.type },\n signal: context.signal,\n });\n\n if (result.expired) expired.push(device.id);\n else {\n delivered += 1;\n if (result.retryable) retryable = true;\n }\n } catch (error) {\n lastError = error instanceof Error ? error.message : String(error);\n retryable = true;\n }\n }\n\n if (expired.length > 0) await ctx.store.remove(DEVICE, { id: { in: expired } });\n\n if (delivered > 0) return { result: \"sent\" };\n\n // Every endpoint was gone: retrying cannot help, and the rows are\n // already deleted.\n if (expired.length === devices.length) {\n return { result: \"failed\", error: \"all devices expired\", retryable: false };\n }\n\n return {\n result: \"failed\",\n error: lastError || \"no device accepted the push\",\n retryable,\n };\n },\n },\n\n routes: [\n {\n path: \"/push/devices\",\n method: \"POST\",\n scope: { type: \"user\" },\n handler: async ({ request, userId }) => {\n const body = (await request.json().catch(() => null)) as PushSubscription | null;\n if (!body?.endpoint || !body.keys?.p256dh || !body.keys?.auth) {\n return Response.json({ error: \"endpoint and keys are required\" }, { status: 400 });\n }\n\n // Upsert on endpoint: the same browser re-registering after a\n // service-worker update must not create a second row.\n await ctx.store.upsert(\n DEVICE,\n [\n {\n id: crypto.randomUUID(),\n userId: userId ?? \"\",\n endpoint: body.endpoint,\n p256dh: body.keys.p256dh,\n auth: body.keys.auth,\n userAgent: request.headers.get(\"user-agent\"),\n createdAt: new Date(),\n lastSeenAt: new Date(),\n },\n ],\n { onConflict: [\"endpoint\"] },\n );\n\n return Response.json({ ok: true });\n },\n },\n\n {\n path: \"/push/devices/remove\",\n method: \"POST\",\n scope: { type: \"user\" },\n handler: async ({ request, userId }) => {\n const body = (await request.json().catch(() => null)) as { endpoint?: string } | null;\n if (!body?.endpoint) {\n return Response.json({ error: \"endpoint is required\" }, { status: 400 });\n }\n\n // Scoped by userId as well as endpoint: an endpoint string is not a\n // secret, and must not let one user unregister another's device.\n const removed = await ctx.store.remove(DEVICE, {\n userId: userId ?? \"\",\n endpoint: body.endpoint,\n });\n\n return removed === 0 ? new Response(null, { status: 404 }) : Response.json({ ok: true });\n },\n },\n\n {\n path: \"/push/prune\",\n method: \"POST\",\n scope: { type: \"machine\" },\n handler: async () => {\n const cutoff = new Date(Date.now() - staleAfterDays * 86_400_000);\n const removed = await ctx.store.remove(DEVICE, { lastSeenAt: { lt: cutoff } });\n return Response.json({ removed });\n },\n },\n ],\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/plugins/push/index.ts"],"names":[],"mappings":";AAQA,IAAM,M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AAIA,UAAA,MAAM,OAAA,GAAU,MAAM,GAAA,CAAI,KAAA,CAAM,OAAO,MAAA,EAAQ;AAAA,YAC7C,QAAQ,MAAA,IAAU,EAAA;AAAA,YAClB,UAAU,IAAA,CAAK;AAAA,WAChB,CAAA;AAED,UAAA,OAAO,OAAA,KAAY,CAAA,GAAI,IAAI,QAAA,CAAS,MAAM,EAAE,MAAA,EAAQ,GAAA,EAAK,IAAI,QAAA,CAAS,IAAA,CAAK,EAAE,EAAA,EAAI,MAAM,CAAA;AAAA,QACzF;AAAA,OACF;AAAA,MAEA;AAAA,QACE,IAAA,EAAM,aAAA;AAAA,QACN,MAAA,EAAQ,MAAA;AAAA,QACR,KAAA,EAAO,EAAE,IAAA,EAAM,SAAA,EAAU;AAAA,QACzB,SAAS,YAAY;AACnB,UAAA,MAAM,SAAS,IAAI,IAAA,CAAK,KAAK,GAAA,EAAI,GAAI,iBAAiB,KAAU,CAAA;AAChE,UAAA,MAAM,OAAA,GAAU,MAAM,GAAA,CAAI,KAAA,CAAM,MAAA,CAAO,MAAA,EAAQ,EAAE,UAAA,EAAY,EAAE,EAAA,EAAI,MAAA,EAAO,EAAG,CAAA;AAC7E,UAAA,OAAO,QAAA,CAAS,IAAA,CAAK,EAAE,OAAA,EAAS,CAAA;AAAA,QAClC;AAAA;AACF;AACF,GACF;AACF","file":"push.js","sourcesContent":["import type { DeliveryOutcome } from \"../../core/adapter\";\nimport type {\n DeliverContext,\n EasyPingPlugin,\n PluginInitContext,\n SchemaDeclaration,\n} from \"../../core/plugin\";\n\nconst DEVICE = \"notification_push_device\";\n\nexport type PushSubscription = {\n endpoint: string;\n keys: { p256dh: string; auth: string };\n};\n\nexport type PushMessage = {\n subscription: PushSubscription;\n title: string;\n body: string;\n data?: Record<string, unknown> | undefined;\n signal?: AbortSignal | undefined;\n};\n\nexport type PushSendResult = {\n /** True when the endpoint is permanently gone (404/410) and must be pruned. */\n expired?: boolean;\n retryable?: boolean;\n};\n\nexport type PushProvider = {\n name: string;\n send(message: PushMessage): Promise<PushSendResult>;\n};\n\nexport type PushDevice = {\n id: string;\n userId: string;\n endpoint: string;\n p256dh: string;\n auth: string;\n userAgent: string | null;\n createdAt: Date;\n lastSeenAt: Date;\n};\n\nexport type PushOptions = {\n provider: PushProvider;\n /** Builds the notification shown on the device. */\n render: (input: { type: string; payload: unknown }) => { title: string; body: string };\n /** Devices untouched for this long are pruned on next delivery. */\n staleAfterDays?: number;\n};\n\n/**\n * Web push over the device registry.\n *\n * Tokens are per device, not per user, so a delivery fans out and succeeds if\n * any endpoint accepts. Endpoints that report themselves gone are deleted\n * immediately: an unpruned registry accumulates dead subscriptions forever and\n * every send slows down behind them.\n */\n/**\n * The tables this plugin owns, as a standalone value.\n *\n * Exported separately from `push()` so DDL can be rendered without building a\n * plugin instance — otherwise creating the tables means inventing a provider\n * and a render function you never intend to call.\n */\nexport const pushSchema = {\n pushDevice: {\n tableName: DEVICE,\n fields: {\n id: { type: \"string\", required: true },\n userId: { type: \"string\", required: true },\n endpoint: { type: \"string\", required: true },\n p256dh: { type: \"string\", required: true },\n auth: { type: \"string\", required: true },\n userAgent: { type: \"string\" },\n createdAt: { type: \"date\", required: true, defaultNow: true },\n lastSeenAt: { type: \"date\", required: true, defaultNow: true },\n },\n primaryKey: [\"id\"],\n indexes: [\n { on: [\"userId\"], name: \"push_device_user_idx\" },\n // One row per endpoint: re-registering the same browser must update,\n // not duplicate, or every send goes out N times to one device.\n { on: [\"endpoint\"], unique: true, name: \"push_device_endpoint_idx\" },\n ],\n },\n} as const satisfies SchemaDeclaration;\n\nexport function push(options: PushOptions): EasyPingPlugin<\"push\"> {\n let ctx: PluginInitContext;\n const staleAfterDays = options.staleAfterDays ?? 180;\n\n return {\n id: \"push\",\n channels: [\"push\"],\n\n init: (context) => {\n ctx = context;\n },\n\n schema: pushSchema,\n\n hooks: {\n deliver: async (context: DeliverContext): Promise<DeliveryOutcome> => {\n const devices = await ctx.store.find<PushDevice>(DEVICE, {\n userId: context.notification.userId,\n });\n\n if (devices.length === 0) {\n // Not a failure: this person has simply not enabled push anywhere.\n return { result: \"skipped\", reason: \"no registered devices\" };\n }\n\n const content = options.render({\n type: context.notification.type,\n payload: context.notification.payload,\n });\n\n const expired: string[] = [];\n let delivered = 0;\n let retryable = false;\n let lastError = \"\";\n\n for (const device of devices) {\n try {\n const result = await options.provider.send({\n subscription: {\n endpoint: device.endpoint,\n keys: { p256dh: device.p256dh, auth: device.auth },\n },\n ...content,\n data: { notificationId: context.notification.id, type: context.notification.type },\n signal: context.signal,\n });\n\n if (result.expired) expired.push(device.id);\n else {\n delivered += 1;\n if (result.retryable) retryable = true;\n }\n } catch (error) {\n lastError = error instanceof Error ? error.message : String(error);\n retryable = true;\n }\n }\n\n if (expired.length > 0) await ctx.store.remove(DEVICE, { id: { in: expired } });\n\n if (delivered > 0) return { result: \"sent\" };\n\n // Every endpoint was gone: retrying cannot help, and the rows are\n // already deleted.\n if (expired.length === devices.length) {\n return { result: \"failed\", error: \"all devices expired\", retryable: false };\n }\n\n return {\n result: \"failed\",\n error: lastError || \"no device accepted the push\",\n retryable,\n };\n },\n },\n\n routes: [\n {\n path: \"/push/devices\",\n method: \"POST\",\n scope: { type: \"user\" },\n handler: async ({ request, userId }) => {\n const body = (await request.json().catch(() => null)) as PushSubscription | null;\n if (!body?.endpoint || !body.keys?.p256dh || !body.keys?.auth) {\n return Response.json({ error: \"endpoint and keys are required\" }, { status: 400 });\n }\n\n // Upsert on endpoint: the same browser re-registering after a\n // service-worker update must not create a second row.\n await ctx.store.upsert(\n DEVICE,\n [\n {\n id: crypto.randomUUID(),\n userId: userId ?? \"\",\n endpoint: body.endpoint,\n p256dh: body.keys.p256dh,\n auth: body.keys.auth,\n userAgent: request.headers.get(\"user-agent\"),\n createdAt: new Date(),\n lastSeenAt: new Date(),\n },\n ],\n { onConflict: [\"endpoint\"] },\n );\n\n return Response.json({ ok: true });\n },\n },\n\n {\n path: \"/push/devices/remove\",\n method: \"POST\",\n scope: { type: \"user\" },\n handler: async ({ request, userId }) => {\n const body = (await request.json().catch(() => null)) as { endpoint?: string } | null;\n if (!body?.endpoint) {\n return Response.json({ error: \"endpoint is required\" }, { status: 400 });\n }\n\n // Scoped by userId as well as endpoint: an endpoint string is not a\n // secret, and must not let one user unregister another's device.\n const removed = await ctx.store.remove(DEVICE, {\n userId: userId ?? \"\",\n endpoint: body.endpoint,\n });\n\n return removed === 0 ? new Response(null, { status: 404 }) : Response.json({ ok: true });\n },\n },\n\n {\n path: \"/push/prune\",\n method: \"POST\",\n scope: { type: \"machine\" },\n handler: async () => {\n const cutoff = new Date(Date.now() - staleAfterDays * 86_400_000);\n const removed = await ctx.store.remove(DEVICE, { lastSeenAt: { lt: cutoff } });\n return Response.json({ removed });\n },\n },\n ],\n };\n}\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { PushProvider } from '../plugins/push.cjs';
|
|
2
|
-
import '../plugin-
|
|
3
|
-
import '../adapter-
|
|
2
|
+
import '../plugin-f5KaFWSN.cjs';
|
|
3
|
+
import '../adapter-BfLe2J0t.cjs';
|
|
4
4
|
|
|
5
5
|
/** One record: record size less the padding delimiter and the GCM tag. */
|
|
6
6
|
declare const MAX_PAYLOAD_BYTES: number;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { PushProvider } from '../plugins/push.js';
|
|
2
|
-
import '../plugin-
|
|
3
|
-
import '../adapter-
|
|
2
|
+
import '../plugin-CmPOFVmn.js';
|
|
3
|
+
import '../adapter-BfLe2J0t.js';
|
|
4
4
|
|
|
5
5
|
/** One record: record size less the padding delimiter and the GCM tag. */
|
|
6
6
|
declare const MAX_PAYLOAD_BYTES: number;
|
package/dist/react.cjs
CHANGED
|
@@ -66,15 +66,13 @@ function createNotifyClient(options = {}) {
|
|
|
66
66
|
}
|
|
67
67
|
async function refresh() {
|
|
68
68
|
const startedAt = generation;
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
request("/count")
|
|
72
|
-
]);
|
|
69
|
+
const page = await request(`/?limit=${limit}`);
|
|
70
|
+
const unseenCount = page.unseenCount ?? (await request("/count")).unseen;
|
|
73
71
|
if (generation !== startedAt) return;
|
|
74
72
|
set({
|
|
75
73
|
notifications: page.notifications,
|
|
76
74
|
nextCursor: page.nextCursor,
|
|
77
|
-
unseenCount
|
|
75
|
+
unseenCount,
|
|
78
76
|
isLoading: false,
|
|
79
77
|
error: null
|
|
80
78
|
});
|
package/dist/react.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react/index.ts","../src/client/index.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n createNotifyClient,\n type NotifyClient,\n type NotifyClientOptions,\n type NotifyState,\n} from \"../client\";\n\nexport type UseNotificationsResult = NotifyState & {\n markAsRead: (id: string) => Promise<void>;\n markAllRead: () => Promise<void>;\n markSeen: () => Promise<void>;\n loadMore: () => Promise<void>;\n refresh: () => Promise<void>;\n};\n\n/**\n * All state and optimistic-rollback logic lives in the framework-agnostic\n * client; this binding only wires it to React's lifecycle.\n */\nexport function useNotifications(\n options: NotifyClientOptions & { client?: NotifyClient } = {},\n): UseNotificationsResult {\n const { client: provided, baseUrl, limit, pollIntervalMs, maxPollIntervalMs } = options;\n\n // Callbacks are usually inline literals. Held in a ref and called through a\n // stable wrapper so a new function identity each render does not rebuild the\n // client and restart polling.\n const callbacksRef = useRef(options);\n callbacksRef.current = options;\n\n const client = useMemo(\n () =>\n provided ??\n createNotifyClient({\n baseUrl,\n limit,\n pollIntervalMs,\n maxPollIntervalMs,\n fetch: (...args) => (callbacksRef.current.fetch ?? globalThis.fetch)(...args),\n isDocumentHidden: () =>\n callbacksRef.current.isDocumentHidden?.() ??\n (typeof document !== \"undefined\" && document.visibilityState === \"hidden\"),\n }),\n [provided, baseUrl, limit, pollIntervalMs, maxPollIntervalMs],\n );\n\n const [state, setState] = useState<NotifyState>(() => client.getState());\n\n useEffect(() => client.subscribe(setState), [client]);\n\n return {\n ...state,\n markAsRead: useCallback((id: string) => client.markAsRead(id), [client]),\n markAllRead: useCallback(() => client.markAllRead(), [client]),\n markSeen: useCallback(() => client.markSeen(), [client]),\n loadMore: useCallback(() => client.loadMore(), [client]),\n refresh: useCallback(() => client.refresh(), [client]),\n };\n}\n\nexport type {\n NotificationView,\n NotifyClient,\n NotifyClientOptions,\n NotifyState,\n} from \"../client\";\nexport { createNotifyClient } from \"../client\";\n","export type NotificationView = {\n id: string;\n userId: string;\n type: string;\n payload: unknown;\n actorId: string | null;\n groupKey: string | null;\n seenAt: string | null;\n readAt: string | null;\n createdAt: string;\n};\n\nexport type NotifyState = {\n notifications: readonly NotificationView[];\n /** Badge count — cleared when the dropdown opens. Server-authoritative. */\n unseenCount: number;\n /** Items still bold. Derived from what is loaded, not a server total. */\n unreadCount: number;\n nextCursor: string | null;\n isLoading: boolean;\n error: Error | null;\n};\n\nexport type NotifyClientOptions = {\n baseUrl?: string | undefined;\n fetch?: typeof globalThis.fetch | undefined;\n limit?: number | undefined;\n pollIntervalMs?: number | undefined;\n maxPollIntervalMs?: number | undefined;\n /** Injectable so the poller can be tested without a DOM. */\n isDocumentHidden?: (() => boolean) | undefined;\n};\n\nconst INITIAL: NotifyState = {\n notifications: [],\n unseenCount: 0,\n unreadCount: 0,\n nextCursor: null,\n isLoading: true,\n error: null,\n};\n\nconst countUnread = (rows: readonly NotificationView[]) =>\n rows.reduce((total, row) => (row.readAt === null ? total + 1 : total), 0);\n\nexport function createNotifyClient(options: NotifyClientOptions = {}) {\n const baseUrl = (options.baseUrl ?? \"/api/notifications\").replace(/\\/$/, \"\");\n const doFetch = options.fetch ?? ((...args) => globalThis.fetch(...args));\n const limit = options.limit ?? 20;\n const pollIntervalMs = options.pollIntervalMs ?? 15_000;\n const maxPollIntervalMs = options.maxPollIntervalMs ?? 5 * 60_000;\n const isHidden =\n options.isDocumentHidden ??\n (() => typeof document !== \"undefined\" && document.visibilityState === \"hidden\");\n\n let state: NotifyState = INITIAL;\n const listeners = new Set<(state: NotifyState) => void>();\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n let consecutiveFailures = 0;\n\n // Bumped per mutation: an in-flight poll returns pre-mutation data, which\n // would silently revert the optimistic update.\n let generation = 0;\n\n function set(patch: Partial<NotifyState>) {\n state = { ...state, ...patch };\n state = { ...state, unreadCount: countUnread(state.notifications) };\n for (const listener of listeners) listener(state);\n }\n\n async function request<T>(path: string, init?: RequestInit): Promise<T> {\n const response = await doFetch(`${baseUrl}${path}`, {\n ...init,\n headers: { \"content-type\": \"application/json\", ...init?.headers },\n });\n if (!response.ok)\n throw new Error(`${init?.method ?? \"GET\"} ${path} failed: ${response.status}`);\n return (await response.json()) as T;\n }\n\n async function refresh(): Promise<void> {\n const startedAt = generation;\n\n const [page, count] = await Promise.all([\n request<{ notifications: NotificationView[]; nextCursor: string | null }>(`/?limit=${limit}`),\n request<{ unseen: number }>(\"/count\"),\n ]);\n\n // A mutation landed while this was in flight, so the response is already\n // stale. Dropping it is correct: the mutation's own optimistic state is\n // newer, and the next poll will reconcile.\n if (generation !== startedAt) return;\n\n set({\n notifications: page.notifications,\n nextCursor: page.nextCursor,\n unseenCount: count.unseen,\n isLoading: false,\n error: null,\n });\n }\n\n let loadingMore: Promise<void> | undefined;\n\n async function loadMore(): Promise<void> {\n if (!state.nextCursor) return;\n\n // Two clicks before the first response lands would both read the same\n // cursor and append the same page twice. Share the in-flight request.\n if (loadingMore) return loadingMore;\n\n const cursor = state.nextCursor;\n\n loadingMore = (async () => {\n try {\n const page = await request<{\n notifications: NotificationView[];\n nextCursor: string | null;\n }>(`/?limit=${limit}&cursor=${encodeURIComponent(cursor)}`);\n\n // Guard against a duplicate arriving anyway — a concurrent refresh may\n // already have pulled some of these into the list.\n const known = new Set(state.notifications.map((row) => row.id));\n\n set({\n notifications: [\n ...state.notifications,\n ...page.notifications.filter((row) => !known.has(row.id)),\n ],\n nextCursor: page.nextCursor,\n });\n } finally {\n loadingMore = undefined;\n }\n })();\n\n return loadingMore;\n }\n\n /** Applies a patch immediately and reverts it if the request fails. */\n async function optimistic(\n apply: (rows: readonly NotificationView[]) => readonly NotificationView[],\n patch: Partial<NotifyState>,\n send: () => Promise<unknown>,\n ): Promise<void> {\n const previous = state;\n generation += 1;\n set({ notifications: apply(state.notifications), ...patch });\n\n try {\n await send();\n } catch (error) {\n generation += 1;\n state = previous;\n for (const listener of listeners) listener(state);\n throw error;\n }\n }\n\n const stamp = () => new Date().toISOString();\n\n async function markAsRead(id: string): Promise<void> {\n await optimistic(\n (rows) =>\n rows.map((row) => (row.id === id ? { ...row, readAt: row.readAt ?? stamp() } : row)),\n {},\n () => request(\"/read\", { method: \"POST\", body: JSON.stringify({ ids: [id] }) }),\n );\n }\n\n async function markAllRead(): Promise<void> {\n await optimistic(\n (rows) => rows.map((row) => ({ ...row, readAt: row.readAt ?? stamp() })),\n {},\n () => request(\"/read-all\", { method: \"POST\" }),\n );\n }\n\n async function markSeen(): Promise<void> {\n // Only what the user could actually have seen. Sending no cutoff would\n // mark notifications that landed after the last poll as seen too.\n const newest = state.notifications[0]?.createdAt;\n\n await optimistic(\n (rows) => rows.map((row) => ({ ...row, seenAt: row.seenAt ?? stamp() })),\n { unseenCount: 0 },\n () =>\n request(\"/seen\", {\n method: \"POST\",\n body: JSON.stringify(newest ? { before: newest } : {}),\n }),\n );\n }\n\n function schedule(delay: number) {\n clearTimeout(timer);\n timer = setTimeout(tick, delay);\n }\n\n async function tick() {\n // A hidden tab still holds an open bell. Polling it burns requests for a\n // UI nobody is looking at.\n if (isHidden()) {\n schedule(pollIntervalMs);\n return;\n }\n\n try {\n await refresh();\n consecutiveFailures = 0;\n } catch (error) {\n consecutiveFailures += 1;\n set({ isLoading: false, error: error instanceof Error ? error : new Error(String(error)) });\n }\n\n // Back off on failure so an outage does not turn every open tab into a\n // retry loop against a struggling server.\n schedule(\n consecutiveFailures === 0\n ? pollIntervalMs\n : Math.min(pollIntervalMs * 2 ** consecutiveFailures, maxPollIntervalMs),\n );\n }\n\n function subscribe(listener: (state: NotifyState) => void): () => void {\n listeners.add(listener);\n listener(state);\n\n // One poller regardless of how many components subscribe — otherwise two\n // bells, or a StrictMode double-mount, double the request rate.\n if (listeners.size === 1) void tick();\n\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n }\n\n return {\n subscribe,\n refresh,\n loadMore,\n markAsRead,\n markAllRead,\n markSeen,\n getState: () => state,\n };\n}\n\nexport type NotifyClient = ReturnType<typeof createNotifyClient>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAAkE;;;AC+BlE,IAAM,UAAuB;AAAA,EAC3B,eAAe,CAAC;AAAA,EAChB,aAAa;AAAA,EACb,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,OAAO;AACT;AAEA,IAAM,cAAc,CAAC,SACnB,KAAK,OAAO,CAAC,OAAO,QAAS,IAAI,WAAW,OAAO,QAAQ,IAAI,OAAQ,CAAC;AAEnE,SAAS,mBAAmB,UAA+B,CAAC,GAAG;AACpE,QAAM,WAAW,QAAQ,WAAW,sBAAsB,QAAQ,OAAO,EAAE;AAC3E,QAAM,UAAU,QAAQ,UAAU,IAAI,SAAS,WAAW,MAAM,GAAG,IAAI;AACvE,QAAM,QAAQ,QAAQ,SAAS;AAC/B,QAAM,iBAAiB,QAAQ,kBAAkB;AACjD,QAAM,oBAAoB,QAAQ,qBAAqB,IAAI;AAC3D,QAAM,WACJ,QAAQ,qBACP,MAAM,OAAO,aAAa,eAAe,SAAS,oBAAoB;AAEzE,MAAI,QAAqB;AACzB,QAAM,YAAY,oBAAI,IAAkC;AAExD,MAAI;AACJ,MAAI,sBAAsB;AAI1B,MAAI,aAAa;AAEjB,WAAS,IAAI,OAA6B;AACxC,YAAQ,EAAE,GAAG,OAAO,GAAG,MAAM;AAC7B,YAAQ,E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AAA,MACA,OAAO,IAAI,UAAU,aAAa,QAAQ,SAAS,WAAW,OAAO,GAAG,IAAI;AAAA,MAC5E,kBAAkB,MAChB,aAAa,QAAQ,mBAAmB,MACvC,OAAO,aAAa,eAAe,SAAS,oBAAoB;AAAA,IACrE,CAAC;AAAA,IACH,CAAC,UAAU,SAAS,OAAO,gBAAgB,iBAAiB;AAAA,EAC9D;AAEA,QAAM,CAAC,OAAO,QAAQ,QAAI,uBAAsB,MAAM,OAAO,SAAS,CAAC;AAEvE,8BAAU,MAAM,OAAO,UAAU,QAAQ,GAAG,CAAC,MAAM,CAAC;AAEpD,SAAO;AAAA,IACL,GAAG;AAAA,IACH,gBAAY,0BAAY,CAAC,OAAe,OAAO,WAAW,EAAE,GAAG,CAAC,MAAM,CAAC;AAAA,IACvE,iBAAa,0BAAY,MAAM,OAAO,YAAY,GAAG,CAAC,MAAM,CAAC;AAAA,IAC7D,cAAU,0BAAY,MAAM,OAAO,SAAS,GAAG,CAAC,MAAM,CAAC;AAAA,IACvD,cAAU,0BAAY,MAAM,OAAO,SAAS,GAAG,CAAC,MAAM,CAAC;AAAA,IACvD,aAAS,0BAAY,MAAM,OAAO,QAAQ,GAAG,CAAC,MAAM,CAAC;AAAA,EACvD;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/react/index.ts","../src/client/index.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n createNotifyClient,\n type NotifyClient,\n type NotifyClientOptions,\n type NotifyState,\n} from \"../client\";\n\nexport type UseNotificationsResult = NotifyState & {\n markAsRead: (id: string) => Promise<void>;\n markAllRead: () => Promise<void>;\n markSeen: () => Promise<void>;\n loadMore: () => Promise<void>;\n refresh: () => Promise<void>;\n};\n\n/**\n * All state and optimistic-rollback logic lives in the framework-agnostic\n * client; this binding only wires it to React's lifecycle.\n */\nexport function useNotifications(\n options: NotifyClientOptions & { client?: NotifyClient } = {},\n): UseNotificationsResult {\n const { client: provided, baseUrl, limit, pollIntervalMs, maxPollIntervalMs } = options;\n\n // Callbacks are usually inline literals. Held in a ref and called through a\n // stable wrapper so a new function identity each render does not rebuild the\n // client and restart polling.\n const callbacksRef = useRef(options);\n callbacksRef.current = options;\n\n const client = useMemo(\n () =>\n provided ??\n createNotifyClient({\n baseUrl,\n limit,\n pollIntervalMs,\n maxPollIntervalMs,\n fetch: (...args) => (callbacksRef.current.fetch ?? globalThis.fetch)(...args),\n isDocumentHidden: () =>\n callbacksRef.current.isDocumentHidden?.() ??\n (typeof document !== \"undefined\" && document.visibilityState === \"hidden\"),\n }),\n [provided, baseUrl, limit, pollIntervalMs, maxPollIntervalMs],\n );\n\n const [state, setState] = useState<NotifyState>(() => client.getState());\n\n useEffect(() => client.subscribe(setState), [client]);\n\n return {\n ...state,\n markAsRead: useCallback((id: string) => client.markAsRead(id), [client]),\n markAllRead: useCallback(() => client.markAllRead(), [client]),\n markSeen: useCallback(() => client.markSeen(), [client]),\n loadMore: useCallback(() => client.loadMore(), [client]),\n refresh: useCallback(() => client.refresh(), [client]),\n };\n}\n\nexport type {\n NotificationView,\n NotifyClient,\n NotifyClientOptions,\n NotifyState,\n} from \"../client\";\nexport { createNotifyClient } from \"../client\";\n","export type NotificationView = {\n id: string;\n userId: string;\n type: string;\n payload: unknown;\n actorId: string | null;\n groupKey: string | null;\n seenAt: string | null;\n readAt: string | null;\n createdAt: string;\n};\n\nexport type NotifyState = {\n notifications: readonly NotificationView[];\n /** Badge count — cleared when the dropdown opens. Server-authoritative. */\n unseenCount: number;\n /** Items still bold. Derived from what is loaded, not a server total. */\n unreadCount: number;\n nextCursor: string | null;\n isLoading: boolean;\n error: Error | null;\n};\n\nexport type NotifyClientOptions = {\n baseUrl?: string | undefined;\n fetch?: typeof globalThis.fetch | undefined;\n limit?: number | undefined;\n pollIntervalMs?: number | undefined;\n maxPollIntervalMs?: number | undefined;\n /** Injectable so the poller can be tested without a DOM. */\n isDocumentHidden?: (() => boolean) | undefined;\n};\n\nconst INITIAL: NotifyState = {\n notifications: [],\n unseenCount: 0,\n unreadCount: 0,\n nextCursor: null,\n isLoading: true,\n error: null,\n};\n\nconst countUnread = (rows: readonly NotificationView[]) =>\n rows.reduce((total, row) => (row.readAt === null ? total + 1 : total), 0);\n\nexport function createNotifyClient(options: NotifyClientOptions = {}) {\n const baseUrl = (options.baseUrl ?? \"/api/notifications\").replace(/\\/$/, \"\");\n const doFetch = options.fetch ?? ((...args) => globalThis.fetch(...args));\n const limit = options.limit ?? 20;\n const pollIntervalMs = options.pollIntervalMs ?? 15_000;\n const maxPollIntervalMs = options.maxPollIntervalMs ?? 5 * 60_000;\n const isHidden =\n options.isDocumentHidden ??\n (() => typeof document !== \"undefined\" && document.visibilityState === \"hidden\");\n\n let state: NotifyState = INITIAL;\n const listeners = new Set<(state: NotifyState) => void>();\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n let consecutiveFailures = 0;\n\n // Bumped per mutation: an in-flight poll returns pre-mutation data, which\n // would silently revert the optimistic update.\n let generation = 0;\n\n function set(patch: Partial<NotifyState>) {\n state = { ...state, ...patch };\n state = { ...state, unreadCount: countUnread(state.notifications) };\n for (const listener of listeners) listener(state);\n }\n\n async function request<T>(path: string, init?: RequestInit): Promise<T> {\n const response = await doFetch(`${baseUrl}${path}`, {\n ...init,\n headers: { \"content-type\": \"application/json\", ...init?.headers },\n });\n if (!response.ok)\n throw new Error(`${init?.method ?? \"GET\"} ${path} failed: ${response.status}`);\n return (await response.json()) as T;\n }\n\n async function refresh(): Promise<void> {\n const startedAt = generation;\n\n // One request, not two. The feed carries unseenCount for a first page,\n // which is every poll. A server too old to send it still works: the\n // fallback asks /count the way this always used to.\n const page = await request<{\n notifications: NotificationView[];\n nextCursor: string | null;\n unseenCount?: number;\n }>(`/?limit=${limit}`);\n\n const unseenCount = page.unseenCount ?? (await request<{ unseen: number }>(\"/count\")).unseen;\n\n // A mutation landed while this was in flight, so the response is already\n // stale. Dropping it is correct: the mutation's own optimistic state is\n // newer, and the next poll will reconcile.\n if (generation !== startedAt) return;\n\n set({\n notifications: page.notifications,\n nextCursor: page.nextCursor,\n unseenCount,\n isLoading: false,\n error: null,\n });\n }\n\n let loadingMore: Promise<void> | undefined;\n\n async function loadMore(): Promise<void> {\n if (!state.nextCursor) return;\n\n // Two clicks before the first response lands would both read the same\n // cursor and append the same page twice. Share the in-flight request.\n if (loadingMore) return loadingMore;\n\n const cursor = state.nextCursor;\n\n loadingMore = (async () => {\n try {\n const page = await request<{\n notifications: NotificationView[];\n nextCursor: string | null;\n }>(`/?limit=${limit}&cursor=${encodeURIComponent(cursor)}`);\n\n // Guard against a duplicate arriving anyway — a concurrent refresh may\n // already have pulled some of these into the list.\n const known = new Set(state.notifications.map((row) => row.id));\n\n set({\n notifications: [\n ...state.notifications,\n ...page.notifications.filter((row) => !known.has(row.id)),\n ],\n nextCursor: page.nextCursor,\n });\n } finally {\n loadingMore = undefined;\n }\n })();\n\n return loadingMore;\n }\n\n /** Applies a patch immediately and reverts it if the request fails. */\n async function optimistic(\n apply: (rows: readonly NotificationView[]) => readonly NotificationView[],\n patch: Partial<NotifyState>,\n send: () => Promise<unknown>,\n ): Promise<void> {\n const previous = state;\n generation += 1;\n set({ notifications: apply(state.notifications), ...patch });\n\n try {\n await send();\n } catch (error) {\n generation += 1;\n state = previous;\n for (const listener of listeners) listener(state);\n throw error;\n }\n }\n\n const stamp = () => new Date().toISOString();\n\n async function markAsRead(id: string): Promise<void> {\n await optimistic(\n (rows) =>\n rows.map((row) => (row.id === id ? { ...row, readAt: row.readAt ?? stamp() } : row)),\n {},\n () => request(\"/read\", { method: \"POST\", body: JSON.stringify({ ids: [id] }) }),\n );\n }\n\n async function markAllRead(): Promise<void> {\n await optimistic(\n (rows) => rows.map((row) => ({ ...row, readAt: row.readAt ?? stamp() })),\n {},\n () => request(\"/read-all\", { method: \"POST\" }),\n );\n }\n\n async function markSeen(): Promise<void> {\n // Only what the user could actually have seen. Sending no cutoff would\n // mark notifications that landed after the last poll as seen too.\n const newest = state.notifications[0]?.createdAt;\n\n await optimistic(\n (rows) => rows.map((row) => ({ ...row, seenAt: row.seenAt ?? stamp() })),\n { unseenCount: 0 },\n () =>\n request(\"/seen\", {\n method: \"POST\",\n body: JSON.stringify(newest ? { before: newest } : {}),\n }),\n );\n }\n\n function schedule(delay: number) {\n clearTimeout(timer);\n timer = setTimeout(tick, delay);\n }\n\n async function tick() {\n // A hidden tab still holds an open bell. Polling it burns requests for a\n // UI nobody is looking at.\n if (isHidden()) {\n schedule(pollIntervalMs);\n return;\n }\n\n try {\n await refresh();\n consecutiveFailures = 0;\n } catch (error) {\n consecutiveFailures += 1;\n set({ isLoading: false, error: error instanceof Error ? error : new Error(String(error)) });\n }\n\n // Back off on failure so an outage does not turn every open tab into a\n // retry loop against a struggling server.\n schedule(\n consecutiveFailures === 0\n ? pollIntervalMs\n : Math.min(pollIntervalMs * 2 ** consecutiveFailures, maxPollIntervalMs),\n );\n }\n\n function subscribe(listener: (state: NotifyState) => void): () => void {\n listeners.add(listener);\n listener(state);\n\n // One poller regardless of how many components subscribe — otherwise two\n // bells, or a StrictMode double-mount, double the request rate.\n if (listeners.size === 1) void tick();\n\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n }\n\n return {\n subscribe,\n refresh,\n loadMore,\n markAsRead,\n markAllRead,\n markSeen,\n getState: () => state,\n };\n}\n\nexport type NotifyClient = ReturnType<typeof createNotifyClient>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAEA,mBAAkE;;;AC+BlE,IAAM,UAAuB;AAAA,EAC3B,eAAe,CAAC;AAAA,EAChB,aAAa;AAAA,EACb,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,OAAO;AACT;AAEA,IAAM,cAAc,CAAC,SACnB,KAAK,OAAO,CAAC,OAAO,QAAS,IAAI,WAAW,OAAO,QA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0BAAY,MAAM,OAAO,QAAQ,GAAG,CAAC,MAAM,CAAC;AAAA,EACvD;AACF;","names":[]}
|
package/dist/react.js
CHANGED
|
@@ -42,15 +42,13 @@ function createNotifyClient(options = {}) {
|
|
|
42
42
|
}
|
|
43
43
|
async function refresh() {
|
|
44
44
|
const startedAt = generation;
|
|
45
|
-
const
|
|
46
|
-
|
|
47
|
-
request("/count")
|
|
48
|
-
]);
|
|
45
|
+
const page = await request(`/?limit=${limit}`);
|
|
46
|
+
const unseenCount = page.unseenCount ?? (await request("/count")).unseen;
|
|
49
47
|
if (generation !== startedAt) return;
|
|
50
48
|
set({
|
|
51
49
|
notifications: page.notifications,
|
|
52
50
|
nextCursor: page.nextCursor,
|
|
53
|
-
unseenCount
|
|
51
|
+
unseenCount,
|
|
54
52
|
isLoading: false,
|
|
55
53
|
error: null
|
|
56
54
|
});
|
package/dist/react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react/index.ts","../src/client/index.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n createNotifyClient,\n type NotifyClient,\n type NotifyClientOptions,\n type NotifyState,\n} from \"../client\";\n\nexport type UseNotificationsResult = NotifyState & {\n markAsRead: (id: string) => Promise<void>;\n markAllRead: () => Promise<void>;\n markSeen: () => Promise<void>;\n loadMore: () => Promise<void>;\n refresh: () => Promise<void>;\n};\n\n/**\n * All state and optimistic-rollback logic lives in the framework-agnostic\n * client; this binding only wires it to React's lifecycle.\n */\nexport function useNotifications(\n options: NotifyClientOptions & { client?: NotifyClient } = {},\n): UseNotificationsResult {\n const { client: provided, baseUrl, limit, pollIntervalMs, maxPollIntervalMs } = options;\n\n // Callbacks are usually inline literals. Held in a ref and called through a\n // stable wrapper so a new function identity each render does not rebuild the\n // client and restart polling.\n const callbacksRef = useRef(options);\n callbacksRef.current = options;\n\n const client = useMemo(\n () =>\n provided ??\n createNotifyClient({\n baseUrl,\n limit,\n pollIntervalMs,\n maxPollIntervalMs,\n fetch: (...args) => (callbacksRef.current.fetch ?? globalThis.fetch)(...args),\n isDocumentHidden: () =>\n callbacksRef.current.isDocumentHidden?.() ??\n (typeof document !== \"undefined\" && document.visibilityState === \"hidden\"),\n }),\n [provided, baseUrl, limit, pollIntervalMs, maxPollIntervalMs],\n );\n\n const [state, setState] = useState<NotifyState>(() => client.getState());\n\n useEffect(() => client.subscribe(setState), [client]);\n\n return {\n ...state,\n markAsRead: useCallback((id: string) => client.markAsRead(id), [client]),\n markAllRead: useCallback(() => client.markAllRead(), [client]),\n markSeen: useCallback(() => client.markSeen(), [client]),\n loadMore: useCallback(() => client.loadMore(), [client]),\n refresh: useCallback(() => client.refresh(), [client]),\n };\n}\n\nexport type {\n NotificationView,\n NotifyClient,\n NotifyClientOptions,\n NotifyState,\n} from \"../client\";\nexport { createNotifyClient } from \"../client\";\n","export type NotificationView = {\n id: string;\n userId: string;\n type: string;\n payload: unknown;\n actorId: string | null;\n groupKey: string | null;\n seenAt: string | null;\n readAt: string | null;\n createdAt: string;\n};\n\nexport type NotifyState = {\n notifications: readonly NotificationView[];\n /** Badge count — cleared when the dropdown opens. Server-authoritative. */\n unseenCount: number;\n /** Items still bold. Derived from what is loaded, not a server total. */\n unreadCount: number;\n nextCursor: string | null;\n isLoading: boolean;\n error: Error | null;\n};\n\nexport type NotifyClientOptions = {\n baseUrl?: string | undefined;\n fetch?: typeof globalThis.fetch | undefined;\n limit?: number | undefined;\n pollIntervalMs?: number | undefined;\n maxPollIntervalMs?: number | undefined;\n /** Injectable so the poller can be tested without a DOM. */\n isDocumentHidden?: (() => boolean) | undefined;\n};\n\nconst INITIAL: NotifyState = {\n notifications: [],\n unseenCount: 0,\n unreadCount: 0,\n nextCursor: null,\n isLoading: true,\n error: null,\n};\n\nconst countUnread = (rows: readonly NotificationView[]) =>\n rows.reduce((total, row) => (row.readAt === null ? total + 1 : total), 0);\n\nexport function createNotifyClient(options: NotifyClientOptions = {}) {\n const baseUrl = (options.baseUrl ?? \"/api/notifications\").replace(/\\/$/, \"\");\n const doFetch = options.fetch ?? ((...args) => globalThis.fetch(...args));\n const limit = options.limit ?? 20;\n const pollIntervalMs = options.pollIntervalMs ?? 15_000;\n const maxPollIntervalMs = options.maxPollIntervalMs ?? 5 * 60_000;\n const isHidden =\n options.isDocumentHidden ??\n (() => typeof document !== \"undefined\" && document.visibilityState === \"hidden\");\n\n let state: NotifyState = INITIAL;\n const listeners = new Set<(state: NotifyState) => void>();\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n let consecutiveFailures = 0;\n\n // Bumped per mutation: an in-flight poll returns pre-mutation data, which\n // would silently revert the optimistic update.\n let generation = 0;\n\n function set(patch: Partial<NotifyState>) {\n state = { ...state, ...patch };\n state = { ...state, unreadCount: countUnread(state.notifications) };\n for (const listener of listeners) listener(state);\n }\n\n async function request<T>(path: string, init?: RequestInit): Promise<T> {\n const response = await doFetch(`${baseUrl}${path}`, {\n ...init,\n headers: { \"content-type\": \"application/json\", ...init?.headers },\n });\n if (!response.ok)\n throw new Error(`${init?.method ?? \"GET\"} ${path} failed: ${response.status}`);\n return (await response.json()) as T;\n }\n\n async function refresh(): Promise<void> {\n const startedAt = generation;\n\n const [page, count] = await Promise.all([\n request<{ notifications: NotificationView[]; nextCursor: string | null }>(`/?limit=${limit}`),\n request<{ unseen: number }>(\"/count\"),\n ]);\n\n // A mutation landed while this was in flight, so the response is already\n // stale. Dropping it is correct: the mutation's own optimistic state is\n // newer, and the next poll will reconcile.\n if (generation !== startedAt) return;\n\n set({\n notifications: page.notifications,\n nextCursor: page.nextCursor,\n unseenCount: count.unseen,\n isLoading: false,\n error: null,\n });\n }\n\n let loadingMore: Promise<void> | undefined;\n\n async function loadMore(): Promise<void> {\n if (!state.nextCursor) return;\n\n // Two clicks before the first response lands would both read the same\n // cursor and append the same page twice. Share the in-flight request.\n if (loadingMore) return loadingMore;\n\n const cursor = state.nextCursor;\n\n loadingMore = (async () => {\n try {\n const page = await request<{\n notifications: NotificationView[];\n nextCursor: string | null;\n }>(`/?limit=${limit}&cursor=${encodeURIComponent(cursor)}`);\n\n // Guard against a duplicate arriving anyway — a concurrent refresh may\n // already have pulled some of these into the list.\n const known = new Set(state.notifications.map((row) => row.id));\n\n set({\n notifications: [\n ...state.notifications,\n ...page.notifications.filter((row) => !known.has(row.id)),\n ],\n nextCursor: page.nextCursor,\n });\n } finally {\n loadingMore = undefined;\n }\n })();\n\n return loadingMore;\n }\n\n /** Applies a patch immediately and reverts it if the request fails. */\n async function optimistic(\n apply: (rows: readonly NotificationView[]) => readonly NotificationView[],\n patch: Partial<NotifyState>,\n send: () => Promise<unknown>,\n ): Promise<void> {\n const previous = state;\n generation += 1;\n set({ notifications: apply(state.notifications), ...patch });\n\n try {\n await send();\n } catch (error) {\n generation += 1;\n state = previous;\n for (const listener of listeners) listener(state);\n throw error;\n }\n }\n\n const stamp = () => new Date().toISOString();\n\n async function markAsRead(id: string): Promise<void> {\n await optimistic(\n (rows) =>\n rows.map((row) => (row.id === id ? { ...row, readAt: row.readAt ?? stamp() } : row)),\n {},\n () => request(\"/read\", { method: \"POST\", body: JSON.stringify({ ids: [id] }) }),\n );\n }\n\n async function markAllRead(): Promise<void> {\n await optimistic(\n (rows) => rows.map((row) => ({ ...row, readAt: row.readAt ?? stamp() })),\n {},\n () => request(\"/read-all\", { method: \"POST\" }),\n );\n }\n\n async function markSeen(): Promise<void> {\n // Only what the user could actually have seen. Sending no cutoff would\n // mark notifications that landed after the last poll as seen too.\n const newest = state.notifications[0]?.createdAt;\n\n await optimistic(\n (rows) => rows.map((row) => ({ ...row, seenAt: row.seenAt ?? stamp() })),\n { unseenCount: 0 },\n () =>\n request(\"/seen\", {\n method: \"POST\",\n body: JSON.stringify(newest ? { before: newest } : {}),\n }),\n );\n }\n\n function schedule(delay: number) {\n clearTimeout(timer);\n timer = setTimeout(tick, delay);\n }\n\n async function tick() {\n // A hidden tab still holds an open bell. Polling it burns requests for a\n // UI nobody is looking at.\n if (isHidden()) {\n schedule(pollIntervalMs);\n return;\n }\n\n try {\n await refresh();\n consecutiveFailures = 0;\n } catch (error) {\n consecutiveFailures += 1;\n set({ isLoading: false, error: error instanceof Error ? error : new Error(String(error)) });\n }\n\n // Back off on failure so an outage does not turn every open tab into a\n // retry loop against a struggling server.\n schedule(\n consecutiveFailures === 0\n ? pollIntervalMs\n : Math.min(pollIntervalMs * 2 ** consecutiveFailures, maxPollIntervalMs),\n );\n }\n\n function subscribe(listener: (state: NotifyState) => void): () => void {\n listeners.add(listener);\n listener(state);\n\n // One poller regardless of how many components subscribe — otherwise two\n // bells, or a StrictMode double-mount, double the request rate.\n if (listeners.size === 1) void tick();\n\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n }\n\n return {\n subscribe,\n refresh,\n loadMore,\n markAsRead,\n markAllRead,\n markSeen,\n getState: () => state,\n };\n}\n\nexport type NotifyClient = ReturnType<typeof createNotifyClient>;\n"],"mappings":";;;;AAEA,SAAS,aAAa,WAAW,SAAS,QAAQ,gBAAgB;;;AC+BlE,IAAM,UAAuB;AAAA,EAC3B,eAAe,CAAC;AAAA,EAChB,aAAa;AAAA,EACb,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,OAAO;AACT;AAEA,IAAM,cAAc,CAAC,SACnB,KAAK,OAAO,CAAC,OAAO,QAAS,IAAI,WAAW,OAAO,QAAQ,IAAI,OAAQ,CAAC;AAEnE,SAAS,mBAAmB,UAA+B,CAAC,GAAG;AACpE,QAAM,WAAW,QAAQ,WAAW,sBAAsB,QAAQ,OAAO,EAAE;AAC3E,QAAM,UAAU,QAAQ,UAAU,IAAI,SAAS,WAAW,MAAM,GAAG,IAAI;AACvE,QAAM,QAAQ,QAAQ,SAAS;AAC/B,QAAM,iBAAiB,QAAQ,kBAAkB;AACjD,QAAM,oBAAoB,QAAQ,qBAAqB,IAAI;AAC3D,QAAM,WACJ,QA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S,iBACd,UAA2D,CAAC,GACpC;AACxB,QAAM,EAAE,QAAQ,UAAU,SAAS,OAAO,gBAAgB,kBAAkB,IAAI;AAKhF,QAAM,eAAe,OAAO,OAAO;AACnC,eAAa,UAAU;AAEvB,QAAM,SAAS;AAAA,IACb,MACE,YACA,mBAAmB;AAAA,MACjB;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,OAAO,IAAI,UAAU,aAAa,QAAQ,SAAS,WAAW,OAAO,GAAG,IAAI;AAAA,MAC5E,kBAAkB,MAChB,aAAa,QAAQ,mBAAmB,MACvC,OAAO,aAAa,eAAe,SAAS,oBAAoB;AAAA,IACrE,CAAC;AAAA,IACH,CAAC,UAAU,SAAS,OAAO,gBAAgB,iBAAiB;AAAA,EAC9D;AAEA,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAsB,MAAM,OAAO,SAAS,CAAC;AAEvE,YAAU,MAAM,OAAO,UAAU,QAAQ,GAAG,CAAC,MAAM,CAAC;AAEpD,SAAO;AAAA,IACL,GAAG;AAAA,IACH,YAAY,YAAY,CAAC,OAAe,OAAO,WAAW,EAAE,GAAG,CAAC,MAAM,CAAC;AAAA,IACvE,aAAa,YAAY,MAAM,OAAO,YAAY,GAAG,CAAC,MAAM,CAAC;AAAA,IAC7D,UAAU,YAAY,MAAM,OAAO,SAAS,GAAG,CAAC,MAAM,CAAC;AAAA,IACvD,UAAU,YAAY,MAAM,OAAO,SAAS,GAAG,CAAC,MAAM,CAAC;AAAA,IACvD,SAAS,YAAY,MAAM,OAAO,QAAQ,GAAG,CAAC,MAAM,CAAC;AAAA,EACvD;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/react/index.ts","../src/client/index.ts"],"sourcesContent":["\"use client\";\n\nimport { useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport {\n createNotifyClient,\n type NotifyClient,\n type NotifyClientOptions,\n type NotifyState,\n} from \"../client\";\n\nexport type UseNotificationsResult = NotifyState & {\n markAsRead: (id: string) => Promise<void>;\n markAllRead: () => Promise<void>;\n markSeen: () => Promise<void>;\n loadMore: () => Promise<void>;\n refresh: () => Promise<void>;\n};\n\n/**\n * All state and optimistic-rollback logic lives in the framework-agnostic\n * client; this binding only wires it to React's lifecycle.\n */\nexport function useNotifications(\n options: NotifyClientOptions & { client?: NotifyClient } = {},\n): UseNotificationsResult {\n const { client: provided, baseUrl, limit, pollIntervalMs, maxPollIntervalMs } = options;\n\n // Callbacks are usually inline literals. Held in a ref and called through a\n // stable wrapper so a new function identity each render does not rebuild the\n // client and restart polling.\n const callbacksRef = useRef(options);\n callbacksRef.current = options;\n\n const client = useMemo(\n () =>\n provided ??\n createNotifyClient({\n baseUrl,\n limit,\n pollIntervalMs,\n maxPollIntervalMs,\n fetch: (...args) => (callbacksRef.current.fetch ?? globalThis.fetch)(...args),\n isDocumentHidden: () =>\n callbacksRef.current.isDocumentHidden?.() ??\n (typeof document !== \"undefined\" && document.visibilityState === \"hidden\"),\n }),\n [provided, baseUrl, limit, pollIntervalMs, maxPollIntervalMs],\n );\n\n const [state, setState] = useState<NotifyState>(() => client.getState());\n\n useEffect(() => client.subscribe(setState), [client]);\n\n return {\n ...state,\n markAsRead: useCallback((id: string) => client.markAsRead(id), [client]),\n markAllRead: useCallback(() => client.markAllRead(), [client]),\n markSeen: useCallback(() => client.markSeen(), [client]),\n loadMore: useCallback(() => client.loadMore(), [client]),\n refresh: useCallback(() => client.refresh(), [client]),\n };\n}\n\nexport type {\n NotificationView,\n NotifyClient,\n NotifyClientOptions,\n NotifyState,\n} from \"../client\";\nexport { createNotifyClient } from \"../client\";\n","export type NotificationView = {\n id: string;\n userId: string;\n type: string;\n payload: unknown;\n actorId: string | null;\n groupKey: string | null;\n seenAt: string | null;\n readAt: string | null;\n createdAt: string;\n};\n\nexport type NotifyState = {\n notifications: readonly NotificationView[];\n /** Badge count — cleared when the dropdown opens. Server-authoritative. */\n unseenCount: number;\n /** Items still bold. Derived from what is loaded, not a server total. */\n unreadCount: number;\n nextCursor: string | null;\n isLoading: boolean;\n error: Error | null;\n};\n\nexport type NotifyClientOptions = {\n baseUrl?: string | undefined;\n fetch?: typeof globalThis.fetch | undefined;\n limit?: number | undefined;\n pollIntervalMs?: number | undefined;\n maxPollIntervalMs?: number | undefined;\n /** Injectable so the poller can be tested without a DOM. */\n isDocumentHidden?: (() => boolean) | undefined;\n};\n\nconst INITIAL: NotifyState = {\n notifications: [],\n unseenCount: 0,\n unreadCount: 0,\n nextCursor: null,\n isLoading: true,\n error: null,\n};\n\nconst countUnread = (rows: readonly NotificationView[]) =>\n rows.reduce((total, row) => (row.readAt === null ? total + 1 : total), 0);\n\nexport function createNotifyClient(options: NotifyClientOptions = {}) {\n const baseUrl = (options.baseUrl ?? \"/api/notifications\").replace(/\\/$/, \"\");\n const doFetch = options.fetch ?? ((...args) => globalThis.fetch(...args));\n const limit = options.limit ?? 20;\n const pollIntervalMs = options.pollIntervalMs ?? 15_000;\n const maxPollIntervalMs = options.maxPollIntervalMs ?? 5 * 60_000;\n const isHidden =\n options.isDocumentHidden ??\n (() => typeof document !== \"undefined\" && document.visibilityState === \"hidden\");\n\n let state: NotifyState = INITIAL;\n const listeners = new Set<(state: NotifyState) => void>();\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n let consecutiveFailures = 0;\n\n // Bumped per mutation: an in-flight poll returns pre-mutation data, which\n // would silently revert the optimistic update.\n let generation = 0;\n\n function set(patch: Partial<NotifyState>) {\n state = { ...state, ...patch };\n state = { ...state, unreadCount: countUnread(state.notifications) };\n for (const listener of listeners) listener(state);\n }\n\n async function request<T>(path: string, init?: RequestInit): Promise<T> {\n const response = await doFetch(`${baseUrl}${path}`, {\n ...init,\n headers: { \"content-type\": \"application/json\", ...init?.headers },\n });\n if (!response.ok)\n throw new Error(`${init?.method ?? \"GET\"} ${path} failed: ${response.status}`);\n return (await response.json()) as T;\n }\n\n async function refresh(): Promise<void> {\n const startedAt = generation;\n\n // One request, not two. The feed carries unseenCount for a first page,\n // which is every poll. A server too old to send it still works: the\n // fallback asks /count the way this always used to.\n const page = await request<{\n notifications: NotificationView[];\n nextCursor: string | null;\n unseenCount?: number;\n }>(`/?limit=${limit}`);\n\n const unseenCount = page.unseenCount ?? (await request<{ unseen: number }>(\"/count\")).unseen;\n\n // A mutation landed while this was in flight, so the response is already\n // stale. Dropping it is correct: the mutation's own optimistic state is\n // newer, and the next poll will reconcile.\n if (generation !== startedAt) return;\n\n set({\n notifications: page.notifications,\n nextCursor: page.nextCursor,\n unseenCount,\n isLoading: false,\n error: null,\n });\n }\n\n let loadingMore: Promise<void> | undefined;\n\n async function loadMore(): Promise<void> {\n if (!state.nextCursor) return;\n\n // Two clicks before the first response lands would both read the same\n // cursor and append the same page twice. Share the in-flight request.\n if (loadingMore) return loadingMore;\n\n const cursor = state.nextCursor;\n\n loadingMore = (async () => {\n try {\n const page = await request<{\n notifications: NotificationView[];\n nextCursor: string | null;\n }>(`/?limit=${limit}&cursor=${encodeURIComponent(cursor)}`);\n\n // Guard against a duplicate arriving anyway — a concurrent refresh may\n // already have pulled some of these into the list.\n const known = new Set(state.notifications.map((row) => row.id));\n\n set({\n notifications: [\n ...state.notifications,\n ...page.notifications.filter((row) => !known.has(row.id)),\n ],\n nextCursor: page.nextCursor,\n });\n } finally {\n loadingMore = undefined;\n }\n })();\n\n return loadingMore;\n }\n\n /** Applies a patch immediately and reverts it if the request fails. */\n async function optimistic(\n apply: (rows: readonly NotificationView[]) => readonly NotificationView[],\n patch: Partial<NotifyState>,\n send: () => Promise<unknown>,\n ): Promise<void> {\n const previous = state;\n generation += 1;\n set({ notifications: apply(state.notifications), ...patch });\n\n try {\n await send();\n } catch (error) {\n generation += 1;\n state = previous;\n for (const listener of listeners) listener(state);\n throw error;\n }\n }\n\n const stamp = () => new Date().toISOString();\n\n async function markAsRead(id: string): Promise<void> {\n await optimistic(\n (rows) =>\n rows.map((row) => (row.id === id ? { ...row, readAt: row.readAt ?? stamp() } : row)),\n {},\n () => request(\"/read\", { method: \"POST\", body: JSON.stringify({ ids: [id] }) }),\n );\n }\n\n async function markAllRead(): Promise<void> {\n await optimistic(\n (rows) => rows.map((row) => ({ ...row, readAt: row.readAt ?? stamp() })),\n {},\n () => request(\"/read-all\", { method: \"POST\" }),\n );\n }\n\n async function markSeen(): Promise<void> {\n // Only what the user could actually have seen. Sending no cutoff would\n // mark notifications that landed after the last poll as seen too.\n const newest = state.notifications[0]?.createdAt;\n\n await optimistic(\n (rows) => rows.map((row) => ({ ...row, seenAt: row.seenAt ?? stamp() })),\n { unseenCount: 0 },\n () =>\n request(\"/seen\", {\n method: \"POST\",\n body: JSON.stringify(newest ? { before: newest } : {}),\n }),\n );\n }\n\n function schedule(delay: number) {\n clearTimeout(timer);\n timer = setTimeout(tick, delay);\n }\n\n async function tick() {\n // A hidden tab still holds an open bell. Polling it burns requests for a\n // UI nobody is looking at.\n if (isHidden()) {\n schedule(pollIntervalMs);\n return;\n }\n\n try {\n await refresh();\n consecutiveFailures = 0;\n } catch (error) {\n consecutiveFailures += 1;\n set({ isLoading: false, error: error instanceof Error ? error : new Error(String(error)) });\n }\n\n // Back off on failure so an outage does not turn every open tab into a\n // retry loop against a struggling server.\n schedule(\n consecutiveFailures === 0\n ? pollIntervalMs\n : Math.min(pollIntervalMs * 2 ** consecutiveFailures, maxPollIntervalMs),\n );\n }\n\n function subscribe(listener: (state: NotifyState) => void): () => void {\n listeners.add(listener);\n listener(state);\n\n // One poller regardless of how many components subscribe — otherwise two\n // bells, or a StrictMode double-mount, double the request rate.\n if (listeners.size === 1) void tick();\n\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) {\n clearTimeout(timer);\n timer = undefined;\n }\n };\n }\n\n return {\n subscribe,\n refresh,\n loadMore,\n markAsRead,\n markAllRead,\n markSeen,\n getState: () => state,\n };\n}\n\nexport type NotifyClient = ReturnType<typeof createNotifyClient>;\n"],"mappings":";;;;AAEA,SAAS,aAAa,WAAW,SAAS,QAAQ,gBAAgB;;;AC+BlE,IAAM,UAAu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OAAO,YAAY,GAAG,CAAC,MAAM,CAAC;AAAA,IAC7D,UAAU,YAAY,MAAM,OAAO,SAAS,GAAG,CAAC,MAAM,CAAC;AAAA,IACvD,UAAU,YAAY,MAAM,OAAO,SAAS,GAAG,CAAC,MAAM,CAAC;AAAA,IACvD,SAAS,YAAY,MAAM,OAAO,QAAQ,GAAG,CAAC,MAAM,CAAC;AAAA,EACvD;AACF;","names":[]}
|
package/dist/schema.d.cts
CHANGED
package/dist/schema.d.ts
CHANGED
package/dist/schema.js
CHANGED
|
@@ -1,200 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
export { INTROSPECT_SQL, planPostgresMigration, renderDrizzleSchema, renderPostgresDdl } from './chunk-RBDW4S6F.js';
|
|
2
2
|
export { coreSchema, toSnakeCase } from './chunk-NYDVNMKG.js';
|
|
3
|
-
|
|
4
|
-
// src/schema/render-sql.ts
|
|
5
|
-
var SQL_TYPE = {
|
|
6
|
-
string: "text",
|
|
7
|
-
number: "integer",
|
|
8
|
-
boolean: "boolean",
|
|
9
|
-
date: "timestamptz",
|
|
10
|
-
json: "jsonb"
|
|
11
|
-
};
|
|
12
|
-
var quote = (value) => `"${value.replace(/"/g, '""')}"`;
|
|
13
|
-
var defaultClause = (field) => {
|
|
14
|
-
if (field.defaultNow) return " DEFAULT now()";
|
|
15
|
-
if (field.default === void 0) return "";
|
|
16
|
-
if (typeof field.default === "string") return ` DEFAULT '${field.default.replace(/'/g, "''")}'`;
|
|
17
|
-
return ` DEFAULT ${field.default}`;
|
|
18
|
-
};
|
|
19
|
-
function renderPostgresDdl(schema, prefix = "") {
|
|
20
|
-
const statements = [];
|
|
21
|
-
for (const table of Object.values(schema)) {
|
|
22
|
-
const name = quote(prefix + table.tableName);
|
|
23
|
-
const columns = Object.entries(table.fields).map(([field, spec]) => {
|
|
24
|
-
const nullability = spec.required ? " NOT NULL" : "";
|
|
25
|
-
return ` ${quote(toSnakeCase(field))} ${SQL_TYPE[spec.type]}${nullability}${defaultClause(spec)}`;
|
|
26
|
-
});
|
|
27
|
-
if (table.primaryKey?.length) {
|
|
28
|
-
const key = table.primaryKey.map((field) => quote(toSnakeCase(field))).join(", ");
|
|
29
|
-
columns.push(` PRIMARY KEY (${key})`);
|
|
30
|
-
}
|
|
31
|
-
statements.push(`CREATE TABLE IF NOT EXISTS ${name} (
|
|
32
|
-
${columns.join(",\n")}
|
|
33
|
-
)`);
|
|
34
|
-
for (const declaration of table.indexes ?? []) {
|
|
35
|
-
const indexName2 = quote(
|
|
36
|
-
prefix + (declaration.name ?? `${table.tableName}_${declaration.on.join("_")}_idx`)
|
|
37
|
-
);
|
|
38
|
-
const columns2 = declaration.on.map((field) => quote(toSnakeCase(field))).join(", ");
|
|
39
|
-
const unique = declaration.unique ? "UNIQUE " : "";
|
|
40
|
-
statements.push(`CREATE ${unique}INDEX IF NOT EXISTS ${indexName2} ON ${name} (${columns2})`);
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
return statements;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
// src/schema/migrate-sql.ts
|
|
47
|
-
var SQL_TYPE2 = {
|
|
48
|
-
string: "text",
|
|
49
|
-
number: "integer",
|
|
50
|
-
boolean: "boolean",
|
|
51
|
-
date: "timestamptz",
|
|
52
|
-
json: "jsonb"
|
|
53
|
-
};
|
|
54
|
-
var LIVE_TYPE = {
|
|
55
|
-
string: ["text", "character varying", "character"],
|
|
56
|
-
number: ["integer", "bigint", "smallint"],
|
|
57
|
-
boolean: ["boolean"],
|
|
58
|
-
date: ["timestamp with time zone", "timestamp without time zone"],
|
|
59
|
-
json: ["jsonb", "json"]
|
|
60
|
-
};
|
|
61
|
-
var quote2 = (value) => `"${value.replace(/"/g, '""')}"`;
|
|
62
|
-
var defaultClause2 = (field) => {
|
|
63
|
-
if (field.defaultNow) return " DEFAULT now()";
|
|
64
|
-
if (field.default === void 0) return "";
|
|
65
|
-
if (typeof field.default === "string") return ` DEFAULT '${field.default.replace(/'/g, "''")}'`;
|
|
66
|
-
return ` DEFAULT ${field.default}`;
|
|
67
|
-
};
|
|
68
|
-
var indexName = (table, declaration) => declaration.name ?? `${table.tableName}_${declaration.on.join("_")}_idx`;
|
|
69
|
-
var INTROSPECT_SQL = `
|
|
70
|
-
SELECT table_name, column_name, data_type, is_nullable
|
|
71
|
-
FROM information_schema.columns
|
|
72
|
-
WHERE table_schema = current_schema()
|
|
73
|
-
`;
|
|
74
|
-
async function planPostgresMigration(introspect, schema, prefix = "") {
|
|
75
|
-
const live = await introspect();
|
|
76
|
-
const byTable = /* @__PURE__ */ new Map();
|
|
77
|
-
for (const column of live) {
|
|
78
|
-
const columns = byTable.get(column.table) ?? /* @__PURE__ */ new Map();
|
|
79
|
-
columns.set(column.column, column);
|
|
80
|
-
byTable.set(column.table, columns);
|
|
81
|
-
}
|
|
82
|
-
const statements = [];
|
|
83
|
-
const unsupported = [];
|
|
84
|
-
const createdTables = [];
|
|
85
|
-
for (const table of Object.values(schema)) {
|
|
86
|
-
const qualified = prefix + table.tableName;
|
|
87
|
-
const existing = byTable.get(qualified);
|
|
88
|
-
if (!existing || existing.size === 0) {
|
|
89
|
-
createdTables.push(qualified);
|
|
90
|
-
statements.push(...renderPostgresDdl({ [table.tableName]: table }, prefix));
|
|
91
|
-
continue;
|
|
92
|
-
}
|
|
93
|
-
for (const [field, spec] of Object.entries(table.fields)) {
|
|
94
|
-
const column = toSnakeCase(field);
|
|
95
|
-
const found = existing.get(column);
|
|
96
|
-
if (!found) {
|
|
97
|
-
const canFill = spec.defaultNow || spec.default !== void 0;
|
|
98
|
-
const nullability = spec.required && canFill ? " NOT NULL" : "";
|
|
99
|
-
statements.push(
|
|
100
|
-
`ALTER TABLE ${quote2(qualified)} ADD COLUMN IF NOT EXISTS ${quote2(column)} ${SQL_TYPE2[spec.type]}${nullability}${defaultClause2(spec)}`
|
|
101
|
-
);
|
|
102
|
-
if (spec.required && !canFill) {
|
|
103
|
-
unsupported.push(
|
|
104
|
-
`${qualified}.${column} is declared required but has no default; it was added nullable. Backfill it, then ALTER ... SET NOT NULL yourself.`
|
|
105
|
-
);
|
|
106
|
-
}
|
|
107
|
-
continue;
|
|
108
|
-
}
|
|
109
|
-
if (!LIVE_TYPE[spec.type].includes(found.type)) {
|
|
110
|
-
unsupported.push(
|
|
111
|
-
`${qualified}.${column} is ${found.type} but ${spec.type} is declared (${SQL_TYPE2[spec.type]}). Changing a column type can lose data \u2014 do it yourself.`
|
|
112
|
-
);
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
for (const declaration of table.indexes ?? []) {
|
|
116
|
-
const name = quote2(prefix + indexName(table, declaration));
|
|
117
|
-
const columns = declaration.on.map((field) => quote2(toSnakeCase(field))).join(", ");
|
|
118
|
-
statements.push(
|
|
119
|
-
`CREATE ${declaration.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS ${name} ON ${quote2(qualified)} (${columns})`
|
|
120
|
-
);
|
|
121
|
-
}
|
|
122
|
-
for (const column of existing.keys()) {
|
|
123
|
-
const declared = Object.keys(table.fields).some((field) => toSnakeCase(field) === column);
|
|
124
|
-
if (!declared) {
|
|
125
|
-
unsupported.push(
|
|
126
|
-
`${qualified}.${column} exists but is not declared. Left alone \u2014 drop it yourself if it is ours and no longer needed.`
|
|
127
|
-
);
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
return { statements, unsupported, createdTables };
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
// src/schema/render-drizzle.ts
|
|
135
|
-
var COLUMN_BUILDER = {
|
|
136
|
-
string: "text",
|
|
137
|
-
number: "integer",
|
|
138
|
-
boolean: "boolean",
|
|
139
|
-
date: "timestamp",
|
|
140
|
-
json: "jsonb"
|
|
141
|
-
};
|
|
142
|
-
var literal = (value) => typeof value === "string" ? JSON.stringify(value) : String(value);
|
|
143
|
-
function renderColumn(name, field, isSinglePk) {
|
|
144
|
-
const builder = COLUMN_BUILDER[field.type];
|
|
145
|
-
const column = toSnakeCase(name);
|
|
146
|
-
let expression = field.type === "date" ? `${builder}(${JSON.stringify(column)}, { withTimezone: true })` : `${builder}(${JSON.stringify(column)})`;
|
|
147
|
-
if (isSinglePk) return ` ${name}: ${expression}.primaryKey(),`;
|
|
148
|
-
if (field.required) expression += ".notNull()";
|
|
149
|
-
if (field.defaultNow) expression += ".defaultNow()";
|
|
150
|
-
else if (field.default !== void 0) expression += `.default(${literal(field.default)})`;
|
|
151
|
-
return ` ${name}: ${expression},`;
|
|
152
|
-
}
|
|
153
|
-
function renderTable(key, table, prefix) {
|
|
154
|
-
const compositePk = (table.primaryKey?.length ?? 0) > 1;
|
|
155
|
-
const singlePk = !compositePk ? table.primaryKey?.[0] : void 0;
|
|
156
|
-
const columns = Object.entries(table.fields).map(([name, field]) => renderColumn(name, field, name === singlePk)).join("\n");
|
|
157
|
-
const extras = [];
|
|
158
|
-
for (const declaration of table.indexes ?? []) {
|
|
159
|
-
const builder = declaration.unique ? "uniqueIndex" : "index";
|
|
160
|
-
const name = declaration.name ?? `${table.tableName}_${declaration.on.join("_")}_idx`;
|
|
161
|
-
const columns2 = declaration.on.map((field) => `table.${field}`).join(", ");
|
|
162
|
-
extras.push(` ${builder}(${JSON.stringify(prefix + name)}).on(${columns2}),`);
|
|
163
|
-
}
|
|
164
|
-
if (compositePk) {
|
|
165
|
-
const columns2 = (table.primaryKey ?? []).map((field) => `table.${field}`).join(", ");
|
|
166
|
-
extras.push(` primaryKey({ columns: [${columns2}] }),`);
|
|
167
|
-
}
|
|
168
|
-
const third = extras.length ? `,
|
|
169
|
-
(table) => [
|
|
170
|
-
${extras.join("\n")}
|
|
171
|
-
]` : "";
|
|
172
|
-
return `export const ${key} = pgTable(
|
|
173
|
-
${JSON.stringify(prefix + table.tableName)},
|
|
174
|
-
{
|
|
175
|
-
${columns}
|
|
176
|
-
}${third},
|
|
177
|
-
);`;
|
|
178
|
-
}
|
|
179
|
-
function renderDrizzleSchema(schema, prefix = "") {
|
|
180
|
-
const tables = Object.entries(schema);
|
|
181
|
-
const used = /* @__PURE__ */ new Set(["pgTable"]);
|
|
182
|
-
for (const [, table] of tables) {
|
|
183
|
-
for (const field of Object.values(table.fields)) used.add(COLUMN_BUILDER[field.type]);
|
|
184
|
-
for (const declaration of table.indexes ?? []) {
|
|
185
|
-
used.add(declaration.unique ? "uniqueIndex" : "index");
|
|
186
|
-
}
|
|
187
|
-
if ((table.primaryKey?.length ?? 0) > 1) used.add("primaryKey");
|
|
188
|
-
}
|
|
189
|
-
const imports = [...used].sort().join(", ");
|
|
190
|
-
const body = tables.map(([key, table]) => renderTable(key, table, prefix)).join("\n\n");
|
|
191
|
-
return `// Generated by easy-ping. Do not edit by hand.
|
|
192
|
-
import { ${imports} } from "drizzle-orm/pg-core";
|
|
193
|
-
|
|
194
|
-
${body}
|
|
195
|
-
`;
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
export { INTROSPECT_SQL, planPostgresMigration, renderDrizzleSchema, renderPostgresDdl };
|
|
199
3
|
//# sourceMappingURL=schema.js.map
|
|
200
4
|
//# sourceMappingURL=schema.js.map
|