@omg-dev/server 0.4.27 → 0.4.29

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/index.mjs CHANGED
@@ -953,7 +953,7 @@ function openDb(path) {
953
953
  let _dbInstance = null;
954
954
  const dbProxy = new Proxy({}, { get(_target, prop) {
955
955
  if (!_dbInstance) throw new Error(`[vibes] db not initialized. Call createVibesServer() before using db.`);
956
- return _dbInstance[prop];
956
+ return Reflect.get(_dbInstance, prop);
957
957
  } });
958
958
  function setDbInstance(instance) {
959
959
  _dbInstance = instance;
@@ -1496,9 +1496,10 @@ async function registerTriggers(entries) {
1496
1496
  storageHookHandlers.get(e.kind).add(e.handler);
1497
1497
  }
1498
1498
  }
1499
- const inProcessCron = vibesMode$1() === "dev" || cronDriver() === "in-process";
1499
+ const inBuild = inBuildMode();
1500
+ const inProcessCron = !inBuild && (vibesMode$1() === "dev" || cronDriver() === "in-process");
1500
1501
  if (inProcessCron) scheduleAllCronInProcess();
1501
- console.log(`[vibes:triggers] registered ${entries.length} trigger(s) — mode=${vibesMode$1()}, cron=${inProcessCron ? "in-process" : "orchestrator"}`);
1502
+ console.log(`[vibes:triggers] registered ${entries.length} trigger(s) — mode=${vibesMode$1()}, cron=${inBuild ? "unarmed (build)" : inProcessCron ? "in-process" : "orchestrator"}`);
1502
1503
  }
1503
1504
  /** Snapshot of the registry — used by the in-dev Inspect endpoints. */
