@hatk/hatk 0.0.1-alpha.1 → 0.0.1-alpha.100

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 (226) hide show
  1. package/dist/adapter.d.ts +19 -0
  2. package/dist/adapter.d.ts.map +1 -0
  3. package/dist/adapter.js +113 -0
  4. package/dist/backfill.d.ts +90 -1
  5. package/dist/backfill.d.ts.map +1 -1
  6. package/dist/backfill.js +254 -55
  7. package/dist/car.d.ts +59 -1
  8. package/dist/car.d.ts.map +1 -1
  9. package/dist/car.js +179 -7
  10. package/dist/cbor.d.ts +37 -0
  11. package/dist/cbor.d.ts.map +1 -1
  12. package/dist/cbor.js +36 -3
  13. package/dist/cid.d.ts +37 -0
  14. package/dist/cid.d.ts.map +1 -1
  15. package/dist/cid.js +38 -3
  16. package/dist/cli.js +247 -986
  17. package/dist/config.d.ts +145 -1
  18. package/dist/config.d.ts.map +1 -1
  19. package/dist/config.js +62 -9
  20. package/dist/database/adapter-factory.d.ts +6 -0
  21. package/dist/database/adapter-factory.d.ts.map +1 -0
  22. package/dist/database/adapter-factory.js +20 -0
  23. package/dist/database/adapters/duckdb-search.d.ts +12 -0
  24. package/dist/database/adapters/duckdb-search.d.ts.map +1 -0
  25. package/dist/database/adapters/duckdb-search.js +27 -0
  26. package/dist/database/adapters/duckdb.d.ts +25 -0
  27. package/dist/database/adapters/duckdb.d.ts.map +1 -0
  28. package/dist/database/adapters/duckdb.js +161 -0
  29. package/dist/database/adapters/sqlite-search.d.ts +16 -0
  30. package/dist/database/adapters/sqlite-search.d.ts.map +1 -0
  31. package/dist/database/adapters/sqlite-search.js +76 -0
  32. package/dist/database/adapters/sqlite.d.ts +18 -0
  33. package/dist/database/adapters/sqlite.d.ts.map +1 -0
  34. package/dist/database/adapters/sqlite.js +88 -0
  35. package/dist/{db.d.ts → database/db.d.ts} +94 -6
  36. package/dist/database/db.d.ts.map +1 -0
  37. package/dist/database/db.js +1833 -0
  38. package/dist/database/dialect.d.ts +45 -0
  39. package/dist/database/dialect.d.ts.map +1 -0
  40. package/dist/database/dialect.js +72 -0
  41. package/dist/{fts.d.ts → database/fts.d.ts} +7 -0
  42. package/dist/database/fts.d.ts.map +1 -0
  43. package/dist/{fts.js → database/fts.js} +122 -34
  44. package/dist/database/index.d.ts +7 -0
  45. package/dist/database/index.d.ts.map +1 -0
  46. package/dist/database/index.js +6 -0
  47. package/dist/database/ports.d.ts +50 -0
  48. package/dist/database/ports.d.ts.map +1 -0
  49. package/dist/database/ports.js +1 -0
  50. package/dist/database/schema.d.ts +91 -0
  51. package/dist/database/schema.d.ts.map +1 -0
  52. package/dist/{schema.js → database/schema.js} +153 -54
  53. package/dist/dev-entry.d.ts +8 -0
  54. package/dist/dev-entry.d.ts.map +1 -0
  55. package/dist/dev-entry.js +126 -0
  56. package/dist/feeds.d.ts +26 -8
  57. package/dist/feeds.d.ts.map +1 -1
  58. package/dist/feeds.js +72 -16
  59. package/dist/hooks.d.ts +102 -0
  60. package/dist/hooks.d.ts.map +1 -0
  61. package/dist/hooks.js +186 -0
  62. package/dist/hydrate.d.ts +55 -6
  63. package/dist/hydrate.d.ts.map +1 -1
  64. package/dist/hydrate.js +21 -20
  65. package/dist/indexer.d.ts +195 -3
  66. package/dist/indexer.d.ts.map +1 -1
  67. package/dist/indexer.js +634 -94
  68. package/dist/jetstream.d.ts +118 -0
  69. package/dist/jetstream.d.ts.map +1 -0
  70. package/dist/jetstream.js +238 -0
  71. package/dist/labels.d.ts +36 -0
  72. package/dist/labels.d.ts.map +1 -1
  73. package/dist/labels.js +71 -6
  74. package/dist/lex-types.d.ts +2 -0
  75. package/dist/lex-types.d.ts.map +1 -1
  76. package/dist/lexicon-resolve.d.ts.map +1 -1
  77. package/dist/lexicon-resolve.js +27 -112
  78. package/dist/lexicons/com/atproto/label/defs.json +75 -0
  79. package/dist/lexicons/com/atproto/moderation/defs.json +30 -0
  80. package/dist/lexicons/com/atproto/repo/strongRef.json +21 -0
  81. package/dist/lexicons/dev/hatk/applyWrites.json +87 -0
  82. package/dist/lexicons/dev/hatk/createRecord.json +40 -0
  83. package/dist/lexicons/dev/hatk/createReport.json +48 -0
  84. package/dist/lexicons/dev/hatk/deleteRecord.json +25 -0
  85. package/dist/lexicons/dev/hatk/describeCollections.json +41 -0
  86. package/dist/lexicons/dev/hatk/describeFeeds.json +29 -0
  87. package/dist/lexicons/dev/hatk/describeLabels.json +45 -0
  88. package/dist/lexicons/dev/hatk/getFeed.json +30 -0
  89. package/dist/lexicons/dev/hatk/getPreferences.json +19 -0
  90. package/dist/lexicons/dev/hatk/getRecord.json +26 -0
  91. package/dist/lexicons/dev/hatk/getRecords.json +32 -0
  92. package/dist/lexicons/dev/hatk/putPreference.json +28 -0
  93. package/dist/lexicons/dev/hatk/putRecord.json +41 -0
  94. package/dist/lexicons/dev/hatk/searchRecords.json +32 -0
  95. package/dist/lexicons/dev/hatk/uploadBlob.json +23 -0
  96. package/dist/logger.d.ts +29 -0
  97. package/dist/logger.d.ts.map +1 -1
  98. package/dist/logger.js +29 -0
  99. package/dist/main.js +197 -75
  100. package/dist/mst.d.ts +18 -1
  101. package/dist/mst.d.ts.map +1 -1
  102. package/dist/mst.js +19 -8
  103. package/dist/oauth/db.d.ts +27 -1
  104. package/dist/oauth/db.d.ts.map +1 -1
  105. package/dist/oauth/db.js +80 -19
  106. package/dist/oauth/discovery.d.ts +10 -0
  107. package/dist/oauth/discovery.d.ts.map +1 -1
  108. package/dist/oauth/discovery.js +54 -2
  109. package/dist/oauth/server.d.ts +131 -1
  110. package/dist/oauth/server.d.ts.map +1 -1
  111. package/dist/oauth/server.js +504 -39
  112. package/dist/oauth/service-describe.d.ts +42 -0
  113. package/dist/oauth/service-describe.d.ts.map +1 -0
  114. package/dist/oauth/service-describe.js +108 -0
  115. package/dist/oauth/session.d.ts +32 -0
  116. package/dist/oauth/session.d.ts.map +1 -0
  117. package/dist/oauth/session.js +131 -0
  118. package/dist/opengraph.d.ts +10 -0
  119. package/dist/opengraph.d.ts.map +1 -1
  120. package/dist/opengraph.js +94 -42
  121. package/dist/pds-proxy.d.ts +92 -0
  122. package/dist/pds-proxy.d.ts.map +1 -0
  123. package/dist/pds-proxy.js +396 -0
  124. package/dist/private-collections.d.ts +13 -0
  125. package/dist/private-collections.d.ts.map +1 -0
  126. package/dist/private-collections.js +27 -0
  127. package/dist/push.d.ts +54 -0
  128. package/dist/push.d.ts.map +1 -0
  129. package/dist/push.js +367 -0
  130. package/dist/renderer.d.ts +27 -0
  131. package/dist/renderer.d.ts.map +1 -0
  132. package/dist/renderer.js +46 -0
  133. package/dist/resolve-hatk.d.ts +6 -0
  134. package/dist/resolve-hatk.d.ts.map +1 -0
  135. package/dist/resolve-hatk.js +20 -0
  136. package/dist/response.d.ts +16 -0
  137. package/dist/response.d.ts.map +1 -0
  138. package/dist/response.js +69 -0
  139. package/dist/scanner.d.ts +21 -0
  140. package/dist/scanner.d.ts.map +1 -0
  141. package/dist/scanner.js +88 -0
  142. package/dist/seed.d.ts +19 -0
  143. package/dist/seed.d.ts.map +1 -1
  144. package/dist/seed.js +43 -4
  145. package/dist/server-init.d.ts +8 -0
  146. package/dist/server-init.d.ts.map +1 -0
  147. package/dist/server-init.js +62 -0
  148. package/dist/server.d.ts +34 -3
  149. package/dist/server.d.ts.map +1 -1
  150. package/dist/server.js +1053 -626
  151. package/dist/setup.d.ts +28 -1
  152. package/dist/setup.d.ts.map +1 -1
  153. package/dist/setup.js +50 -3
  154. package/dist/spaces/blob.d.ts +112 -0
  155. package/dist/spaces/blob.d.ts.map +1 -0
  156. package/dist/spaces/blob.js +460 -0
  157. package/dist/spaces/credential.d.ts +62 -0
  158. package/dist/spaces/credential.d.ts.map +1 -0
  159. package/dist/spaces/credential.js +184 -0
  160. package/dist/spaces/engine.d.ts +97 -0
  161. package/dist/spaces/engine.d.ts.map +1 -0
  162. package/dist/spaces/engine.js +559 -0
  163. package/dist/spaces/guard.d.ts +41 -0
  164. package/dist/spaces/guard.d.ts.map +1 -0
  165. package/dist/spaces/guard.js +79 -0
  166. package/dist/spaces/identity.d.ts +37 -0
  167. package/dist/spaces/identity.d.ts.map +1 -0
  168. package/dist/spaces/identity.js +88 -0
  169. package/dist/spaces/index.d.ts +55 -0
  170. package/dist/spaces/index.d.ts.map +1 -0
  171. package/dist/spaces/index.js +133 -0
  172. package/dist/spaces/notify.d.ts +51 -0
  173. package/dist/spaces/notify.d.ts.map +1 -0
  174. package/dist/spaces/notify.js +121 -0
  175. package/dist/spaces/records.d.ts +37 -0
  176. package/dist/spaces/records.d.ts.map +1 -0
  177. package/dist/spaces/records.js +63 -0
  178. package/dist/spaces/store.d.ts +51 -0
  179. package/dist/spaces/store.d.ts.map +1 -0
  180. package/dist/spaces/store.js +99 -0
  181. package/dist/spaces/uri.d.ts +60 -0
  182. package/dist/spaces/uri.d.ts.map +1 -0
  183. package/dist/spaces/uri.js +97 -0
  184. package/dist/spaces/verify.d.ts +46 -0
  185. package/dist/spaces/verify.d.ts.map +1 -0
  186. package/dist/spaces/verify.js +94 -0
  187. package/dist/spaces/viewer.d.ts +51 -0
  188. package/dist/spaces/viewer.d.ts.map +1 -0
  189. package/dist/spaces/viewer.js +167 -0
  190. package/dist/spaces/visibility.d.ts +57 -0
  191. package/dist/spaces/visibility.d.ts.map +1 -0
  192. package/dist/spaces/visibility.js +81 -0
  193. package/dist/templates/feed.tpl +18 -0
  194. package/dist/templates/hook.tpl +5 -0
  195. package/dist/templates/label.tpl +15 -0
  196. package/dist/templates/og.tpl +17 -0
  197. package/dist/templates/seed.tpl +11 -0
  198. package/dist/templates/setup.tpl +5 -0
  199. package/dist/templates/test-feed.tpl +19 -0
  200. package/dist/templates/test-xrpc.tpl +19 -0
  201. package/dist/templates/xrpc.tpl +53 -0
  202. package/dist/test.d.ts +3 -1
  203. package/dist/test.d.ts.map +1 -1
  204. package/dist/test.js +60 -36
  205. package/dist/views.js +1 -1
  206. package/dist/vite-plugin.d.ts +1 -1
  207. package/dist/vite-plugin.d.ts.map +1 -1
  208. package/dist/vite-plugin.js +254 -65
  209. package/dist/xrpc.d.ts +122 -12
  210. package/dist/xrpc.d.ts.map +1 -1
  211. package/dist/xrpc.js +270 -55
  212. package/package.json +34 -10
  213. package/public/admin-auth.js +271 -306
  214. package/public/admin.html +177 -61
  215. package/public/robots.txt +2 -0
  216. package/dist/db.d.ts.map +0 -1
  217. package/dist/db.js +0 -1361
  218. package/dist/fts.d.ts.map +0 -1
  219. package/dist/oauth/hooks.d.ts +0 -10
  220. package/dist/oauth/hooks.d.ts.map +0 -1
  221. package/dist/oauth/hooks.js +0 -40
  222. package/dist/schema.d.ts +0 -51
  223. package/dist/schema.d.ts.map +0 -1
  224. package/dist/test-browser.d.ts +0 -14
  225. package/dist/test-browser.d.ts.map +0 -1
  226. package/dist/test-browser.js +0 -26
