@vite-hub/webhooks 0.4.1 → 0.5.1

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/dist/vite.js CHANGED
@@ -1,11 +1,12 @@
1
- import { t as webhooksErrors } from "./errors-1y5fWGlX.js";
2
- import { t as webhooksQueueName } from "./queue-name-RURp9SQf.js";
3
- import { t as webhooksTableNames } from "./table-names-DVvicXhh.js";
4
- import { t as isRecordOrFunction } from "./object-BJb1W_q5.js";
1
+ import { n as isRecordOrFunction, t as isRecord } from "./object-CAK6UYR5.js";
2
+ import { t as webhooksErrors } from "./errors-DT8uyCh7.js";
3
+ import { t as webhooksQueueName } from "./queue-name-jmgeppja.js";
4
+ import { n as webhooksTableNames, t as webhookEndpointsTableNames } from "./table-names-DAUip4v2.js";
5
5
  import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
6
6
  import { tmpdir } from "node:os";
7
7
  import { basename, dirname, join, parse, relative, resolve } from "node:path";
8
- //#region ../internal/src/build/vite.ts
8
+ import { mkdir, writeFile } from "node:fs/promises";
9
+ // ../internal/src/build/vite.ts
9
10
  const projectRootDirectoryMarkers = [
10
11
  ["server", "agents"],
11
12
  ["server", "channels"],
@@ -55,7 +56,7 @@ function hasProjectRootDirectoryMarker(root) {
55
56
  for (const marker of projectRootDirectoryMarkers) try {
56
57
  if (statSync(resolve(root, ...marker)).isDirectory()) return true;
57
58
  } catch (error) {
58
- if (error.code !== "ENOENT") throw error;
59
+ if (!isMissingProjectMarker(error)) throw error;
59
60
  }
60
61
  return false;
61
62
  }
@@ -69,13 +70,57 @@ function hasProjectRootFileMarker(root, markers) {
69
70
  try {
70
71
  if (statSync(resolve(root, ...path)).isFile()) return true;
71
72
  } catch (error) {
72
- if (error.code !== "ENOENT") throw error;
73
+ if (!isMissingProjectMarker(error)) throw error;
73
74
  }
74
75
  }
75
76
  return false;
76
77
  }
77
- //#endregion
78
- //#region ../internal/src/definition-catalog.ts
78
+ function isMissingProjectMarker(error) {
79
+ const code = error.code;
80
+ return code === "ENOENT" || code === "ENOTDIR";
81
+ }
82
+ // ../internal/src/vite-stage.ts
83
+ /**
84
+ * Vite's `loadEnv(mode, envDir, "")`: every `.env` value of the mode and the whole shell. With `DEBUG=vite:env`, Vite
85
+ * logs that result to stderr, secrets included. loadEnv is synchronous, so this drops only the writes of this call.
86
+ */
87
+ function loadAllEnv(loadEnv, mode, envDir) {
88
+ const write = process.stderr.write;
89
+ process.stderr.write = () => true;
90
+ try {
91
+ return loadEnv(mode, envDir, "");
92
+ } finally {
93
+ process.stderr.write = write;
94
+ }
95
+ }
96
+ // ../internal/src/contributions.ts
97
+ function isThenable(value) {
98
+ return typeof value.then === "function";
99
+ }
100
+ async function flattenPlugins(value, plugins, seen) {
101
+ if (Array.isArray(value)) {
102
+ for (const item of value) await flattenPlugins(item, plugins, seen);
103
+ return;
104
+ }
105
+ if (!isRecord(value) || seen.has(value)) return;
106
+ seen.add(value);
107
+ if (isThenable(value)) {
108
+ await flattenPlugins(await value, plugins, seen);
109
+ return;
110
+ }
111
+ plugins.push(value);
112
+ }
113
+ /**
114
+ * Flattens Vite plugin options as `collectContributions` reads them: nested arrays and promised options become one
115
+ * list of plugin objects, and falsy entries are dropped. A plugin that filters itself out of `context.plugins` must
116
+ * filter this list, because `vitehub()` nests its plugins in an array.
117
+ */
118
+ async function flattenPluginOptions(plugins) {
119
+ const flattened = [];
120
+ await flattenPlugins(plugins ?? [], flattened, /* @__PURE__ */ new Set());
121
+ return flattened;
122
+ }
123
+ // ../internal/src/definition-catalog.ts
79
124
  const sourceFilePattern = /\.(?:c|m)?[jt]sx?$/i;
