trellis 3.2.2 → 3.2.4

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 (210) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +4 -0
  3. package/dist/better-sqlite-backend-CDYOAJDF.js +209 -0
  4. package/dist/boot-middleware-LBJX4N2S.js +9 -0
  5. package/dist/boot-middleware-PATBLD52.js +9 -0
  6. package/dist/bridge-G5DPW6TY.js +2361 -0
  7. package/dist/bridge-JSSPQPRH.js +2389 -0
  8. package/dist/bridge-LNXE4HAW.js +2389 -0
  9. package/dist/bridge-OAAXJWSA.js +2389 -0
  10. package/dist/bridge-SFS63RHC.js +2367 -0
  11. package/dist/bridge-U5TOUBVM.js +2389 -0
  12. package/dist/browser/index.js +9 -9
  13. package/dist/{chunk-KSU2GW22.js → chunk-276W52FK.js} +8 -0
  14. package/dist/{chunk-KFQGP6VL.js → chunk-2ESYSVXG.js} +15 -0
  15. package/dist/{chunk-L5N5PR2S.js → chunk-2WW2X2BR.js} +313 -77
  16. package/dist/chunk-3XCOAP6G.js +48 -0
  17. package/dist/chunk-53PDCTJ3.js +1856 -0
  18. package/dist/{chunk-N6MYZT4O.js → chunk-547FZFKO.js} +1 -1
  19. package/dist/{chunk-H6JB3PZ3.js → chunk-5KSGGKET.js} +1 -1
  20. package/dist/{chunk-J2TXUFCZ.js → chunk-6RWGFC3N.js} +134 -20
  21. package/dist/{chunk-QB5ISE47.js → chunk-7WVOPXJV.js} +3 -3
  22. package/dist/chunk-CMSFD6OV.js +11801 -0
  23. package/dist/{chunk-RSWUFTO2.js → chunk-CPUYCCLT.js} +2 -2
  24. package/dist/{chunk-4HYPLFJD.js → chunk-FA5TFVA5.js} +1 -1
  25. package/dist/{chunk-4XIVMVHC.js → chunk-G3XIHPSQ.js} +1 -1
  26. package/dist/{chunk-JHHEXEDM.js → chunk-GCQF75T4.js} +3 -3
  27. package/dist/{chunk-FKQO5A3H.js → chunk-GHG4H3AS.js} +2 -2
  28. package/dist/{chunk-GLM4HGN4.js → chunk-GRWQPKYK.js} +1 -1
  29. package/dist/{chunk-PZ4XYZ4J.js → chunk-GXA73CNC.js} +33 -8
  30. package/dist/{chunk-6GEZ6DN5.js → chunk-H6VTC5SS.js} +3 -3
  31. package/dist/{chunk-S3XLFZ27.js → chunk-IHHSOBJS.js} +1 -1
  32. package/dist/chunk-IJNC25UD.js +2243 -0
  33. package/dist/{chunk-VDAKEOML.js → chunk-J6OUIION.js} +1 -1
  34. package/dist/chunk-JAVAYMMS.js +6 -0
  35. package/dist/{chunk-S6GBJ2ZB.js → chunk-JCQQFLO5.js} +1 -1
  36. package/dist/{chunk-FWRS4CSC.js → chunk-KQG6ZYXP.js} +3 -3
  37. package/dist/chunk-KXAISKZT.js +119 -0
  38. package/dist/chunk-N3R74ZSR.js +7949 -0
  39. package/dist/{chunk-GU374KWZ.js → chunk-NLFRRGX6.js} +3 -3
  40. package/dist/{chunk-XMQ7G77X.js → chunk-OB4CMMX6.js} +1 -1
  41. package/dist/chunk-OKNASCZY.js +182 -0
  42. package/dist/chunk-ONOPPX5E.js +394 -0
  43. package/dist/chunk-QMSU2RAH.js +98 -0
  44. package/dist/{chunk-TCKXSOBP.js → chunk-RARKFVWU.js} +8 -1
  45. package/dist/{chunk-2W3MHTMG.js → chunk-SJWVDS5M.js} +835 -127
  46. package/dist/{chunk-SPSPV5BC.js → chunk-SZ3VAB5P.js} +159 -2
  47. package/dist/chunk-V2ASD6RQ.js +147 -0
  48. package/dist/{chunk-KQ4A2D2P.js → chunk-V4YCJDYL.js} +58 -38
  49. package/dist/{chunk-LNUIGRDZ.js → chunk-VWKLKLYB.js} +1 -1
  50. package/dist/chunk-W5PADCDF.js +1856 -0
  51. package/dist/{chunk-MLC5BUYO.js → chunk-WMERMSWI.js} +1 -1
  52. package/dist/{chunk-IZX2PLIB.js → chunk-WXAURJUD.js} +835 -127
  53. package/dist/chunk-YC5I32PS.js +147 -0
  54. package/dist/{chunk-VBYUTRXX.js → chunk-YKVB4LUQ.js} +3 -3
  55. package/dist/{chunk-7ZFRVCUE.js → chunk-YPT6XMS4.js} +48 -64
  56. package/dist/cli/deploy-cli.d.ts.map +1 -1
  57. package/dist/{deploy-cli-C35HTITO.js → cli/deploy-cli.js} +45 -6
  58. package/dist/cli/gateway-deploy-cli.d.ts +19 -0
  59. package/dist/cli/gateway-deploy-cli.d.ts.map +1 -0
  60. package/dist/cli/index.d.ts.map +1 -1
  61. package/dist/cli/index.js +1363 -884
  62. package/dist/cli/lane.d.ts.map +1 -1
  63. package/dist/cli/protocol.d.ts +6 -0
  64. package/dist/cli/protocol.d.ts.map +1 -0
  65. package/dist/client/index.browser.js +2 -2
  66. package/dist/client/index.js +11 -11
  67. package/dist/client/sdk.browser.d.ts +28 -1
  68. package/dist/client/sdk.browser.d.ts.map +1 -1
  69. package/dist/client/sdk.browser.js +2 -2
  70. package/dist/client/sdk.js +2 -2
  71. package/dist/cms/index.js +1 -1
  72. package/dist/config-KMY6RRK3.js +19 -0
  73. package/dist/core/index.js +17 -17
  74. package/dist/core/kernel/boot-middleware.d.ts +1 -1
  75. package/dist/core/kernel/boot-middleware.d.ts.map +1 -1
  76. package/dist/core/kernel/schema-middleware.d.ts +2 -1
  77. package/dist/core/kernel/schema-middleware.d.ts.map +1 -1
  78. package/dist/core/kernel/trellis-kernel.d.ts +10 -10
  79. package/dist/core/kernel/trellis-kernel.d.ts.map +1 -1
  80. package/dist/core/persist/factory.js +2 -2
  81. package/dist/core/persist/sqljs-backend.js +2 -2
  82. package/dist/db/index.js +32 -27
  83. package/dist/decisions/index.js +4 -4
  84. package/dist/embeddings/index.js +2 -2
  85. package/dist/engine.d.ts +24 -6
  86. package/dist/engine.d.ts.map +1 -1
  87. package/dist/gateway-deploy-cli-4TU4V3QI.js +312 -0
  88. package/dist/gateway-deploy-cli-A4ISTDHJ.js +298 -0
  89. package/dist/gateway-deploy-cli-D3XTKJQJ.js +312 -0
  90. package/dist/gateway-deploy-cli-ECV3OQCN.js +305 -0
  91. package/dist/gateway-deploy-cli-JUHKVIJE.js +296 -0
  92. package/dist/gateway-deploy-cli-NSDW2JLT.js +310 -0
  93. package/dist/gateway-serve-CM5EAZ52.js +113 -0
  94. package/dist/import-AJLYHFIA.js +10 -0
  95. package/dist/index.js +11 -11
  96. package/dist/launch-explorer-FVX6ZABW.js +95 -0
  97. package/dist/links/index.js +2 -2
  98. package/dist/mcp/bridge.d.ts +45 -0
  99. package/dist/mcp/bridge.d.ts.map +1 -0
  100. package/dist/mcp/discovery.d.ts +15 -0
  101. package/dist/mcp/discovery.d.ts.map +1 -0
  102. package/dist/mcp/gateway-config.d.ts +20 -0
  103. package/dist/mcp/gateway-config.d.ts.map +1 -0
  104. package/dist/mcp/gateway-serve.d.ts +19 -0
  105. package/dist/mcp/gateway-serve.d.ts.map +1 -0
  106. package/dist/mcp/gateway-serve.js +119 -0
  107. package/dist/mcp/graph-summary.d.ts +47 -0
  108. package/dist/mcp/graph-summary.d.ts.map +1 -0
  109. package/dist/mcp/room-audit.d.ts +14 -0
  110. package/dist/mcp/room-audit.d.ts.map +1 -0
  111. package/dist/mcp/room-helpers.d.ts +43 -0
  112. package/dist/mcp/room-helpers.d.ts.map +1 -0
  113. package/dist/mcp/room-registry.d.ts +32 -0
  114. package/dist/mcp/room-registry.d.ts.map +1 -0
  115. package/dist/mcp/room.d.ts +28 -0
  116. package/dist/mcp/room.d.ts.map +1 -0
  117. package/dist/plugins/agent-memory/index.js +1 -1
  118. package/dist/plugins/idea-garden/index.js +1 -1
  119. package/dist/plugins/plan-approval/index.js +1 -1
  120. package/dist/plugins/proactive-watcher/index.js +1 -1
  121. package/dist/protocol/envelope.d.ts +30 -0
  122. package/dist/protocol/envelope.d.ts.map +1 -0
  123. package/dist/protocol/index.d.ts +3 -0
  124. package/dist/protocol/index.d.ts.map +1 -0
  125. package/dist/protocol/whereami.d.ts +33 -0
  126. package/dist/protocol/whereami.d.ts.map +1 -0
  127. package/dist/query-KHDDIR5G.js +31 -0
  128. package/dist/react/index.js +3 -3
  129. package/dist/react/realtime.js +1 -1
  130. package/dist/react/schema-hooks.js +6 -6
  131. package/dist/realtime/index.js +3 -3
  132. package/dist/realtime/relay-server.d.ts.map +1 -1
  133. package/dist/realtime/room.d.ts.map +1 -1
  134. package/dist/realtime.bundle.js +2 -0
  135. package/dist/relay-server-BT6DCJ7F.js +12 -0
  136. package/dist/relay-server-MPQVGNQU.js +12 -0
  137. package/dist/relay-server-PAPW2EWC.js +12 -0
  138. package/dist/remote-manager-6ERQUBSL.js +224 -0
  139. package/dist/remote-manager-G665WWYY.js +224 -0
  140. package/dist/remote-manager-HJTEZ4OF.js +224 -0
  141. package/dist/remote-manager-NYP2Y5UR.js +224 -0
  142. package/dist/remote-manager-WGLCAMMC.js +224 -0
  143. package/dist/scaffold/write.d.ts.map +1 -1
  144. package/dist/schema/index.js +1 -1
  145. package/dist/server/cors.d.ts +13 -0
  146. package/dist/server/cors.d.ts.map +1 -0
  147. package/dist/server/deploy-gateway.d.ts +27 -0
  148. package/dist/server/deploy-gateway.d.ts.map +1 -0
  149. package/dist/server/deploy.d.ts +1 -1
  150. package/dist/server/deploy.d.ts.map +1 -1
  151. package/dist/server/deploy.js +10 -0
  152. package/dist/server/discovery-mcp-gateway.d.ts +13 -0
  153. package/dist/server/discovery-mcp-gateway.d.ts.map +1 -0
  154. package/dist/server/index.js +44 -37
  155. package/dist/server/mcp-gateway.d.ts +27 -0
  156. package/dist/server/mcp-gateway.d.ts.map +1 -0
  157. package/dist/server/mcp-oauth-metadata.d.ts +31 -0
  158. package/dist/server/mcp-oauth-metadata.d.ts.map +1 -0
  159. package/dist/server/node-adapter.d.ts +7 -0
  160. package/dist/server/node-adapter.d.ts.map +1 -1
  161. package/dist/server/node-adapter.js +2 -2
  162. package/dist/server/realtime.d.ts.map +1 -1
  163. package/dist/server/server.d.ts +8 -0
  164. package/dist/server/server.d.ts.map +1 -1
  165. package/dist/server/streamable-mcp-gateway.d.ts +12 -0
  166. package/dist/server/streamable-mcp-gateway.d.ts.map +1 -0
  167. package/dist/server/usage-meter.d.ts +11 -0
  168. package/dist/server/usage-meter.d.ts.map +1 -1
  169. package/dist/server-4VEZHXXS.js +23 -0
  170. package/dist/{server-ZVWGLLRF.js → server-556BMK4C.js} +1 -1
  171. package/dist/server-FQT2VYRE.js +23 -0
  172. package/dist/server-HGZE4ECC.js +23 -0
  173. package/dist/server-J4JKEAMH.js +23 -0
  174. package/dist/server-LXPM5TFR.js +23 -0
  175. package/dist/{server-MB3OPSPI.js → server-POB4NEUX.js} +2 -2
  176. package/dist/server-VJKAPGPG.js +23 -0
  177. package/dist/server-YHS3XIIG.js +23 -0
  178. package/dist/server-ZHTPWPXS.js +23 -0
  179. package/dist/sprites-NC6D7YZS.js +27 -0
  180. package/dist/svelte/index.js +3 -3
  181. package/dist/svelte/schema-hooks.js +4 -4
  182. package/dist/sync/index.js +4 -4
  183. package/dist/tenancy-2SZTP4UD.js +16 -0
  184. package/dist/tenancy-7MTSESMJ.js +16 -0
  185. package/dist/tenancy-U4E7ZEAG.js +16 -0
  186. package/dist/vcs/decompose.d.ts.map +1 -1
  187. package/dist/vcs/index.js +5 -5
  188. package/dist/vcs/lane-disk-materialize.d.ts +11 -0
  189. package/dist/vcs/lane-disk-materialize.d.ts.map +1 -0
  190. package/dist/vcs/lane-worktree.d.ts +21 -0
  191. package/dist/vcs/lane-worktree.d.ts.map +1 -0
  192. package/dist/vcs/store.d.ts +28 -0
  193. package/dist/vcs/store.d.ts.map +1 -0
  194. package/dist/vcs/types.d.ts +5 -0
  195. package/dist/vcs/types.d.ts.map +1 -1
  196. package/dist/vm-config-YZRJ3KUB.js +21 -0
  197. package/dist/vue/index.js +3 -3
  198. package/dist/vue/schema-hooks.js +4 -4
  199. package/package.json +4 -3
  200. package/dist/chunk-FF36CQHZ.js +0 -61
  201. package/dist/chunk-GFZCJ4EH.js +0 -108
  202. package/dist/chunk-KIJITUZB.js +0 -419
  203. package/dist/chunk-SGMDTWJJ.js +0 -149
  204. package/dist/chunk-UQISRW6T.js +0 -203
  205. package/dist/db/trellis.css +0 -1
  206. package/dist/deploy-LQ7GUGJ5.js +0 -9
  207. package/dist/deploy-YNVG5E4E.js +0 -9
  208. package/dist/deploy-cli-24BCHAXY.js +0 -67
  209. package/dist/sprites-RU3E4XQN.js +0 -15
  210. package/dist/tenancy-NBLLGCNJ.js +0 -14
