@happyvertical/smrt-core 0.43.9 → 0.44.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 (72) hide show
  1. package/AGENTS.md +24 -1
  2. package/agents/generators.md +78 -5
  3. package/agents/schema-paths.md +99 -0
  4. package/dist/change-feed.d.ts +4 -0
  5. package/dist/change-feed.d.ts.map +1 -1
  6. package/dist/change-feed.js +8 -4
  7. package/dist/change-feed.js.map +1 -1
  8. package/dist/collection.d.ts +10 -0
  9. package/dist/collection.d.ts.map +1 -1
  10. package/dist/collection.js +145 -18
  11. package/dist/collection.js.map +1 -1
  12. package/dist/embedded-write-queue.d.ts +17 -29
  13. package/dist/embedded-write-queue.d.ts.map +1 -1
  14. package/dist/embedded-write-queue.js +44 -6
  15. package/dist/embedded-write-queue.js.map +1 -1
  16. package/dist/generators/custom-action.d.ts.map +1 -1
  17. package/dist/generators/custom-action.js +1 -1
  18. package/dist/generators/custom-action.js.map +1 -1
  19. package/dist/generators/mcp-emit.d.ts +6 -7
  20. package/dist/generators/mcp-emit.d.ts.map +1 -1
  21. package/dist/generators/mcp-emit.js +17 -29
  22. package/dist/generators/mcp-emit.js.map +1 -1
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +3 -2
  26. package/dist/knowledge.d.ts +17 -1
  27. package/dist/knowledge.d.ts.map +1 -1
  28. package/dist/knowledge.js +33 -3
  29. package/dist/knowledge.js.map +1 -1
  30. package/dist/manifest/static-manifest.d.ts.map +1 -1
  31. package/dist/manifest/static-manifest.js +30 -2
  32. package/dist/manifest/static-manifest.js.map +1 -1
  33. package/dist/manifest/store.js +1 -1
  34. package/dist/manifest/store.js.map +1 -1
  35. package/dist/manifest.json +36 -2
  36. package/dist/migrations/differ.d.ts +49 -0
  37. package/dist/migrations/differ.d.ts.map +1 -1
  38. package/dist/migrations/differ.js +220 -4
  39. package/dist/migrations/differ.js.map +1 -1
  40. package/dist/migrations/orchestrate.d.ts +23 -0
  41. package/dist/migrations/orchestrate.d.ts.map +1 -1
  42. package/dist/migrations/orchestrate.js +12 -3
  43. package/dist/migrations/orchestrate.js.map +1 -1
  44. package/dist/object.d.ts +44 -2
  45. package/dist/object.d.ts.map +1 -1
  46. package/dist/object.js +207 -18
  47. package/dist/object.js.map +1 -1
  48. package/dist/registry/types.d.ts +8 -3
  49. package/dist/registry/types.d.ts.map +1 -1
  50. package/dist/schema/foreign-key-ddl.d.ts +7 -0
  51. package/dist/schema/foreign-key-ddl.d.ts.map +1 -1
  52. package/dist/schema/foreign-key-ddl.js +7 -1
  53. package/dist/schema/foreign-key-ddl.js.map +1 -1
  54. package/dist/schema/schema-manager.d.ts +15 -0
  55. package/dist/schema/schema-manager.d.ts.map +1 -1
  56. package/dist/schema/schema-manager.js +52 -9
  57. package/dist/schema/schema-manager.js.map +1 -1
  58. package/dist/schema/types.d.ts +10 -0
  59. package/dist/schema/types.d.ts.map +1 -1
  60. package/dist/schema/uuid-convergence.d.ts +142 -0
  61. package/dist/schema/uuid-convergence.d.ts.map +1 -0
  62. package/dist/schema/uuid-convergence.js +0 -0
  63. package/dist/schema/uuid-convergence.js.map +1 -0
  64. package/dist/smrt-knowledge.json +33 -11
  65. package/dist/utils/scanner-module.d.ts +44 -0
  66. package/dist/utils/scanner-module.d.ts.map +1 -1
  67. package/dist/vite-plugin/index.d.ts +14 -1
  68. package/dist/vite-plugin/index.d.ts.map +1 -1
  69. package/dist/vite-plugin/index.js +54 -2
  70. package/dist/vite-plugin/index.js.map +1 -1
  71. package/dist/vite-plugin.js +3 -2
  72. package/package.json +6 -5
@@ -1,32 +1,4 @@
1
- /**
2
- * In-process write serialization for embedded database engines (#2360).
3
- *
4
- * File-backed SQLite (libsql) allows one writer at a time and the SDK opens a
5
- * NEW connection for every null-aware upsert attempt (`transaction("write")`),
6
- * with no busy timeout on either connection. Any other write on the root
7
- * connection while such a transaction is open — most commonly the change-feed
8
- * append that follows every model save — collides as `SQLITE_BUSY`, and under
9
- * sustained concurrency (a `Promise.all` of creates) the two sides livelock
10
- * through every retry tier. Before the tenant-led conflict target (#2360) the
11
- * null-aware path was rare (custom conflict keys with NULL values, #1246);
12
- * with `tenant_id` leading every tenant-scoped default key, EVERY NULL-tenant
13
- * (global) create takes it, so the collision became the steady state.
14
- *
15
- * The queue makes the process a single writer per database for exactly the
16
- * two participants of that collision:
17
- *
18
- * - a `save()` whose upsert conflict values contain NULL (the only shape the
19
- * SDK routes through a second-connection transaction), and
20
- * - the change-feed append (a root-connection write that follows every save).
21
- *
22
- * Each hold is a LEAF database call — never an interceptor or hook — so the
23
- * queue cannot deadlock on nested saves. PostgreSQL is never serialized here:
24
- * its null-aware upsert already arbitrates through advisory locks
25
- * server-side, and cross-process writers exist that an in-process queue could
26
- * not order anyway (which is also why this queue is a mitigation for embedded
27
- * engines' in-process writers, not a cross-process guarantee — embedded
28
- * engines have no cross-process writers in supported deployments).
29
- */
1
+ import { DatabaseInterface } from '@happyvertical/sql';
30
2
  interface QueueableDatabase {
31
3
  url?: string;
32
4
  }
