@spader/spall-sdk 1.0.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.
Files changed (70) hide show
  1. package/dist/app.d.ts +7 -0
  2. package/dist/app.d.ts.map +1 -0
  3. package/dist/client.d.ts +20 -0
  4. package/dist/client.d.ts.map +1 -0
  5. package/dist/client.js +1642 -0
  6. package/dist/client.js.map +21 -0
  7. package/dist/gen/client/client.gen.d.ts +3 -0
  8. package/dist/gen/client/client.gen.d.ts.map +1 -0
  9. package/dist/gen/client/index.d.ts +9 -0
  10. package/dist/gen/client/index.d.ts.map +1 -0
  11. package/dist/gen/client/types.gen.d.ts +118 -0
  12. package/dist/gen/client/types.gen.d.ts.map +1 -0
  13. package/dist/gen/client/utils.gen.d.ts +34 -0
  14. package/dist/gen/client/utils.gen.d.ts.map +1 -0
  15. package/dist/gen/client.gen.d.ts +13 -0
  16. package/dist/gen/client.gen.d.ts.map +1 -0
  17. package/dist/gen/core/auth.gen.d.ts +19 -0
  18. package/dist/gen/core/auth.gen.d.ts.map +1 -0
  19. package/dist/gen/core/bodySerializer.gen.d.ts +26 -0
  20. package/dist/gen/core/bodySerializer.gen.d.ts.map +1 -0
  21. package/dist/gen/core/params.gen.d.ts +44 -0
  22. package/dist/gen/core/params.gen.d.ts.map +1 -0
  23. package/dist/gen/core/pathSerializer.gen.d.ts +34 -0
  24. package/dist/gen/core/pathSerializer.gen.d.ts.map +1 -0
  25. package/dist/gen/core/queryKeySerializer.gen.d.ts +19 -0
  26. package/dist/gen/core/queryKeySerializer.gen.d.ts.map +1 -0
  27. package/dist/gen/core/serverSentEvents.gen.d.ts +72 -0
  28. package/dist/gen/core/serverSentEvents.gen.d.ts.map +1 -0
  29. package/dist/gen/core/types.gen.d.ts +79 -0
  30. package/dist/gen/core/types.gen.d.ts.map +1 -0
  31. package/dist/gen/core/utils.gen.d.ts +20 -0
  32. package/dist/gen/core/utils.gen.d.ts.map +1 -0
  33. package/dist/gen/index.d.ts +3 -0
  34. package/dist/gen/index.d.ts.map +1 -0
  35. package/dist/gen/sdk.gen.d.ts +358 -0
  36. package/dist/gen/sdk.gen.d.ts.map +1 -0
  37. package/dist/gen/types.gen.d.ts +1596 -0
  38. package/dist/gen/types.gen.d.ts.map +1 -0
  39. package/dist/index.d.ts +5 -0
  40. package/dist/index.d.ts.map +1 -0
  41. package/dist/index.js +2925 -0
  42. package/dist/index.js.map +32 -0
  43. package/dist/lock.d.ts +20 -0
  44. package/dist/lock.d.ts.map +1 -0
  45. package/dist/log.d.ts +22 -0
  46. package/dist/log.d.ts.map +1 -0
  47. package/dist/routes/commit.d.ts +19 -0
  48. package/dist/routes/commit.d.ts.map +1 -0
  49. package/dist/routes/corpus.d.ts +317 -0
  50. package/dist/routes/corpus.d.ts.map +1 -0
  51. package/dist/routes/note.d.ts +79 -0
  52. package/dist/routes/note.d.ts.map +1 -0
  53. package/dist/routes/query.d.ts +314 -0
  54. package/dist/routes/query.d.ts.map +1 -0
  55. package/dist/routes/sse.d.ts +75 -0
  56. package/dist/routes/sse.d.ts.map +1 -0
  57. package/dist/routes/workspace.d.ts +102 -0
  58. package/dist/routes/workspace.d.ts.map +1 -0
  59. package/dist/serve.d.ts +2 -0
  60. package/dist/serve.d.ts.map +1 -0
  61. package/dist/server.d.ts +27 -0
  62. package/dist/server.d.ts.map +1 -0
  63. package/dist/server.js +1433 -0
  64. package/dist/server.js.map +21 -0
  65. package/dist/sse.d.ts +8 -0
  66. package/dist/sse.d.ts.map +1 -0
  67. package/dist/util.d.ts +5 -0
  68. package/dist/util.d.ts.map +1 -0
  69. package/openapi.json +5694 -0
  70. package/package.json +70 -0