80
125
  const declarationFilePattern = /\.d\.(?:c|m)?[jt]sx?$/i;
81
126
  const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
@@ -83,8 +128,8 @@ const testFilePattern = /\.(?:test|spec)\.(?:c|m)?[jt]sx?$/i;
83
128
  function isDefinitionSourceFile(name) {
84
129
  return sourceFilePattern.test(name) && !declarationFilePattern.test(name) && !testFilePattern.test(name);
85
130
  }
86
- //#endregion
87
- //#region ../internal/src/nitro-kit.ts
131
+ Object.freeze({ vitehubAuthAccess: "handler" });
132
+ Object.freeze({ vitehubOwnAccess: true });
88
133
  function cloneArray(value) {
89
134
  return Array.isArray(value) ? [...value] : [];
90
135
  }
@@ -112,11 +157,11 @@ function createNitroServerKit(value = {}) {
112
157
  }
113
158
  };
114
159
  }
115
- //#endregion
116
- //#region src/console.ts
160
+ // src/console.ts
117
161
  /**
118
- * Console section for the webhooks of `server/webhooks/`: each endpoint, the pending debounce timers, and the delivery
119
- * log, with Send test, Send now, Cancel, and Redeliver. It calls the `webhooks.*` operations with the Console user.
162
+ * Console section for the webhooks of `server/webhooks/` and the member endpoints: each endpoint, the pending debounce
163
+ * timers, and the delivery log, with Send test, Send now, Cancel, Redeliver, and Disable or Enable for a member
164
+ * endpoint. It calls the `webhooks.*` operations with the Console user.
120
165
  */