package/dist/xrpc.js CHANGED
@@ -6,12 +6,42 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
6
6
  }
7
7
  return path;
8
8
  };
9
+ /**
10
+ * XRPC method handler system for serving AT Protocol endpoints.
11
+ *
12
+ * Place handler modules in the `xrpc/` directory, nested by NSID segments
13
+ * (e.g. `xrpc/app/bsky/feed/getAuthorFeed.ts` → `app.bsky.feed.getAuthorFeed`).
14
+ * Each module default-exports a `{ handler }` function that receives an
15
+ * {@link XrpcContext} with database access, query params, pagination, and
16
+ * viewer auth.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * // xrpc/xyz/statusphere/getStatuses.ts
21
+ * import { defineXrpc } from '../../hatk.generated.ts'
22
+ *
23
+ * export default defineXrpc('xyz.statusphere.getStatuses', async (ctx) => {
24
+ * const rows = await ctx.db.query('SELECT * FROM statusphere_status LIMIT ?', [ctx.limit])
25
+ * return { statuses: rows }
26
+ * })
27
+ * ```
28
+ */
29
+ import { guardedQuerySQL, unfilteredQuerySQL } from "./spaces/guard.js";
9
30
  import { resolve, relative } from 'node:path';
10
31
  import { readdirSync, statSync } from 'node:fs';