package/dist/server.js ADDED
@@ -0,0 +1,1433 @@
1
+ // @bun
2
+ // src/server.ts
3
+ import { consola } from "consola";
4
+ import pc from "picocolors";
5
+ import { Bus as Bus2 } from "@spader/spall-core/event";
6
+ import { Config as Config3 } from "@spader/spall-core/config";
7
+ import { Model } from "@spader/spall-core/model";
8
+
9
+ // src/app.ts
10
+ import { Hono as Hono7 } from "hono";
11
+ import { logger } from "hono/logger";
12
+ import { describeRoute as describeRoute7, generateSpecs, resolver as resolver7 } from "hono-openapi";
13
+ import { z } from "zod";
14
+
15
+ // src/log.ts
16
+ import { mkdirSync, appendFileSync } from "fs";
17
+ import { dirname, join } from "path";
18
+ import { Config } from "@spader/spall-core/config";
19
+ var ServerLog;
20
+ ((ServerLog) => {
21
+ let dir = null;
22
+ let eventsPath;
23
+ let appPath;
24
+ function ts() {
25
+ return new Date().toISOString();
26
+ }
27
+ function init(port) {
28
+ const stamp = new Date().toISOString().replace(/:/g, "-").replace(/\.\d+Z$/, "Z");
29
+ const name = `${stamp}_${process.pid}_${port}`;
30
+ dir = join(Config.get().dirs.data, "logs", name);
31
+ mkdirSync(dir, { recursive: true });
32
+ eventsPath = join(dir, "events.log");
33
+ appPath = join(dir, "app.log");
34
+ }
35
+ ServerLog.init = init;
36
+ function safeAppend(path2, line) {
37
+ try {
38
+ appendFileSync(path2, line + `
39
+ `);
40
+ } catch {
41
+ try {
42
+ mkdirSync(dirname(path2), { recursive: true });
43
+ appendFileSync(path2, line + `
44
+ `);
45
+ } catch {}
46
+ }
47
+ }
48
+ function event(e) {
49
+ if (!dir)
50
+ return;
51
+ const line = JSON.stringify({ ts: ts(), ...e });
52
+ safeAppend(eventsPath, line);
53
+ }
54
+ ServerLog.event = event;
55
+ function error(err) {
56
+ if (!dir)
57
+ return;
58
+ const message = err instanceof Error ? { message: err.message, stack: err.stack } : { message: String(err) };
59
+ const line = JSON.stringify({ ts: ts(), tag: "error", ...message });
60
+ safeAppend(eventsPath, line);
61
+ }
62
+ ServerLog.error = error;
63
+ const ANSI_RE = /\x1b\[[0-9;]*m/g;
64
+ function appLog(message, ...rest) {
65
+ if (!dir)
66
+ return;
67
+ const raw = `${ts()} ${message} ${rest.join(" ")}`.trimEnd();
68
+ safeAppend(appPath, raw.replace(ANSI_RE, ""));
69
+ }
70
+ ServerLog.appLog = appLog;
71
+ function path() {
72
+ return dir;
73
+ }
74
+ ServerLog.path = path;
75
+ })(ServerLog ||= {});
76
+
77
+ // src/routes/corpus.ts
78
+ import { Hono } from "hono";
79
+ import { describeRoute, resolver, validator } from "hono-openapi";
80
+
81
+ // src/util.ts
82
+ function lazy(fn) {
83
+ let value;
84
+ let loaded = false;
85
+ const result = () => {
86
+ if (loaded)
87
+ return value;
88
+ loaded = true;
89
+ value = fn();
90
+ return value;
91
+ };
92
+ result.reset = () => {
93
+ loaded = false;
94
+ value = undefined;
95
+ };
96
+ return result;
97
+ }
98
+
99
+ // src/routes/corpus.ts
100
+ import { Corpus, Note, Error as Error2 } from "@spader/spall-core";
101
+ var CorpusRoutes = lazy(() => new Hono().get("/:id/list", describeRoute({
102
+ summary: "List notes",
103
+ description: "List all note paths in a corpus.",
104
+ operationId: "note.list",
105
+ responses: {
106
+ 200: {
107
+ description: "List of notes",
108
+ content: {
109
+ "application/json": {
110
+ schema: resolver(Note.ListItem.array())
111
+ }
112
+ }
113
+ },
114
+ 404: {
115
+ description: "Corpus not found",
116
+ content: {
117
+ "application/json": {
118
+ schema: resolver(Error2.Info)
119
+ }
120
+ }
121
+ }
122
+ }
123
+ }), async (c) => {
124
+ const id = c.req.param("id");
125
+ const result = await Note.list({
126
+ corpus: Corpus.Id.parse(id)
127
+ }).then((result2) => c.json(result2)).catch((error) => c.json(Error2.from(error), 404));
128
+ return result;
129
+ }).get("/:id/notes", describeRoute({
130
+ summary: "List notes by path",
131
+ description: "List notes under a path prefix with keyset pagination. Returns full note content.",
132
+ operationId: "note.listByPath",
133
+ responses: {
134
+ 200: {
135
+ description: "Paginated notes",
136
+ content: {
137
+ "application/json": {
138
+ schema: resolver(Note.Page)
139
+ }
140
+ }
141
+ },
142
+ 404: {
143
+ description: "Corpus not found",
144
+ content: {
145
+ "application/json": {
146
+ schema: resolver(Error2.Info)
147
+ }
148
+ }
149
+ }
150
+ }
151
+ }), validator("query", Note.listByPath.schema.omit({ corpus: true })), async (c) => {
152
+ const id = c.req.param("id");
153
+ const query = c.req.valid("query");
154
+ try {
155
+ const result = Note.listByPath({
156
+ corpus: Corpus.Id.parse(id),
157
+ ...query
158
+ });
159
+ return c.json(result);
160
+ } catch (error) {
161
+ return c.json(Error2.from(error), 404);
162
+ }
163
+ }).get("/:id/note/:path{.+}", describeRoute({
164
+ summary: "Get a note",
165
+ description: "Get a note by path within a corpus.",
166
+ operationId: "note.get",
167
+ responses: {
168
+ 200: {
169
+ description: "Note with content",
170
+ content: {
171
+ "application/json": {
172
+ schema: resolver(Note.Info)
173
+ }
174
+ }
175
+ },
176
+ 404: {
177
+ description: "Corpus or note not found",
178
+ content: {
179
+ "application/json": {
180
+ schema: resolver(Error2.Info)
181
+ }
182
+ }
183
+ }
184
+ }
185
+ }), async (c) => {
186
+ const id = c.req.param("id");
187
+ const path = c.req.param("path");
188
+ try {
189
+ const result = Note.get({
190
+ corpus: Corpus.Id.parse(id),
191
+ path
192
+ });
193
+ return c.json(result);
194
+ } catch (error) {
195
+ return c.json(Error2.from(error), 404);
196
+ }
197
+ }).post("/", describeRoute({
198
+ summary: "Create a corpus",
199
+ description: "Get or create a corpus. Returns existing corpus if name matches, creates new one otherwise.",
200
+ operationId: "corpus.create",
201
+ responses: {
202
+ 200: {
203
+ description: "Corpus info",
204
+ content: {
205
+ "application/json": {
206
+ schema: resolver(Corpus.Info)
207
+ }
208
+ }
209
+ }
210
+ }
211
+ }), validator("json", Corpus.create.schema), async (context) => {
212
+ const input = context.req.valid("json") ?? {};
213
+ const result = await Corpus.create(input);
214
+ return context.json(result);
215
+ }).get("/list", describeRoute({
216
+ summary: "List corpora",
217
+ description: "List all corpora.",
218
+ operationId: "corpus.list",
219
+ responses: {
220
+ 200: {
221
+ description: "List of corpora",
222
+ content: {
223
+ "application/json": {
224
+ schema: resolver(Corpus.Info.array())
225
+ }
226
+ }
227
+ },
228
+ 500: {
229
+ description: "Server error",
230
+ content: {
231
+ "application/json": {
232
+ schema: resolver(Error2.Info)
233
+ }
234
+ }
235
+ }
236
+ }
237
+ }), async (c) => {
238
+ try {
239
+ const result = await Corpus.list({});
240
+ return c.json(result);
241
+ } catch (error) {
242
+ return c.json(Error2.from(error), 500);
243
+ }
244
+ }).get("/", describeRoute({
245
+ summary: "Get corpus",
246
+ description: "Look up a corpus by name or id. Returns default corpus if neither specified.",
247
+ operationId: "corpus.get",
248
+ responses: {
249
+ 200: {
250
+ description: "Corpus info",
251
+ content: {
252
+ "application/json": {
253
+ schema: resolver(Corpus.Info)
254
+ }
255
+ }
256
+ },
257
+ 404: {
258
+ description: "Corpus not found",
259
+ content: {
260
+ "application/json": {
261
+ schema: resolver(Error2.Info)
262
+ }
263
+ }
264
+ }
265
+ }
266
+ }), validator("query", Corpus.get.schema), async (context) => {
267
+ const query = context.req.valid("query");
268
+ try {
269
+ const result = await Corpus.get(query);
270
+ return context.json(result);
271
+ } catch (error) {
272
+ return context.json(Error2.from(error), 404);
273
+ }
274
+ }).delete("/:id", describeRoute({
275
+ summary: "Delete corpus",
276
+ description: "Delete a corpus and all associated notes by ID.",
277
+ operationId: "corpus.delete",
278
+ responses: {
279
+ 204: {
280
+ description: "Corpus deleted successfully"
281
+ },
282
+ 404: {
283
+ description: "Corpus not found",
284
+ content: {
285
+ "application/json": {
286
+ schema: resolver(Error2.Info)
287
+ }
288
+ }
289
+ }
290
+ }
291
+ }), async (context) => {
292
+ try {
293
+ const id = context.req.param("id");
294
+ await Corpus.remove({ id: Corpus.Id.parse(id) });
295
+ return context.body(null, 204);
296
+ } catch (error) {
297
+ return context.json(Error2.from(error), 404);
298
+ }
299
+ }).post("/sync", describeRoute({
300
+ summary: "Sync a directory as notes",
301
+ description: "Scan a directory, add matching notes, remove non-matches",
302
+ operationId: "note.sync",
303
+ responses: {
304
+ 204: {
305
+ description: "Index complete"
306
+ }
307
+ }
308
+ }), validator("json", Note.sync.schema), async (context) => {
309
+ const body = context.req.valid("json");
310
+ await Note.sync(body);
311
+ return context.body(null, 204);
312
+ }).post("/note", describeRoute({
313
+ summary: "Add a note",
314
+ description: "Add a note to a corpus and embed it. Requires corpus ID.",
315
+ operationId: "note.add",
316
+ responses: {
317
+ 200: {
318
+ description: "Created note",
319
+ content: {
320
+ "application/json": {
321
+ schema: resolver(Note.Info)
322
+ }
323
+ }
324
+ },
325
+ 404: {
326
+ description: "Corpus not found",
327
+ content: {
328
+ "application/json": {
329
+ schema: resolver(Error2.Info)
330
+ }
331
+ }
332
+ }
333
+ }
334
+ }), validator("json", Note.add.schema), async (context) => {
335
+ const body = context.req.valid("json");
336
+ try {
337
+ const result = await Note.add(body);
338
+ return context.json(result);
339
+ } catch (error) {
340
+ return context.json(Error2.from(error), 404);
341
+ }
342
+ }).put("/:id/note/:path{.+}", describeRoute({
343
+ summary: "Upsert a note",
344
+ description: "Create or update a note by path. Creates if not exists, updates if exists.",
345
+ operationId: "note.upsert",
346
+ responses: {
347
+ 200: {
348
+ description: "Created or updated note",
349
+ content: {
350
+ "application/json": {
351
+ schema: resolver(Note.Info)
352
+ }
353
+ }
354
+ },
355
+ 404: {
356
+ description: "Corpus not found",
357
+ content: {
358
+ "application/json": {
359
+ schema: resolver(Error2.Info)
360
+ }
361
+ }
362
+ }
363
+ }
364
+ }), validator("json", Note.upsert.schema.omit({ corpus: true, path: true })), async (context) => {
365
+ const id = context.req.param("id");
366
+ const path = context.req.param("path");
367
+ const body = context.req.valid("json");
368
+ try {
369
+ const result = await Note.upsert({
370
+ corpus: Corpus.Id.parse(id),
371
+ path,
372
+ ...body
373
+ });
374
+ return context.json(result);
375
+ } catch (error) {
376
+ return context.json(Error2.from(error), 404);
377
+ }
378
+ }));
379
+
380
+ // src/routes/workspace.ts
381
+ import { Hono as Hono2 } from "hono";
382
+ import { describeRoute as describeRoute2, resolver as resolver2, validator as validator2 } from "hono-openapi";
383
+ import { Workspace, Error as Error3 } from "@spader/spall-core";
384
+ var WorkspaceRoutes = lazy(() => new Hono2().post("/", describeRoute2({
385
+ summary: "Create a workspace",
386
+ description: "Get or create a workspace. Returns existing workspace if name matches, creates new one otherwise.",
387
+ operationId: "workspace.create",
388
+ responses: {
389
+ 200: {
390
+ description: "Workspace info",
391
+ content: {
392
+ "application/json": {
393
+ schema: resolver2(Workspace.Info)
394
+ }
395
+ }
396
+ }
397
+ }
398
+ }), validator2("json", Workspace.create.schema), async (context) => {
399
+ const input = context.req.valid("json") ?? {};
400
+ const result = await Workspace.create(input);
401
+ return context.json(result);
402
+ }).get("/list", describeRoute2({
403
+ summary: "List workspaces",
404
+ description: "List all workspaces.",
405
+ operationId: "workspace.list",
406
+ responses: {
407
+ 200: {
408
+ description: "List of workspaces",
409
+ content: {
410
+ "application/json": {
411
+ schema: resolver2(Workspace.Info.array())
412
+ }
413
+ }
414
+ },
415
+ 500: {
416
+ description: "Server error",
417
+ content: {
418
+ "application/json": {
419
+ schema: resolver2(Error3.Info)
420
+ }
421
+ }
422
+ }
423
+ }
424
+ }), async (c) => {
425
+ try {
426
+ const result = await Workspace.list({});
427
+ return c.json(result);
428
+ } catch (error) {
429
+ return c.json(Error3.from(error), 500);
430
+ }
431
+ }).get("/", describeRoute2({
432
+ summary: "Get workspace",
433
+ description: "Look up a workspace by name or id.",
434
+ operationId: "workspace.get",
435
+ responses: {
436
+ 200: {
437
+ description: "Workspace info",
438
+ content: {
439
+ "application/json": {
440
+ schema: resolver2(Workspace.Info)
441
+ }
442
+ }
443
+ },
444
+ 404: {
445
+ description: "Workspace not found",
446
+ content: {
447
+ "application/json": {
448
+ schema: resolver2(Error3.Info)
449
+ }
450
+ }
451
+ }
452
+ }
453
+ }), validator2("query", Workspace.get.schema), async (context) => {
454
+ const query = context.req.valid("query");
455
+ try {
456
+ const result = await Workspace.get(query);
457
+ return context.json(result);
458
+ } catch (error) {
459
+ return context.json(Error3.from(error), 404);
460
+ }
461
+ }).delete("/:id", describeRoute2({
462
+ summary: "Delete workspace",
463
+ description: "Delete a workspace by ID.",
464
+ operationId: "workspace.delete",
465
+ responses: {
466
+ 204: {
467
+ description: "Workspace deleted successfully"
468
+ },
469
+ 404: {
470
+ description: "Workspace not found",
471
+ content: {
472
+ "application/json": {
473
+ schema: resolver2(Error3.Info)
474
+ }
475
+ }
476
+ }
477
+ }
478
+ }), async (context) => {
479
+ try {
480
+ const id = context.req.param("id");
481
+ await Workspace.remove({ id: Workspace.Id.parse(id) });
482
+ return context.body(null, 204);
483
+ } catch (error) {
484
+ return context.json(Error3.from(error), 404);
485
+ }
486
+ }));
487
+
488
+ // src/routes/note.ts
489
+ import { Hono as Hono3 } from "hono";
490
+ import { describeRoute as describeRoute3, resolver as resolver3, validator as validator3 } from "hono-openapi";
491
+ import { Note as Note2, Error as Error4 } from "@spader/spall-core";
492
+ var NoteRoutes = lazy(() => new Hono3().get("/:id", describeRoute3({
493
+ summary: "Get a note by ID",
494
+ description: "Get a note by its globally unique ID.",
495
+ operationId: "note.getById",
496
+ responses: {
497
+ 200: {
498
+ description: "Note with content",
499
+ content: {
500
+ "application/json": {
501
+ schema: resolver3(Note2.Info)
502
+ }
503
+ }
504
+ },
505
+ 404: {
506
+ description: "Note not found",
507
+ content: {
508
+ "application/json": {
509
+ schema: resolver3(Error4.Info)
510
+ }
511
+ }
512
+ }
513
+ }
514
+ }), async (c) => {
515
+ const id = c.req.param("id");
516
+ try {
517
+ const result = Note2.getById({
518
+ id: Note2.Id.parse(id)
519
+ });
520
+ return c.json(result);
521
+ } catch (error) {
522
+ return c.json(Error4.from(error), 404);
523
+ }
524
+ }).put("/:id", describeRoute3({
525
+ summary: "Update a note",
526
+ description: "Update a note's content by ID. Re-embeds the content.",
527
+ operationId: "note.update",
528
+ responses: {
529
+ 200: {
530
+ description: "Updated note",
531
+ content: {
532
+ "application/json": {
533
+ schema: resolver3(Note2.Info)
534
+ }
535
+ }
536
+ },
537
+ 404: {
538
+ description: "Note not found",
539
+ content: {
540
+ "application/json": {
541
+ schema: resolver3(Error4.Info)
542
+ }
543
+ }
544
+ }
545
+ }
546
+ }), validator3("json", Note2.update.schema.omit({ id: true })), async (context) => {
547
+ const id = context.req.param("id");
548
+ const body = context.req.valid("json");
549
+ try {
550
+ const result = await Note2.update({
551
+ id: Note2.Id.parse(id),
552
+ ...body
553
+ });
554
+ return context.json(result);
555
+ } catch (error) {
556
+ return context.json(Error4.from(error), 404);
557
+ }
558
+ }));
559
+
560
+ // src/routes/query.ts
561
+ import { Hono as Hono4 } from "hono";
562
+ import { describeRoute as describeRoute4, resolver as resolver4, validator as validator4 } from "hono-openapi";
563
+ import { Query, Note as Note3, Error as Error5 } from "@spader/spall-core";
564
+ var QueryRoutes = lazy(() => new Hono4().post("/", describeRoute4({
565
+ summary: "Create a query",
566
+ description: "Create a query scope for aggregating notes across multiple corpora.",
567
+ operationId: "query.create",
568
+ responses: {
569
+ 200: {
570
+ description: "Query info",
571
+ content: {
572
+ "application/json": {
573
+ schema: resolver4(Query.Info)
574
+ }
575
+ }
576
+ },
577
+ 404: {
578
+ description: "Query not found",
579
+ content: {
580
+ "application/json": {
581
+ schema: resolver4(Error5.Info)
582
+ }
583
+ }
584
+ }
585
+ }
586
+ }), validator4("json", Query.create.schema), async (c) => {
587
+ const body = c.req.valid("json");
588
+ try {
589
+ const result = Query.create(body);
590
+ return c.json(result);
591
+ } catch (error) {
592
+ return c.json(Error5.from(error), 404);
593
+ }
594
+ }).get("/recent", describeRoute4({
595
+ summary: "List recent queries",
596
+ description: "Get the most recently created queries.",
597
+ operationId: "query.recent",
598
+ responses: {
599
+ 200: {
600
+ description: "Recent queries",
601
+ content: {
602
+ "application/json": {
603
+ schema: resolver4(Query.RecentResults)
604
+ }
605
+ }
606
+ }
607
+ }
608
+ }), validator4("query", Query.recent.schema), async (c) => {
609
+ const query = c.req.valid("query");
610
+ const result = Query.recent(query);
611
+ return c.json(result);
612
+ }).get("/:id", describeRoute4({
613
+ summary: "Get a query",
614
+ description: "Get a query by ID.",
615
+ operationId: "query.get",
616
+ responses: {
617
+ 200: {
618
+ description: "Query info",
619
+ content: {
620
+ "application/json": {
621
+ schema: resolver4(Query.Info)
622
+ }
623
+ }
624
+ },
625
+ 404: {
626
+ description: "Query not found",
627
+ content: {
628
+ "application/json": {
629
+ schema: resolver4(Error5.Info)
630
+ }
631
+ }
632
+ }
633
+ }
634
+ }), async (c) => {
635
+ const id = c.req.param("id");
636
+ try {
637
+ const result = Query.get({ id: Query.Id.parse(id) });
638
+ return c.json(result);
639
+ } catch (error) {
640
+ return c.json(Error5.from(error), 404);
641
+ }
642
+ }).get("/:id/notes", describeRoute4({
643
+ summary: "Query notes",
644
+ description: "List notes across all corpora in a query with keyset pagination.",
645
+ operationId: "query.notes",
646
+ responses: {
647
+ 200: {
648
+ description: "Paginated notes",
649
+ content: {
650
+ "application/json": {
651
+ schema: resolver4(Note3.Page)
652
+ }
653
+ }
654
+ },
655
+ 404: {
656
+ description: "Query not found",
657
+ content: {
658
+ "application/json": {
659
+ schema: resolver4(Error5.Info)
660
+ }
661
+ }
662
+ }
663
+ }
664
+ }), validator4("query", Query.notes.schema.omit({ id: true })), async (c) => {
665
+ const id = c.req.param("id");
666
+ const query = c.req.valid("query");
667
+ try {
668
+ const result = Query.notes({
669
+ id: Query.Id.parse(id),
670
+ ...query
671
+ });
672
+ return c.json(result);
673
+ } catch (error) {
674
+ return c.json(Error5.from(error), 404);
675
+ }
676
+ }).get("/:id/search", describeRoute4({
677
+ summary: "Keyword search",
678
+ description: "Search note content across all corpora in a query using FTS5.",
679
+ operationId: "query.search",
680
+ responses: {
681
+ 200: {
682
+ description: "Search results",
683
+ content: {
684
+ "application/json": {
685
+ schema: resolver4(Query.SearchResults)
686
+ }
687
+ }
688
+ },
689
+ 404: {
690
+ description: "Query not found",
691
+ content: {
692
+ "application/json": {
693
+ schema: resolver4(Error5.Info)
694
+ }
695
+ }
696
+ }
697
+ }
698
+ }), validator4("query", Query.search.schema.omit({ id: true })), async (c) => {
699
+ const id = c.req.param("id");
700
+ const query = c.req.valid("query");
701
+ try {
702
+ const result = Query.search({
703
+ id: Query.Id.parse(id),
704
+ ...query
705
+ });
706
+ return c.json(result);
707
+ } catch (error) {
708
+ return c.json(Error5.from(error), 404);
709
+ }
710
+ }).get("/:id/vsearch", describeRoute4({
711
+ summary: "Vector search",
712
+ description: "Semantic search across all corpora in a query using embeddings.",
713
+ operationId: "query.vsearch",
714
+ responses: {
715
+ 200: {
716
+ description: "Search results",
717
+ content: {
718
+ "application/json": {
719
+ schema: resolver4(Query.VSearchResults)
720
+ }
721
+ }
722
+ },
723
+ 404: {
724
+ description: "Query not found",
725
+ content: {
726
+ "application/json": {
727
+ schema: resolver4(Error5.Info)
728
+ }
729
+ }
730
+ }
731
+ }
732
+ }), validator4("query", Query.vsearch.schema.omit({ id: true })), async (c) => {
733
+ const id = c.req.param("id");
734
+ const query = c.req.valid("query");
735
+ try {
736
+ const result = await Query.vsearch({
737
+ id: Query.Id.parse(id),
738
+ ...query
739
+ });
740
+ return c.json(result);
741
+ } catch (error) {
742
+ return c.json(Error5.from(error), 404);
743
+ }
744
+ }).post("/:id/fetch", describeRoute4({
745
+ summary: "Fetch notes by ID",
746
+ description: "Fetch full note content for a list of note IDs through a query scope. Records access for reweighting.",
747
+ operationId: "query.fetch",
748
+ responses: {
749
+ 200: {
750
+ description: "Fetched notes",
751
+ content: {
752
+ "application/json": {
753
+ schema: resolver4(Query.FetchResults)
754
+ }
755
+ }
756
+ },
757
+ 404: {
758
+ description: "Query not found",
759
+ content: {
760
+ "application/json": {
761
+ schema: resolver4(Error5.Info)
762
+ }
763
+ }
764
+ }
765
+ }
766
+ }), validator4("json", Query.fetch.schema.omit({ id: true })), async (c) => {
767
+ const id = c.req.param("id");
768
+ const body = c.req.valid("json");
769
+ try {
770
+ const result = Query.fetch({
771
+ id: Query.Id.parse(id),
772
+ ...body
773
+ });
774
+ return c.json(result);
775
+ } catch (error) {
776
+ return c.json(Error5.from(error), 404);
777
+ }
778
+ }).get("/:id/paths", describeRoute4({
779
+ summary: "List paths",
780
+ description: "List all note paths across corpora in a query, grouped by corpus.",
781
+ operationId: "query.paths",
782
+ responses: {
783
+ 200: {
784
+ description: "Paths grouped by corpus",
785
+ content: {
786
+ "application/json": {
787
+ schema: resolver4(Query.PathsResults)
788
+ }
789
+ }
790
+ },
791
+ 404: {
792
+ description: "Query not found",
793
+ content: {
794
+ "application/json": {
795
+ schema: resolver4(Error5.Info)
796
+ }
797
+ }
798
+ }
799
+ }
800
+ }), validator4("query", Query.paths.schema.omit({ id: true })), async (c) => {
801
+ const id = c.req.param("id");
802
+ const query = c.req.valid("query");
803
+ try {
804
+ const result = Query.paths({
805
+ id: Query.Id.parse(id),
806
+ ...query
807
+ });
808
+ return c.json(result);
809
+ } catch (error) {
810
+ return c.json(Error5.from(error), 404);
811
+ }
812
+ }));
813
+
814
+ // src/routes/commit.ts
815
+ import { Hono as Hono5 } from "hono";
816
+ import { describeRoute as describeRoute5, resolver as resolver5, validator as validator5 } from "hono-openapi";
817
+ import { Commit } from "@spader/spall-core";
818
+ var CommitRoutes = lazy(() => new Hono5().post("/", describeRoute5({
819
+ summary: "Commit staged events",
820
+ description: "Move all rows from staging to committed.",
821
+ operationId: "commit.run",
822
+ responses: {
823
+ 200: {
824
+ description: "Commit result",
825
+ content: {
826
+ "application/json": {
827
+ schema: resolver5(Commit.Result)
828
+ }
829
+ }
830
+ }
831
+ }
832
+ }), validator5("json", Commit.run.schema), async (c) => {
833
+ const body = c.req.valid("json");
834
+ const result = Commit.run(body);
835
+ return c.json(result);
836
+ }));
837
+
838
+ // src/routes/sse.ts
839
+ import { Hono as Hono6 } from "hono";
840
+ import { describeRoute as describeRoute6, resolver as resolver6, validator as validator6 } from "hono-openapi";
841
+
842
+ // src/sse.ts
843
+ import { streamSSE } from "hono/streaming";
844
+ import { Bus, Context, Error as Error6, Store } from "@spader/spall-core";
845
+ var Sse;
846
+ ((Sse) => {
847
+ function stream(context, handler, input) {
848
+ return streamSSE(context, async (stream2) => {
849
+ Server.Sse.track();
850
+ const write = async (event) => {
851
+ if (stream2.aborted)
852
+ return;
853
+ await stream2.writeSSE({ data: JSON.stringify(event) });
854
+ };
855
+ let unsubscribe = Bus.subscribe(write);
856
+ const [result, ctx] = Context.run(() => handler(input));
857
+ stream2.onAbort(() => {
858
+ ctx.aborted = true;
859
+ unsubscribe();
860
+ unsubscribe = () => false;
861
+ });
862
+ try {
863
+ await result;
864
+ } catch (error) {
865
+ if (!(error instanceof Store.CancelledError)) {
866
+ await write({ tag: "error", error: Error6.from(error) });
867
+ }
868
+ } finally {
869
+ unsubscribe();
870
+ Server.Sse.untrack();
871
+ }
872
+ });
873
+ }
874
+ Sse.stream = stream;
875
+ function subscribe(context) {
876
+ return streamSSE(context, async (stream2) => {
877
+ Server.Sse.track();
878
+ const write = async (event) => {
879
+ await stream2.writeSSE({ data: JSON.stringify(event) });
880
+ };
881
+ await write({ tag: "sse.connected" });
882
+ const unsubscribe = Bus.subscribe(write);
883
+ await new Promise((resolve) => {
884
+ if (stream2.aborted)
885
+ return resolve();
886
+ stream2.onAbort(resolve);
887
+ });
888
+ unsubscribe();
889
+ Server.Sse.untrack();
890
+ });
891
+ }
892
+ Sse.subscribe = subscribe;
893
+ })(Sse ||= {});
894
+
895
+ // src/routes/sse.ts
896
+ import { Corpus as Corpus2, Note as Note4, EventUnion as EventUnion2 } from "@spader/spall-core";
897
+ var SseRoutes = lazy(() => new Hono6().post("/corpus/sync", describeRoute6({
898
+ summary: "Index a directory (SSE)",
899
+ description: "Scan a directory and embed all matching notes. Streams progress events.",
900
+ operationId: "sse.note.sync",
901
+ responses: {
902
+ 200: {
903
+ description: "Event stream",
904
+ content: {
905
+ "text/event-stream": {
906
+ schema: resolver6(EventUnion2)
907
+ }
908
+ }
909
+ }
910
+ }
911
+ }), validator6("json", Note4.sync.schema), async (context) => {
912
+ const body = context.req.valid("json");
913
+ return Sse.stream(context, Note4.sync, body);
914
+ }).post("/corpus/note", describeRoute6({
915
+ summary: "Add a note (SSE)",
916
+ description: "Add a note to a corpus and embed it. Streams progress events.",
917
+ operationId: "sse.note.add",
918
+ responses: {
919
+ 200: {
920
+ description: "Event stream",
921
+ content: {
922
+ "text/event-stream": {
923
+ schema: resolver6(EventUnion2)
924
+ }
925
+ }
926
+ }
927
+ }
928
+ }), validator6("json", Note4.add.schema), async (context) => {
929
+ const body = context.req.valid("json");
930
+ return Sse.stream(context, Note4.add, body);
931
+ }).put("/corpus/:id/note/:path{.+}", describeRoute6({
932
+ summary: "Upsert a note (SSE)",
933
+ description: "Create or update a note by path. Streams progress events.",
934
+ operationId: "sse.note.upsert",
935
+ responses: {
936
+ 200: {
937
+ description: "Event stream",
938
+ content: {
939
+ "text/event-stream": {
940
+ schema: resolver6(EventUnion2)
941
+ }
942
+ }
943
+ }
944
+ }
945
+ }), validator6("json", Note4.upsert.schema.omit({ corpus: true, path: true })), async (context) => {
946
+ const id = context.req.param("id");
947
+ const path = context.req.param("path");
948
+ const body = context.req.valid("json");
949
+ return Sse.stream(context, Note4.upsert, {
950
+ corpus: Corpus2.Id.parse(id),
951
+ path,
952
+ ...body
953
+ });
954
+ }).put("/note/:id", describeRoute6({
955
+ summary: "Update a note (SSE)",
956
+ description: "Update a note's content by ID. Re-embeds the content. Streams progress events.",
957
+ operationId: "sse.note.update",
958
+ responses: {
959
+ 200: {
960
+ description: "Event stream",
961
+ content: {
962
+ "text/event-stream": {
963
+ schema: resolver6(EventUnion2)
964
+ }
965
+ }
966
+ }
967
+ }
968
+ }), validator6("json", Note4.update.schema.omit({ id: true })), async (context) => {
969
+ const id = context.req.param("id");
970
+ const body = context.req.valid("json");
971
+ return Sse.stream(context, Note4.update, {
972
+ id: Note4.Id.parse(id),
973
+ ...body
974
+ });
975
+ }));
976
+
977
+ // src/app.ts
978
+ import { EventUnion as EventUnion3 } from "@spader/spall-core";
979
+ var App;
980
+ ((App) => {
981
+ const app = new Hono7;
982
+ let loaded = false;
983
+ function ensure() {
984
+ if (loaded)
985
+ return;
986
+ loaded = true;
987
+ app.use(async (_, next) => {
988
+ Server.increment();
989
+ try {
990
+ await next();
991
+ } finally {
992
+ Server.decrement();
993
+ }
994
+ }).use(logger()).use(logger(ServerLog.appLog)).route("/workspace", WorkspaceRoutes()).route("/corpus", CorpusRoutes()).route("/note", NoteRoutes()).route("/query", QueryRoutes()).route("/commit", CommitRoutes()).route("/sse", SseRoutes()).get("/health", describeRoute7({
995
+ summary: "Health check",
996
+ description: "Check if the server is running",
997
+ operationId: "health",
998
+ responses: {
999
+ 200: {
1000
+ description: "Server is healthy",
1001
+ content: {
1002
+ "text/plain": {
1003
+ schema: resolver7(z.string())
1004
+ }
1005
+ }
1006
+ }
1007
+ }
1008
+ }), (c) => {
1009
+ return c.text("ok");
1010
+ }).get("/events", describeRoute7({
1011
+ summary: "Event stream",
1012
+ description: "Subscribe to all server events via SSE",
1013
+ operationId: "events",
1014
+ responses: {
1015
+ 200: {
1016
+ description: "Event stream",
1017
+ content: {
1018
+ "text/event-stream": {
1019
+ schema: resolver7(EventUnion3)
1020
+ }
1021
+ }
1022
+ }
1023
+ }
1024
+ }), (c) => {
1025
+ return Sse.subscribe(c);
1026
+ });
1027
+ app.post("/shutdown", describeRoute7({
1028
+ summary: "Shutdown server",
1029
+ description: "Request the server to stop.",
1030
+ operationId: "server.shutdown",
1031
+ responses: {
1032
+ 200: {
1033
+ description: "Shutdown acknowledged",
1034
+ content: {
1035
+ "application/json": {
1036
+ schema: resolver7(z.object({ ok: z.literal(true) }))
1037
+ }
1038
+ }
1039
+ }
1040
+ }
1041
+ }), async (c) => {
1042
+ setTimeout(() => {
1043
+ try {
1044
+ process.kill(process.pid, "SIGTERM");
1045
+ } catch {}
1046
+ }, 0);
1047
+ return c.json({ ok: true });
1048
+ });
1049
+ return app;
1050
+ }
1051
+ App.ensure = ensure;
1052
+ function get() {
1053
+ ensure();
1054
+ return app;
1055
+ }
1056
+ App.get = get;
1057
+ async function spec() {
1058
+ return generateSpecs(App.get(), {
1059
+ documentation: {
1060
+ info: {
1061
+ title: "spall",
1062
+ version: "0.0.1",
1063
+ description: "Local semantic note store with embeddings"
1064
+ },
1065
+ openapi: "3.1.1"
1066
+ }
1067
+ });
1068
+ }
1069
+ App.spec = spec;
1070
+ })(App ||= {});
1071
+
1072
+ // src/lock.ts
1073
+ import { mkdirSync as mkdirSync2, existsSync, readFileSync, writeFileSync, rmSync } from "fs";
1074
+ import { join as join2 } from "path";
1075
+ import { Config as Config2 } from "@spader/spall-core/config";
1076
+ function debugEnabled() {
1077
+ const value = process.env.SPALL_DEBUG;
1078
+ return value === "1" || value === "true";
1079
+ }
1080
+ function debug(message) {
1081
+ if (debugEnabled()) {
1082
+ console.error(`[spall:debug] ${message}`);
1083
+ }
1084
+ }
1085
+ var Cache;
1086
+ ((Cache) => {
1087
+ function ensure() {
1088
+ const dir = Config2.get().dirs.data;
1089
+ if (!existsSync(dir)) {
1090
+ mkdirSync2(dir, { recursive: true });
1091
+ }
1092
+ }
1093
+ Cache.ensure = ensure;
1094
+ })(Cache ||= {});
1095
+ var Lock;
1096
+ ((Lock) => {
1097
+ function path() {
1098
+ return join2(Config2.get().dirs.data, "server.lock");
1099
+ }
1100
+ Lock.path = path;
1101
+ function read() {
1102
+ try {
1103
+ const content = readFileSync(path(), "utf-8");
1104
+ return JSON.parse(content);
1105
+ } catch {
1106
+ return null;
1107
+ }
1108
+ }
1109
+ Lock.read = read;
1110
+ function create() {
1111
+ Cache.ensure();
1112
+ try {
1113
+ writeFileSync(path(), JSON.stringify({ pid: process.pid, port: null }), {
1114
+ flag: "wx"
1115
+ });
1116
+ return true;
1117
+ } catch {
1118
+ return false;
1119
+ }
1120
+ }
1121
+ Lock.create = create;
1122
+ function update(port) {
1123
+ Cache.ensure();
1124
+ writeFileSync(path(), JSON.stringify({ pid: process.pid, port }));
1125
+ }
1126
+ Lock.update = update;
1127
+ function takeover() {
1128
+ Cache.ensure();
1129
+ writeFileSync(path(), JSON.stringify({ pid: process.pid, port: null }));
1130
+ }
1131
+ Lock.takeover = takeover;
1132
+ function remove() {
1133
+ rmSync(path(), { force: true });
1134
+ }
1135
+ Lock.remove = remove;
1136
+ })(Lock ||= {});
1137
+ function isProcessAlive(pid) {
1138
+ try {
1139
+ process.kill(pid, 0);
1140
+ return true;
1141
+ } catch {
1142
+ return false;
1143
+ }
1144
+ }
1145
+ async function checkHealth(port) {
1146
+ try {
1147
+ const response = await fetch(`http://127.0.0.1:${port}/health`);
1148
+ return response.ok;
1149
+ } catch {
1150
+ return false;
1151
+ }
1152
+ }
1153
+ var Role = {
1154
+ Leader: "leader",
1155
+ Follower: "follower"
1156
+ };
1157
+ async function acquire() {
1158
+ while (true) {
1159
+ if (Lock.create()) {
1160
+ debug(`Acquired startup lock as leader pid=${process.pid}`);
1161
+ return { role: Role.Leader };
1162
+ }
1163
+ const lock = Lock.read();
1164
+ if (!lock) {
1165
+ debug("Startup lock disappeared before it could be read; retrying");
1166
+ continue;
1167
+ }
1168
+ if (lock.port !== null) {
1169
+ if (await checkHealth(lock.port)) {
1170
+ debug(`Following healthy server pid=${lock.pid} port=${lock.port}`);
1171
+ return { role: Role.Follower, url: `http://127.0.0.1:${lock.port}` };
1172
+ }
1173
+ debug(`Removing stale unhealthy lock pid=${lock.pid} port=${lock.port}`);
1174
+ Lock.remove();
1175
+ continue;
1176
+ }
1177
+ if (!isProcessAlive(lock.pid)) {
1178
+ debug(`Removing stale startup lock pid=${lock.pid}`);
1179
+ Lock.remove();
1180
+ continue;
1181
+ }
1182
+ debug(`Waiting for leader pid=${lock.pid} to publish server port`);
1183
+ await Bun.sleep(50);
1184
+ }
1185
+ }
1186
+ async function ensure() {
1187
+ const result = await acquire();
1188
+ if (result.role === Role.Follower) {
1189
+ debug(`ensure returning follower url ${result.url}`);
1190
+ return result.url;
1191
+ }
1192
+ const script = join2(import.meta.dir, "serve.ts");
1193
+ debug(`ensure spawning local server from ${script}`);
1194
+ Bun.spawn([process.execPath, script], {
1195
+ stdin: "ignore",
1196
+ stdout: "ignore",
1197
+ stderr: "ignore",
1198
+ env: {
1199
+ ...process.env,
1200
+ SPALL_CACHE_DIR: Config2.get().dirs.cache
1201
+ }
1202
+ }).unref();
1203
+ for (let i = 0;i < 40; i++) {
1204
+ await Bun.sleep(50);
1205
+ const lock = Lock.read();
1206
+ if (lock && lock.port !== null) {
1207
+ debug(`ensure observed server port ${lock.port}`);
1208
+ return `http://127.0.0.1:${lock.port}`;
1209
+ }
1210
+ }
1211
+ debug("ensure timed out waiting for local server port");
1212
+ throw new Error("Claimed leader role, but timed out waiting for server to start");
1213
+ }
1214
+
1215
+ // src/server.ts
1216
+ import { Store as Store2 } from "@spader/spall-core";
1217
+ function formatBytes(bytes) {
1218
+ if (bytes < 1024)
1219
+ return `${bytes} B`;
1220
+ if (bytes < 1024 * 1024)
1221
+ return `${(bytes / 1024).toFixed(1)} KB`;
1222
+ if (bytes < 1024 * 1024 * 1024)
1223
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
1224
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
1225
+ }
1226
+ function parseBooleanEnv(value) {
1227
+ if (!value)
1228
+ return;
1229
+ if (value === "1" || value === "true")
1230
+ return true;
1231
+ if (value === "0" || value === "false")
1232
+ return false;
1233
+ return;
1234
+ }
1235
+ function parseNumberEnv(value) {
1236
+ if (!value)
1237
+ return;
1238
+ const parsed = Number(value);
1239
+ return Number.isFinite(parsed) ? parsed : undefined;
1240
+ }
1241
+ var Server;
1242
+ ((Server) => {
1243
+ let server = null;
1244
+ let persist = false;
1245
+ let activeRequests = 0;
1246
+ let timer;
1247
+ let idleTimeoutMs = 1000;
1248
+ let resolved = null;
1249
+ let unsubscribeBus = null;
1250
+ let processHandlersInstalled = false;
1251
+ function installProcessHandlers() {
1252
+ if (processHandlersInstalled)
1253
+ return;
1254
+ processHandlersInstalled = true;
1255
+ process.once("SIGINT", () => {
1256
+ consola.info(`Received ${pc.gray("SIGINT")}`);
1257
+ stop();
1258
+ });
1259
+ process.once("SIGTERM", () => {
1260
+ consola.info(`Received ${pc.gray("SIGTERM")}`);
1261
+ stop();
1262
+ });
1263
+ process.on("uncaughtException", (err) => {
1264
+ ServerLog.error(err);
1265
+ consola.error("Uncaught exception:", err);
1266
+ });
1267
+ process.on("unhandledRejection", (err) => {
1268
+ ServerLog.error(err);
1269
+ consola.error("Unhandled rejection:", err);
1270
+ });
1271
+ }
1272
+ let Sse2;
1273
+ ((Sse) => {
1274
+ let count = 0;
1275
+ function active() {
1276
+ return count > 0;
1277
+ }
1278
+ Sse.active = active;
1279
+ function track() {
1280
+ count++;
1281
+ clearTimeout(timer);
1282
+ }
1283
+ Sse.track = track;
1284
+ function untrack() {
1285
+ count--;
1286
+ clearTimeout(timer);
1287
+ }
1288
+ Sse.untrack = untrack;
1289
+ function reset() {
1290
+ count = 0;
1291
+ }
1292
+ Sse.reset = reset;
1293
+ })(Sse2 = Server.Sse ||= {});
1294
+ function increment() {
1295
+ activeRequests++;
1296
+ clearTimeout(timer);
1297
+ }
1298
+ Server.increment = increment;
1299
+ function decrement() {
1300
+ activeRequests--;
1301
+ resetShutdownTimer();
1302
+ }
1303
+ Server.decrement = decrement;
1304
+ function resetShutdownTimer() {
1305
+ if (persist)
1306
+ return;
1307
+ if (activeRequests > 0 || Sse2.active())
1308
+ return;
1309
+ timer = setTimeout(() => {
1310
+ if (activeRequests === 0 && !Sse2.active()) {
1311
+ stop();
1312
+ }
1313
+ }, idleTimeoutMs);
1314
+ }
1315
+ function render(event) {
1316
+ switch (event.tag) {
1317
+ case "model.download":
1318
+ return `Downloading ${pc.cyan(event.info.name)}`;
1319
+ case "model.downloaded":
1320
+ return `Finished downloading ${pc.cyanBright(event.info.name)}`;
1321
+ case "model.progress": {
1322
+ const percent = event.downloaded / event.total * 100;
1323
+ const percentStr = percent.toFixed(0).padStart(3);
1324
+ return `${pc.cyan(event.info.name)} ${pc.bold(percentStr + "%")}`;
1325
+ }
1326
+ case "model.load":
1327
+ return `Loaded ${pc.cyanBright(event.info.name)}`;
1328
+ case "model.failed":
1329
+ return `${pc.red("Failed to load model:")} ${event.error}`;
1330
+ case "store.create":
1331
+ return `Creating database at ${pc.cyanBright(event.path)}`;
1332
+ case "store.created":
1333
+ return `Created database at ${pc.cyanBright(event.path)}`;
1334
+ case "note.created":
1335
+ return `${pc.cyanBright(event.info.path)} (${formatBytes(event.info.content.length)}, hash: ${event.info.contentHash})`;
1336
+ case "note.updated":
1337
+ return `${pc.cyanBright(event.info.path)} (${formatBytes(event.info.content.length)}, hash: ${event.info.contentHash})`;
1338
+ case "embed.cancel":
1339
+ return "Cancelled embedding";
1340
+ }
1341
+ return event.tag;
1342
+ }
1343
+ Server.render = render;
1344
+ async function start(request) {
1345
+ const env = {
1346
+ persist: parseBooleanEnv(process.env.SPALL_SERVER_PERSIST),
1347
+ force: parseBooleanEnv(process.env.SPALL_SERVER_FORCE),
1348
+ idleTimeoutMs: parseNumberEnv(process.env.SPALL_SERVER_IDLE_TIMEOUT_MS)
1349
+ };
1350
+ const config = {
1351
+ idleTimeoutMs: Config3.get().server.idleTimeout * 1000
1352
+ };
1353
+ const options = {
1354
+ persist: request?.persist ?? env.persist ?? false,
1355
+ idleTimeoutMs: request?.idleTimeoutMs ?? env.idleTimeoutMs ?? config.idleTimeoutMs ?? 1000,
1356
+ force: request?.force ?? env.force ?? false
1357
+ };
1358
+ Store2.ensure();
1359
+ persist = options.persist;
1360
+ idleTimeoutMs = options.idleTimeoutMs;
1361
+ const existing = Lock.read();
1362
+ if (existing && existing.port !== null && await checkHealth(existing.port)) {
1363
+ if (options.force) {
1364
+ const pid = `${pc.gray("pid")} ${pc.yellow(existing.pid)}`;
1365
+ const port2 = `${pc.gray("port")} ${pc.cyan(existing.port)}`;
1366
+ consola.info(`Killing existing server (${pid}, ${port2})`);
1367
+ Lock.takeover();
1368
+ try {
1369
+ process.kill(existing.pid, "SIGTERM");
1370
+ for (let i = 0;i < 40; i++) {
1371
+ if (!isProcessAlive(existing.pid))
1372
+ break;
1373
+ await Bun.sleep(50);
1374
+ }
1375
+ } catch {}
1376
+ } else {
1377
+ throw new Error(`Server is already running at port ${existing.port}`);
1378
+ }
1379
+ }
1380
+ server = Bun.serve({
1381
+ port: 0,
1382
+ fetch: App.get().fetch,
1383
+ idleTimeout: 0
1384
+ });
1385
+ const port = server.port;
1386
+ if (!port) {
1387
+ server.stop();
1388
+ throw new Error("Failed to start server");
1389
+ }
1390
+ consola.log(`Listening on port ${pc.cyanBright(String(port))}`);
1391
+ Lock.update(port);
1392
+ ServerLog.init(port);
1393
+ installProcessHandlers();
1394
+ resetShutdownTimer();
1395
+ const stopped = new Promise((resolve) => {
1396
+ resolved = resolve;
1397
+ });
1398
+ unsubscribeBus?.();
1399
+ unsubscribeBus = Bus2.subscribe((event) => {
1400
+ consola.info(`${pc.gray(event.tag)} ${render(event)}`);
1401
+ ServerLog.event(event);
1402
+ });
1403
+ Model.load().catch(() => {});
1404
+ return { port, stopped };
1405
+ }
1406
+ Server.start = start;
1407
+ function stop() {
1408
+ if (!server)
1409
+ return;
1410
+ consola.info("Stopping server");
1411
+ server.stop();
1412
+ server = null;
1413
+ Sse2.reset();
1414
+ unsubscribeBus?.();
1415
+ unsubscribeBus = null;
1416
+ const lock = Lock.read();
1417
+ if (lock && lock.pid === process.pid) {
1418
+ Lock.remove();
1419
+ }
1420
+ resolved?.();
1421
+ resolved = null;
1422
+ }
1423
+ Server.stop = stop;
1424
+ })(Server ||= {});
1425
+ export {
1426
+ isProcessAlive,
1427
+ ensure,
1428
+ checkHealth,
1429
+ Server,
1430
+ Lock
1431
+ };
1432
+
1433
+ //# debugId=39A5F6D19C8A6DCE64756E2164756E21