121
166
  const webhooksConsoleSection = {
122
167
  description: "See, test, flush, and redeliver the webhooks that the app sends.",
@@ -125,11 +170,10 @@ const webhooksConsoleSection = {
125
170
  label: "Webhooks",
126
171
  view: {
127
172
  kind: "webhooks",
128
- notice: "The list comes from the webhooks.* operations. The Console shows the names of the URL and secret variables and the URL host, never the full URL or the secret. `vitehub webhooks` and the webhooks MCP tools do the same."
173
+ notice: "The list comes from the webhooks.* operations. The Console shows the names of the URL and secret variables and the host of each URL, never the full URL or the secret. Admins see member endpoints read-only and can disable one. Only the member who owns an endpoint can redeliver to it. `vitehub webhooks` and the webhooks MCP tools do the same."
129
174
  }
130
175
  };
131
- //#endregion
132
- //#region src/vite.ts
176
+ // src/vite.ts
133
177
  const WEBHOOKS_VITE_PLUGIN_NAME = "@vite-hub/webhooks/vite";
134
178
  const extensions = [
135
179
  ".ts",
@@ -164,6 +208,26 @@ function discoverWebhooks(projectRoot, serverDirs = ["server"]) {
164
208
  function usesWebhooks(options) {
165
209
  return discoverWebhooks(options.projectRoot, options.serverDirs).length > 0;
166
210
  }
211
+ /** The plugins that use member endpoints, as `<plugin>: <reason>`. An entry of the wrong shape throws. */
212
+ async function collectWebhooksUses(plugins, context) {
213
+ const candidates = await flattenPluginOptions(plugins);
214
+ const uses = [];
215
+ for (const plugin of candidates) {
216
+ const metadata = Object.hasOwn(plugin, "vitehub") ? Reflect.get(plugin, "vitehub") : void 0;
217
+ if (!isRecord(metadata) || !Object.hasOwn(metadata, "webhooks")) continue;
218
+ const name = Reflect.get(plugin, "name");
219
+ const contributor = typeof name === "string" && name ? name : "unnamed plugin";
220
+ const source = metadata.webhooks;
221
+ const use = typeof source === "function" ? await Reflect.apply(source, void 0, [{
222
+ ...context,
223
+ plugins: candidates
224
+ }]) : source;
225
+ if (use === void 0) continue;
226
+ if (!isRecord(use) || use.memberEndpoints !== true || typeof use.reason !== "string" || !use.reason) throw webhooksErrors.WEBHOOKS_CONTRIBUTION_INVALID({ plugin: JSON.stringify(contributor) });
227
+ uses.push(`${contributor}: ${use.reason}`);
228
+ }
229
+ return uses;
230
+ }
167
231
  const defaultImports = {
168
232
  runtime: "@vite-hub/webhooks/runtime",
169
233
  operations: "@vite-hub/webhooks/operations",
@@ -184,18 +248,30 @@ function webhooksGeneratedFiles(projectRoot) {
184
248
  };
185
249
  }
186
250
  /** The generated module that installs the webhooks. The Queue handler and the Nitro plugin import it. */
187
- function renderWebhooksRegistry(webhooks, imports) {
251
+ function renderWebhooksRegistry(webhooks, imports, features = {
252
+ queue: true,
253
+ memberEndpoints: false
254
+ }) {
255
+ const stores = features.memberEndpoints ? "createDrizzleWebhookEndpointStore, createDrizzleWebhookStore" : "createDrizzleWebhookStore";
256
+ const auth = features.memberEndpoints ? imports.auth : void 0;
188
257
  return [
258
+ ...features.developmentKeyFile ? ["import { readFileSync } from \"node:fs\""] : [],
189
259
  `import { installWebhooks, selectDefaultDatabase } from ${JSON.stringify(imports.runtime)}`,
190
- `import { createDrizzleWebhookStore } from ${JSON.stringify(imports.database)}`,
260
+ `import { ${stores} } from ${JSON.stringify(imports.database)}`,
191
261
  `import { useDatabase } from ${JSON.stringify(imports.databases)}`,
192
- `import { dynamicQueue } from ${JSON.stringify(imports.queue)}`,
262
+ ...auth ? [`import { findVerifiedAuthUserId } from ${JSON.stringify(auth)}`] : [],
263
+ ...features.queue ? [`import { dynamicQueue } from ${JSON.stringify(imports.queue)}`] : [],
193
264
  ...webhooks.map((webhook, index) => `import webhook${index} from ${JSON.stringify(webhook.file)}`),
194
265
  "",
266
+ "const db = () => selectDefaultDatabase(() => useDatabase())",
267
+ "",
195
268
  "installWebhooks({",
196
269
  ` webhooks: { ${webhooks.map((webhook, index) => `${JSON.stringify(webhook.name)}: webhook${index}`).join(", ")} },`,
197
- " store: createDrizzleWebhookStore(() => selectDefaultDatabase(() => useDatabase())),",
198
- ` wake: (wake, options) => dynamicQueue.send(${JSON.stringify(webhooksQueueName)}, wake, options),`,
270
+ " store: createDrizzleWebhookStore(db),",
271
+ ...features.memberEndpoints ? [" endpoints: createDrizzleWebhookEndpointStore(db),"] : [],
272
+ ...features.developmentKeyFile ? [` developmentKey: readFileSync(${JSON.stringify(features.developmentKeyFile)}, "utf8").trim(),`] : [],
273
+ ...auth ? [" resolveVerifiedOwner: findVerifiedAuthUserId,"] : [],
274
+ ...features.queue ? [` wake: (wake, options) => dynamicQueue.send(${JSON.stringify(webhooksQueueName)}, wake, options),`] : [],
199
275
  "})",
200
276
  ""
201
277
  ].join("\n");
@@ -233,10 +309,9 @@ function writeIfChanged(file, contents) {
233
309
  mkdirSync(dirname(file), { recursive: true });
234
310
  writeFileSync(file, contents);
235
311
  }
236
- /** Writes the generated files of the webhooks, or removes them when the app has none. Returns the files. */
237
- function writeWebhooksFiles(projectRoot, webhooks, imports) {
312
+ function writeWebhooksFiles(projectRoot, webhooks, imports, features) {
238
313
  const files = webhooksGeneratedFiles(projectRoot);
239
- if (!webhooks.length) {
314
+ if (!webhooks.length && !features.memberEndpoints) {
240
315
  rmSync(files.directory, {
241
316
  force: true,
242
317
  recursive: true
@@ -244,16 +319,42 @@ function writeWebhooksFiles(projectRoot, webhooks, imports) {
244
319
  rmSync(files.types, { force: true });
245
320
  return files;
246
321
  }
247
- writeIfChanged(files.registry, renderWebhooksRegistry(webhooks, imports));
248
- writeIfChanged(files.queue, renderWebhooksQueue(imports));
322
+ writeIfChanged(files.registry, renderWebhooksRegistry(webhooks, imports, features));
323
+ if (features.queue) writeIfChanged(files.queue, renderWebhooksQueue(imports));
324
+ else rmSync(files.queue, { force: true });
249
325
  writeIfChanged(files.plugin, "import \"./registry.mjs\"\n\nexport default () => {}\n");
250
326
  writeIfChanged(files.types, renderWebhooksTypes(files.types, webhooks, imports.types));
251
327
  return files;
252
328
  }
329
+ /** The path of the key that `vite dev` generates when the app sets no `VITEHUB_WEBHOOKS_KEY`. */
330
+ function webhooksDevelopmentKeyFile(projectRoot) {
331
+ return resolve(projectRoot, ".vitehub/data/webhooks-key");
332
+ }
333
+ async function ensureDevelopmentKey(projectRoot, envDir, mode) {
334
+ const { loadEnv } = await import("vite");
335
+ if (loadAllEnv(loadEnv, mode, envDir).VITEHUB_WEBHOOKS_KEY?.trim()) return void 0;
336
+ const file = webhooksDevelopmentKeyFile(projectRoot);
337
+ if (!existsSync(file)) {
338
+ await mkdir(dirname(file), { recursive: true });
339
+ const generated = btoa(String.fromCharCode(...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32))));
340
+ try {
341
+ await writeFile(file, `${generated}\n`, {
342
+ flag: "wx",
343
+ mode: 384
344
+ });
345
+ } catch (error) {
346
+ if (!existsSync(file)) throw error;
347
+ }
348
+ }
349
+ return file;
350
+ }
253
351
  /**
254
352
  * Webhooks in a ViteHub app: each `server/webhooks/<name>.ts` that default-exports `defineWebhook()` gets a name for
255
353
  * `sendWebhook()`. Deliveries go to the `vitehub_webhook_deliveries` table of the Default Database and out through the
256
354
  * `vitehub-webhooks` Queue, which this plugin contributes. Both features must be on.
355
+ *
356
+ * A sibling plugin that sets `vitehub.webhooks` (see `WebhooksUse`) turns on member endpoints, with no files. They need
357
+ * the Database. With Queue, failed member deliveries are tried again through it.
257
358
  */
258
359
  function hubWebhooks(options = {}) {
259
360
  const imports = {
@@ -262,25 +363,48 @@ function hubWebhooks(options = {}) {
262
363
  };
263
364
  let projectRoot;
264
365
  let serverDirs;
366
+ let memberEndpointsOn = false;
265
367
  const project = (context) => ({
266
368
  projectRoot: projectRoot ?? context.projectRoot ?? context.rootDir ?? context.root ?? process.cwd(),
267
369
  serverDirs: serverDirs ?? context.serverDirs
268
370
  });
371
+ const usage = async (context) => {
372
+ const { projectRoot: root, serverDirs: dirs } = project(context);
373
+ const webhooks = discoverWebhooks(root, dirs);
374
+ const uses = await collectWebhooksUses(context.plugins, {
375
+ root: context.root ?? root,
376
+ projectRoot: root,
377
+ ...dirs ? { serverDirs: dirs } : {}
378
+ });
379
+ return {
380
+ root,
381
+ webhooks,
382
+ uses,
383
+ features: {
384
+ queue: Boolean(options.queue && options.database),
385
+ memberEndpoints: uses.length > 0
386
+ }
387
+ };
388
+ };
269
389
  return {
270
390
  name: WEBHOOKS_VITE_PLUGIN_NAME,
271
391
  enforce: "pre",
392
+ api: { deploymentEnv: () => memberEndpointsOn ? [{
393
+ names: ["VITEHUB_WEBHOOKS_KEY"],
394
+ required: true,
395
+ secret: true,
396
+ hasDefault: false,
397
+ owners: ["webhooks"]
398
+ }] : [] },
272
399
  vitehub: {
273
- operations: () => usesWebhooks(project({})) ? [{
400
+ operations: () => memberEndpointsOn || usesWebhooks(project({})) ? [{
274
401
  export: "webhooksOperations",
275
402
  load: async () => (await (import.meta.url.endsWith(".ts") ? import("./operations.js") : import("./operations.js"))).webhooksOperations,
276
403
  module: imports.operations
277
404
  }] : [],
278
- databases(context) {
279
- const { projectRoot: root, serverDirs: dirs } = project(context);
280
- if (!options.database || !usesWebhooks({
281
- projectRoot: root,
282
- ...dirs ? { serverDirs: dirs } : {}
283
- })) return [];
405
+ async databases(context) {
406
+ const { webhooks, features } = await usage(context);
407
+ if (!options.database || !webhooks.length && !features.memberEndpoints) return [];
284
408
  return [{
285
409
  definition: {
286
410
  export: "webhooksSchema",
@@ -289,40 +413,53 @@ function hubWebhooks(options = {}) {
289
413
  dialect: "sqlite",
290
414
  tables: webhooksTableNames,
291
415
  name: "webhooks",
292
- reason: "Keeps the deliveries of `server/webhooks/`."
293
- }];
416
+ reason: "Keeps the deliveries of `server/webhooks/` and of member endpoints."
417
+ }, ...features.memberEndpoints ? [{
418
+ definition: {
419
+ export: "webhookEndpointsSchema",
420
+ module: imports.database
421
+ },
422
+ dialect: "sqlite",
423
+ tables: webhookEndpointsTableNames,
424
+ name: "webhook-endpoints",
425
+ reason: "Keeps the endpoint of each member, with the URL and secret sealed."
426
+ }] : []];
294
427
  },
295
- queues(context) {
296
- const { projectRoot: root, serverDirs: dirs } = project(context);
297
- const webhooks = discoverWebhooks(root, dirs);
298
- if (!webhooks.length || !options.queue || !options.database) return [];
299
- const files = writeWebhooksFiles(root, webhooks, imports);
428
+ async queues(context) {
429
+ const { root, webhooks, features } = await usage(context);
430
+ if (!webhooks.length && !features.memberEndpoints || !features.queue) return [];
431
+ const files = webhooksGeneratedFiles(root);
432
+ writeIfChanged(files.queue, renderWebhooksQueue(imports));
300
433
  return [{
301
434
  name: webhooksQueueName,
302
435
  definition: { module: files.queue },
303
- reason: "Delivers the webhooks of `server/webhooks/`."
436
+ reason: "Delivers the webhooks of `server/webhooks/` and retries member deliveries."
304
437
  }];
305
438
  }
306
439
  },
307
- config: { handler(config) {
440
+ config: { async handler(config, env) {
308
441
  const configuredRoot = Reflect.get(config, VITEHUB_PROJECT_ROOT);
309
442
  projectRoot = typeof configuredRoot === "string" ? resolve(configuredRoot) : resolveViteHubProjectRoot(resolve(config.root ?? process.cwd()));
310
443
  const dirs = Reflect.get(config, VITEHUB_SERVER_DIRS);
311
444
  serverDirs = Array.isArray(dirs) ? dirs.filter((dir) => typeof dir === "string") : void 0;
312
- const root = projectRoot;
313
- const webhooks = discoverWebhooks(root, serverDirs);
314
- if (webhooks.length) {
315
- const listed = webhooks.map((webhook) => relative(root, webhook.file)).join(", ");
316
- if (!options.queue) throw webhooksErrors.WEBHOOKS_QUEUE_OFF({ files: listed });
317
- if (!options.database) throw webhooksErrors.WEBHOOKS_DATABASE_OFF({ files: listed });
318
- }
319
- const files = writeWebhooksFiles(root, webhooks, imports);
320
- if (!webhooks.length) return;
445
+ const { root, webhooks, uses, features } = await usage({
446
+ root: resolve(config.root ?? process.cwd()),
447
+ plugins: config.plugins
448
+ });
449
+ memberEndpointsOn = features.memberEndpoints;
450
+ const listed = webhooks.map((webhook) => relative(root, webhook.file));
451
+ if (listed.length && !options.queue) throw webhooksErrors.WEBHOOKS_QUEUE_OFF({ files: listed.join(", ") });
452
+ if ((listed.length || uses.length) && !options.database) throw webhooksErrors.WEBHOOKS_DATABASE_OFF({ users: [...listed, ...uses].join(", ") });
453
+ const developmentKeyFile = features.memberEndpoints && env.command === "serve" ? await ensureDevelopmentKey(root, config.envDir === false ? false : resolve(config.root ?? root, config.envDir ?? "."), env.mode) : void 0;
454
+ const files = writeWebhooksFiles(root, webhooks, imports, {
455
+ ...features,
456
+ developmentKeyFile
457
+ });
458
+ if (!webhooks.length && !features.memberEndpoints) return;
321
459
  const kit = createNitroServerKit(Reflect.get(config, "nitro"));
322
460
  kit.addPlugin(files.plugin);
323
461
  Reflect.set(config, "nitro", kit.config);
324
462
  } }
325
463
  };
326
464
  }
327
- //#endregion
328
- export { WEBHOOKS_VITE_PLUGIN_NAME, discoverWebhooks, hubWebhooks, renderWebhooksQueue, renderWebhooksRegistry, renderWebhooksTypes, usesWebhooks, webhooksConsoleSection, webhooksGeneratedFiles, webhooksQueueName };
465
+ export { WEBHOOKS_VITE_PLUGIN_NAME, collectWebhooksUses, discoverWebhooks, hubWebhooks, renderWebhooksQueue, renderWebhooksRegistry, renderWebhooksTypes, usesWebhooks, webhooksConsoleSection, webhooksDevelopmentKeyFile, webhooksGeneratedFiles, webhooksQueueName };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vite-hub/webhooks",
3
- "version": "0.4.1",
3
+ "version": "0.5.1",
4
4
  "description": "Send ViteHub events to an outside URL: signed, retried, and debounced on every host.",
5
5
  "keywords": [
6
6
  "debounce",
@@ -55,24 +55,24 @@
55
55
  },
56
56
  "dependencies": {
57
57
  "@standard-schema/spec": "^1.1.0",
58
- "@vite-hub/env": "0.4.1",
59
- "@vite-hub/runtime": "0.4.1",
58
+ "@vite-hub/env": "0.5.1",
59
+ "@vite-hub/runtime": "0.5.1",
60
60
  "valibot": "^1.5.0"
61
61
  },
62
62
  "devDependencies": {
63
63
  "@libsql/client": "^0.18.0",
64
- "@types/node": "^24.19.1",
64
+ "@types/node": "^24.19.2",
65
65
  "@vite-hub/internal": "0.0.1",
66
- "drizzle-orm": "1.0.0-rc.5",
66
+ "drizzle-orm": "1.0.0-rc.6",
67
67
  "nitro": "^3.0.261103-rc",
68
68
  "publint": "^0.3.25",
69
69
  "typescript": "^6.0.3",
70
- "vite": "^8.2.2",
71
- "vite-plus": "^0.3.3",
72
- "vitest": "^4.1.11"
70
+ "vite": "^8.3.8",
71
+ "vite-plus": "^1.7.0",
72
+ "vitest": "5.1.0"
73
73
  },
74
74
  "peerDependencies": {
75
- "drizzle-orm": "1.0.0-rc.5 || ^1.0.0",
75
+ "drizzle-orm": "1.0.0-rc.5 || 1.0.0-rc.6 || ^1.0.0",
76
76
  "vite": ">=8.0.0",
77
77
  "nitro": "3.0.261102-rc || ^3.0.261103-rc"
78
78
  },