@@ -37,10 +9,26 @@ interface QueueableDatabase {
37
9
  * handle reintroduces the livelock.
38
10
  */
39
11
  export declare function isEmbeddedDatabase(db: QueueableDatabase): boolean;
12
+ /**
13
+ * Whether revision compare-and-swap needs the process-local read/upsert path.
14
+ *
15
+ * DuckDB/JSON cannot express the timestamp predicate through the generic
16
+ * update API, and local SQLite has only the process's writers in supported
17
+ * deployments. Remote LibSQL/Turso is different: other processes may write
18
+ * the same database, so it must use one conditional UPDATE at the server.
19
+ */
20
+ export declare function usesEmbeddedRevisionFallback(db: QueueableDatabase): boolean;
40
21
  /**
41
22
  * Run `operation` after every previously queued write on the same database
42
23
  * has settled. When `serialize` is false the operation runs immediately.
43
24
  */
44
25
  export declare function withEmbeddedWriteQueue<T>(db: QueueableDatabase, serialize: boolean, operation: () => Promise<T>): Promise<T>;
26
+ /**
27
+ * Serialize a complete embedded root transaction with ordinary model writes.
28
+ * The transaction handle is registered as a reentrant alias so saves and
29
+ * change-feed appends inside the callback do not queue behind their own root
30
+ * transaction.
31
+ */
32
+ export declare function withEmbeddedWriteTransaction<T>(db: DatabaseInterface, serialize: boolean, operation: (transaction: DatabaseInterface) => Promise<T>): Promise<T>;
45
33
  export {};
46
34
  //# sourceMappingURL=embedded-write-queue.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"embedded-write-queue.d.ts","sourceRoot":"","sources":["../src/embedded-write-queue.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAMH,UAAU,iBAAiB;IACzB,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,iBAAiB,GAAG,OAAO,CAEjE;AAMD;;;GAGG;AACH,wBAAsB,sBAAsB,CAAC,CAAC,EAC5C,EAAE,EAAE,iBAAiB,EACrB,SAAS,EAAE,OAAO,EAClB,SAAS,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAC1B,OAAO,CAAC,CAAC,CAAC,CAoBZ"}
1
+ {"version":3,"file":"embedded-write-queue.d.ts","sourceRoot":"","sources":["../src/embedded-write-queue.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AA0C5D,UAAU,iBAAiB;IACzB,GAAG,CAAC,EAAE,MAAM,CAAC;CACd;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,EAAE,EAAE,iBAAiB,GAAG,OAAO,CAEjE;AAED;;;;;;;GAOG;AACH,wBAAgB,4BAA4B,CAAC,EAAE,EAAE,iBAAiB,GAAG,OAAO,CAG3E;AAMD;;;GAGG;AACH,wBAAsB,sBAAsB,CAAC,CAAC,EAC5C,EAAE,EAAE,iBAAiB,EACrB,SAAS,EAAE,OAAO,EAClB,SAAS,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAC1B,OAAO,CAAC,CAAC,CAAC,CAwBZ;AAED;;;;;GAKG;AACH,wBAAsB,4BAA4B,CAAC,CAAC,EAClD,EAAE,EAAE,iBAAiB,EACrB,SAAS,EAAE,OAAO,EAClB,SAAS,EAAE,CAAC,WAAW,EAAE,iBAAiB,KAAK,OAAO,CAAC,CAAC,CAAC,GACxD,OAAO,CAAC,CAAC,CAAC,CAeZ"}
@@ -1,3 +1,4 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
1
2
  //#region src/embedded-write-queue.ts
2
3
  /**
3
4
  * In-process write serialization for embedded database engines (#2360).
@@ -13,15 +14,20 @@
13
14
  * with `tenant_id` leading every tenant-scoped default key, EVERY NULL-tenant
14
15
  * (global) create takes it, so the collision became the steady state.
15
16
  *
16
- * The queue makes the process a single writer per database for exactly the
17
- * two participants of that collision:
17
+ * The queue makes the process a single writer per embedded database for:
18
18
  *
19
19
  * - a `save()` whose upsert conflict values contain NULL (the only shape the
20
20
  * SDK routes through a second-connection transaction), and
21
21
  * - the change-feed append (a root-connection write that follows every save).
22
+ * - every model save and delete, so the embedded revision-CAS compare/upsert
23
+ * fallback cannot race an ordinary save, natural-key create, or delete.
24
+ * - a complete root `SmrtObject.withTransaction()` callback, with writes on
25
+ * its bound handle re-entering the same hold instead of self-deadlocking.
22
26
  *
23
- * Each hold is a LEAF database call — never an interceptor or hook — so the
24
- * queue cannot deadlock on nested saves. PostgreSQL is never serialized here:
27
+ * Ordinary save/delete holds contain database calls only — never an
28
+ * interceptor or hook. Explicit transaction callbacks are caller-controlled,
29
+ * so their bound model writes re-enter the existing hold. PostgreSQL is never
30
+ * serialized here:
25
31
  * its null-aware upsert already arbitrates through advisory locks
26
32
  * server-side, and cross-process writers exist that an in-process queue could
27
33
  * not order anyway (which is also why this queue is a mitigation for embedded
@@ -31,6 +37,7 @@
31
37
  /** Queue tail per database identity (URL string, or the handle itself). */
32
38
  var urlQueues = /* @__PURE__ */ new Map();
33
39
  var handleQueues = /* @__PURE__ */ new WeakMap();
40
+ var activeQueueKeys = new AsyncLocalStorage();
34
41
  /**
35
42
  * Whether `db` is an embedded engine (SQLite/DuckDB/JSON — anything that is
36
43
  * not PostgreSQL). Handles without a URL are treated as embedded: serializing
@@ -40,6 +47,18 @@ var handleQueues = /* @__PURE__ */ new WeakMap();
40
47
  function isEmbeddedDatabase(db) {
41
48
  return !/^postgres(?:ql)?:/iu.test(db?.url ?? "");
42
49
  }
50
+ /**
51
+ * Whether revision compare-and-swap needs the process-local read/upsert path.
52
+ *
53
+ * DuckDB/JSON cannot express the timestamp predicate through the generic
54
+ * update API, and local SQLite has only the process's writers in supported
55
+ * deployments. Remote LibSQL/Turso is different: other processes may write
56
+ * the same database, so it must use one conditional UPDATE at the server.
57
+ */
58
+ function usesEmbeddedRevisionFallback(db) {
59
+ const url = db?.url ?? "";
60
+ return isEmbeddedDatabase(db) && !/^(?:https?|libsql):\/\//iu.test(url);
61
+ }
43
62
  function queueKey(db) {
44
63
  return typeof db?.url === "string" && db.url.length > 0 ? db.url : db;
45
64
  }
@@ -50,7 +69,11 @@ function queueKey(db) {
50
69
  async function withEmbeddedWriteQueue(db, serialize, operation) {
51
70
  if (!serialize) return operation();
52
71
  const key = queueKey(db);
53
- const next = ((typeof key === "string" ? urlQueues.get(key) : handleQueues.get(key)) ?? Promise.resolve()).then(operation, operation);
72
+ const active = activeQueueKeys.getStore();
73
+ if (active?.has(key)) return operation();
74
+ const previous = (typeof key === "string" ? urlQueues.get(key) : handleQueues.get(key)) ?? Promise.resolve();
75
+ const run = () => activeQueueKeys.run(/* @__PURE__ */ new Set([...active ?? [], key]), operation);
76
+ const next = previous.then(run, run);
54
77
  const tail = next.catch(() => void 0);
55
78
  if (typeof key === "string") {
56
79
  urlQueues.set(key, tail);
@@ -60,7 +83,22 @@ async function withEmbeddedWriteQueue(db, serialize, operation) {
60
83
  } else handleQueues.set(key, tail);
61
84
  return next;
62
85
  }
86
+ /**
87
+ * Serialize a complete embedded root transaction with ordinary model writes.
88
+ * The transaction handle is registered as a reentrant alias so saves and
89
+ * change-feed appends inside the callback do not queue behind their own root
90
+ * transaction.
91
+ */
92
+ async function withEmbeddedWriteTransaction(db, serialize, operation) {
93
+ const transaction = db.transaction?.bind(db);
94
+ if (!transaction) throw new Error("Database transaction support is required");
95
+ return withEmbeddedWriteQueue(db, serialize, () => transaction((bound) => {
96
+ if (!serialize) return operation(bound);
97
+ const active = activeQueueKeys.getStore();
98
+ return activeQueueKeys.run(/* @__PURE__ */ new Set([...active ?? [], queueKey(bound)]), () => operation(bound));
99
+ }));
100
+ }
63
101
  //#endregion
64
- export { isEmbeddedDatabase, withEmbeddedWriteQueue };
102
+ export { isEmbeddedDatabase, usesEmbeddedRevisionFallback, withEmbeddedWriteQueue, withEmbeddedWriteTransaction };
65
103
 
66
104
  //# sourceMappingURL=embedded-write-queue.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"embedded-write-queue.js","names":[],"sources":["../src/embedded-write-queue.ts"],"sourcesContent":["/**\n * In-process write serialization for embedded database engines (#2360).\n *\n * File-backed SQLite (libsql) allows one writer at a time and the SDK opens a\n * NEW connection for every null-aware upsert attempt (`transaction(\"write\")`),\n * with no busy timeout on either connection. Any other write on the root\n * connection while such a transaction is open — most commonly the change-feed\n * append that follows every model save — collides as `SQLITE_BUSY`, and under\n * sustained concurrency (a `Promise.all` of creates) the two sides livelock\n * through every retry tier. Before the tenant-led conflict target (#2360) the\n * null-aware path was rare (custom conflict keys with NULL values, #1246);\n * with `tenant_id` leading every tenant-scoped default key, EVERY NULL-tenant\n * (global) create takes it, so the collision became the steady state.\n *\n * The queue makes the process a single writer per database for exactly the\n * two participants of that collision:\n *\n * - a `save()` whose upsert conflict values contain NULL (the only shape the\n * SDK routes through a second-connection transaction), and\n * - the change-feed append (a root-connection write that follows every save).\n *\n * Each hold is a LEAF database call — never an interceptor or hook — so the\n * queue cannot deadlock on nested saves. PostgreSQL is never serialized here:\n * its null-aware upsert already arbitrates through advisory locks\n * server-side, and cross-process writers exist that an in-process queue could\n * not order anyway (which is also why this queue is a mitigation for embedded\n * engines' in-process writers, not a cross-process guarantee — embedded\n * engines have no cross-process writers in supported deployments).\n */\n\n/** Queue tail per database identity (URL string, or the handle itself). */\nconst urlQueues = new Map<string, Promise<unknown>>();\nconst handleQueues = new WeakMap<object, Promise<unknown>>();\n\ninterface QueueableDatabase {\n url?: string;\n}\n\n/**\n * Whether `db` is an embedded engine (SQLite/DuckDB/JSON — anything that is\n * not PostgreSQL). Handles without a URL are treated as embedded: serializing\n * them is at worst a throughput cost, while not serializing an embedded\n * handle reintroduces the livelock.\n */\nexport function isEmbeddedDatabase(db: QueueableDatabase): boolean {\n return !/^postgres(?:ql)?:/iu.test(db?.url ?? '');\n}\n\nfunction queueKey(db: QueueableDatabase): string | object {\n return typeof db?.url === 'string' && db.url.length > 0 ? db.url : db;\n}\n\n/**\n * Run `operation` after every previously queued write on the same database\n * has settled. When `serialize` is false the operation runs immediately.\n */\nexport async function withEmbeddedWriteQueue<T>(\n db: QueueableDatabase,\n serialize: boolean,\n operation: () => Promise<T>,\n): Promise<T> {\n if (!serialize) return operation();\n\n const key = queueKey(db);\n const previous =\n (typeof key === 'string' ? urlQueues.get(key) : handleQueues.get(key)) ??\n Promise.resolve();\n const next = previous.then(operation, operation);\n // The stored tail must never reject, or one failed write would poison the\n // queue for every later writer.\n const tail = next.catch(() => undefined);\n if (typeof key === 'string') {\n urlQueues.set(key, tail);\n void tail.finally(() => {\n if (urlQueues.get(key) === tail) urlQueues.delete(key);\n });\n } else {\n handleQueues.set(key, tail);\n }\n return next;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BA,IAAM,4BAAY,IAAI,IAA8B;AACpD,IAAM,+BAAe,IAAI,QAAkC;;;;;;;AAY3D,SAAgB,mBAAmB,IAAgC;CACjE,OAAO,CAAC,sBAAsB,KAAK,IAAI,OAAO,EAAE;AAClD;AAEA,SAAS,SAAS,IAAwC;CACxD,OAAO,OAAO,IAAI,QAAQ,YAAY,GAAG,IAAI,SAAS,IAAI,GAAG,MAAM;AACrE;;;;;AAMA,eAAsB,uBACpB,IACA,WACA,WACY;CACZ,IAAI,CAAC,WAAW,OAAO,UAAU;CAEjC,MAAM,MAAM,SAAS,EAAE;CAIvB,MAAM,SAFH,OAAO,QAAQ,WAAW,UAAU,IAAI,GAAG,IAAI,aAAa,IAAI,GAAG,MACpE,QAAQ,QAAQ,EAAA,CACI,KAAK,WAAW,SAAS;CAG/C,MAAM,OAAO,KAAK,YAAY,KAAA,CAAS;CACvC,IAAI,OAAO,QAAQ,UAAU;EAC3B,UAAU,IAAI,KAAK,IAAI;EACvB,KAAU,cAAc;GACtB,IAAI,UAAU,IAAI,GAAG,MAAM,MAAM,UAAU,OAAO,GAAG;EACvD,CAAC;CACH,OACE,aAAa,IAAI,KAAK,IAAI;CAE5B,OAAO;AACT"}
1
+ {"version":3,"file":"embedded-write-queue.js","names":[],"sources":["../src/embedded-write-queue.ts"],"sourcesContent":["import { AsyncLocalStorage } from 'node:async_hooks';\nimport type { DatabaseInterface } from '@happyvertical/sql';\n\n/**\n * In-process write serialization for embedded database engines (#2360).\n *\n * File-backed SQLite (libsql) allows one writer at a time and the SDK opens a\n * NEW connection for every null-aware upsert attempt (`transaction(\"write\")`),\n * with no busy timeout on either connection. Any other write on the root\n * connection while such a transaction is open — most commonly the change-feed\n * append that follows every model save — collides as `SQLITE_BUSY`, and under\n * sustained concurrency (a `Promise.all` of creates) the two sides livelock\n * through every retry tier. Before the tenant-led conflict target (#2360) the\n * null-aware path was rare (custom conflict keys with NULL values, #1246);\n * with `tenant_id` leading every tenant-scoped default key, EVERY NULL-tenant\n * (global) create takes it, so the collision became the steady state.\n *\n * The queue makes the process a single writer per embedded database for:\n *\n * - a `save()` whose upsert conflict values contain NULL (the only shape the\n * SDK routes through a second-connection transaction), and\n * - the change-feed append (a root-connection write that follows every save).\n * - every model save and delete, so the embedded revision-CAS compare/upsert\n * fallback cannot race an ordinary save, natural-key create, or delete.\n * - a complete root `SmrtObject.withTransaction()` callback, with writes on\n * its bound handle re-entering the same hold instead of self-deadlocking.\n *\n * Ordinary save/delete holds contain database calls only — never an\n * interceptor or hook. Explicit transaction callbacks are caller-controlled,\n * so their bound model writes re-enter the existing hold. PostgreSQL is never\n * serialized here:\n * its null-aware upsert already arbitrates through advisory locks\n * server-side, and cross-process writers exist that an in-process queue could\n * not order anyway (which is also why this queue is a mitigation for embedded\n * engines' in-process writers, not a cross-process guarantee — embedded\n * engines have no cross-process writers in supported deployments).\n */\n\n/** Queue tail per database identity (URL string, or the handle itself). */\nconst urlQueues = new Map<string, Promise<unknown>>();\nconst handleQueues = new WeakMap<object, Promise<unknown>>();\nconst activeQueueKeys = new AsyncLocalStorage<ReadonlySet<string | object>>();\n\ninterface QueueableDatabase {\n url?: string;\n}\n\n/**\n * Whether `db` is an embedded engine (SQLite/DuckDB/JSON — anything that is\n * not PostgreSQL). Handles without a URL are treated as embedded: serializing\n * them is at worst a throughput cost, while not serializing an embedded\n * handle reintroduces the livelock.\n */\nexport function isEmbeddedDatabase(db: QueueableDatabase): boolean {\n return !/^postgres(?:ql)?:/iu.test(db?.url ?? '');\n}\n\n/**\n * Whether revision compare-and-swap needs the process-local read/upsert path.\n *\n * DuckDB/JSON cannot express the timestamp predicate through the generic\n * update API, and local SQLite has only the process's writers in supported\n * deployments. Remote LibSQL/Turso is different: other processes may write\n * the same database, so it must use one conditional UPDATE at the server.\n */\nexport function usesEmbeddedRevisionFallback(db: QueueableDatabase): boolean {\n const url = db?.url ?? '';\n return isEmbeddedDatabase(db) && !/^(?:https?|libsql):\\/\\//iu.test(url);\n}\n\nfunction queueKey(db: QueueableDatabase): string | object {\n return typeof db?.url === 'string' && db.url.length > 0 ? db.url : db;\n}\n\n/**\n * Run `operation` after every previously queued write on the same database\n * has settled. When `serialize` is false the operation runs immediately.\n */\nexport async function withEmbeddedWriteQueue<T>(\n db: QueueableDatabase,\n serialize: boolean,\n operation: () => Promise<T>,\n): Promise<T> {\n if (!serialize) return operation();\n\n const key = queueKey(db);\n const active = activeQueueKeys.getStore();\n if (active?.has(key)) return operation();\n const previous =\n (typeof key === 'string' ? urlQueues.get(key) : handleQueues.get(key)) ??\n Promise.resolve();\n const run = () =>\n activeQueueKeys.run(new Set([...(active ?? []), key]), operation);\n const next = previous.then(run, run);\n // The stored tail must never reject, or one failed write would poison the\n // queue for every later writer.\n const tail = next.catch(() => undefined);\n if (typeof key === 'string') {\n urlQueues.set(key, tail);\n void tail.finally(() => {\n if (urlQueues.get(key) === tail) urlQueues.delete(key);\n });\n } else {\n handleQueues.set(key, tail);\n }\n return next;\n}\n\n/**\n * Serialize a complete embedded root transaction with ordinary model writes.\n * The transaction handle is registered as a reentrant alias so saves and\n * change-feed appends inside the callback do not queue behind their own root\n * transaction.\n */\nexport async function withEmbeddedWriteTransaction<T>(\n db: DatabaseInterface,\n serialize: boolean,\n operation: (transaction: DatabaseInterface) => Promise<T>,\n): Promise<T> {\n const transaction = db.transaction?.bind(db);\n if (!transaction) {\n throw new Error('Database transaction support is required');\n }\n return withEmbeddedWriteQueue(db, serialize, () =>\n transaction((bound) => {\n if (!serialize) return operation(bound);\n const active = activeQueueKeys.getStore();\n return activeQueueKeys.run(\n new Set([...(active ?? []), queueKey(bound)]),\n () => operation(bound),\n );\n }),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,IAAM,4BAAY,IAAI,IAA8B;AACpD,IAAM,+BAAe,IAAI,QAAkC;AAC3D,IAAM,kBAAkB,IAAI,kBAAgD;;;;;;;AAY5E,SAAgB,mBAAmB,IAAgC;CACjE,OAAO,CAAC,sBAAsB,KAAK,IAAI,OAAO,EAAE;AAClD;;;;;;;;;AAUA,SAAgB,6BAA6B,IAAgC;CAC3E,MAAM,MAAM,IAAI,OAAO;CACvB,OAAO,mBAAmB,EAAE,KAAK,CAAC,4BAA4B,KAAK,GAAG;AACxE;AAEA,SAAS,SAAS,IAAwC;CACxD,OAA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,IAAI,EAAE,QAAQ,GACb,OAAO,EAAE,CAwBX;AAED;;;;GAIG;AACH,MAAM,WAAW,mBAAmB;IAClC,EAAE,EAAE,KAAK,CAAC;IACV,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB,aAAa,CAAC,EAAE,MAAM,CAAC;CACxB;AAED,gFAAgF;AAChF,eAAO,MAAM,qCAAqC,0BAA0B,CAAC;AAE7E;;;;GAIG;AACH,wBAAgB,4BAA4B,CAC1C,KAAK,EAAE,OAAO,GACb,mBAAmB,GAAG,SAAS,CA6BjC"}
@@ -26,7 +26,7 @@ function resolveCustomActionMetadata(options) {
26
26
  ...options.method?.parameters ? { parameters: options.method.parameters } : {},
27
27
  isStatic: options.method?.isStatic === true,
28
28
  effect,
29
- idempotent: configured.idempotent ?? effect === "read",
29
+ idempotent: configured.idempotent ?? false,
30
30
  openWorld: configured.openWorld ?? true
31
31
  };
32
32
  }
@@ -1 +1 @@
1
- {"version":3,"file":"custom-action.js","names":[],"sources":["../../src/generators/custom-action.ts"],"sourcesContent":["/**\n * Canonical custom-action metadata and transport-safe result helpers.\n *\n * Custom actions are intentionally distinct from generated CRUD. Their target\n * is derived from method metadata: instance methods target an item and static\n * methods target the collection. API route configuration may shape an HTTP\n * route, but it cannot change a method's receiver.\n */\n\nimport type { ToolEffect } from '../registry/types.js';\nimport type { MethodDefinition } from '../scanner/types.js';\nimport { convertTypeToJsonSchema } from '../tools/tool-generator.js';\n\nexport type CustomActionScope = 'item' | 'collection';\nexport type { ToolEffect } from '../registry/types.js';\n\nexport interface CustomActionMetadata {\n scope: CustomActionScope;\n /** An item-targeted action requires its target identifier. */\n idRequired: boolean;\n /** Present only when scanner/manifest metadata is available. */\n parameters?: MethodDefinition['parameters'];\n /** Collection actions on a model class invoke its static method. */\n isStatic: boolean;\n /** Browser/agent-visible effect. Omitted declarations fail closed. */\n effect?: ToolEffect;\n /** Whether repeating the action with the same arguments is safe. */\n idempotent?: boolean;\n /** Whether the opaque action may interact outside the SMRT application. */\n openWorld?: boolean;\n}\n\n/** Fully resolved metadata returned by {@link resolveCustomActionMetadata}. */\nexport type ResolvedCustomActionMetadata = CustomActionMetadata &\n Required<Pick<CustomActionMetadata, 'effect' | 'idempotent' | 'openWorld'>>;\n\n/**\n * Return the transport field for a method parameter. Flat tool and CLI\n * transports reserve `id` for receiver parsing even when a collection action\n * rejects it, so every action parameter named `id` is exposed as `actionId`.\n * REST already has separate path/body namespaces.\n */\nexport function customActionParameterInputName(\n _metadata: Pick<CustomActionMetadata, 'idRequired'>,\n parameterName: string,\n): string {\n return parameterName === 'id' ? 'actionId' : parameterName;\n}\n\nexport interface ResolveCustomActionMetadataOptions {\n actionName: string;\n method?: {\n isStatic?: boolean;\n parameters?: MethodDefinition['parameters'];\n };\n apiConfig?: unknown;\n /** Collection-class actions have a collection receiver even when non-static. */\n defaultScope?: CustomActionScope;\n}\n\ntype JsonSchema = Record<string, unknown>;\ntype ToolArgs = Record<string, unknown>;\n\n/**\n * Resolve the target contract shared by MCP, generated REST, CLI discovery,\n * and WebMCP. A missing manifest method retains the historical item-shaped\n * schema; runtime callers may still provide their legacy collection fallback.\n */\nexport function resolveCustomActionMetadata(\n options: ResolveCustomActionMetadataOptions,\n): ResolvedCustomActionMetadata {\n const defaultScope =\n options.defaultScope ?? (options.method?.isStatic ? 'collection' : 'item');\n const requestedScope = readConfiguredScope(\n options.apiConfig,\n options.actionName,\n );\n // A route-only scope override cannot manufacture a receiver. A normal\n // instance method is always item-targeted; a static model method and a\n // recognized collection-class method are always collection-targeted. Keep\n // a matching explicit value for diagnostics/config round-tripping only.\n const scope = requestedScope === defaultScope ? requestedScope : defaultScope;\n const configured = readConfiguredToolMetadata(\n options.apiConfig,\n options.actionName,\n );\n const effect = configured.effect ?? 'destructive';\n\n return {\n scope,\n idRequired: scope === 'item',\n ...(options.method?.parameters\n ? { parameters: options.method.parameters }\n : {}),\n isStatic: options.method?.isStatic === true,\n effect,\n idempotent: configured.idempotent ?? effect === 'read',\n openWorld: configured.openWorld ?? true,\n };\n}\n\n/** Build the custom-action portion of an MCP/WebMCP JSON Schema. */\nexport function buildCustomActionInputSchema(\n metadata: CustomActionMetadata,\n): JsonSchema {\n const properties: Record<string, JsonSchema> = {};\n const required: string[] = [];\n\n if (metadata.idRequired) {\n properties.id = {\n type: 'string',\n description: 'ID of the object to execute action on',\n };\n required.push('id');\n }\n\n // Absent metadata is the legacy options-bag contract. Do not infer direct\n // positional arguments from runtime function arity: it is lossy after\n // transpilation and would make discovery non-deterministic.\n if (!metadata.parameters) {\n properties.options = {\n type: 'object',\n description: 'Additional options for the custom action',\n additionalProperties: true,\n };\n } else if (\n metadata.parameters.length === 1 &&\n metadata.parameters[0]?.name === 'options'\n ) {\n const parameter = metadata.parameters[0];\n properties.options = {\n ...convertTypeToJsonSchema(parameter.type),\n description: 'Options for the custom action',\n ...(parameter.default !== undefined\n ? { default: parameter.default }\n : {}),\n };\n if (!parameter.optional) required.push('options');\n } else {\n for (const parameter of metadata.parameters) {\n const inputName = customActionParameterInputName(\n metadata,\n parameter.name,\n );\n properties[inputName] = {\n ...convertTypeToJsonSchema(parameter.type),\n ...(parameter.default !== undefined\n ? { default: parameter.default }\n : {}),\n };\n if (!parameter.optional) required.push(inputName);\n }\n }\n\n return {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n };\n}\n\n/**\n * Translate a transport object into the method's call arguments. Legacy\n * actions retain their single options-bag invocation; scanner metadata enables\n * an exact positional projection without changing legacy action behavior.\n */\nexport function buildCustomActionInvocationArgs(\n metadata: CustomActionMetadata,\n args: ToolArgs,\n): unknown[] {\n const { id: _id, options, ...directArgs } = args;\n\n if (!metadata.parameters) {\n return [\n isRecord(options) && Object.keys(options).length > 0\n ? options\n : directArgs,\n ];\n }\n if (metadata.parameters.length === 0) return [];\n if (\n metadata.parameters.length === 1 &&\n metadata.parameters[0]?.name === 'options'\n ) {\n // Preserve `undefined` (and an explicit `null`) so JavaScript default\n // parameter initializers and intentional null handling retain their native\n // semantics. Legacy options bags still receive an empty object below.\n return [options];\n }\n return metadata.parameters.map(\n (parameter) =>\n args[customActionParameterInputName(metadata, parameter.name)],\n );\n}\n\n/**\n * Domain-neutral returned-failure convention for custom actions. The explicit\n * `ok: false` marker prevents successful opaque values such as `{ code,\n * message }` from being reclassified as failures by a transport.\n */\nexport interface CustomActionFailure {\n ok: false;\n code: string;\n message: string;\n status: number;\n details?: unknown;\n retryable?: boolean;\n correlationId?: string;\n}\n\n/** Stable MCP `_meta` member shared with the app discovery contract (#2181). */\nexport const SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY = 'io.happyvertical/smrt';\n\n/**\n * Detect, validate, and redact an explicitly returned custom-action failure.\n * Unknown return values remain opaque successes. `status` defaults to 400 so\n * REST callers receive non-2xx semantics even when an adapter omits it.\n */\nexport function normalizeCustomActionFailure(\n value: unknown,\n): CustomActionFailure | undefined {\n if (!isRecord(value) || value.ok !== false) return undefined;\n if (typeof value.code !== 'string' || typeof value.message !== 'string') {\n return undefined;\n }\n\n const status =\n typeof value.status === 'number' &&\n Number.isInteger(value.status) &&\n value.status >= 400 &&\n value.status <= 599\n ? value.status\n : 400;\n\n return {\n ok: false,\n code: value.code,\n message: redactText(value.message),\n status,\n ...(Object.hasOwn(value, 'details')\n ? { details: redactValue(value.details) }\n : {}),\n ...(typeof value.retryable === 'boolean'\n ? { retryable: value.retryable }\n : {}),\n ...(typeof value.correlationId === 'string'\n ? { correlationId: value.correlationId }\n : {}),\n };\n}\n\nfunction readConfiguredScope(\n apiConfig: unknown,\n actionName: string,\n): CustomActionScope | undefined {\n if (!isRecord(apiConfig) || !isRecord(apiConfig.routes)) return undefined;\n const route = apiConfig.routes[actionName];\n return isRecord(route) &&\n (route.scope === 'item' || route.scope === 'collection')\n ? route.scope\n : undefined;\n}\n\nfunction readConfiguredToolMetadata(\n apiConfig: unknown,\n actionName: string,\n): {\n effect?: ToolEffect;\n idempotent?: boolean;\n openWorld?: boolean;\n} {\n if (!isRecord(apiConfig) || !isRecord(apiConfig.routes)) return {};\n const route = apiConfig.routes[actionName];\n if (!isRecord(route)) return {};\n const effect =\n route.effect === 'read' ||\n route.effect === 'write' ||\n route.effect === 'destructive'\n ? route.effect\n : undefined;\n if (\n effect === 'read' &&\n (route.method === 'PUT' ||\n route.method === 'PATCH' ||\n route.method === 'DELETE')\n ) {\n throw new Error(\n `Custom action ${actionName} cannot declare a read effect for a ${route.method} route`,\n );\n }\n return {\n ...(effect ? { effect } : {}),\n ...(typeof route.idempotent === 'boolean'\n ? { idempotent: route.idempotent }\n : {}),\n ...(typeof route.openWorld === 'boolean'\n ? { openWorld: route.openWorld }\n : {}),\n };\n}\n\nfunction redactValue(value: unknown, seen = new WeakSet<object>()): unknown {\n if (typeof value === 'string') return redactText(value);\n if (value === null || typeof value !== 'object') return value;\n if (seen.has(value)) return '[REDACTED]';\n seen.add(value);\n if (Array.isArray(value))\n return value.map((entry) => redactValue(entry, seen));\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return '[REDACTED]';\n const result: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value)) {\n result[key] = isSensitiveKey(key)\n ? '[REDACTED]'\n : redactValue(nested, seen);\n }\n return result;\n}\n\nfunction redactText(value: string): string {\n return value\n .replace(/\\bBearer\\s+[^\\s,;]+/giu, 'Bearer [REDACTED]')\n .replace(\n /\\b(token|secret|password|api[_-]?key)=([^\\s&]+)/giu,\n '$1=[REDACTED]',\n );\n}\n\nfunction isSensitiveKey(key: string): boolean {\n return /(?:token|secret|password|authorization|cookie|credential|api[_-]?key)/iu.test(\n key,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n"],"mappings":";;;;;;;;AA0CA,SAAgB,+B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aAAa,cAAc,MAAM,OAAO;CACjE,MAAM,SAAkC,CAAC;CACzC,KAAK,MAAM,CAAC,KAAK,WAAW,OAAO,QAAQ,KAAK,GAC9C,OAAO,OAAO,eAAe,GAAG,IAC5B,eACA,YAAY,QAAQ,IAAI;CAE9B,OAAO;AACT;AAEA,SAAS,WAAW,OAAuB;CACzC,OAAO,MACJ,QAAQ,0BAA0B,mBAAmB,CAAC,CACtD,QACC,sDACA,eACF;AACJ;AAEA,SAAS,eAAe,KAAsB;CAC5C,OAAO,0EAA0E,KAC/E,GACF;AACF;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E"}
1
+ {"version":3,"file":"custom-action.js","names":[],"sources":["../../src/generators/custom-action.ts"],"sourcesContent":["/**\n * Canonical custom-action metadata and transport-safe result helpers.\n *\n * Custom actions are intentionally distinct from generated CRUD. Their target\n * is derived from method metadata: instance methods target an item and static\n * methods target the collection. API route configuration may shape an HTTP\n * route, but it cannot change a method's receiver.\n */\n\nimport type { ToolEffect } from '../registry/types.js';\nimport type { MethodDefinition } from '../scanner/types.js';\nimport { convertTypeToJsonSchema } from '../tools/tool-generator.js';\n\nexport type CustomActionScope = 'item' | 'collection';\nexport type { ToolEffect } from '../registry/types.js';\n\nexport interface CustomActionMetadata {\n scope: CustomActionScope;\n /** An item-targeted action requires its target identifier. */\n idRequired: boolean;\n /** Present only when scanner/manifest metadata is available. */\n parameters?: MethodDefinition['parameters'];\n /** Collection actions on a model class invoke its static method. */\n isStatic: boolean;\n /** Browser/agent-visible effect. Omitted declarations fail closed. */\n effect?: ToolEffect;\n /** Whether repeating the action with the same arguments is safe. */\n idempotent?: boolean;\n /** Whether the opaque action may interact outside the SMRT application. */\n openWorld?: boolean;\n}\n\n/** Fully resolved metadata returned by {@link resolveCustomActionMetadata}. */\nexport type ResolvedCustomActionMetadata = CustomActionMetadata &\n Required<Pick<CustomActionMetadata, 'effect' | 'idempotent' | 'openWorld'>>;\n\n/**\n * Return the transport field for a method parameter. Flat tool and CLI\n * transports reserve `id` for receiver parsing even when a collection action\n * rejects it, so every action parameter named `id` is exposed as `actionId`.\n * REST already has separate path/body namespaces.\n */\nexport function customActionParameterInputName(\n _metadata: Pick<CustomActionMetadata, 'idRequired'>,\n parameterName: string,\n): string {\n return parameterName === 'id' ? 'actionId' : parameterName;\n}\n\nexport interface ResolveCustomActionMetadataOptions {\n actionName: string;\n method?: {\n isStatic?: boolean;\n parameters?: MethodDefinition['parameters'];\n };\n apiConfig?: unknown;\n /** Collection-class actions have a collection receiver even when non-static. */\n defaultScope?: CustomActionScope;\n}\n\ntype JsonSchema = Record<string, unknown>;\ntype ToolArgs = Record<string, unknown>;\n\n/**\n * Resolve the target contract shared by MCP, generated REST, CLI discovery,\n * and WebMCP. A missing manifest method retains the historical item-shaped\n * schema; runtime callers may still provide their legacy collection fallback.\n */\nexport function resolveCustomActionMetadata(\n options: ResolveCustomActionMetadataOptions,\n): ResolvedCustomActionMetadata {\n const defaultScope =\n options.defaultScope ?? (options.method?.isStatic ? 'collection' : 'item');\n const requestedScope = readConfiguredScope(\n options.apiConfig,\n options.actionName,\n );\n // A route-only scope override cannot manufacture a receiver. A normal\n // instance method is always item-targeted; a static model method and a\n // recognized collection-class method are always collection-targeted. Keep\n // a matching explicit value for diagnostics/config round-tripping only.\n const scope = requestedScope === defaultScope ? requestedScope : defaultScope;\n const configured = readConfiguredToolMetadata(\n options.apiConfig,\n options.actionName,\n );\n const effect = configured.effect ?? 'destructive';\n\n return {\n scope,\n idRequired: scope === 'item',\n ...(options.method?.parameters\n ? { parameters: options.method.parameters }\n : {}),\n isStatic: options.method?.isStatic === true,\n effect,\n // Per-field fail-closed default (#2587, CapabilityDeclaration in\n // @happyvertical/smrt-types): an omitted `idempotent` resolves to\n // `false` regardless of the declared `effect` — a declared 'read'\n // action is not guaranteed idempotent (e.g. a dequeue-shaped read that\n // advances state), so a caller who wants the idempotent hint must\n // declare it explicitly.\n idempotent: configured.idempotent ?? false,\n openWorld: configured.openWorld ?? true,\n };\n}\n\n/** Build the custom-action portion of an MCP/WebMCP JSON Schema. */\nexport function buildCustomActionInputSchema(\n metadata: CustomActionMetadata,\n): JsonSchema {\n const properties: Record<string, JsonSchema> = {};\n const required: string[] = [];\n\n if (metadata.idRequired) {\n properties.id = {\n type: 'string',\n description: 'ID of the object to execute action on',\n };\n required.push('id');\n }\n\n // Absent metadata is the legacy options-bag contract. Do not infer direct\n // positional arguments from runtime function arity: it is lossy after\n // transpilation and would make discovery non-deterministic.\n if (!metadata.parameters) {\n properties.options = {\n type: 'object',\n description: 'Additional options for the custom action',\n additionalProperties: true,\n };\n } else if (\n metadata.parameters.length === 1 &&\n metadata.parameters[0]?.name === 'options'\n ) {\n const parameter = metadata.parameters[0];\n properties.options = {\n ...convertTypeToJsonSchema(parameter.type),\n description: 'Options for the custom action',\n ...(parameter.default !== undefined\n ? { default: parameter.default }\n : {}),\n };\n if (!parameter.optional) required.push('options');\n } else {\n for (const parameter of metadata.parameters) {\n const inputName = customActionParameterInputName(\n metadata,\n parameter.name,\n );\n properties[inputName] = {\n ...convertTypeToJsonSchema(parameter.type),\n ...(parameter.default !== undefined\n ? { default: parameter.default }\n : {}),\n };\n if (!parameter.optional) required.push(inputName);\n }\n }\n\n return {\n type: 'object',\n properties,\n ...(required.length > 0 ? { required } : {}),\n };\n}\n\n/**\n * Translate a transport object into the method's call arguments. Legacy\n * actions retain their single options-bag invocation; scanner metadata enables\n * an exact positional projection without changing legacy action behavior.\n */\nexport function buildCustomActionInvocationArgs(\n metadata: CustomActionMetadata,\n args: ToolArgs,\n): unknown[] {\n const { id: _id, options, ...directArgs } = args;\n\n if (!metadata.parameters) {\n return [\n isRecord(options) && Object.keys(options).length > 0\n ? options\n : directArgs,\n ];\n }\n if (metadata.parameters.length === 0) return [];\n if (\n metadata.parameters.length === 1 &&\n metadata.parameters[0]?.name === 'options'\n ) {\n // Preserve `undefined` (and an explicit `null`) so JavaScript default\n // parameter initializers and intentional null handling retain their native\n // semantics. Legacy options bags still receive an empty object below.\n return [options];\n }\n return metadata.parameters.map(\n (parameter) =>\n args[customActionParameterInputName(metadata, parameter.name)],\n );\n}\n\n/**\n * Domain-neutral returned-failure convention for custom actions. The explicit\n * `ok: false` marker prevents successful opaque values such as `{ code,\n * message }` from being reclassified as failures by a transport.\n */\nexport interface CustomActionFailure {\n ok: false;\n code: string;\n message: string;\n status: number;\n details?: unknown;\n retryable?: boolean;\n correlationId?: string;\n}\n\n/** Stable MCP `_meta` member shared with the app discovery contract (#2181). */\nexport const SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY = 'io.happyvertical/smrt';\n\n/**\n * Detect, validate, and redact an explicitly returned custom-action failure.\n * Unknown return values remain opaque successes. `status` defaults to 400 so\n * REST callers receive non-2xx semantics even when an adapter omits it.\n */\nexport function normalizeCustomActionFailure(\n value: unknown,\n): CustomActionFailure | undefined {\n if (!isRecord(value) || value.ok !== false) return undefined;\n if (typeof value.code !== 'string' || typeof value.message !== 'string') {\n return undefined;\n }\n\n const status =\n typeof value.status === 'number' &&\n Number.isInteger(value.status) &&\n value.status >= 400 &&\n value.status <= 599\n ? value.status\n : 400;\n\n return {\n ok: false,\n code: value.code,\n message: redactText(value.message),\n status,\n ...(Object.hasOwn(value, 'details')\n ? { details: redactValue(value.details) }\n : {}),\n ...(typeof value.retryable === 'boolean'\n ? { retryable: value.retryable }\n : {}),\n ...(typeof value.correlationId === 'string'\n ? { correlationId: value.correlationId }\n : {}),\n };\n}\n\nfunction readConfiguredScope(\n apiConfig: unknown,\n actionName: string,\n): CustomActionScope | undefined {\n if (!isRecord(apiConfig) || !isRecord(apiConfig.routes)) return undefined;\n const route = apiConfig.routes[actionName];\n return isRecord(route) &&\n (route.scope === 'item' || route.scope === 'collection')\n ? route.scope\n : undefined;\n}\n\nfunction readConfiguredToolMetadata(\n apiConfig: unknown,\n actionName: string,\n): {\n effect?: ToolEffect;\n idempotent?: boolean;\n openWorld?: boolean;\n} {\n if (!isRecord(apiConfig) || !isRecord(apiConfig.routes)) return {};\n const route = apiConfig.routes[actionName];\n if (!isRecord(route)) return {};\n const effect =\n route.effect === 'read' ||\n route.effect === 'write' ||\n route.effect === 'destructive'\n ? route.effect\n : undefined;\n if (\n effect === 'read' &&\n (route.method === 'PUT' ||\n route.method === 'PATCH' ||\n route.method === 'DELETE')\n ) {\n throw new Error(\n `Custom action ${actionName} cannot declare a read effect for a ${route.method} route`,\n );\n }\n return {\n ...(effect ? { effect } : {}),\n ...(typeof route.idempotent === 'boolean'\n ? { idempotent: route.idempotent }\n : {}),\n ...(typeof route.openWorld === 'boolean'\n ? { openWorld: route.openWorld }\n : {}),\n };\n}\n\nfunction redactValue(value: unknown, seen = new WeakSet<object>()): unknown {\n if (typeof value === 'string') return redactText(value);\n if (value === null || typeof value !== 'object') return value;\n if (seen.has(value)) return '[REDACTED]';\n seen.add(value);\n if (Array.isArray(value))\n return value.map((entry) => redactValue(entry, seen));\n const prototype = Object.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return '[REDACTED]';\n const result: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value)) {\n result[key] = isSensitiveKey(key)\n ? '[REDACTED]'\n : redactValue(nested, seen);\n }\n return result;\n}\n\nfunction redactText(value: string): string {\n return value\n .replace(/\\bBearer\\s+[^\\s,;]+/giu, 'Bearer [REDACTED]')\n .replace(\n /\\b(token|secret|password|api[_-]?key)=([^\\s&]+)/giu,\n '$1=[REDACTED]',\n );\n}\n\nfunction isSensitiveKey(key: string): boolean {\n return /(?:token|secret|password|authorization|cookie|credential|api[_-]?key)/iu.test(\n key,\n );\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return value !== null && typeof value === 'object' && !Array.isArray(value);\n}\n"],"mappings":";;;;;;;;AA0CA,SAAgB,+BACd,WACA,eACQ;CACR,OAAO,kBAAkB,OAAO,aAAa;AAC/C;;;;;;AAqBA,SAAgB,4BAC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AW,OAAO,QAAQ,KAAK,GAC9C,OAAO,OAAO,eAAe,GAAG,IAC5B,eACA,YAAY,QAAQ,IAAI;CAE9B,OAAO;AACT;AAEA,SAAS,WAAW,OAAuB;CACzC,OAAO,MACJ,QAAQ,0BAA0B,mBAAmB,CAAC,CACtD,QACC,sDACA,eACF;AACJ;AAEA,SAAS,eAAe,KAAsB;CAC5C,OAAO,0EAA0E,KAC/E,GACF;AACF;AAEA,SAAS,SAAS,OAAkD;CAClE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK;AAC5E"}
@@ -16,9 +16,9 @@
16
16
  * `node .smrt/mcp-server/index.js` runs instead of dying on
17
17
  * `SyntaxError: Unexpected identifier 'CallToolRequest'`.
18
18
  *
19
- * Transpilation uses the `typescript` package that `@happyvertical/smrt-core`
20
- * already depends on, imported lazily so that merely importing the generators
21
- * does not pull the compiler into memory.
19
+ * Transpilation uses `oxc-transform`, which strips the generated source's
20
+ * erasable TypeScript syntax without making the TypeScript compiler a runtime
21
+ * dependency of `@happyvertical/smrt-core` (#2339).
22
22
  */
23
23
  /** Language a generated file is written in, derived from its extension. */
24
24
  export type GeneratedSourceLanguage = 'typescript' | 'javascript';
@@ -49,10 +49,9 @@ export declare function generatedSiblingExtension(outputPath: string): Generated
49
49
  /**
50
50
  * Transpile generated TypeScript to runnable ESM JavaScript.
51
51
  *
52
- * `verbatimModuleSyntax` keeps every value import the template emits (an
53
- * unused-looking import must not be elided: the generated server relies on
54
- * side effects and on imports whose only use is inside emitted switch cases),
55
- * while type-only import specifiers are dropped.
52
+ * Generated source is constrained to erasable TypeScript syntax, so OXC can
53
+ * strip annotations and type-only import specifiers while leaving the ES
54
+ * module's runtime imports intact.
56
55
  *
57
56
  * @param source - Generated TypeScript source
58
57
  * @param label - Target path or name reported in transpile diagnostics
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-emit.d.ts","sourceRoot":"","sources":["../../src/generators/mcp-emit.ts"],"names":[],"m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,OAAO,CAAC,MAAM,CAAC,CAejB;AAED;;;;;;;GAOG;AACH,wBAAsB,qBAAqB,CACzC,MAAM,EAAE,MAAM,EACd,QAAQ,EAAE,uBAAuB,EACjC,KAAK,SAAyB,GAC7B,OAAO,CAAC,MAAM,CAAC,CAKjB"}
@@ -5,6 +5,15 @@ var TYPESCRIPT_EXTENSIONS = [".ts", ".mts"];
5
5
  * so a CommonJS target can never run whatever language it is written in.
6
6
  */
7
7
  var COMMONJS_EXTENSIONS = [".cjs", ".cts"];
8
+ /**
9
+ * Load OXC only for JavaScript emission. Core exports every generator from its
10
+ * package root, so loading native OXC bindings at module evaluation would make
11
+ * ordinary ORM and TypeScript-output consumers depend on this optional path.
12
+ */
13
+ async function loadOxcTransform() {
14
+ const { transform } = await import("oxc-transform");
15
+ return transform;
16
+ }
8
17
  function assertModuleTarget(outputPath, lowerCased) {
9
18
  const commonJs = COMMONJS_EXTENSIONS.find((extension) => lowerCased.endsWith(extension));
10
19
  if (commonJs) throw new Error(`Cannot generate an MCP server at '${outputPath}': the generated server is an ES module, so a ${commonJs} target cannot run. Use .js/.mjs for JavaScript or .ts/.mts for TypeScript.`);
@@ -43,22 +52,11 @@ function generatedSiblingExtension(outputPath) {
43
52
  return ".js";
44
53
  }
45
54
  /**
46
- * Load the TypeScript compiler API lazily.
47
- *
48
- * `typescript` is CommonJS: Node's ESM interop exposes the whole API on
49
- * `default`, while bundlers hand back the namespace itself.
50
- */
51
- async function loadTypeScript() {
52
- const imported = await import("typescript");
53
- return imported.default ?? imported;
54
- }
55
- /**
56
55
  * Transpile generated TypeScript to runnable ESM JavaScript.
57
56
  *
58
- * `verbatimModuleSyntax` keeps every value import the template emits (an
59
- * unused-looking import must not be elided: the generated server relies on
60
- * side effects and on imports whose only use is inside emitted switch cases),
61
- * while type-only import specifiers are dropped.
57
+ * Generated source is constrained to erasable TypeScript syntax, so OXC can
58
+ * strip annotations and type-only import specifiers while leaving the ES
59
+ * module's runtime imports intact.
62
60
  *
63
61
  * @param source - Generated TypeScript source
64
62
  * @param label - Target path or name reported in transpile diagnostics
@@ -66,25 +64,15 @@ async function loadTypeScript() {
66
64
  * @throws When the generated source is not valid TypeScript
67
65
  */
68
66
  async function transpileGeneratedSource(source, label = "generated MCP source") {
69
- const ts = await loadTypeScript();
70
- const { outputText, diagnostics } = ts.transpileModule(source, {
71
- fileName: "smrt-generated-mcp-source.ts",
72
- reportDiagnostics: true,
73
- compilerOptions: {
74
- target: ts.ScriptTarget.ESNext,
75
- module: ts.ModuleKind.ESNext,
76
- moduleResolution: ts.ModuleResolutionKind.Bundler,
77
- verbatimModuleSyntax: true,
78
- removeComments: false,
79
- newLine: ts.NewLineKind.LineFeed
80
- }
67
+ const { code, errors } = await (await loadOxcTransform())("smrt-generated-mcp-source.ts", source, {
68
+ lang: "ts",
69
+ sourceType: "module"
81
70
  });
82
- const errors = (diagnostics ?? []).filter((diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error);
83
71
  if (errors.length > 0) {
84
- const details = errors.map((diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, " ")).join("; ");
72
+ const details = errors.map((diagnostic) => diagnostic.message).join("; ");
85
73
  throw new Error(`Failed to transpile generated MCP source (${label}): ${details}`);
86
74
  }
87
- return outputText;
75
+ return code;
88
76
  }
89
77
  /**
90
78
  * Render generated TypeScript for the requested output language.
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-emit.js","names":[],"sources":["../../src/generators/mcp-emit.ts"],"sourcesContent":["/**\n * Emit helpers for generated MCP server sources.\n *\n * The MCP generators build their output as TypeScript source: the runtime\n * template carries type-only imports, type annotations, and generics. Whatever\n * the caller asked for as `outputPath` decides how that source has to be\n * written (#2279):\n *\n * - `.ts` / `.mts` — write the TypeScript verbatim. The consumer runs it\n * through `tsx` or Node's type stripping, which is what the repository's own\n * MCP conformance fixture does. The generated source therefore has to stay\n * erasable-syntax-only.\n * - `.cjs` / `.cts` — rejected. Generated servers are ES modules, so a\n * CommonJS target cannot run in any language.\n * - anything else (`.js` by default) — transpile to JavaScript first, so\n * `node .smrt/mcp-server/index.js` runs instead of dying on\n * `SyntaxError: Unexpected identifier 'CallToolRequest'`.\n *\n * Transpilation uses the `typescript` package that `@happyvertical/smrt-core`\n * already depends on, imported lazily so that merely importing the generators\n * does not pull the compiler into memory.\n */\n\n/** Language a generated file is written in, derived from its extension. */\nexport type GeneratedSourceLanguage = 'typescript' | 'javascript';\n\n/** Extension a generated module may be written with. */\nexport type GeneratedSourceExtension = '.ts' | '.mts' | '.js' | '.mjs';\n\nconst TYPESCRIPT_EXTENSIONS = ['.ts', '.mts'];\n\n/**\n * Generated servers are ES modules — they use `import` and `import.meta.url` —\n * so a CommonJS target can never run whatever language it is written in.\n */\nconst COMMONJS_EXTENSIONS = ['.cjs', '.cts'];\n\nfunction assertModuleTarget(outputPath: string, lowerCased: string): void {\n const commonJs = COMMONJS_EXTENSIONS.find((extension) =>\n lowerCased.endsWith(extension),\n );\n if (commonJs) {\n throw new Error(\n `Cannot generate an MCP server at '${outputPath}': the generated server is an ES module, so a ${commonJs} target cannot run. Use .js/.mjs for JavaScript or .ts/.mts for TypeScript.`,\n );\n }\n}\n\n/**\n * Decide how a generated file must be written from the path the caller asked\n * for. Unknown extensions emit JavaScript: `node` is the documented way to run\n * a generated server, so JavaScript is the safe default.\n *\n * @param outputPath - Path the generated file will be written to\n * @returns The language the file contents must be written in\n * @throws When the path asks for a CommonJS target\n */\nexport function resolveGeneratedSourceLanguage(\n outputPath: string,\n): GeneratedSourceLanguage {\n const lowerCased = outputPath.toLowerCase();\n assertModuleTarget(outputPath, lowerCased);\n return TYPESCRIPT_EXTENSIONS.some((extension) =>\n lowerCased.endsWith(extension),\n )\n ? 'typescript'\n : 'javascript';\n}\n\n/**\n * Extension for modules emitted alongside a generated entry point, so the\n * modular server's relative imports resolve to files that exist on disk *and*\n * are loaded with the entry's own module semantics. An `.mjs` entry point in a\n * CommonJS package needs `.mjs` siblings, not `.js` ones that Node would then\n * parse as CommonJS.\n *\n * @param outputPath - Path of the generated entry point\n * @returns The extension every sibling module is written with\n * @throws When the path asks for a CommonJS target\n */\nexport function generatedSiblingExtension(\n outputPath: string,\n): GeneratedSourceExtension {\n const lowerCased = outputPath.toLowerCase();\n assertModuleTarget(outputPath, lowerCased);\n if (lowerCased.endsWith('.mts')) return '.mts';\n if (lowerCased.endsWith('.ts')) return '.ts';\n if (lowerCased.endsWith('.mjs')) return '.mjs';\n return '.js';\n}\n\ntype TypeScriptApi = typeof import('typescript');\n\n/**\n * Load the TypeScript compiler API lazily.\n *\n * `typescript` is CommonJS: Node's ESM interop exposes the whole API on\n * `default`, while bundlers hand back the namespace itself.\n */\nasync function loadTypeScript(): Promise<TypeScriptApi> {\n const imported = (await import('typescript')) as TypeScriptApi & {\n default?: TypeScriptApi;\n };\n return imported.default ?? imported;\n}\n\n/**\n * Transpile generated TypeScript to runnable ESM JavaScript.\n *\n * `verbatimModuleSyntax` keeps every value import the template emits (an\n * unused-looking import must not be elided: the generated server relies on\n * side effects and on imports whose only use is inside emitted switch cases),\n * while type-only import specifiers are dropped.\n *\n * @param source - Generated TypeScript source\n * @param label - Target path or name reported in transpile diagnostics\n * @returns Equivalent JavaScript source\n * @throws When the generated source is not valid TypeScript\n */\nexport async function transpileGeneratedSource(\n source: string,\n label = 'generated MCP source',\n): Promise<string> {\n const ts = await loadTypeScript();\n\n const { outputText, diagnostics } = ts.transpileModule(source, {\n // The input is always TypeScript regardless of where it will be written;\n // a `.js` file name here would make the compiler parse it as JavaScript.\n fileName: 'smrt-generated-mcp-source.ts',\n reportDiagnostics: true,\n compilerOptions: {\n target: ts.ScriptTarget.ESNext,\n module: ts.ModuleKind.ESNext,\n moduleResolution: ts.ModuleResolutionKind.Bundler,\n verbatimModuleSyntax: true,\n removeComments: false,\n newLine: ts.NewLineKind.LineFeed,\n },\n });\n\n const errors = (diagnostics ?? []).filter(\n (diagnostic) => diagnostic.category === ts.DiagnosticCategory.Error,\n );\n if (errors.length > 0) {\n const details = errors\n .map((diagnostic) =>\n ts.flattenDiagnosticMessageText(diagnostic.messageText, ' '),\n )\n .join('; ');\n throw new Error(\n `Failed to transpile generated MCP source (${label}): ${details}`,\n );\n }\n\n return outputText;\n}\n\n/**\n * Render generated TypeScript for the requested output language.\n *\n * @param source - Generated TypeScript source\n * @param language - Language the file must be written in\n * @param label - Target path or name reported in transpile diagnostics\n * @returns Source ready to be written to disk\n */\nexport async function renderGeneratedSource(\n source: string,\n language: GeneratedSourceLanguage,\n label = 'generated MCP source',\n): Promise<string> {\n if (language === 'typescript') {\n return source;\n }\n return transpileGeneratedSource(source, label);\n}\n"],"mappings":";AA6BA,IAAM,wBAAwB,CAAC,OAAO,MAAM;;;;;AAM5C,IAAM,sBAAsB,CAAC,QAAQ,MAAM;AAE3C,SAAS,mBAAmB,YAAoB,YAA0B;CACxE,MAAM,WAAW,oBAAoB,MAAM,cACzC,WAAW,SAAS,SAAS,CAC/B;CACA,IAAI,UACF,MAAM,IAAI,MACR,qCAAqC,WAAW,gDAAgD,SAAS,4EAC3G;AAEJ;;;;;;;;;;AAWA,SAAgB,+BACd,YACyB;CACzB,MAAM,aAAa,WAAW,YAAY;CAC1C,mBAAmB,YAAY,UAAU;CACzC,OAAO,sBAAsB,MAAM,cACjC,WAAW,SAAS,SAAS,CAC/B,IACI,eACA;AACN;;;;;;;;;;;;AAaA,SAAgB,0BACd,YAC0B;CAC1B,MAAM,aAAa,WAAW,YAAY;CAC1C,mBAAmB,YAAY,UAAU;CACzC,IAAI,WAAW,SAAS,MAAM,GAAG,OAAO;CACxC,IAAI,WAAW,SAAS,KAAK,GAAG,OAAO;CACvC,IAAI,WAAW,SAAS,MAAM,GAAG,OAAO;CACxC,OAAO;AACT;;;;;;;AAUA,eAAe,iBAAyC;CACtD,MAAM,WAAY,MAAM,OAAO;CAG/B,OAAO,SAAS,WAAW;AAC7B;;;;;;;;;;;;;;AAeA,eAAsB,yBACpB,QACA,QAAQ,wBACS;CACjB,MAAM,KAAK,MAAM,eAAe;CAEhC,MAAM,EAAE,YAAY,gBAAgB,GAAG,gBAAgB,QAAQ;EAG7D,UAAU;EACV,mBAAmB;EACnB,iBAAiB;GACf,QAAQ,GAAG,aAAa;GACxB,QAAQ,GAAG,WAAW;GACtB,kBAAkB,GAAG,qBAAqB;GAC1C,sBAAsB;GACtB,gBAAgB;GAChB,SAAS,GAAG,YAAY;EAC1B;CACF,CAAC;CAED,MAAM,UAAU,eAAe,CAAC,EAAA,CAAG,QAChC,eAAe,WAAW,aAAa,GAAG,mBAAmB,KAChE;CACA,IAAI,OAAO,SAAS,GAAG;EACrB,MAAM,UAAU,OACb,KAAK,eACJ,GAAG,6BAA6B,WAAW,aAAa,GAAG,CAC7D,CAAC,CACA,KAAK,IAAI;EACZ,MAAM,IAAI,MACR,6CAA6C,MAAM,KAAK,SAC1D;CACF;CAEA,OAAO;AACT;;;;;;;;;AAUA,eAAsB,sBACpB,QACA,UACA,QAAQ,wBACS;CACjB,IAAI,aAAa,cACf,OAAO;CAET,OAAO,yBAAyB,QAAQ,KAAK;AAC/C"}
1
+ {"version":3,"file":"mcp-emit.js","names":[],"sources":["../../src/generators/mcp-emit.ts"],"sourcesContent":["/**\n * Emit helpers for generated MCP server sources.\n *\n * The MCP generators build their output as TypeScript source: the runtime\n * template carries type-only imports, type annotations, and generics. Whatever\n * the caller asked for as `outputPath` decides how that source has to be\n * written (#2279):\n *\n * - `.ts` / `.mts` — write the TypeScript verbatim. The consumer runs it\n * through `tsx` or Node's type stripping, which is what the repository's own\n * MCP conformance fixture does. The generated source therefore has to stay\n * erasable-syntax-only.\n * - `.cjs` / `.cts` — rejected. Generated servers are ES modules, so a\n * CommonJS target cannot run in any language.\n * - anything else (`.js` by default) — transpile to JavaScript first, so\n * `node .smrt/mcp-server/index.js` runs instead of dying on\n * `SyntaxError: Unexpected identifier 'CallToolRequest'`.\n *\n * Transpilation uses `oxc-transform`, which strips the generated source's\n * erasable TypeScript syntax without making the TypeScript compiler a runtime\n * dependency of `@happyvertical/smrt-core` (#2339).\n */\n\n/** Language a generated file is written in, derived from its extension. */\nexport type GeneratedSourceLanguage = 'typescript' | 'javascript';\n\n/** Extension a generated module may be written with. */\nexport type GeneratedSourceExtension = '.ts' | '.mts' | '.js' | '.mjs';\n\nconst TYPESCRIPT_EXTENSIONS = ['.ts', '.mts'];\n\n/**\n * Generated servers are ES modules — they use `import` and `import.meta.url` —\n * so a CommonJS target can never run whatever language it is written in.\n */\nconst COMMONJS_EXTENSIONS = ['.cjs', '.cts'];\n\ntype OxcTransform = typeof import('oxc-transform').transform;\n\n/**\n * Load OXC only for JavaScript emission. Core exports every generator from its\n * package root, so loading native OXC bindings at module evaluation would make\n * ordinary ORM and TypeScript-output consumers depend on this optional path.\n */\nasync function loadOxcTransform(): Promise<OxcTransform> {\n const { transform } = await import('oxc-transform');\n return transform;\n}\n\nfunction assertModuleTarget(outputPath: string, lowerCased: string): void {\n const commonJs = COMMONJS_EXTENSIONS.find((extension) =>\n lowerCased.endsWith(extension),\n );\n if (commonJs) {\n throw new Error(\n `Cannot generate an MCP server at '${outputPath}': the generated server is an ES module, so a ${commonJs} target cannot run. Use .js/.mjs for JavaScript or .ts/.mts for TypeScript.`,\n );\n }\n}\n\n/**\n * Decide how a generated file must be written from the path the caller asked\n * for. Unknown extensions emit JavaScript: `node` is the documented way to run\n * a generated server, so JavaScript is the safe default.\n *\n * @param outputPath - Path the generated file will be written to\n * @returns The language the file contents must be written in\n * @throws When the path asks for a CommonJS target\n */\nexport function resolveGeneratedSourceLanguage(\n outputPath: string,\n): GeneratedSourceLanguage {\n const lowerCased = outputPath.toLowerCase();\n assertModuleTarget(outputPath, lowerCased);\n return TYPESCRIPT_EXTENSIONS.some((extension) =>\n lowerCased.endsWith(extension),\n )\n ? 'typescript'\n : 'javascript';\n}\n\n/**\n * Extension for modules emitted alongside a generated entry point, so the\n * modular server's relative imports resolve to files that exist on disk *and*\n * are loaded with the entry's own module semantics. An `.mjs` entry point in a\n * CommonJS package needs `.mjs` siblings, not `.js` ones that Node would then\n * parse as CommonJS.\n *\n * @param outputPath - Path of the generated entry point\n * @returns The extension every sibling module is written with\n * @throws When the path asks for a CommonJS target\n */\nexport function generatedSiblingExtension(\n outputPath: string,\n): GeneratedSourceExtension {\n const lowerCased = outputPath.toLowerCase();\n assertModuleTarget(outputPath, lowerCased);\n if (lowerCased.endsWith('.mts')) return '.mts';\n if (lowerCased.endsWith('.ts')) return '.ts';\n if (lowerCased.endsWith('.mjs')) return '.mjs';\n return '.js';\n}\n\n/**\n * Transpile generated TypeScript to runnable ESM JavaScript.\n *\n * Generated source is constrained to erasable TypeScript syntax, so OXC can\n * strip annotations and type-only import specifiers while leaving the ES\n * module's runtime imports intact.\n *\n * @param source - Generated TypeScript source\n * @param label - Target path or name reported in transpile diagnostics\n * @returns Equivalent JavaScript source\n * @throws When the generated source is not valid TypeScript\n */\nexport async function transpileGeneratedSource(\n source: string,\n label = 'generated MCP source',\n): Promise<string> {\n const transform = await loadOxcTransform();\n const { code, errors } = await transform(\n 'smrt-generated-mcp-source.ts',\n source,\n { lang: 'ts', sourceType: 'module' },\n );\n if (errors.length > 0) {\n const details = errors.map((diagnostic) => diagnostic.message).join('; ');\n throw new Error(\n `Failed to transpile generated MCP source (${label}): ${details}`,\n );\n }\n\n return code;\n}\n\n/**\n * Render generated TypeScript for the requested output language.\n *\n * @param source - Generated TypeScript source\n * @param language - Language the file must be written in\n * @param label - Target path or name reported in transpile diagnostics\n * @returns Source ready to be written to disk\n */\nexport async function renderGeneratedSource(\n source: string,\n language: GeneratedSourceLanguage,\n label = 'generated MCP source',\n): Promise<string> {\n if (language === 'typescript') {\n return source;\n }\n return transpileGeneratedSource(source, label);\n}\n"],"mappings":";AA6BA,IAAM,wBAAwB,CAAC,OAAO,MAAM;;;;;AAM5C,IAAM,sBAAsB,CAAC,QAAQ,MAAM;;;;;;AAS3C,eAAe,mBAA0C;CACvD,MAAM,EAAE,cAAc,MAAM,OAAO;CACnC,OAAO;AACT;AAEA,SAAS,mBAAmB,YAAoB,YAA0B;CACxE,MAAM,WAAW,oBAAoB,MAAM,cACzC,WAAW,SAAS,SAAS,CAC/B;CACA,IAAI,UACF,MAAM,IAAI,MACR,qCAAqC,WAAW,gDAAgD,SAAS,4EAC3G;AAEJ;;;;;;;;;;AAWA,SAAgB,+BACd,YACyB;CACzB,MAAM,aAAa,WAAW,YAAY;CAC1C,mBAAmB,YAAY,UAAU;CACzC,OAAO,sBAAsB,MAAM,cACjC,WAAW,SAAS,SAAS,CAC/B,IACI,eACA;AACN;;;;;;;;;;;;AAaA,SAAgB,0BACd,YAC0B;CAC1B,MAAM,aAAa,WAAW,YAAY;CAC1C,mBAAmB,YAAY,UAAU;CACzC,IAAI,WAAW,SAAS,MAAM,GAAG,OAAO;CACxC,IAAI,WAAW,SAAS,KAAK,GAAG,OAAO;CACvC,IAAI,WAAW,SAAS,MAAM,GAAG,OAAO;CACxC,OAAO;AACT;;;;;;;;;;;;;AAcA,eAAsB,yBACpB,QACA,QAAQ,wBACS;CAEjB,MAAM,EAAE,MAAM,WAAW,OAAM,MADP,iBAAiB,EAAA,CAEvC,gCACA,QACA;EAAE,MAAM;EAAM,YAAY;CAAS,CACrC;CACA,IAAI,OAAO,SAAS,GAAG;EACrB,MAAM,UAAU,OAAO,KAAK,eAAe,WAAW,OAAO,CAAC,CAAC,KAAK,IAAI;EACxE,MAAM,IAAI,MACR,6CAA6C,MAAM,KAAK,SAC1D;CACF;CAEA,OAAO;AACT;;;;;;;;;AAUA,eAAsB,sBACpB,QACA,UACA,QAAQ,wBACS;CACjB,IAAI,aAAa,cACf,OAAO;CAET,OAAO,yBAAyB,QAAQ,KAAK;AAC/C"}
package/dist/index.d.ts CHANGED
@@ -32,6 +32,7 @@ export { classifyDatabaseError, classifyDialectMessage, type DatabaseErrorClassi
32
32
  export { applyPendingDecoratorRegistrations, type CompatiblePropertyDecorator, type CompatiblePropertyDecoratorContext, type LegacyPropertyDecoratorTarget, registerCompatibleFieldDecorator, } from './decorators/compatibility';
33
33
  export { type CrossPackageRefOptions, crossPackageRef, type FieldOptions, type FieldUIHints, field, foreignKey, type Meta, manyToMany, meta, type NumericFieldOptions, oneToMany, type RelationshipFieldOptions, type TextFieldOptions, } from './decorators/index';
34
34
  export * from './dispatch/index';
35
+ export { isEmbeddedDatabase, usesEmbeddedRevisionFallback, withEmbeddedWriteQueue, withEmbeddedWriteTransaction, } from './embedded-write-queue';
35
36
  export * from './embeddings/index';
36
37
  export * from './errors';
37
38
  export { createFilesystemAdapter, type FilesystemAdapterFactory, registerFilesystemAdapterFactory, } from './filesystem-loader';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAGH,cAAc,kBAAkB,CAAC;AAEjC,OAAO,EACL,gBAAgB,EAChB,KAAK,WAAW,EAChB,KAAK,2BAA2B,EAChC,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,EACxB,KAAK,aAAa,EAClB,mBAAmB,EACnB,iBAAiB,EACjB,KAAK,cAAc,EACnB,gBAAgB,GACjB,MAAM,WAAW,CAAC;AAGnB,OAAO,EACL,KAAK,iBAAiB,EACtB,YAAY,EACZ,cAAc,EACd,4BAA4B,EAC5B,iBAAiB,EACjB,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,mBAAmB,EACxB,KAAK,eAAe,EACpB,qBAAqB,EACrB,qBAAqB,EACrB,KAAK,iBAAiB,EACtB,eAAe,EACf,eAAe,EACf,2BAA2B,EAC3B,iBAAiB,EACjB,eAAe,EACf,wBAAwB,EACxB,uBAAuB,EACvB,0BAA0B,GAC3B,MAAM,eAAe,CAAC;AAKvB,OAAO,EACL,qBAAqB,EACrB,KAAK,YAAY,EACjB,KAAK,oBAAoB,EACzB,kBAAkB,EAClB,yBAAyB,EACzB,wBAAwB,GACzB,MAAM,kBAAkB,CAAC;AAE1B,OAAO,EACL,4BAA4B,EAC5B,iBAAiB,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AAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAEpD,OAAO,EACL,eAAe,EACf,KAAK,mBAAmB,GACzB,MAAM,oBAAoB,CAAC;AAE5B,cAAc,eAAe,CAAC;AAE9B,OAAO,EACL,KAAK,EACL,cAAc,EACd,OAAO,EACP,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,EACL,KAAK,MAAM,EACX,KAAK,cAAc,EACnB,SAAS,EACT,aAAa,EACb,SAAS,GACV,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,mBAAmB,EACnB,YAAY,EACZ,2BAA2B,EAC3B,aAAa,EACb,eAAe,EACf,MAAM,EACN,KAAK,mBAAmB,EACxB,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAGH,cAAc,kBAAkB,CAAC;AAEjC,OAAO,EACL,gBAAgB,EAChB,KAAK,WAAW,EAChB,KAAK,2BAA2B,EAChC,KAAK,gBAAgB,EACrB,KAAK,mBAAmB,EACxB,KAAK,aAAa,EAClB,mBAAmB,EACnB,iBAAiB,EACjB,KAAK,cAAc,EACnB,gBAAgB,GACjB,MAAM,WAAW,CAAC;AAGnB,OAAO,EACL,KAAK,iBAAiB,EACtB,YAAY,EACZ,cAAc,EACd,4BAA4B,EAC5B,iBAAiB,EACjB,KAAK,eAAe,EACpB,KAAK,cAAc,EACnB,KAAK,mBAAmB,EACxB,KAAK,eAAe,EACpB,qBAAqB,EACrB,qBAAqB,EACrB,KAAK,iBAAiB,EACtB,eAAe,EACf,eAAe,EACf,2BAA2B,EAC3B,iBAAiB,EACjB,eAAe,EACf,wBAAwB,EACxB,uBAAuB,EACvB,0BAA0B,GAC3B,MAAM,eAAe,CAAC;AAKvB,OAAO,EACL,qBAA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E,MAAM,gBAAgB,CAAC;AAEvD,cAAc,iBAAiB,CAAC;AAGhC,cAAc,cAAc,CAAC;AAE7B,cAAc,gBAAgB,CAAC;AAC/B,YAAY,EACV,iBAAiB,EACjB,aAAa,EACb,kBAAkB,EAClB,YAAY,EACZ,WAAW,EACX,gBAAgB,EAChB,aAAa,EACb,iBAAiB,GAClB,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAEpD,OAAO,EACL,eAAe,EACf,KAAK,mBAAmB,GACzB,MAAM,oBAAoB,CAAC;AAE5B,cAAc,eAAe,CAAC;AAE9B,OAAO,EACL,KAAK,EACL,cAAc,EACd,OAAO,EACP,KAAK,WAAW,EAChB,KAAK,UAAU,EACf,KAAK,EACL,KAAK,MAAM,EACX,KAAK,cAAc,EACnB,SAAS,EACT,aAAa,EACb,SAAS,GACV,MAAM,cAAc,CAAC;AAEtB,OAAO,EACL,mBAAmB,EACnB,YAAY,EACZ,2BAA2B,EAC3B,aAAa,EACb,eAAe,EACf,MAAM,EACN,KAAK,mBAAmB,EACxB,kBAAkB,EAClB,mBAAmB,GACpB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAAE,UAAU,EAAE,MAAM,qBAAqB,CAAC"}
package/dist/index.js CHANGED
@@ -9,6 +9,7 @@ import { buildCascadePlan, cascadeReferencesTo, normalizeOnDelete, runCascadeDel
9
9
  import { CACHE_INVALIDATION_CHANNEL, broadcastCacheInvalidation, ensureCacheInvalidationListener, getCacheGeneration, invalidateCollectionCache, resetCollectionCache, resolveDbCacheKey, stopCacheInvalidationListeners } from "./collection-cache.js";
10
10
  import { CHANGE_SIGNAL_CHANNEL, resetChangeSignals, stopChangeSignalListeners, subscribeToChangeSignals } from "./change-signals.js";
11
11
  import { isTenantScopedClassResolved, resolveDispatchTenantId, resolveDispatchTenantScope, setDispatchTenantResolver, setTenantScopedClassResolver } from "./dispatch/tenant-resolver.js";
12
+ import { isEmbeddedDatabase, usesEmbeddedRevisionFallback, withEmbeddedWriteQueue, withEmbeddedWriteTransaction } from "./embedded-write-queue.js";
12
13
  import { GlobalInterceptors, createInterceptorContext, resolveGetStringFilter } from "./interceptors.js";
13
14
  import { detectEngine, generateDDLForEngine } from "./schema/ddl/index.js";
14
15
  import { SYSTEM_TABLE_NAMES, getSystemTableShapes } from "./schema/system-table-shapes.js";
@@ -65,7 +66,7 @@ import { generateOpenAPISpec, setupSwaggerUI } from "./generators/swagger.js";
65
66
  import "./generators/index.js";
66
67
  import { SmrtHierarchical } from "./hierarchical.js";
67
68
  import { SmrtJunction } from "./junction.js";
68
- import { MODULE_DOC_HASH_PREFIX, buildDomainKnowledgeManifest, readAgentModuleDocs, resolveAgentModuleDocPaths } from "./knowledge.js";
69
+ import { AGENT_SURFACE_HASH_PREFIX, MODULE_DOC_HASH_PREFIX, buildDomainKnowledgeManifest, readAgentModuleDocs, resolveAgentModuleDocPaths } from "./knowledge.js";
69
70
  import { getClassConfigResolvers, getConfigResolver, isLazyConfigSentinel, listConfigResolvers, registerConfigResolver, resetConfigResolvers, resolveLazyConfig, unregisterConfigResolver } from "./lazy-config.js";
70
71
  import { DEFAULT_LEARNING_CONFIG, LearningMemory } from "./learning/memory.js";
71
72
  import { ManifestBuilder } from "./manifest/generator.js";
@@ -84,4 +85,4 @@ import "./system/index.js";
84
85
  import { getTestDatabase } from "./testing/database.js";
85
86
  import "./tools/index.js";
86
87
  import { smrtPlugin } from "./vite-plugin/index.js";
87
- export { AIError, APIGenerator, AiUsageCollector, AiUsagePersistenceHandler, CACHE_INVALIDATION_CHANNEL, CHANGE_FEED_INTERCEPTOR_NAME, CHANGE_FEED_TABLE, CHANGE_SIGNAL_CHANNEL, CLIGenerator, ConfigurationError, ContentHasher, CosineSimilarity, DEFAULT_AI_COST_RATES, DEFAULT_CHANGES_LIMIT, DEFAULT_DATA_QUERY_PAGE_LIMIT, DEFAULT_DATA_QUERY_RESULT_BYTES, DEFAULT_EMBEDDING_CONFIG, DEFAULT_EVENTS_HEARTBEAT_MS, DEFAULT_EVENTS_MAX_SUBSCRIBERS, DEFAULT_EVENTS_RETRY_AFTER_SECONDS, DEFAULT_FACET_LIMIT, DEFAULT_LEARNING_CONFIG, DEFAULT_LIST_LIMIT, DEFAULT_LIST_ORDER_BY, DEFAULT_POSTGRES_TIMEOUTS, DEFAULT_RETENTION_POLICY, DataQueryValidationError, DatabaseError, Dispatch, DispatchBus, DispatchCollection, DispatchSubscription, DispatchSubscriptionCollection, EmbeddingProvider, EmbeddingStorage, ErrorUtils, FilesystemError, GlobalInterceptors, LearningMemory, LiveSchemaParityError, MAX_CHANGES_LIMIT, MAX_DATA_QUERY_CURSOR_LENGTH, MAX_DATA_QUERY_FACETS, MAX_DATA_QUERY_FILTERS, MAX_DATA_QUERY_FILTER_DEPTH, MAX_DATA_QUERY_IN_VALUES, MAX_DATA_QUERY_OFFSET, MAX_DATA_QUERY_PAGE_LIMIT, MAX_DATA_QUERY_REQUEST_BYTES, MAX_DATA_QUERY_RESULT_BYTES, MAX_DATA_QUERY_WARNINGS, MAX_FACET_FIELDS, MAX_FACET_LIMIT, MAX_LIST_LIMIT, MAX_STI_READ_SCOPE_TYPES, MAX_SYNC_APPLY_BATCH_SIZE, MCPGenerator, MCP_STABLE_CATALOG_TTL_MS, MODULE_DOC_HASH_PREFIX, ManifestBuilder, ManifestGenerator, ManifestManager, MetricsAdapter, NetworkError, ObjectRegistry, POSTGRES_TIMEOUT_ENV_VARS, PRIVATE_READ_CACHE_CONTROL, PubSubAdapter, QueryBoundsError, QueryOrderByError, RuntimeError, SMRT_COLLECTION_BASE_NAMES, SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY, SYNC_APPLY_ROUTE_SEGMENTS, SYNC_APPLY_UUID_PATTERN, SYSTEM_TABLE_NAMES, SchemaComparer, SignalBus, SignalSanitizer, SmrtClass, SmrtCollection, SmrtError, SmrtHierarchical, SmrtJunction, SmrtMCPServer, SmrtObject, SmrtPolymorphicAssociation, TenantIsolationError, ValidationError, ValidationReport, ValidationUtils, appendChange, applyOneToManyChildAccessors, applyPendingDecoratorRegistrations, applyPostgresRuntimeTimeouts, applySyncWritablePolicy, assertPostgresSystemTimestampsCurrent, broadcastCacheInvalidation, buildCascadePlan, buildChangeEventStream, buildCustomActionInputSchema, buildCustomActionInvocationArgs, buildDefaultListOrderBy, buildDomainKnowledgeManifest, bumpChangeFeed, canonicalReadRepresentation, canonicalizeDataQuery, cascadeReferencesTo, changeEventSubscribersAtCapacity, checkLiveSchemaParity, childAccessorName, classifyDatabaseError, classifyDialectMessage, clearRetentionTasks, clone, computeBodyEtag, computeRuntimeWebManifestHash, computeTableVersionEtag, conditionalJsonResponse, config, convertTypeToJsonSchema, createDataQueryFingerprint, createDispatchBus, createFilesystemAdapter, createInterceptorContext, createMCPServer, createQualifiedName, createRestServer, createSmrtClient, createSmrtServer, crossPackageRef, customActionParameterInputName, detectEngine, discoverManifestEntry, ensureBootstrapSystemTableCompatibility, ensureCacheInvalidationListener, ensureChangeFeedTable, ensureDeferredSystemTableCompatibility, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, ensureSystemTables, estimateAiUsageCost, eventStreamCapacityExceededResponse, executeCollectionReadPlan, executeToolCall, executeToolCalls, field, findManifestEntryByQualifiedName, foreignKey, formatToolResults, generateDDLForEngine, generateOpenAPISpec, generateSchemaDiff, generateToolFromMethod, generateToolManifest, getAdapterInfo, getCLIHandler, getCacheGeneration, getChangesSince, getClassConfigResolvers, getClassName, getConfigResolver, getDatabaseEngine, getManifest, getPackageFromQualifiedName, getRetentionTasks, getSQLFromDiff, getSystemTableShapes, getTableVersion, getTenantScopedChangesSince, getTestDatabase, hasActionableChanges, ifNoneMatchHasConcreteMatch, ifNoneMatchSatisfied, importOptionalDependency, invalidateCollectionCache, isAbortedTransactionError, isAdvisoryOnlyChange, isDatabaseInterface, isDeterministicDatabaseError, isFromPackage, isLazyConfigSentinel, isManualOrAdvisoryChange, isNotNullViolationError, isQualifiedName, isSmrtCollectionExtendsName, isStaleWrite, isTenantScopedClassResolved, isTransientDatabaseError, isType, isUniqueViolationError, isValid, listConfigResolvers, loadExternalManifest, loadExternalManifestSync, loadLocalTestManifestSync, loadManifestFromPathSync, manifest, manyToMany, meta, migratePostgresSystemTimestamps, normalizeCustomActionFailure, normalizeDataQueryRequest, normalizeDataQueryResult, normalizeDataQuerySchema, normalizeEventsMaxSubscribers, normalizeOnDelete, normalizeTypedHttpError, oneToMany, parse, parseQualifiedName, parseSyncApplyBatch, payloadMatchesRow, planForeignKeyCreation, planPostgresSystemTimestampMigrations, processSyncApplyBatch, pruneAiUsage, pruneChangeFeed, pruneExpiredContexts, qualifiedNamesEqual, readAgentModuleDocs, registerChangeFeedWriter, registerCompatibleFieldDecorator, registerConfigResolver, registerFilesystemAdapterFactory, registerOptionalDependency, registerRetentionTask, resetChangeFeedWarnings, resetChangeSignals, resetCollectionCache, resetConfigResolvers, resetVerifiedTables, resolveAgentModuleDocPaths, resolveCustomActionMetadata, resolveDatabase, resolveDbCacheKey, resolveDispatchTenantId, resolveDispatchTenantScope, resolveGetStringFilter, resolveLazyConfig, resolveListLimit, resolveListOffset, resolveMCPToolListCacheHint, resolvePostgresTimeouts, resolveReadCacheControl, resolveTenantEtagDiscriminator, runCascadeDelete, runRetentionSweep, runWithTenantGate, safeParse, safeStringify, setDispatchTenantResolver, setTenantEntryPointRunner, setTenantScopedClassResolver, setupCLI, setupSwaggerUI, shouldIncludeMethod, signalVisibleToTenant, smrt, smrtPlugin, smrt as smrtRegistry, sortMCPTools, startRestServer, staticManifest, stopCacheInvalidationListeners, stopChangeSignalListeners, stringify, subscribeToChangeSignals, tableExists, tryReserveChangeEventSubscriberSlot, unregisterChangeFeedWriter, unregisterConfigResolver, unregisterRetentionTask, validateSyncApplyItem, validateToolCall, versionConditionalResponse, warnIfSharedCacheNeutralized };
88
+ export { AGENT_SURFACE_HASH_PREFIX, AIError, APIGenerator, AiUsageCollector, AiUsagePersistenceHandler, CACHE_INVALIDATION_CHANNEL, CHANGE_FEED_INTERCEPTOR_NAME, CHANGE_FEED_TABLE, CHANGE_SIGNAL_CHANNEL, CLIGenerator, ConfigurationError, ContentHasher, CosineSimilarity, DEFAULT_AI_COST_RATES, DEFAULT_CHANGES_LIMIT, DEFAULT_DATA_QUERY_PAGE_LIMIT, DEFAULT_DATA_QUERY_RESULT_BYTES, DEFAULT_EMBEDDING_CONFIG, DEFAULT_EVENTS_HEARTBEAT_MS, DEFAULT_EVENTS_MAX_SUBSCRIBERS, DEFAULT_EVENTS_RETRY_AFTER_SECONDS, DEFAULT_FACET_LIMIT, DEFAULT_LEARNING_CONFIG, DEFAULT_LIST_LIMIT, DEFAULT_LIST_ORDER_BY, DEFAULT_POSTGRES_TIMEOUTS, DEFAULT_RETENTION_POLICY, DataQueryValidationError, DatabaseError, Dispatch, DispatchBus, DispatchCollection, DispatchSubscription, DispatchSubscriptionCollection, EmbeddingProvider, EmbeddingStorage, ErrorUtils, FilesystemError, GlobalInterceptors, LearningMemory, LiveSchemaParityError, MAX_CHANGES_LIMIT, MAX_DATA_QUERY_CURSOR_LENGTH, MAX_DATA_QUERY_FACETS, MAX_DATA_QUERY_FILTERS, MAX_DATA_QUERY_FILTER_DEPTH, MAX_DATA_QUERY_IN_VALUES, MAX_DATA_QUERY_OFFSET, MAX_DATA_QUERY_PAGE_LIMIT, MAX_DATA_QUERY_REQUEST_BYTES, MAX_DATA_QUERY_RESULT_BYTES, MAX_DATA_QUERY_WARNINGS, MAX_FACET_FIELDS, MAX_FACET_LIMIT, MAX_LIST_LIMIT, MAX_STI_READ_SCOPE_TYPES, MAX_SYNC_APPLY_BATCH_SIZE, MCPGenerator, MCP_STABLE_CATALOG_TTL_MS, MODULE_DOC_HASH_PREFIX, ManifestBuilder, ManifestGenerator, ManifestManager, MetricsAdapter, NetworkError, ObjectRegistry, POSTGRES_TIMEOUT_ENV_VARS, PRIVATE_READ_CACHE_CONTROL, PubSubAdapter, QueryBoundsError, QueryOrderByError, RuntimeError, SMRT_COLLECTION_BASE_NAMES, SMRT_CUSTOM_ACTION_ERROR_METADATA_KEY, SYNC_APPLY_ROUTE_SEGMENTS, SYNC_APPLY_UUID_PATTERN, SYSTEM_TABLE_NAMES, SchemaComparer, SignalBus, SignalSanitizer, SmrtClass, SmrtCollection, SmrtError, SmrtHierarchical, SmrtJunction, SmrtMCPServer, SmrtObject, SmrtPolymorphicAssociation, TenantIsolationError, ValidationError, ValidationReport, ValidationUtils, appendChange, applyOneToManyChildAccessors, applyPendingDecoratorRegistrations, applyPostgresRuntimeTimeouts, applySyncWritablePolicy, assertPostgresSystemTimestampsCurrent, broadcastCacheInvalidation, buildCascadePlan, buildChangeEventStream, buildCustomActionInputSchema, buildCustomActionInvocationArgs, buildDefaultListOrderBy, buildDomainKnowledgeManifest, bumpChangeFeed, canonicalReadRepresentation, canonicalizeDataQuery, cascadeReferencesTo, changeEventSubscribersAtCapacity, checkLiveSchemaParity, childAccessorName, classifyDatabaseError, classifyDialectMessage, clearRetentionTasks, clone, computeBodyEtag, computeRuntimeWebManifestHash, computeTableVersionEtag, conditionalJsonResponse, config, convertTypeToJsonSchema, createDataQueryFingerprint, createDispatchBus, createFilesystemAdapter, createInterceptorContext, createMCPServer, createQualifiedName, createRestServer, createSmrtClient, createSmrtServer, crossPackageRef, customActionParameterInputName, detectEngine, discoverManifestEntry, ensureBootstrapSystemTableCompatibility, ensureCacheInvalidationListener, ensureChangeFeedTable, ensureDeferredSystemTableCompatibility, ensureDispatchSubscriptionsSystemTableCompatibility, ensureDispatchSystemTableCompatibility, ensureJobEventsSystemTableCompatibility, ensureJobsSystemTableCompatibility, ensureLegacySystemTableCompatibility, ensureSystemTables, estimateAiUsageCost, eventStreamCapacityExceededResponse, executeCollectionReadPlan, executeToolCall, executeToolCalls, field, findManifestEntryByQualifiedName, foreignKey, formatToolResults, generateDDLForEngine, generateOpenAPISpec, generateSchemaDiff, generateToolFromMethod, generateToolManifest, getAdapterInfo, getCLIHandler, getCacheGeneration, getChangesSince, getClassConfigResolvers, getClassName, getConfigResolver, getDatabaseEngine, getManifest, getPackageFromQualifiedName, getRetentionTasks, getSQLFromDiff, getSystemTableShapes, getTableVersion, getTenantScopedChangesSince, getTestDatabase, hasActionableChanges, ifNoneMatchHasConcreteMatch, ifNoneMatchSatisfied, importOptionalDependency, invalidateCollectionCache, isAbortedTransactionError, isAdvisoryOnlyChange, isDatabaseInterface, isDeterministicDatabaseError, isEmbeddedDatabase, isFromPackage, isLazyConfigSentinel, isManualOrAdvisoryChange, isNotNullViolationError, isQualifiedName, isSmrtCollectionExtendsName, isStaleWrite, isTenantScopedClassResolved, isTransientDatabaseError, isType, isUniqueViolationError, isValid, listConfigResolvers, loadExternalManifest, loadExternalManifestSync, loadLocalTestManifestSync, loadManifestFromPathSync, manifest, manyToMany, meta, migratePostgresSystemTimestamps, normalizeCustomActionFailure, normalizeDataQueryRequest, normalizeDataQueryResult, normalizeDataQuerySchema, normalizeEventsMaxSubscribers, normalizeOnDelete, normalizeTypedHttpError, oneToMany, parse, parseQualifiedName, parseSyncApplyBatch, payloadMatchesRow, planForeignKeyCreation, planPostgresSystemTimestampMigrations, processSyncApplyBatch, pruneAiUsage, pruneChangeFeed, pruneExpiredContexts, qualifiedNamesEqual, readAgentModuleDocs, registerChangeFeedWriter, registerCompatibleFieldDecorator, registerConfigResolver, registerFilesystemAdapterFactory, registerOptionalDependency, registerRetentionTask, resetChangeFeedWarnings, resetChangeSignals, resetCollectionCache, resetConfigResolvers, resetVerifiedTables, resolveAgentModuleDocPaths, resolveCustomActionMetadata, resolveDatabase, resolveDbCacheKey, resolveDispatchTenantId, resolveDispatchTenantScope, resolveGetStringFilter, resolveLazyConfig, resolveListLimit, resolveListOffset, resolveMCPToolListCacheHint, resolvePostgresTimeouts, resolveReadCacheControl, resolveTenantEtagDiscriminator, runCascadeDelete, runRetentionSweep, runWithTenantGate, safeParse, safeStringify, setDispatchTenantResolver, setTenantEntryPointRunner, setTenantScopedClassResolver, setupCLI, setupSwaggerUI, shouldIncludeMethod, signalVisibleToTenant, smrt, smrtPlugin, smrt as smrtRegistry, sortMCPTools, startRestServer, staticManifest, stopCacheInvalidationListeners, stopChangeSignalListeners, stringify, subscribeToChangeSignals, tableExists, tryReserveChangeEventSubscriberSlot, unregisterChangeFeedWriter, unregisterConfigResolver, unregisterRetentionTask, usesEmbeddedRevisionFallback, validateSyncApplyItem, validateToolCall, versionConditionalResponse, warnIfSharedCacheNeutralized, withEmbeddedWriteQueue, withEmbeddedWriteTransaction };
@@ -1,4 +1,4 @@
1
- import { DomainKnowledgeConfig, DomainKnowledgeManifest, DomainKnowledgeModuleDoc } from '@happyvertical/smrt-types';
1
+ import { DomainKnowledgeAgentSurface, DomainKnowledgeConfig, DomainKnowledgeManifest, DomainKnowledgeModuleDoc } from '@happyvertical/smrt-types';
2
2
  import { SmartObjectManifest } from './scanner/types.js';
3
3
  /**
4
4
  * Minimal package.json shape consumed by the knowledge builder.
@@ -17,9 +17,25 @@ export interface BuildDomainKnowledgeOptions {
17
17
  packageJson?: PackageJsonLike;
18
18
  manifestPath?: string;
19
19
  config?: DomainKnowledgeConfig;
20
+ /**
21
+ * The package's declared view intents and playbooks (#2591), produced by the
22
+ * scanner's agent-surface matcher.
23
+ *
24
+ * Passed in rather than scanned here for one reason: the scanner carries a
25
+ * native parser binary, and `smrt-core`'s main entry is browser-reachable.
26
+ * The Vite plugin already imports the scanner lazily on the Node side and is
27
+ * the one caller that writes this artifact, so it does the scan and hands the
28
+ * result over.
29
+ */
30
+ agentSurface?: DomainKnowledgeAgentSurface;
20
31
  }
21
32
  /** `sourceHashes` key prefix for a linked module doc, e.g. `moduleDoc:agents/crm.md`. */
22
33
  export declare const MODULE_DOC_HASH_PREFIX = "moduleDoc:";
34
+ /**
35
+ * `sourceHashes` key prefix for a module declaring a view intent or playbook,
36
+ * e.g. `agentSurface:src/lib/orders.intents.ts` (#2591).
37
+ */
38
+ export declare const AGENT_SURFACE_HASH_PREFIX = "agentSurface:";
23
39
  /**
24
40
  * Module doc paths linked from a package's `AGENTS.md`, relative to the package
25
41
  * root and in document order.
@@ -1 +1 @@
1
- {"version":3,"file":"knowledge.d.ts","sourceRoot":"","sources":["../src/knowledge.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,qBAAqB,EAGrB,uBAAuB,EAEvB,wBAAwB,EAIzB,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAEV,mBAAmB,EACpB,MAAM,oBAAoB,CAAC;AAG5B;;;;;GAKG;AACH,MAAM,WAAW,eAAe;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,2BAA2B;IAC1C,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,MAAM,CAAC,EAAE,qBAAqB,CAAC;CAChC;AA2CD,yFAAyF;AACzF,eAAO,MAAM,sBAAsB,eAAe,CAAC;AAEnD;;;;;;;;;;GAUG;AACH,wBAAgB,0BAA0B,CACxC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,GAAG,SAAS,GAC3B,MAAM,EAAE,CAgBV;AAED,yEAAyE;AACzE,wBAAgB,mBAAmB,CACjC,OAAO,EAAE,MAAM,EACf,QAAQ,EAAE,MAAM,GAAG,SAAS,GAC3B,wBAAwB,EAAE,CAM5B;AAED,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,2BAA2B,GACnC,uBAAuB,CAqEzB"}
1
+ {"version":3,"file":"knowledge.d.ts","sourceRoot":"","sources":["../src/knowledge.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,2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