@@ -1,61 +0,0 @@
1
- // src/server/sprites.ts
2
- import { execFile, spawn } from "child_process";
3
- import { promisify } from "util";
4
- var execFileAsync = promisify(execFile);
5
- async function runSpriteCmd(args) {
6
- try {
7
- const { stdout } = await execFileAsync("sprite", args);
8
- return stdout.trim();
9
- } catch (err) {
10
- throw new Error(
11
- `sprite ${args[0]} failed (exit ${err.code ?? "?"}): ${err.stderr ?? err.message}`
12
- );
13
- }
14
- }
15
- async function runSpriteCopy(localPath, spriteName, remotePath) {
16
- try {
17
- await execFileAsync("sprite", [
18
- "cp",
19
- localPath,
20
- `${spriteName}:${remotePath}`
21
- ]);
22
- } catch (err) {
23
- throw new Error(
24
- `sprite cp failed (exit ${err.code ?? "?"}): ${err.stderr ?? err.message}`
25
- );
26
- }
27
- }
28
- async function runSpriteInteractive(args) {
29
- return new Promise((resolve, reject) => {
30
- const proc = spawn("sprite", args, { stdio: "inherit" });
31
- proc.on("close", (code) => {
32
- if (code !== 0)
33
- reject(new Error(`sprite ${args[0]} failed (exit ${code})`));
34
- else resolve();
35
- });
36
- proc.on("error", reject);
37
- });
38
- }
39
- async function assertSpriteCli() {
40
- await runSpriteCmd(["--version"]).catch(() => {
41
- throw new Error(
42
- "`sprite` CLI not found. Install it from https://docs.sprites.dev and authenticate."
43
- );
44
- });
45
- }
46
- function resolveSprite(explicitName) {
47
- if (explicitName) {
48
- return explicitName;
49
- }
50
- throw new Error(
51
- "No sprite specified. Use --sprite <name> or set an active sprite with `trellis vm use <name>`"
52
- );
53
- }
54
-
55
- export {
56
- runSpriteCmd,
57
- runSpriteCopy,
58
- runSpriteInteractive,
59
- assertSpriteCli,
60
- resolveSprite
61
- };
@@ -1,108 +0,0 @@
1
- // src/realtime/relay-persistence.ts
2
- var DEFAULT_MAX_CHAT = 200;
3
- var DEFAULT_MAX_TEXT_OPS = 2e3;
4
- function chatKey(msg) {
5
- return msg.id ?? `${msg.from}:${msg.ts}`;
6
- }
7
- function tieKey(msg) {
8
- if (msg.t === "msg") return chatKey(msg);
9
- if (msg.t === "presence" || msg.t === "bye") return msg.from;
10
- return "";
11
- }
12
- function messageTs(msg) {
13
- if (msg.t === "presence" || msg.t === "bye" || msg.t === "msg") {
14
- return msg.ts;
15
- }
16
- return 0;
17
- }
18
- var RelayPersistence = class {
19
- maxChat;
20
- maxTextOps;
21
- presence = /* @__PURE__ */ new Map();
22
- /** Chat is a grow-only set keyed by {@link chatKey} — dedup on record. */
23
- chatLog = [];
24
- chatKeys = /* @__PURE__ */ new Set();
25
- textSnapshot = null;
26
- textOps = [];
27
- constructor(opts = {}) {
28
- this.maxChat = opts.maxChat ?? DEFAULT_MAX_CHAT;
29
- this.maxTextOps = opts.maxTextOps ?? DEFAULT_MAX_TEXT_OPS;
30
- }
31
- /** Record an inbound client message (skip `hello` / `replay`). */
32
- record(message) {
33
- if (message.v !== 1) return;
34
- switch (message.t) {
35
- case "hello":
36
- return;
37
- case "replay":
38
- return;
39
- case "presence":
40
- this.presence.set(message.from, message);
41
- return;
42
- case "bye":
43
- this.presence.delete(message.from);
44
- return;
45
- case "msg":
46
- this.recordBroadcast(message);
47
- return;
48
- }
49
- }
50
- /** Ordered messages to replay to a peer that just connected. */
51
- buildReplay() {
52
- const out = [
53
- ...this.presence.values(),
54
- ...this.chatLog
55
- ];
56
- if (this.textSnapshot) {
57
- out.push(this.textSnapshot);
58
- } else {
59
- out.push(...this.textOps);
60
- }
61
- out.sort((a, b) => {
62
- const dt = messageTs(a) - messageTs(b);
63
- if (dt !== 0) return dt;
64
- return tieKey(a).localeCompare(tieKey(b));
65
- });
66
- return out;
67
- }
68
- getPresenceCount() {
69
- return this.presence.size;
70
- }
71
- getChatCount() {
72
- return this.chatLog.length;
73
- }
74
- hasTextSnapshot() {
75
- return this.textSnapshot !== null;
76
- }
77
- recordBroadcast(message) {
78
- if (message.channel === "chat" && message.event === "message") {
79
- const key = chatKey(message);
80
- if (this.chatKeys.has(key)) return;
81
- this.chatKeys.add(key);
82
- this.chatLog.push(message);
83
- if (this.chatLog.length > this.maxChat) {
84
- const evicted = this.chatLog.splice(0, this.chatLog.length - this.maxChat);
85
- for (const m of evicted) this.chatKeys.delete(chatKey(m));
86
- }
87
- return;
88
- }
89
- if (message.channel === "text" && message.event === "state") {
90
- this.textSnapshot = message;
91
- this.textOps = [];
92
- return;
93
- }
94
- if (message.channel === "text" && message.event === "op") {
95
- if (this.textSnapshot) return;
96
- this.textOps.push(message);
97
- if (this.textOps.length > this.maxTextOps) {
98
- this.textOps.splice(0, this.textOps.length - this.maxTextOps);
99
- }
100
- }
101
- }
102
- };
103
-
104
- export {
105
- DEFAULT_MAX_CHAT,
106
- DEFAULT_MAX_TEXT_OPS,
107
- RelayPersistence
108
- };
@@ -1,419 +0,0 @@
1
- // src/client/sdk.ts
2
- function isRemote(opts) {
3
- return "url" in opts;
4
- }
5
- var TrellisDb = class _TrellisDb {
6
- opts;
7
- _pool = null;
8
- _poolPromise = null;
9
- _ws = null;
10
- /** In-flight connect — concurrent subscribe() shares one socket open. */
11
- _wsPromise = null;
12
- _subCallbacks = /* @__PURE__ */ new Map();
13
- _subOpts = /* @__PURE__ */ new Map();
14
- constructor(opts) {
15
- this.opts = opts;
16
- }
17
- /**
18
- * Create a TrellisDb instance from `.trellis-db.json` in the given directory.
19
- */
20
- static async fromConfig(dir = ".") {
21
- const { readConfig } = await import("./config-PFTP67TR.js");
22
- const config = readConfig(dir);
23
- if (!config)
24
- throw new Error(
25
- "No .trellis-db.json found. Run `trellis db init` first."
26
- );
27
- if (config.mode === "remote" && config.url) {
28
- return new _TrellisDb({ url: config.url, apiKey: config.apiKey });
29
- }
30
- if (config.dbPath) {
31
- return new _TrellisDb({ path: config.dbPath });
32
- }
33
- throw new Error("Invalid .trellis-db.json: missing url or dbPath.");
34
- }
35
- // -------------------------------------------------------------------------
36
- // CRUD
37
- // -------------------------------------------------------------------------
38
- /**
39
- * Create a new entity.
40
- * Returns the generated entity ID.
41
- */
42
- async create(type, attributes = {}, links) {
43
- if (isRemote(this.opts)) {
44
- const res = await this._fetch("POST", "/entities", {
45
- type,
46
- attributes,
47
- links
48
- });
49
- return res.id;
50
- }
51
- const pool = await this._getPool();
52
- const tenantId = this.opts.tenantId ?? null;
53
- const kernel = pool.get(tenantId);
54
- const entityId = `${type.toLowerCase()}:${crypto.randomUUID()}`;
55
- await kernel.createEntity(entityId, type, attributes, links);
56
- return entityId;
57
- }
58
- /**
59
- * Read an entity by ID.
60
- * Returns null if not found.
61
- */
62
- async read(id) {
63
- if (isRemote(this.opts)) {
64
- try {
65
- return await this._fetch(
66
- "GET",
67
- `/entities/${encodeURIComponent(id)}`
68
- );
69
- } catch (err) {
70
- if (err?.status === 404) return null;
71
- throw err;
72
- }
73
- }
74
- const pool = await this._getPool();
75
- const tenantId = this.opts.tenantId ?? null;
76
- const kernel = pool.get(tenantId);
77
- const entity = kernel.getEntity(id);
78
- if (!entity) return null;
79
- return entityToPlain(entity);
80
- }
81
- /**
82
- * Update an entity's attributes (partial update).
83
- */
84
- async update(id, attributes) {
85
- if (isRemote(this.opts)) {
86
- await this._fetch(
87
- "PUT",
88
- `/entities/${encodeURIComponent(id)}`,
89
- attributes
90
- );
91
- return;
92
- }
93
- const pool = await this._getPool();
94
- const tenantId = this.opts.tenantId ?? null;
95
- const kernel = pool.get(tenantId);
96
- await kernel.updateEntity(id, attributes);
97
- }
98
- /**
99
- * Delete an entity by ID.
100
- */
101
- async delete(id) {
102
- if (isRemote(this.opts)) {
103
- await this._fetch("DELETE", `/entities/${encodeURIComponent(id)}`);
104
- return;
105
- }
106
- const pool = await this._getPool();
107
- const tenantId = this.opts.tenantId ?? null;
108
- const kernel = pool.get(tenantId);
109
- await kernel.deleteEntity(id);
110
- }
111
- /**
112
- * List entities of a given type.
113
- */
114
- async list(type, opts = {}) {
115
- if (isRemote(this.opts)) {
116
- const params = new URLSearchParams();
117
- if (type) params.set("type", type);
118
- if (opts.limit) params.set("limit", String(opts.limit));
119
- if (opts.offset) params.set("offset", String(opts.offset));
120
- const qs = params.toString() ? `?${params}` : "";
121
- return await this._fetch("GET", `/entities${qs}`);
122
- }
123
- const pool = await this._getPool();
124
- const tenantId = this.opts.tenantId ?? null;
125
- const kernel = pool.get(tenantId);
126
- const entities = kernel.listEntities(type, opts.filters);
127
- const limit = opts.limit ?? 100;
128
- const offset = opts.offset ?? 0;
129
- const page = entities.slice(offset, offset + limit);
130
- return {
131
- data: page.map(entityToPlain),
132
- total: entities.length,
133
- limit,
134
- offset
135
- };
136
- }
137
- // -------------------------------------------------------------------------
138
- // Query
139
- // -------------------------------------------------------------------------
140
- /**
141
- * Run an EQL-S query string.
142
- */
143
- async query(eql) {
144
- if (isRemote(this.opts)) {
145
- return await this._fetch("POST", "/query", {
146
- query: eql
147
- });
148
- }
149
- const { parseSimple } = await import("./query-XYLTJYSA.js");
150
- const pool = await this._getPool();
151
- const tenantId = this.opts.tenantId ?? null;
152
- const kernel = pool.get(tenantId);
153
- const parsed = parseSimple(eql);
154
- return kernel.query(parsed);
155
- }
156
- // -------------------------------------------------------------------------
157
- // Schema registration
158
- // -------------------------------------------------------------------------
159
- /**
160
- * Register a user/system-tier ontology schema with the kernel.
161
- *
162
- * Accepts a {@link SchemaDefinition} or anything carrying one (e.g. a
163
- * `defineType` handle: `client.registerType(NavItem)`). Local mode calls
164
- * `kernel.createOntology` directly; remote mode POSTs to `/ontologies`.
165
- */
166
- async registerType(schema) {
167
- const def = "@id" in schema ? schema : schema.definition;
168
- if (isRemote(this.opts)) {
169
- try {
170
- await this._fetch("POST", "/ontologies", def);
171
- } catch (err) {
172
- if (err instanceof FetchError && err.status === 409) return;
173
- throw err;
174
- }
175
- return;
176
- }
177
- const pool = await this._getPool();
178
- const tenantId = this.opts.tenantId ?? null;
179
- const kernel = pool.get(tenantId);
180
- const exists = kernel.listOntologies().some((ont) => ont["@id"] === def["@id"]);
181
- if (exists) return;
182
- try {
183
- kernel.createOntology(def);
184
- } catch (err) {
185
- const msg = err instanceof Error ? err.message : String(err);
186
- if (msg.includes("already exists")) return;
187
- throw err;
188
- }
189
- }
190
- // -------------------------------------------------------------------------
191
- // File upload
192
- // -------------------------------------------------------------------------
193
- /**
194
- * Upload a file to the blob store.
195
- * Returns a content-addressed hash.
196
- */
197
- async upload(data, contentType = "application/octet-stream") {
198
- const raw = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
199
- const cleanBuf = raw.buffer.slice(
200
- raw.byteOffset,
201
- raw.byteOffset + raw.byteLength
202
- );
203
- const buffer = new Uint8Array(cleanBuf);
204
- if (isRemote(this.opts)) {
205
- const res = await fetch(`${this.opts.url}/upload`, {
206
- method: "POST",
207
- headers: {
208
- "Content-Type": contentType,
209
- ...this.opts.apiKey ? { Authorization: `Bearer ${this.opts.apiKey}` } : {}
210
- },
211
- body: cleanBuf
212
- });
213
- if (!res.ok) throw new FetchError(res.status, await res.text());
214
- return await res.json();
215
- }
216
- const hashBuf = await crypto.subtle.digest("SHA-256", buffer);
217
- const hash = `blob:${Array.from(new Uint8Array(hashBuf)).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
218
- const pool = await this._getPool();
219
- const tenantId = this.opts.tenantId ?? null;
220
- const kernel = pool.get(tenantId);
221
- const backend = kernel.getBackend();
222
- if (!backend.hasBlob(hash)) backend.putBlob(hash, buffer);
223
- return { hash, size: buffer.length, contentType };
224
- }
225
- /**
226
- * Download a file by its blob hash.
227
- */
228
- async getFile(hash) {
229
- if (isRemote(this.opts)) {
230
- const res = await fetch(
231
- `${this.opts.url}/files/${encodeURIComponent(hash)}`,
232
- {
233
- headers: this.opts.apiKey ? { Authorization: `Bearer ${this.opts.apiKey}` } : {}
234
- }
235
- );
236
- if (res.status === 404) return null;
237
- if (!res.ok) throw new FetchError(res.status, await res.text());
238
- return new Uint8Array(await res.arrayBuffer());
239
- }
240
- const pool = await this._getPool();
241
- const tenantId = this.opts.tenantId ?? null;
242
- const kernel = pool.get(tenantId);
243
- const backend = kernel.getBackend();
244
- return backend.getBlob(hash) ?? null;
245
- }
246
- // -------------------------------------------------------------------------
247
- // Auth helpers
248
- // -------------------------------------------------------------------------
249
- async register(email, password, name) {
250
- if (!isRemote(this.opts))
251
- throw new Error("register() requires remote mode");
252
- return await this._fetch("POST", "/auth/register", {
253
- email,
254
- password,
255
- name
256
- });
257
- }
258
- async login(email, password) {
259
- if (!isRemote(this.opts)) throw new Error("login() requires remote mode");
260
- return await this._fetch("POST", "/auth/login", {
261
- email,
262
- password
263
- });
264
- }
265
- /**
266
- * Set the active API key / JWT token for subsequent requests.
267
- */
268
- setToken(token) {
269
- if (!isRemote(this.opts)) return;
270
- this.opts.apiKey = token;
271
- }
272
- // -------------------------------------------------------------------------
273
- // Realtime
274
- // -------------------------------------------------------------------------
275
- /**
276
- * Subscribe to a live EQL-S query.
277
- * Callback is fired immediately with the initial result, then on every update.
278
- *
279
- * Requires remote mode (WebSocket to server).
280
- */
281
- subscribe(eql, callback, opts) {
282
- if (!isRemote(this.opts)) {
283
- throw new Error(
284
- "subscribe() requires remote mode (connect to a running server)"
285
- );
286
- }
287
- const subId = `sub_${crypto.randomUUID()}`;
288
- this._subCallbacks.set(subId, callback);
289
- if (opts) this._subOpts.set(subId, opts);
290
- this._ensureWs().then((ws) => {
291
- ws.send(
292
- JSON.stringify({
293
- type: "subscribe",
294
- id: subId,
295
- query: eql,
296
- ...opts?.entityType ? { entityType: opts.entityType } : {},
297
- ...opts?.resolve ? { resolve: opts.resolve } : {}
298
- })
299
- );
300
- });
301
- return {
302
- unsubscribe: () => {
303
- this._subCallbacks.delete(subId);
304
- this._subOpts.delete(subId);
305
- this._ws?.send(JSON.stringify({ type: "unsubscribe", id: subId }));
306
- }
307
- };
308
- }
309
- /**
310
- * Close the WebSocket connection.
311
- */
312
- disconnect() {
313
- const ws = this._ws;
314
- this._ws = null;
315
- this._wsPromise = null;
316
- ws?.close();
317
- }
318
- /**
319
- * Close local kernel pool connections.
320
- */
321
- close() {
322
- this._pool?.closeAll();
323
- this._pool = null;
324
- this._poolPromise = null;
325
- this.disconnect();
326
- }
327
- // -------------------------------------------------------------------------
328
- // Private
329
- // -------------------------------------------------------------------------
330
- async _getPool() {
331
- if (this._pool) return this._pool;
332
- if (!this._poolPromise) {
333
- this._poolPromise = import("./tenancy-NBLLGCNJ.js").then(({ TenantPool }) => {
334
- const path = this.opts.path;
335
- this._pool = new TenantPool(path);
336
- return this._pool;
337
- });
338
- }
339
- return this._poolPromise;
340
- }
341
- async _fetch(method, path, body) {
342
- const opts = this.opts;
343
- const url = `${opts.url}${path}`;
344
- const res = await fetch(url, {
345
- method,
346
- headers: {
347
- "Content-Type": "application/json",
348
- ...opts.apiKey ? { Authorization: `Bearer ${opts.apiKey}` } : {}
349
- },
350
- body: body !== void 0 ? JSON.stringify(body) : void 0
351
- });
352
- const data = await res.json();
353
- if (!res.ok)
354
- throw new FetchError(
355
- res.status,
356
- data?.message ?? res.statusText,
357
- data
358
- );
359
- return data;
360
- }
361
- _ensureWs() {
362
- if (this._ws?.readyState === WebSocket.OPEN) {
363
- return Promise.resolve(this._ws);
364
- }
365
- if (this._wsPromise) {
366
- return this._wsPromise;
367
- }
368
- const opts = this.opts;
369
- const wsUrl = opts.url.replace(/^https?/, opts.url.startsWith("https") ? "wss" : "ws") + "/realtime";
370
- this._wsPromise = new Promise((resolve, reject) => {
371
- const ws = new WebSocket(wsUrl);
372
- ws.onopen = () => {
373
- this._ws = ws;
374
- resolve(ws);
375
- };
376
- ws.onerror = (e) => {
377
- reject(e instanceof Error ? e : new Error("WebSocket error"));
378
- };
379
- ws.onmessage = (e) => {
380
- try {
381
- const msg = JSON.parse(e.data);
382
- if (msg.type === "data" && this._subCallbacks.has(msg.id)) {
383
- const meta = msg.resolved === true ? { resolved: true } : void 0;
384
- this._subCallbacks.get(msg.id)(msg.result, msg.diff, meta);
385
- }
386
- } catch {
387
- }
388
- };
389
- ws.onclose = () => {
390
- if (this._ws === ws) {
391
- this._ws = null;
392
- }
393
- };
394
- }).finally(() => {
395
- this._wsPromise = null;
396
- });
397
- return this._wsPromise;
398
- }
399
- };
400
- function entityToPlain(entity) {
401
- const obj = { id: entity.id, type: entity.type };
402
- for (const f of entity.facts) {
403
- if (f.a !== "type") obj[f.a] = f.v;
404
- }
405
- return obj;
406
- }
407
- var FetchError = class extends Error {
408
- constructor(status, message, body) {
409
- super(`HTTP ${status}: ${message}`);
410
- this.status = status;
411
- this.body = body;
412
- this.name = "FetchError";
413
- }
414
- };
415
-
416
- export {
417
- TrellisDb,
418
- FetchError
419
- };