11
- import { log } from "./logger.js";
12
- import { querySQL, runSQL, packCursor, unpackCursor, isTakendownDid, filterTakendownDids, searchRecords, findUriByFields, lookupByFieldBatch, countByFieldBatch, queryLabelsForUris, } from "./db.js";
13
- import { resolveRecords } from "./hydrate.js";
14
- import { getLexicon } from "./schema.js";
32
+ import { log, emit, timer } from "./logger.js";
33
+ import { runSQL, packCursor, unpackCursor, isTakendownDid, filterTakendownDids, searchRecords, findUriByFields, } from "./database/db.js";
34
+ import { resolveRecords, buildBaseContext } from "./hydrate.js";
35
+ import { getLexicon } from "./database/schema.js";
36
+ import { createHmac } from 'node:crypto';
37
+ import { pdsCreateRecord, pdsPutRecord, pdsDeleteRecord, pdsApplyWrites, pdsXrpc } from "./pds-proxy.js";
38
+ import { obtainSession, ObtainSessionError } from "./oauth/server.js";
39
+ let _oauthConfig = null;
40
+ /** Set the OAuth config used for record write helpers. Called once during boot. */
41
+ export function configureOAuth(config) {
42
+ _oauthConfig = config;
43
+ }
44
+ /** Thrown from XRPC handlers to return a 400 response with an error message. */
15
45
  export class InvalidRequestError extends Error {
16
46
  status = 400;
17
47
  errorName;
@@ -20,6 +50,7 @@ export class InvalidRequestError extends Error {
20
50
  this.errorName = errorName;
21
51
  }
22
52
  }