1504
1505
  function listTriggers() {
@@ -1907,6 +1908,9 @@ function vibesMode$1() {
1907
1908
  _vibesMode$1 = ((typeof process !== "undefined" ? process.env?.VIBES_MODE : void 0) ?? "") === "dev" ? "dev" : "prod";
1908
1909
  return _vibesMode$1;
1909
1910
  }
1911
+ function inBuildMode() {
1912
+ return (typeof process !== "undefined" ? process.env?.VIBES_BUILD : void 0) === "1";
1913
+ }
1910
1914
  function devInspectTriggers() {
1911
1915
  return Array.from(triggerRegistry.values()).map(({ entry }, i) => ({
1912
1916
  id: `trg_dev_${i}_${entry.handler}`,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@omg-dev/server",
3
- "version": "0.4.27",
3
+ "version": "0.4.29",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -14,13 +14,13 @@
14
14
  },
15
15
  "dependencies": {
16
16
  "@restatedev/restate-sdk": "1.14.5",
17
- "@omg-dev/auth": "0.4.27",
18
- "@omg-dev/schema": "0.4.27",
19
- "@omg-dev/stream": "0.4.27",
17
+ "@omg-dev/auth": "0.4.29",
18
+ "@omg-dev/schema": "0.4.29",
19
+ "@omg-dev/stream": "0.4.29",
20
20
  "web-push": "^3.6.7"
21
21
  },
22
22
  "scripts": {
23
- "build": "vp pack src/index.ts src/trigger-scan.ts",
23
+ "build": "vp pack src/index.ts src/trigger-scan.ts --no-dts",
24
24
  "test": "vp test run"
25
25
  },
26
26
  "license": "MIT",
package/src/auto-crud.ts CHANGED
@@ -9,6 +9,7 @@
9
9
  // owned by someone else" the same (404) to avoid leaking row existence.
10
10
 
11
11
  import type { Schema, FieldType, CollectionConfig } from "@omg-dev/schema"
12
+ import type { SQLQueryBindings } from "bun:sqlite"
12
13
  import { getDbInstance } from "./db.ts"
13
14
  import { invalidate } from "./broker.ts"
14
15
  import { notifyRowChange } from "./subscriptions.ts"
@@ -127,7 +128,7 @@ function makeCreateHandler(
127
128
 
128
129
  const cols = Object.keys(record)
129
130
  const placeholders = cols.map(() => "?").join(", ")
130
- const values = Object.values(record)
131
+ const values = Object.values(record) as SQLQueryBindings[]
131
132
  db.raw().prepare(`INSERT INTO ${name} (${cols.join(", ")}) VALUES (${placeholders})`).run(...values)
132
133
 
133
134
  invalidate(name)
@@ -171,7 +172,7 @@ function makeUpdateHandler(
171
172
  updates.updated_at = new Date().toISOString()
172
173
 
173
174
  const setClauses = Object.keys(updates).map(k => `${k} = ?`).join(", ")
174
- const values = [...Object.values(updates), params.id]
175
+ const values = [...Object.values(updates), params.id] as SQLQueryBindings[]
175
176
  db.raw().prepare(`UPDATE ${name} SET ${setClauses} WHERE id = ?`).run(...values)
176
177
 
177
178
  const merged = { ...existing, ...updates }
package/src/db.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { Database } from "bun:sqlite"
2
+ import type { SQLQueryBindings } from "bun:sqlite"
2
3
  import { ctxStore } from "./ctx.ts"
3
4
  import { invalidate } from "./broker.ts"
4
5
  import { notifyRowChange } from "./subscriptions.ts"
@@ -83,7 +84,7 @@ export function openDb(path: string): VibesDb {
83
84
  const db: VibesDb = {
84
85
  async getAll(table: string, opts: GetAllOpts = {}): Promise<Record<string, unknown>[]> {
85
86
  const conditions: string[] = []
86
- const params: unknown[] = []
87
+ const params: SQLQueryBindings[] = []
87
88
 
88
89
  if (isScoped(table)) {
89
90
  const owner = getOwner()
@@ -119,7 +120,7 @@ export function openDb(path: string): VibesDb {
119
120
 
120
121
  async get(table: string, id: string): Promise<Record<string, unknown> | null> {
121
122
  const conditions = ["id = ?"]
122
- const params: unknown[] = [id]
123
+ const params: SQLQueryBindings[] = [id]
123
124
 
124
125
  if (isScoped(table)) {
125
126
  const owner = getOwner()
@@ -152,7 +153,7 @@ export function openDb(path: string): VibesDb {
152
153
 
153
154
  const columns = Object.keys(record)
154
155
  const placeholders = columns.map(() => "?").join(", ")
155
- const values = Object.values(record)
156
+ const values = Object.values(record) as SQLQueryBindings[]
156
157
 
157
158
  const sql = `INSERT INTO ${table} (${columns.join(", ")}) VALUES (${placeholders})`
158
159
  bun.prepare(sql).run(...values)
@@ -174,7 +175,7 @@ export function openDb(path: string): VibesDb {
174
175
 
175
176
  const updates = { ...stripReserved(data), updated_at: now() }
176
177
  const setClauses = Object.keys(updates).map(k => `${k} = ?`).join(", ")
177
- const values = [...Object.values(updates), id]
178
+ const values = [...Object.values(updates), id] as SQLQueryBindings[]
178
179
 
179
180
  // Belt-and-braces: db.get already filtered by _owner for scoped tables,
180
181
  // but include the same predicate in the UPDATE WHERE so the mutation
@@ -203,7 +204,7 @@ export function openDb(path: string): VibesDb {
203
204
  if (!existing) return false
204
205
 
205
206
  const conditions = ["id = ?"]
206
- const params: unknown[] = [id]
207
+ const params: SQLQueryBindings[] = [id]
207
208
 
208
209
  if (isScoped(table)) {
209
210
  const owner = getOwner()
@@ -245,7 +246,7 @@ export const dbProxy = new Proxy({} as VibesDb, {
245
246
  `[vibes] db not initialized. Call createVibesServer() before using db.`
246
247
  )
247
248
  }
248
- return (_dbInstance as Record<string, unknown>)[prop]
249
+ return Reflect.get(_dbInstance, prop)
249
250
  },
250
251
  })
251
252
 
@@ -1,4 +1,5 @@
1
1
  import { collection, defineSchema, fields, type Schema } from "@omg-dev/schema"
2
+ import type { SQLQueryBindings } from "bun:sqlite"
2
3
  import { ctx } from "./ctx.ts"
3
4
  import { getDbInstance, type VibesDb } from "./db.ts"
4
5
  import { invalidate } from "./broker.ts"
@@ -204,7 +205,7 @@ function patchRaw(db: VibesDb, table: string, id: string, patch: Record<string,
204
205
  const cols = Object.keys(write)
205
206
  db.raw()
206
207
  .prepare(`UPDATE ${table} SET ${cols.map((c) => `${c} = ?`).join(", ")} WHERE id = ?`)
207
- .run(...cols.map((c) => write[c]), id)
208
+ .run(...cols.map((c) => write[c]) as SQLQueryBindings[], id)
208
209
  const after = { ...before, ...write }
209
210
  invalidate(table)
210
211
  void notifyRowChange(table, "update", before, after)
package/src/predicate.ts CHANGED
@@ -18,6 +18,8 @@
18
18
  // so the WHERE clause stays interpolation-safe. Values are always bound as
19
19
  // parameters — never string-concatenated.
20
20
 
21
+ import type { SQLQueryBindings } from "bun:sqlite"
22
+
21
23
  // ── Types ────────────────────────────────────────────────────────────────────
22
24
 
23
25
  export type Literal = string | number | boolean | null
@@ -175,16 +177,16 @@ export interface CompiledSql {
175
177
  /** Parenthesized SQL fragment safe to AND with other WHERE conditions. */
176
178
  sql: string
177
179
  /** Bound parameters in left-to-right order. */
178
- params: unknown[]
180
+ params: SQLQueryBindings[]
179
181
  }
180
182
 
181
183
  export function compileToSql(pred: Predicate): CompiledSql {
182
- const params: unknown[] = []
184
+ const params: SQLQueryBindings[] = []
183
185
  const sql = emitSql(pred, params)
184
186
  return { sql, params }
185
187
  }
186
188
 
187
- function emitSql(p: Predicate, params: unknown[]): string {
189
+ function emitSql(p: Predicate, params: SQLQueryBindings[]): string {
188
190
  switch (p.op) {
189
191
  case "and":
190
192
  return `(${p.clauses.map(c => emitSql(c, params)).join(" AND ")})`
@@ -226,7 +228,7 @@ function emitSql(p: Predicate, params: unknown[]): string {
226
228
 
227
229
  // SQLite stores booleans as INTEGER 0/1 — coerce on the way to a bound param
228
230
  // so an `eq done true` predicate hits a `done = 1` row.
229
- function encodeLiteral(v: Literal): unknown {
231
+ function encodeLiteral(v: Literal): SQLQueryBindings {
230
232
  if (typeof v === "boolean") return v ? 1 : 0
231
233
  return v
232
234
  }
@@ -21,6 +21,7 @@
21
21
  // package in dev to that shape.
22
22
 
23
23
  import type { Schema } from "@omg-dev/schema"
24
+ import type { SQLQueryBindings } from "bun:sqlite"
24
25
  import { getDbInstance } from "./db.ts"
25
26
  import { decodeRow } from "./codec.ts"
26
27
  import {
@@ -349,7 +350,7 @@ export function notifyRowChange(
349
350
  ? (newRowRaw?._owner as string | undefined) ?? (oldRowRaw?._owner as string | undefined) ?? null
350
351
  : null
351
352
 
352
- const pending: Promise<void>[] = []
353
+ const pending: Promise<boolean>[] = []
353
354
  // Snapshot to a stable array — sends may evict clients mid-iteration.
354
355
  const targets = Array.from(set)
355
356
  for (const client of targets) {
@@ -499,7 +500,7 @@ async function sendSnapshot(client: SubClient, sub: ClientSub): Promise<void> {
499
500
 
500
501
  const scoped = col.scope === "user"
501
502
  const conditions: string[] = []
502
- const params: unknown[] = []
503
+ const params: SQLQueryBindings[] = []
503
504
 
504
505
  if (scoped) {
505
506
  if (!client.ctx.userId) {
@@ -0,0 +1,80 @@
1
+ // Regression test for the vibes-build hang (confirmed: `[vibes-build] done.`
2
+ // prints, process never exits when the project declares cron()/on()).
3
+ //
4
+ // Root cause: registerTriggers() arms an in-process setTimeout chain for
5
+ // every cron() handler whenever vibesMode()==="dev" or cronDriver()===
6
+ // "in-process" — including when createVibesServer() is constructed by the
7
+ // vibes vite-plugin's configureServer hook, which prerenderApp() (part of
8
+ // `vibes-build`) triggers indirectly via a nested Vite dev server. Those
9
+ // timers keep the event loop alive forever with no caller left to clear
10
+ // them, since a build process has no request loop to eventually close it.
11
+ //
12
+ // This can only be observed as a live-process behavior (does the process
13
+ // exit on its own?), not through a return-value assertion on
14
+ // registerTriggers() — so this test spawns a real Bun subprocess and checks
15
+ // whether it terminates within a bounded window.
16
+
17
+ import { describe, expect, test } from "bun:test"
18
+ import fs from "node:fs"
19
+ import os from "node:os"
20
+ import path from "node:path"
21
+
22
+ const triggersModulePath = path.join(import.meta.dir, "..", "triggers.ts")
23
+
24
+ function writeRegisterScript(): string {
25
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "vibes-build-mode-cron-"))
26
+ const file = path.join(dir, "register.ts")
27
+ fs.writeFileSync(
28
+ file,
29
+ [
30
+ `import { registerTriggers } from ${JSON.stringify(triggersModulePath)}`,
31
+ "await registerTriggers([",
32
+ ' { handler: "trg.tick", kind: "cron", key: "* * * * *", module: "/dev/null", exportName: "tick", mod: { tick: async () => {} } },',
33
+ ' { handler: "trg.onEvt", kind: "on", key: "some.topic", module: "/dev/null", exportName: "onEvt", mod: { onEvt: async () => {} } },',
34
+ "])",
35
+ 'console.log("REGISTERED")',
36
+ "",
37
+ ].join("\n"),
38
+ )
39
+ return file
40
+ }
41
+
42
+ // Runs `script` in a fresh Bun subprocess with `env` merged over the current
43
+ // process env. Resolves `{ exited: true }` if the process exits within
44
+ // `timeoutMs` on its own, or `{ exited: false }` (after force-killing it) if
45
+ // it's still alive at the deadline — the exact symptom of the original bug.
46
+ async function runAndWaitForExit(
47
+ script: string,
48
+ env: Record<string, string>,
49
+ timeoutMs: number,
50
+ ): Promise<{ exited: boolean }> {
51
+ const proc = Bun.spawn(["bun", "run", script], {
52
+ env: { ...process.env, ...env },
53
+ stdout: "pipe",
54
+ stderr: "pipe",
55
+ })
56
+ let timedOut = false
57
+ const timer = setTimeout(() => {
58
+ timedOut = true
59
+ proc.kill()
60
+ }, timeoutMs)
61
+ await proc.exited
62
+ clearTimeout(timer)
63
+ return { exited: !timedOut }
64
+ }
65
+
66
+ describe("registerTriggers build-mode cron gating", () => {
67
+ test("VIBES_BUILD=1: a cron()+on() project terminates on its own", async () => {
68
+ const script = writeRegisterScript()
69
+ const { exited } = await runAndWaitForExit(script, { VIBES_BUILD: "1", VIBES_MODE: "dev" }, 8000)
70
+ expect(exited).toBe(true)
71
+ }, 15000)
72
+
73
+ test("sanity: without VIBES_BUILD, dev-mode cron is still armed (stays alive)", async () => {
74
+ // Mirrors the fixed case above to prove the guard is scoped to build
75
+ // mode only — normal `bun dev` cron scheduling must be unaffected.
76
+ const script = writeRegisterScript()
77
+ const { exited } = await runAndWaitForExit(script, { VIBES_MODE: "dev" }, 2000)
78
+ expect(exited).toBe(false)
79
+ }, 15000)
80
+ })
package/src/triggers.ts CHANGED
@@ -242,12 +242,20 @@ export async function registerTriggers(entries: TriggerEntry[]): Promise<void> {
242
242
  }
243
243
  }
244
244
  void registeredFirstTime // suppress unused — kept for future HMR diff
245
- const inProcessCron = vibesMode() === "dev" || cronDriver() === "in-process"
245
+ // vibes-build sets VIBES_BUILD=1 for its whole process, including the
246
+ // nested Vite dev server it spins up for prerender SSG. A build is not a
247
+ // runtime — nothing should ever arm a live setTimeout chain there, or the
248
+ // process hangs forever after writing its artifacts (confirmed hang: cron
249
+ // schedulers keep the event loop open with no caller left to clear them).
250
+ const inBuild = inBuildMode()
251
+ const inProcessCron = !inBuild && (vibesMode() === "dev" || cronDriver() === "in-process")
246
252
  if (inProcessCron) {
247
253
  scheduleAllCronInProcess()
248
254
  }
249
255
  console.log(
250
- `[vibes:triggers] registered ${entries.length} trigger(s) — mode=${vibesMode()}, cron=${inProcessCron ? "in-process" : "orchestrator"}`,
256
+ `[vibes:triggers] registered ${entries.length} trigger(s) — mode=${vibesMode()}, cron=${
257
+ inBuild ? "unarmed (build)" : inProcessCron ? "in-process" : "orchestrator"
258
+ }`,
251
259
  )
252
260
  }
253
261
 
@@ -810,6 +818,15 @@ function vibesMode(): "dev" | "prod" {
810
818
  return _vibesMode
811
819
  }
812
820
 
821
+ // Set for the whole lifetime of `vibes-build` (packages/vite-plugin/src/build.ts).
822
+ // A build process has no caller left to clear timers once it "finishes" —
823
+ // so cron must never be armed in-process while this is set, however
824
+ // createVibesServer() got invoked (directly, or via prerender's nested dev
825
+ // server).
826
+ function inBuildMode(): boolean {
827
+ return (typeof process !== "undefined" ? process.env?.VIBES_BUILD : undefined) === "1"
828
+ }
829
+
813
830
  // ── Dev Inspect data accessors ───────────────────────────────────────────────
814
831
  //
815
832
  // In dev mode, the dashboard's Inspect tabs read the in-memory rings