53
+ /** Thrown from XRPC handlers to return a 404 response. */
23
54
  export class NotFoundError extends InvalidRequestError {
24
55
  status = 404;
25
56
  constructor(message = 'Not found') {
@@ -27,21 +58,138 @@ export class NotFoundError extends InvalidRequestError {
27
58
  }
28
59
  }
29
60
  let _relayUrl = '';
61
+ let _cdn = null;
62
+ /** Set the relay URL used for blob URL generation. Called once during boot. */
63
+ /** True when the relay is a loopback URL — a dev PDS rather than the network. */
64
+ export function isLocalRelay() {
65
+ try {
66
+ const host = new URL(_relayUrl).hostname;
67
+ return (host === 'localhost' || host === '127.0.0.1' || host === '[::1]' || host === '::1' || host.endsWith('.localhost'));
68
+ }
69
+ catch {
70
+ return false;
71
+ }
72
+ }
30
73
  export function configureRelay(relay) {
31
74
  _relayUrl = relay;
32
75
  }
76
+ /** Set the CDN config for imgproxy URL signing. Called once during boot. */
77
+ export function configureCdn(cdn) {
78
+ if (cdn) {
79
+ _cdn = {
80
+ url: cdn.url.replace(/\/$/, ''),
81
+ key: Buffer.from(cdn.key, 'hex'),
82
+ salt: Buffer.from(cdn.salt, 'hex'),
83
+ };
84
+ }
85
+ else {
86
+ _cdn = null;
87
+ }
88
+ }
89
+ /** Sign an imgproxy path with HMAC-SHA256 (URL-safe base64). */
90
+ function signPath(path) {
91
+ const hmac = createHmac('sha256', _cdn.key);
92
+ hmac.update(_cdn.salt);
93
+ hmac.update(path);
94
+ const sig = hmac.digest('base64url');
95
+ return `/${sig}${path}`;
96
+ }
97
+ /**
98
+ * Generate a CDN URL for a blob ref. Uses the PDS directly in local dev,
99
+ * a configured imgproxy CDN if available, or the Bluesky CDN as fallback.
100
+ */
33
101
  export function blobUrl(did, ref, preset = 'avatar') {
34
102
  if (!ref)
35
103
  return undefined;
36
104
  const p = typeof ref === 'string' ? JSON.parse(ref) : ref;
37
105
  if (!p?.ref?.$link)
38
106
  return undefined;
39
- if (_relayUrl.includes('localhost:2583')) {
40
- return `http://localhost:2583/xrpc/com.atproto.sync.getBlob?did=${did}&cid=${p.ref.$link}`;
107
+ // A local network has no image CDN. Serve blobs through the dev proxy
108
+ // (see /blob/ in server.ts), which fetches from each repo's own PDS — on a
109
+ // multi-PDS dev stack the repos are not all behind the relay being tailed.
110
+ if (isLocalRelay()) {
111
+ return `/blob/${did}/${p.ref.$link}`;
112
+ }
113
+ if (_cdn) {
114
+ const path = `/${preset}/plain/${did}/${p.ref.$link}`;
115
+ return `${_cdn.url}${signPath(path)}`;
41
116
  }
42
117
  return `https://cdn.bsky.app/img/${preset}/plain/${did}/${p.ref.$link}@jpeg`;
43
118
  }
119
+ /** Build a full XrpcContext from request parameters. Reuses buildBaseContext for shared fields. */
120
+ export function buildXrpcContext(params, cursor, limit, viewer, input) {
121
+ const base = buildBaseContext(viewer);
122
+ return {
123
+ ...base,
124
+ db: { query: guardedQuerySQL, run: runSQL, unfiltered: unfilteredQuerySQL },
125
+ params,
126
+ input: input || {},
127
+ cursor,
128
+ limit,
129
+ packCursor,
130
+ unpackCursor,
131
+ isTakendown: isTakendownDid,
132
+ filterTakendownDids,
133
+ search: searchRecords,
134
+ resolve: resolveRecords,
135
+ exists: async (collection, filters) => {
136
+ const conditions = Object.entries(filters).map(([field, value]) => ({ field, value }));
137
+ const uri = await findUriByFields(collection, conditions);
138
+ return uri !== null;
139
+ },
140
+ ...accountHelpers(viewer),
141
+ asAccount: (did) => accountHelpers({ did }),
142
+ obtainSession: async (url, body, opts) => {
143
+ if (!_oauthConfig)
144
+ throw new Error('No OAuth config — cannot obtain a session');
145
+ try {
146
+ return await obtainSession(_oauthConfig, url, body, opts);
147
+ }
148
+ catch (err) {
149
+ if (err instanceof ObtainSessionError)
150
+ throw new InvalidRequestError(err.message, err.error);
151
+ throw err;
152
+ }
153
+ },
154
+ };
155
+ }
156
+ /**
157
+ * The PDS helpers for one account, with the session this app holds for it: the
158
+ * viewer's, or another account's through {@link XrpcContext.asAccount}.
159
+ */
160
+ function accountHelpers(account) {
161
+ const ready = (what) => {
162
+ if (!_oauthConfig)
163
+ throw new Error(`No OAuth config — cannot ${what}`);
164
+ if (!account)
165
+ throw new Error(`Authentication required to ${what}`);
166
+ return { config: _oauthConfig, account };
167
+ };
168
+ return {
169
+ createRecord: async (collection, record, opts) => {
170
+ const { config, account } = ready('write records');
171
+ return pdsCreateRecord(config, account, { collection, record, rkey: opts?.rkey });
172
+ },
173
+ putRecord: async (collection, rkey, record) => {
174
+ const { config, account } = ready('write records');
175
+ return pdsPutRecord(config, account, { collection, rkey, record });
176
+ },
177
+ deleteRecord: async (collection, rkey) => {
178
+ const { config, account } = ready('write records');
179
+ await pdsDeleteRecord(config, account, { collection, rkey });
180
+ },
181
+ applyWrites: async (writes) => {
182
+ const { config, account } = ready('write records');
183
+ return pdsApplyWrites(config, account, { writes });
184
+ },
185
+ pds: async (nsid, options) => {
186
+ const { config, account } = ready('call the PDS');
187
+ return pdsXrpc(config, account, nsid, options);
188
+ },
189
+ };
190
+ }
44
191
  const handlers = new Map();
192
+ /** Recursively collect .ts/.js files in a directory, skipping files prefixed with `_`. */
45
193
  function walkDir(dir) {
46
194
  const results = [];
47
195
  try {
@@ -58,6 +206,11 @@ function walkDir(dir) {
58
206
  catch { }
59
207
  return results.sort();
60
208
  }
209
+ /**
210
+ * Discover and load XRPC handler modules from the `xrpc/` directory.
211
+ * Directory nesting maps to NSID segments. Parameters are validated and
212
+ * coerced against the matching lexicon definition.
213
+ */
61
214
  export async function initXrpc(xrpcDir) {
62
215
  const files = walkDir(xrpcDir);
63
216
  if (files.length === 0)
@@ -65,7 +218,7 @@ export async function initXrpc(xrpcDir) {
65
218
  for (const scriptPath of files) {
66
219
  const rel = relative(xrpcDir, scriptPath).replace(/\.(ts|js)$/, '');
67
220
  const name = rel.replace(/[\\/]/g, '.');
68
- const mod = await import(__rewriteRelativeImportExtension(scriptPath));
221
+ const mod = await import(__rewriteRelativeImportExtension(/* @vite-ignore */ `${scriptPath}?t=${Date.now()}`));
69
222
  const handler = mod.default;
70
223
  // Extract param schema from lexicon for validation and defaults
71
224
  const lexicon = getLexicon(name);
@@ -75,65 +228,127 @@ export async function initXrpc(xrpcDir) {
75
228
  handlers.set(name, {
76
229
  name,
77
230
  execute: async (params, cursor, limit, viewer, input) => {
78
- // Apply defaults and coerce types from lexicon
79
- for (const [key, def] of Object.entries(paramProperties)) {
80
- if (params[key] == null && def.default != null) {
81
- params[key] = String(def.default);
82
- }
83
- if (params[key] != null && def.type === 'integer') {
84
- params[key] = Number(params[key]);
85
- }
86
- }
87
- for (const param of requiredParams) {
88
- if (!params[param]) {
89
- throw new InvalidRequestError(`Missing required parameter: ${param}`, 'InvalidRequest');
90
- }
91
- }
92
- const ctx = {
93
- db: { query: querySQL, run: runSQL },
94
- params,
95
- input: input || {},
96
- cursor,
97
- limit,
98
- viewer,
99
- packCursor,
100
- unpackCursor,
101
- isTakendown: isTakendownDid,
102
- filterTakendownDids,
103
- search: searchRecords,
104
- resolve: resolveRecords,
105
- lookup: async (collection, field, values) => {
106
- if (values.length === 0)
107
- return new Map();
108
- const unique = [...new Set(values.filter(Boolean))];
109
- return lookupByFieldBatch(collection, field, unique);
110
- },
111
- count: async (collection, field, values) => {
112
- if (values.length === 0)
113
- return new Map();
114
- const unique = [...new Set(values.filter(Boolean))];
115
- return countByFieldBatch(collection, field, unique);
116
- },
117
- exists: async (collection, filters) => {
118
- const conditions = Object.entries(filters).map(([field, value]) => ({ field, value }));
119
- const uri = await findUriByFields(collection, conditions);
120
- return uri !== null;
121
- },
122
- labels: queryLabelsForUris,
123
- blobUrl,
124
- };
231
+ coerceParams(params, paramProperties, requiredParams);
232
+ const ctx = buildXrpcContext(params, cursor, limit, viewer, input);
125
233
  return handler.handler(ctx);
126
234
  },
127
235
  });
128
236
  log(`[xrpc] discovered: ${name}`);
129
237
  }
130
238
  }
239
+ /** Register a single XRPC handler from a scanned server/ module. */
240
+ export function registerXrpcHandler(nsid, handlerModule) {
241
+ const lexicon = getLexicon(nsid);
242
+ const paramsDef = lexicon?.defs?.main?.parameters;
243
+ const requiredParams = paramsDef?.required || [];
244
+ const paramProperties = paramsDef?.properties || {};
245
+ handlers.set(nsid, {
246
+ name: nsid,
247
+ execute: async (params, cursor, limit, viewer, input) => {
248
+ coerceParams(params, paramProperties, requiredParams);
249
+ const ctx = buildXrpcContext(params, cursor, limit, viewer, input);
250
+ return handlerModule.handler(ctx);
251
+ },
252
+ });
253
+ }
254
+ /** Collect a query string into params, keeping every value of a repeated key. */
255
+ export function paramsFromSearch(search) {
256
+ const params = {};
257
+ for (const [key, value] of search) {
258
+ const prior = params[key];
259
+ if (prior === undefined)
260
+ params[key] = value;
261
+ else if (Array.isArray(prior))
262
+ prior.push(value);
263
+ else
264
+ params[key] = [prior, value];
265
+ }
266
+ return params;
267
+ }
268
+ function coerceScalar(value, def) {
269
+ // Only integers, as before: a boolean still reaches the handler as the
270
+ // string it was sent as, and handlers written against that keep working.
271
+ return def?.type === 'integer' ? Number(value) : value;
272
+ }
273
+ /**
274
+ * Apply the lexicon's parameter schema before a handler runs: defaults,
275
+ * integer coercion, and arrays. A query string cannot say whether
276
+ * `dids=x` is one string or a one-element list, so the schema decides: a
277
+ * parameter declared `array` always reaches the handler as one, or a handler
278
+ * that spreads it would spread the characters of a DID instead.
279
+ */
280
+ export function coerceParams(params, properties, required) {
281
+ for (const [key, def] of Object.entries(properties)) {
282
+ if (params[key] == null && def.default != null) {
283
+ params[key] = def.type === 'array' ? [...def.default] : def.type === 'string' ? String(def.default) : def.default;
284
+ }
285
+ if (params[key] == null)
286
+ continue;
287
+ if (def.type === 'array') {
288
+ const list = Array.isArray(params[key]) ? params[key] : [params[key]];
289
+ params[key] = list.map((v) => coerceScalar(v, def.items));
290
+ }
291
+ else if (Array.isArray(params[key])) {
292
+ // A scalar given twice: the last one wins, as a form submission would.
293
+ params[key] = coerceScalar(params[key][params[key].length - 1], def);
294
+ }
295
+ else {
296
+ params[key] = coerceScalar(params[key], def);
297
+ }
298
+ }
299
+ for (const param of required) {
300
+ const v = params[param];
301
+ if (v == null || v === '' || (Array.isArray(v) && v.length === 0)) {
302
+ throw new InvalidRequestError(`Missing required parameter: ${param}`, 'InvalidRequest');
303
+ }
304
+ }
305
+ }
306
+ /** Execute a registered XRPC handler by name. Returns null if no handler matches. */
131
307
  export async function executeXrpc(name, params, cursor, limit, viewer, input) {
132
308
  const handler = handlers.get(name);
133
309
  if (!handler)
134
310
  return null;
135
- return handler.execute(params, cursor, limit, viewer || null, input);
311
+ const elapsed = timer();
312
+ try {
313
+ const result = await handler.execute(params, cursor, limit, viewer || null, input);
314
+ emit('xrpc', name, { duration_ms: elapsed(), params, cursor, limit, viewer: viewer?.did });
315
+ return result;
316
+ }
317
+ catch (err) {
318
+ emit('xrpc', name, { duration_ms: elapsed(), params, cursor, limit, viewer: viewer?.did, error: err.message });
319
+ throw err;
320
+ }
321
+ }
322
+ /** Call a registered XRPC handler directly (no HTTP). For use in SSR renderers. */
323
+ export async function callXrpc(nsid, params = {}, input) {
324
+ const viewer = globalThis.__hatk_viewer ?? null;
325
+ // In externalized module context (e.g. SSR), delegate to the runner's callXrpc via globalThis.
326
+ // The runner's module instance has all registered handlers; this (Node's) instance may not.
327
+ if (handlers.size === 0 && globalThis.__hatk_callXrpc) {
328
+ return globalThis.__hatk_callXrpc(nsid, params, input);
329
+ }
330
+ const stringParams = {};
331
+ for (const [k, v] of Object.entries(params)) {
332
+ if (v == null)
333
+ continue;
334
+ // A list stays a list, as the query string would have carried it.
335
+ stringParams[k] = Array.isArray(v) ? v.map(String) : String(v);
336
+ }
337
+ const limit = params.limit ? Number(params.limit) : 20;
338
+ const cursor = params.cursor ?? undefined;
339
+ const result = await executeXrpc(nsid, stringParams, cursor, limit, viewer, input);
340
+ if (result === null)
341
+ throw new Error(`No XRPC handler registered for ${nsid}`);
342
+ return result;
343
+ }
344
+ /**
345
+ * Register a core XRPC handler directly (no XrpcContext wrapping).
346
+ * Used for built-in dev.hatk.* handlers that manage their own dependencies.
347
+ */
348
+ export function registerCoreXrpcHandler(nsid, fn) {
349
+ handlers.set(nsid, { name: nsid, execute: fn });
136
350
  }
351
+ /** Return all registered XRPC method names. */
137
352
  export function listXrpc() {
138
353
  return Array.from(handlers.keys());
139
354
  }
package/package.json CHANGED
@@ -1,9 +1,15 @@
1
1
  {
2
2
  "name": "@hatk/hatk",
3
- "version": "0.0.1-alpha.1",
3
+ "version": "0.0.1-alpha.100",
4
+ "license": "MIT",
4
5
  "bin": {
5
6
  "hatk": "dist/cli.js"
6
7
  },
8
+ "files": [
9
+ "dist",
10
+ "fonts",
11
+ "public"
12
+ ],
7
13
  "type": "module",
8
14
  "exports": {
9
15
  "./feeds": "./dist/feeds.js",
@@ -14,28 +20,46 @@
14
20
  "./xrpc-client": "./dist/xrpc-client.js",
15
21
  "./views": "./dist/views.js",
16
22
  "./seed": "./dist/seed.js",
23
+ "./hooks": "./dist/hooks.js",
17
24
  "./setup": "./dist/setup.js",
18
25
  "./test": "./dist/test.js",
19
- "./test/browser": "./dist/test-browser.js",
20
- "./vite-plugin": "./dist/vite-plugin.js"
26
+ "./config": "./dist/config.js",
27
+ "./vite-plugin": "./dist/vite-plugin.js",
28
+ "./renderer": "./dist/renderer.js",
29
+ "./spaces": "./dist/spaces/index.js"
21
30
  },
22
- "files": ["dist", "fonts", "public"],
23
31
  "scripts": {
24
- "build": "tsc -p tsconfig.build.json",
25
- "prepublishOnly": "npm run build"
32
+ "clean": "rm -rf dist",
33
+ "build": "npm run clean && tsc -p tsconfig.build.json && cp -r src/templates dist/templates && cp -r src/lexicons dist/lexicons",
34
+ "prepublishOnly": "npm run build",
35
+ "test": "vitest run --coverage",
36
+ "test:watch": "vitest"
26
37
  },
27
38
  "dependencies": {
28
- "@bigmoves/lexicon": "^0.2.1",
39
+ "@bigmoves/lexicon": "^0.2.4",
29
40
  "@duckdb/node-api": "^1.4.4-r.1",
30
41
  "@hatk/oauth-client": "*",
42
+ "@noble/curves": "^2.4.0",
31
43
  "@resvg/resvg-js": "^2.6.2",
32
- "satori": "^0.19.2",
44
+ "better-sqlite3": "^12.6.2",
45
+ "satori": "^0.28.1",
33
46
  "vitest": "^4",
34
47
  "yaml": "^2.7.0"
35
48
  },
36
49
  "devDependencies": {
37
- "@playwright/test": "^1.58.2",
50
+ "@types/better-sqlite3": "^7.6.13",
38
51
  "@types/react": "^19.2.14",
39
- "vite": "^6"
52
+ "@vitest/coverage-v8": "^4.1.11",
53
+ "sharp": "^0.35.4",
54
+ "vite": "^8.0.0"
55
+ },
56
+ "peerDependencies": {
57
+ "sharp": "^0.35.4",
58
+ "vite": "^8.0.0"
59
+ },
60
+ "peerDependenciesMeta": {
61
+ "sharp": {
62
+ "optional": true
63
+ }
40
64
  }
41
65
  }